Skip to content
Binary & Unary Expressions
step 1/3

Reading — step 1 of 3

Parsing Binary and Unary Operations

~2 min readParsing Expressions

Binary & Unary Expressions

Expressions are the core of any programming language. A binary expression has two operands and an operator (a + b), while a unary expression has one operand (-x, !flag).

Binary Expressions

Binary operators in our language include arithmetic (+, -, *, /), comparison (<, <=, >, >=), and equality (==, !=). Each has a left operand, an operator, and a right operand.

The parser produces a tree node:

Binary {
    left:  Expression
    op:    Token       // PLUS, MINUS, STAR, etc.
    right: Expression
}

For 1 + 2 * 3, the tree is:

    +
   / \
  1   *
     / \
    2   3

Notice that * is deeper in the tree — it binds tighter. This is how precedence works structurally.

Unary Expressions

Our language has two unary operators:

  • Negation (-): negates a number. -42 produces Unary(MINUS, 42)
  • Logical NOT (!): inverts truthiness. !true produces Unary(BANG, true)

Unary operators are right-associative and bind tighter than any binary operator:

-2 + 3   → (+ (- 2) 3)      // negate first, then add
!!true   → (! (! true))      // double negation

Parsing Unary

function unary():
    if match(BANG, MINUS):
        op = previous()
        operand = unary()     // recursive!
        return Unary(op, operand)
    return primary()

The recursion in unary() calling itself handles chained unary operators like --x or !!flag.

S-Expression Output

We represent the AST as S-expressions (parenthesized prefix notation):

  • 1 + 2 becomes (+ 1.0 2.0)
  • -1 becomes (- 1.0)
  • !true becomes (! true)

This format is unambiguous — it explicitly shows the tree structure. Lisp uses this as its actual syntax, which is why Lisp is so easy to parse — the programmer writes the AST directly.

Type Interactions

What happens when you negate a string? -"hello" should be a runtime error. We will add type checking later, but for now the parser accepts anything syntactically valid.

Your Task

Extend the parser to handle all binary and unary operators with correct precedence. Output the AST in S-expression format.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…