Complex Expressions
This page explores how the compiler handles complex arithmetic expressions, demonstrating operator precedence, associativity, and the use of parentheses.Operator Precedence
The compiler correctly implements mathematical operator precedence where multiplication and division have higher precedence than addition and subtraction.- Example
- AST
- IR
14 (not 20)The expression evaluates as 2 + (3 * 4) because * has higher precedence than +.Precedence Levels
The compiler implements two precedence levels:High Precedence
Operators:
* (multiplication), / (division)These are evaluated first in any expression.Example: 10 + 5 * 2 → 10 + 10 → 20Low Precedence
Operators:
+ (addition), - (subtraction)These are evaluated after high-precedence operators.Example: 10 - 3 + 2 → 7 + 2 → 9Precedence Examples
Left Associativity
Operators at the same precedence level are evaluated left-to-right (left-associative).Parentheses for Grouping
Parentheses() can override operator precedence by forcing evaluation order.
Basic Grouping
- Without Parentheses
- With Parentheses
AST Comparison
See how parentheses change the AST structure:ExpresionAgrupada node that wraps the addition, forcing it to be evaluated first.
Nested Parentheses
Parentheses can be nested to create complex expressions.Multiple Nesting
(10 + 5)=15(3 - 1)=215 * 2=30
Complex Expression Examples
Putting it all together with real-world scenarios.Mathematical Formula
(a + b)→(10 + 5)=15(c - d)→(8 - 3)=515 * 5=7575 / 3=25
Intermediate Code Generated
Expression Parsing Details
Understanding how the parser works internally.Parser Grammar Rules
Parser Grammar Rules
The compiler uses recursive descent parsing with these grammar rules:
- expresion: Entry point for all expressions
- suma_resta: Handles addition and subtraction (lower precedence)
- mult_div: Handles multiplication and division (higher precedence)
- primario: Base cases (numbers, variables, grouped expressions)
Parsing Steps for '2 + 3 * 4'
Parsing Steps for '2 + 3 * 4'
expresion()callssuma_resta()suma_resta()callsmult_div()mult_div()callsprimario()→ gets2- Back in
suma_resta(), sees+operator - Calls
mult_div()again for the right side mult_div()gets3, sees*, gets4- Returns
3 * 4as a subtree suma_resta()combines:2+(3 * 4)
* deeper than +Practice Problems
Test your understanding of operator precedence:Problem 1
What does this output?
Problem 2
What does this output?
Problem 3
What does this output?
Problem 4
What does this output?