Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rljacobson/346b5e8ccce28c70b3c10d193b88cbd6 to your computer and use it in GitHub Desktop.
Save rljacobson/346b5e8ccce28c70b3c10d193b88cbd6 to your computer and use it in GitHub Desktop.
EBNF Precedence and Associativity Cheat Sheet

EBNF Precedence and Associativity Cheat Sheet

These are the standard patterns for encoding precedence and associativity into an expresion grammar in (E)BNF.

View in EBNF playground.

<ADD_OP>   ::= "+" | "-" 
<MUL_OP>   ::= "*" | "/"
<POWER_OP> ::= "^"
<NUMBER>   ::= [0-9]+

/* Just for illustrative purposes, as this production can be left out. */
<expr> ::= <term>

/* A term is composed of a factor, so factor is parsed/produced first */
<term> ::= <term> <ADD_OP> <factor>
    | <factor>
    
/* Left associative, so written as left recursive */
<factor> ::= <factor> <MUL_OP> <power> 
    | <power>
    
/* Right associative, so written as right recursive */
<power> ::= <unary> <POWER_OP> <power>
    | <unary>
    
<unary> ::= "-" <primary>
	| <primary>
    
/* The leaf nodes……or parenthesized expressions. */
<primary> ::= <NUMBER>
    | "(" <expr> ")"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment