Next: Expressing precedence, Previous: Operators, Up: Top [Contents][Index]
We have seen how we can extract an integer from pacc’s input into a C ‘int’ value. To do much more, we need to be able to bind a name to that value so that we can refer to it in expressions. In pacc, we use the ‘:’ operator, and write ‘name:something’ to bind ‘name’ to the value of ‘something’.
So what are the type and value assigned to ‘name’? There are two separate cases. If ‘something’ is the name of a rule, then ‘name’ has the same type as that rule, and the value of evaluating that rule. In all other cases, ‘name’ has the type ‘ref_t’ and its value is everything matched by ‘something’. For example, if there is a rule ‘Number :: int’, then after ‘n:Number’, the type of ‘n’ is ‘int’, but after ‘n:Number*’ or ‘n:(Number)’ the type of ‘n’ is ‘ref_t’.
Let’s expand our example to do simple additions.
Sum <- d:Decimal "+" s:Sum -> { d + s }
/ d:Decimal -> d
Decimal <- [0-9]+ -> { atoi(ref_str()) }
We are using recursion. The base case is the second alternative: a ‘Sum’ can be simply a ‘Decimal’. In this case, we bind ‘d’ to the value returned by the ‘Decimal’ rule, and that value is then returned as the value of the ‘Sum’ rule. For the recursive case, we have a ‘Decimal’, followed by a literal plus sign, followed by the recursive call to ‘Sum’. We bind ‘d’ to the ‘Decimal’, and ‘s’ to the value returned by the recursive call. The overall value returned in this case is the sum of ‘d’ and ‘s’.
A name bound by the ‘:’ operator is in scope from its binding to the end of the alternative in which it occurs. Thus, the two occurences of ‘d’ in the ‘Sum’ rule are in different scopes.
Note that the second alternative in ‘Sum’ is a prefix of the first alternative. This means that it is imperative to write the longer expression first, just like in the ‘"non" / "no"’ example (see Alternatives).
It is fairly common for one or more alternatives in a rule simply to call another rule and return its result. As a shorthand, pacc allows you to omit the binding and expression for this case. Thus the ‘Sum’ rule can be written like this.
Sum <- d:Decimal "+" s:Sum -> { d + s }
/ Decimal
Next: Expressing precedence, Previous: Operators, Up: Top [Contents][Index]
Last updated: 2016-08-03 21:39:50 UTC
One thing pacc needs is more users. And, perhaps, one way to get more users is to reduce the friction in getting started with pacc. An obvious lubricant is packaging. Read More...
Looking at _pacc_coords(), I noticed that it seemed to have the same realloc() bug that I'd just fixed in _pacc_result(). However, the "list of arrays" trick really wasn't going to work here. Read More...