0

I would like to create my own programming language and I would like to implement the operators (and,or) with parentheses like that for example.

x  = 1
x2 = 2
x3 = 0
x4 = 0
// tmpMap = {x = 1 , x2 = 2, x3 = 0 , x4 = 0}
r1 = ((x and x2) or x3) and x4 // System.out.println("false");
r2 = ((x and x2) or x3) or x4  // System.out.println("true");

My problem is how I can define this rule and how I can evaluate it in my listener to display (true | false). Can someone give me a simple prototype for this problem ?. Thank you in advance.

Ghiloufi
  • 311
  • 4
  • 10

1 Answers1

0

You want to write a grammar which defines expressions, terms, and factors. An expressions is defined as "factor ± factor" and a factor is "term [* or /] term". A term is either a number or a parenthised expression, i.e. "( expression )".

Then, simply by the way your language is parsed, you get operator precedence. If your language only supports "and" and "or" as operators, then "and" is equivalent to "*" and "or" is equivalent to "+", thus:

expression = factor OR factor
factor = term AND term
term = identifier | ( expression ) 

See this answer for a complete grammar definition (for arithmetic operators, but you can easily swap them for boolean operators)

knittl
  • 246,190
  • 53
  • 318
  • 364