Child pages
  • Binding power syntax

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

In order to specify binding power we use "^" which is power symbol:

Here is sample from Calculator grammar:

Code Block
syntax expr
{
  | num        = number
  | rounds     = '(' expr ')'
  | add        = expr sm '+' sm expr  { precedence 10;  }
  | sub        = expr sm '-' sm expr  { precedence 10;  }
  | mul        = expr sm '*' sm expr  { precedence 20;  }
  | div        = expr sm '/' sm expr  { precedence 20;  }
  | mod        = expr sm '%' sm expr  { precedence 20;  }
  | pow        = expr sm '^' sm expr  { precedence 30 right-associative; }
  | neg        = '-' expr             { precedence 100; }
  | prefixDec  = "--" expr            { precedence 200; }
  | postfixDec = expr "--"            { precedence 200; }
  | cond       = Condition sm '?' sm  expr sm  Colon=':' sm expr 
  | coalescing = expr ^401 sm "??" sm expr ^400
}

???


Binding power controls how to resolve ambiguities in parsing rules when text parsed with one rule can be prefix or suffix of text parsed with another rule. Since this problem is most frequently arise in expressions, it can be formulated as this: "Given an operand between two operators, is the operand bound to the left operator or the right?". Hence the name, "binding power".

When checking alternatives for a subrule, we will only consider rules with power higher than power of subrule currently being parsed, and prefer them if match is found. In "1 + 2 * 3", if "+" has a BP of 10 and "*" of 20, the "2 * 3" part will be preferred and its result passed as a right expression to the first "+".