build-a-programming-language / lesson-13.md
Lesson 13 · Parsing

Comparison operators

Comparisons like < and == bind looser than arithmetic, so 1 + 2 < 3 compares the sum. Today you add two more precedence levels for the comparison and equality operators.

The goal

Parse comparison and equality operators at their own precedence levels, below arithmetic.

Start here - the target
TO DO
Scenario: Comparison binds looser than arithmetic
Giventhe source 5 > 4 == 3 < 4
Whenthe parser parses the program and prints it
Thenthe printed form is ((5 > 4) == (3 < 4))
Andparsing 1 + 2 < 3 prints ((1 + 2) < 3)
Background

Comparisons slot in as two more precedence levels beneath arithmetic: < and > (call it LESSGREATER) bind looser than +/-, and ==/!= (EQUALS) looser still. Because arithmetic binds tighter, 1 + 2 < 3 naturally parses the 1 + 2 first and then compares the result, giving ((1 + 2) < 3).

The satisfying part: you write no new parsing code. The Pratt loop from the last lesson already consults the precedence table, so adding operators is just adding rows to that table. 5 > 4 == 3 < 4 grouping as ((5 > 4) == (3 < 4)) falls out for free - a good sign your precedence machinery is right rather than special-cased.

Make it work
const ( LOWEST = iota; EQUALS; LESSGREATER; SUM; PRODUCT )
// add to the precedence map:
// "==" and "!=" -> EQUALS
// "<" and ">" -> LESSGREATER
// the parseInfix code does not change - only the level table does
CheckpointDONE
Comparison and equality operators parse at their own precedence, below arithmetic. Commit.