11 Implementing expressions: Binary operations

 

This chapter covers

  • Why, how, and what expressions are useful for
  • Why binary operations are especially useful
  • How to represent expressions with binary operations as ASTs
  • How to implement binary operations across all key aspects of a DSL

If you look at our example DSL content, you’ll notice that the attributes of the Rental record type should be related more intricately than they currently are. The value of rental price after discount should be calculated from the values of rental price before discount and discount—see figure 11.1.

Unfortunately, we can’t express such relations yet: the DSL doesn’t have any concept with the appropriate notation and the corresponding meaning. Leaving it up to the user of the generated web app to set the rental price after discount to a value governed by the preceding arithmetical relation is unfair.

In this chapter, we’re going to add expressions to the DSL to remedy that. An expression is a piece of DSL content whose meaning aspect consists of it evaluating to a value. We can stick that value in other expressions to get another value, and so on, and so on. Expressions can be anything, ranging from constant values, to references to “things” holding values, to arithmetical computations such as the one in figure 11.1. The only rule is that they evaluate to a value. Arithmetical formulas—of the sort you learned in school and that you also see in figure 11.1—form a well-known class of expressions.

11.1 Representing expressions as DSL content

11.1.1 Changing the structure

11.2 Changing the projection

11.3 Changing the runtime

11.4 Changing the code generator

11.5 Postscript: Expressions in general

11.5.1 Characterizing expressions by arity

11.5.2 Compositionality and expressiveness

11.5.3 Characterizing expressions by operator

Summary