Writing a parser: ADL parser node types

In this post, I’ll show you the different types of parser nodes. If you remember from one of the first posts I made in this series, the parser analyzes the tokens it gets from the tokenizer and turns it into structured trees. The nodes in this tree represent the different constructs (additions, multiplications, comparisons, …).

The different types of parser tree nodes

  • ParserNode
    • Statement
      • Assignment: x := …
      • IfStatement: if … then … else … end if
      • WhileStatement: while … do … end while
      • ForStatement: for i := … to … by … do … end for
      • FunctionCallStatement: f(…)
    • Expression
      • UnaryExpression
        • Negation: -x
        • NotExpression: not x
      • BinaryExpression
        • Addition: x + y
        • Subtraction: x - y
        • Multiplication: x * y
        • Division: x / y
        • AndExpression: x and y
        • OrExpression: x or y
        • Comparison: x < y or x > y or x == y or …
      • Variable: x
      • IntegerConstant: 123
      • StringConstant: "abc"
      • FunctionCall: f(…)

A statement is an instruction that does not return a value. An expression is an instruction that does return a value. A unary expression has an operator and a single child expression. A binary expression has an operator and 2 child expressions.

You might have noticed that I defined both a FunctionCall and a FunctionCallStatement. The difference is that a FunctionCall is an expression that returns the value of the function call, and a FunctionCallStatement is a statement that ignores the value of the function call.

The basic types look like this:

public abstract class ParserNode

public abstract class Statement : ParserNode

public abstract class Expression : ParserNode

As you can see, they don’t contain any code. Because I’m just explaining how parsers work, they don’t have to contain code. You should add code if you use these classes to build an interpreter or a compiler. For an interpreter, the Statement class could have a method Execute to execute the statement, and the Expression class could have a method Evaluate to evaluate the expression and return the result.

There’s no point in showing the source code in this blog post for all the classes, so you can download them here. Just create a new folder ParserNodes in the TC.Adl project and include the downloaded C# files.

Next time, we’ll write the actual parser and a test application.