12 Implementing expressions: Order of operations
This chapter covers
- What “order of operations” means for expressions
- How and why the evaluation of an expression should shape the AST representing it
- How to take the order of operations into account in a projectional DSL
- How to use side-transforms to improve the editing experience for domain experts
The notion of expressions should be very familiar: when you learned arithmetic and algebra in school, that was expressed in terms of expressions. You can’t do anything “science-y” or any engineering without writing down formulas and doing math—all of this relies heavily on expressions. Almost any statement in a programming language has one or more expressions at its heart. This means that expressions are essentially everywhere, even if they’re not always explicitly identified as such.
This ubiquity comes at a price: almost everyone has a lot of intuition, assumptions, and expectations around expressions. We’ve become accustomed to writing them down as strings of symbols such as +
, -
, 42
, x
, etc. We do that when using paper, when using tools such as spreadsheet programs, and certainly when writing code. This linear, textual structure, which can be navigated with a cursor, also shapes the editing experience: expressions are typically created and edited as text, using a keyboard. To convert this text into an AST that can be processed further, it has to be parsed—I’ll explain that a bit more in section 15.1.