Skip to content

FourOps

Julien Rialland edited this page Dec 4, 2017 · 1 revision

The FourOps grammar is the silliest example that I found that explains how a grammar can be written.

  • It illustrates well left-associativity operator priority issues
  • It illustrates well how operator precedences might be defined
  • It shows how concrete things (i.e calculus) can be done when exploring the generated AST
  • It has few rules

Purpose

The FourOps grammar is used to express simple integer-based maths expressions. Only the four basic operations are handles : addition, substraction, multiplication and division.

Definition

A "formal" definition of the FourOps grammar is the following :

Expression :
      Number
    | AdditionOrSubstraction
    | MultiplicationOrDivision
    ;

AdditionOrSubstraction :
      Expression '+' Expression
    | Expression '-' Expressions
    ;

MultiplicationOrDivision :
      Expression '*' Expression
    | Expression '/' Expressions
    ;

An "informal" definition could be : "handle mathematical operation, like the one pupils learn in primary school"

Example

The FourOpsTest class explains how to use the @Before and @After annotations to express the code that needs to be executed when we visit a certain AST node.

In this example, a stack is used as the memory.

  • A new number is stored when we read a number
  • the uppermost 2 elements at the top of the stack are removed, and the result is put back on the stack when we do a computation.

Clone this wiki locally