简体   繁体   中英

Javascript and automatic semicolon insertion

test262 test suite has test containing source:

var x=0, y=0;
var z=
x
++
++
y

The annotation says:

Since LineTerminator(LT) between Postfix Increment/Decrement Operator(I/DO) and operand is not allowed, two IO(just as two DO and their combination) between two references separated by [LT] after automatic semicolon insertion lead to syntax error

Why does this code lead to syntax error? I think it's a valid code snippet. The code above equals to var z=x; ++ ++ y; var z=x; ++ ++ y; . Expression ++ ++ y is allowed by javascript grammar. So what's the problem?

This code will become:

var z = x;
++ ++ y;

The ++ ++ y is the root of the problem. Let's look at why...

++ ++ y gets evaluated as ++(++y) . The first step is to evaluate (++y) . The ++ operator increments the value referenced by the variable it is next to, and returns the incremented value. The important part here is that it does not return a reference, just a value . So the second step would be ++(1) , (or whatever ++y yielded), which is an error, since only references can be incremented.

That evaluates to:

var x = 0, y = 0;
var z = x ++ ++ y; //MAKES NO SENSE!

The grammar does not allow a new-line to precede a ++ or -- operator; such a new-line must be converted to a ; . Consequently, the expression must be parsed as though it had been:

var x = 0 , y = 0 ;
var z = x ;
++ ;
++ y ;

The third line is illegal.

References:

Section 7.9.1, "Rules of Automatic Semicolon Insertion", rule 3

Section 11.3, "11.3 Postfix Expressions".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM