labs-lang / labs

LAbS: a Language with Attribute-based Stigmergies - Parser + Code generator
BSD 3-Clause "New" or "Revised" License
7 stars 0 forks source link

"Let" bindings #14

Open lou1306 opened 5 years ago

lou1306 commented 5 years ago

Properties and link predicates may contain multiple occurrences of the same expression. Consider this example (adapted from examples/formation1d.labs):

stigmergy Left {
    link =
        pos of c1 - pos of c2 > 0 and
        pos of c1 - pos of c2 <= 5
        #...
}

The translator simply emits the same C expression multiple times:

_Bool link(int __LABS_link1, int __LABS_link2, int key) {
    // ..
    __LABS_link = (((( I[__LABS_link1][0] - I[__LABS_link2][0] )) > (0)) && 
    ((( I[__LABS_link1][0] - I[__LABS_link2][0] )) <= (5)));
    // ...
}

Proposal

Introduce a new construct in the syntax of boolean expressions.

Bexpr = true | false | Bexpr and Bexpr | Bexpr or Bexpr | let KEYNAME = Expr in Bexpr

where KEYNAME is a valid and unused variable identifier (alphanumeric, starts with lowercase). The example therefore becomes:

stigmergy Left {
    link =
        let distance = pos of c1 - pos of c2 in
        distance > 0 and distance <= 5
        #...
}

This improves the readability of the specification and may also allow to generate simpler C code:

_Bool link(int __LABS_link1, int __LABS_link2, int key) {
    // ..
    int distance = (( I[__LABS_link1][0] - I[__LABS_link2][0] ));
    __LABS_link = ((distance > (0)) && (distance <= (5)));
    // ...
}