I am attempting to parse javascript (using javascript), and I’ve run into a problem with objects. How does javascript determine the difference between an object or a block?
For instance
{ x : 1, y : 2}
Token Stream:
[{][x][:][1][,][y][:][2][}]
Is clearly an object, however
{ var x = 1; var y = 2}
Token Stream:
[{][var][x][=][1][;][var][y][=][2][}]
Is a perfectly valid anonymous javascript block. How would I go about efficiently identifying each token stream as an object or block?
However, more important then both of these how would I determine the difference between a token stream that could be an object or a block like the following:
{ a : null }
Token Stream:
[{][a][:][null][}]
This could either be an object whose parameter a is equal to null, or it could be a block where the first statement in the block (null) has a label (a)
You don’t.
The context of the syntax affects it’s identity. You can’t just pluck things out of context and determine what they are.
In the grammar, an object literal is:
whereas a block is:
But literals only exist where expressions are allowed, while blocks exist where statements are allowed. And those aren’t the same thing.
So, it’s the surrounding context that distinguishes the two forms.