statements that could be expressions?

Mike Samuel mikesamuel at gmail.com
Wed Jun 1 18:04:39 PDT 2011


2011/6/1 Waldemar Horwat <waldemar at google.com>:
> On 06/01/11 16:07, Peter Michaux wrote:
>>
>> Could some of JavaScript's statements also be allowed as expressions?
>>
>> In Perl there is the common idiom when opening a file
>>
>>   open F, "<  $f" or die "Can't open $f : $!";
>>
>> In JavaScript could "throw" be an expression?
>>
>>   f() || throw 'f failed';
>>
>> Could JavaScript's "if" become an expression? (I know JavaScript the
>> ?: operator but this is just a for example.)
>>
>> Could a Block statement also be an expression like Scheme's "begin"?
>>
>> Peter
>
> Theoretically it's possible to allow statements as expressions, but you run
> into a number of practical problems:
>
> - Precedence inversion:
>
> a = if (b) c
>
> So far so good.  However, the substatement of an if can also be a comma
> expression, which causes trouble:
>
> a = if (b) c, d
>
> Also, what should be stored in a if b is false?  You can argue between
> false, null, and undefined.
>
> - Conflict between blocks and statements:
>
> a = {x: while (x) { ... break x;}}
>
> is either an object initializer or a block containing a labeled while
> statement.
>
> - Semicolon insertion:
>
> return
>  if (longcondition) {
>    ...
>  } else {
>    ...
>  }
>
> will not do what you want.  The entire if is dead code.

If the goal is to allow some subset (such as the following) of
statement types to be embedded in expressions:
    IfStatement
    IterationStatement
    SwitchStatement
    ThrowStatement
    ReturnStatement
    BreakStatement
    ContinueStatement
    TryStatement
    DebuggerStatement

then I think it can be done without to much syntactic trouble.

Modify PrimaryExpression to add the following productions
   "(" IfStatement ")"
   | "(" SwitchStatement ")"
   | ...

Basically an uncontextually reserved keyword that always starts a
statement following an open parenthesis is treated as a statement
embedded in an expression.  And a semicolon is neither required nor
allowed before the closing ")".

This would require changing expression semantics to be specified in
the same way as statement semantics.  Specifically, labels and
exception would have to be propagated out of all expression
computations early.

Semicolon insertion should continue to work unchanged.




>    Waldemar
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list