GFem language documentation -- 3.10 Language internals

Previous: 3.9 Other features
Up: 3 The Gory Details

## 3.10 Language internals

- Like most interpreters it has a lexical and a syntaxic part. In the lexical part the source is broken into tokens and recognized as symbols (see the enum symbol in the source file `lexical.h`). For instance if the first character is a digit then it is a number and the symbol type associated is `cste`. This job is done by function `nextsym`.In addition it constructs a table of constants and variables (which for convenience contains also the reserved words of the language).
- The lexical analyzer is a function called by the syntax analyzer. Hence the second is the main routine in the program except for a few initialization; it's name is `instruction` .The syntax analysis is driven by the syntax rules because the language is LL(1). Thus there is C-function for each non-terminal.
- The program does not generate an object code but a tree. For example, parsing `x * y` would generate a tree with root `*` and two branches `x` and `y` . Trees are C-struct with four pointers for the 4 branches (here two would point to NULL) and a symbol for the operator. The C-function which builds trees is called `plante` . In the end the program is transformed into a full tree and to execute the program there is only one thing to do: evaluate the operator at the root of the tree.
- The evaluation of the program is done by the C-function `eval` . It looks at the root symbol and perform the corresponding operation. Here it would do: return "value pointed by L1"*"value pointed by L2" if L1 and L2 where the addresses of the two branches.
- The art of the game is to associate a tree to each operation. For example when the value of the variable `x` is required, this is also done by a tree which has the operator "oldvar" as root. The trickiest of all is the compound instruction `{...;....};` . Here `{` is considered as an operator with one branch on the current instruction and one branch on the next one. Similarly for the `if...then... else` instruction.

Suppose one wants to add an instruction to freefem, here is what must be done:

- Make sure the syntax is LL(1) and does not conflict with the old one.
- Add reserved words to the table with `installe` . As there will be a new Symbol, update the list of symbols (an enum structure). Add the C-functions for the syntax analysis according to the diagrams. Modify eval by adding to the `switch` the new case.

Here is the very simple structure we used for the nodes of the tree:

    typedef struct noeud
    {
      Symbol symb;
      creal value;
      ident *name;
      long  junk;
      char  *path;
      struct noeud *l1, *l2, *l3, *l4;
    } noeud, *arbre;