During my participation in the last Code Sprint UI Patterns, I had the opportunity to work on a new module to address the project's needs.
UI Patterns Devel, is a sub-module of UI Patterns 2.x, which among other things includes a Twig validator that allows to statically check the syntax of Twig template for Drupal Single-Directory Components.
The task of creating a static analyzer for Twig took a little more work than I had estimated. But it allowed me to learn more about the internals of Twig.
I started like any programmer by looking at what had been done, and I came across this project: phpstan-twig-analyis, which served as a starting point and allowed me to determine an initial approach to loading a Twig template, analyzing it, and collecting errors.
The main architecture is to ingest a Twig source, parse it to get the NodeTree: $nodeTree = $this->twig->parse($this->twig->tokenize($source));
and use NodeTraverser to traverse the template as objects.
After that, I just had to create a rule manager to apply rules and use a collector to receive the messages. Then a Drupal page and a Drush command ui-patterns:validate
to display the errors.
In the end, the most interesting part was defining rules for the usage of variables in the template. For Drupal SDC, the variables for each template are described in a Yaml file, which allows determining if a variable is missing or doesn't exist in the template.