chharvey / counterpoint

A robust programming language.
GNU Affero General Public License v3.0
2 stars 0 forks source link

Syntax & Semantics: Conditional Expressions #26

Closed chharvey closed 4 years ago

chharvey commented 4 years ago

A conditional expression is a ternary operation if … then … else …, containing 3 expressions.

Syntax:

Expression ::=
    | ExpressionConditional
;

ExpressionConditional
    ::= "if" Expression "then" Expression "else" Expression;

Semantics:

SemanticOperation[operator=COND]
    ::= SemanticExpression[type=Boolean] SemanticExpression SemanticExpression;

Decorate(ExpressionConditional ::= "if" Expression__0 "then" Expression__1 "else" Expression__2)
    := (SemanticOperation[operator=COND]
        Decorate(Expression__0),
        Decorate(Expression__1),
        Decorate(Expression__2),
    );

Type:

Type TypeOf(SemanticOperation[operator=COND] operation) :=
    1. *Assert:* `operation.children.count` is 3.
    2. *Let* `t0` be `TypeOf(operation.children.0)`.
    3. *Let* `t1` be `TypeOf(operation.children.1)`.
    4. *Let* `t2` be `TypeOf(operation.children.2)`.
    5. *If* `TypeOf(t0)` is `Boolean`:
        1. *Return:* `TypeUnion(t1, t2)`.
    6. *Throw:* TypeError "Invalid operation.".

Runtime behavior: A conditional expression has three operands: the condition, the consequent (“then” branch), and the alternative (“else” branch). If the condition evaluates to true or a “truthy” value, the consequent is produced; else, the alternative is produced.

Constant folding: If the compiler can assess the value of the condition at compile-time and definitely determine which branch will execute, then only the instructions for that branch will be produced. (#36)

Short-circuiting: At runtime, exactly one of the consequent or the alternative will be produced, and the branch that is not produced will not even be evaluated (for example, if it contains a procedure call, the procedure will not be called).