Git Product home page Git Product logo

esprima's Introduction

NPM version npm download Tests Coverage Status

Esprima (esprima.org, BSD license) is a high performance, standard-compliant ECMAScript parser written in ECMAScript (also popularly known as JavaScript). Esprima is created and maintained by Ariya Hidayat, with the help of many contributors.

Features

API

Esprima can be used to perform lexical analysis (tokenization) or syntactic analysis (parsing) of a JavaScript program.

A simple example on Node.js REPL:

> var esprima = require('esprima');
> var program = 'const answer = 42';

> esprima.tokenize(program);
[ { type: 'Keyword', value: 'const' },
  { type: 'Identifier', value: 'answer' },
  { type: 'Punctuator', value: '=' },
  { type: 'Numeric', value: '42' } ]
  
> esprima.parseScript(program);
{ type: 'Program',
  body:
   [ { type: 'VariableDeclaration',
       declarations: [Object],
       kind: 'const' } ],
  sourceType: 'script' }

For more information, please read the complete documentation.

esprima's People

Contributors

ad-si avatar ariya avatar constellation avatar fishbar avatar gibson042 avatar ikarienator avatar jasonlaster avatar jboekesteijn avatar jifeon avatar josephpecoraro avatar jryans avatar jugglinmike avatar kingwl avatar kondi avatar lahma avatar ljqx avatar mariusschulz avatar markelog avatar mathiasbynens avatar meir017 avatar michaelficarra avatar mikesherov avatar mrennie avatar nzakas avatar oxyc avatar rdela avatar sebmarkbage avatar serima avatar swatinem avatar syllant avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

esprima's Issues

Location for property getting/setter should be extended

Consider the following test code:

var esprima = require('./esprima');
var code = '({ set width(w) {} })';
var tree = esprima.parse(code, { loc: true });
console.log(tree.body[0].expression.properties[0].key.loc.start.column);
console.log(tree.body[0].expression.properties[0].value.loc.start.column);
console.log(tree.body[0].expression.properties[0].value.params[0].loc.start.column);

The current master branch produced the following output:

7
16
13

This is because the key of Property node looks like:

{ loc: { start: { line: 1, column: 7 }, end: { line: 1, column: 12 } },
  type: 'Identifier',
  name: 'width' }

and the value of Property node:

{ loc: { start: { line: 1, column: 16 }, end: { line: 1, column: 18 } },
  type: 'FunctionExpression',
  id: null,
  params: [ { loc: [Object], type: 'Identifier', name: 'w' } ],
  defaults: [],
  body: 
   { loc: { start: [Object], end: [Object] },
     type: 'BlockStatement',
     body: [] },
  rest: null,
  generator: false,
  expression: false }

with its first parameter as:

{ loc: { start: { line: 1, column: 13 }, end: { line: 1, column: 14 } },
  type: 'Identifier',
  name: 'w' }

This is different than the result of SpiderMonkey (Reflect.parse instead of esprima.parse):

7
7
13

For the analysis, this is how the Property looks like:

{
  "loc": {
    "start": {
      "line": 1,
      "column": 7
    },
    "end": {
      "line": 1,
      "column": 18
    },
    "source": null
  },
  "type": "Property",
  "key": {
    "loc": {
      "start": {
        "line": 1,
        "column": 7
      },
      "end": {
        "line": 1,
        "column": 12
      },
      "source": null
    },
    "type": "Identifier",
    "name": "width"
  },
  "value": {
    "loc": {
      "start": {
        "line": 1,
        "column": 7
      },
      "end": {
        "line": 1,
        "column": 18
      },
      "source": null
    },
    "type": "FunctionExpression",
    "id": null,
    "params": [
      {
        "loc": {
          "start": {
            "line": 1,
            "column": 13
          },
          "end": {
            "line": 1,
            "column": 14
          },
          "source": null
        },
        "type": "Identifier",
        "name": "w"
      }
    ],
    "defaults": [],
    "body": {
      "loc": {
        "start": {
          "line": 1,
          "column": 16
        },
        "end": {
          "line": 1,
          "column": 17
        },
        "source": null
      },
      "type": "BlockStatement",
      "body": []
    },
    "rest": null,
    "generator": false,
    "expression": false
  },
  "kind": "set",
  "method": false,
  "shorthand": false
}

The result from SpiderMonkey is more sensible. Note how the value of the Property node starts as the same place (column: 7) as the key.

Harmony: Shorthand functions in objects do not add the `shorthand` flag

Code:

var obj = {
  myfunc() { return null; }
}

myfunc node doesn't have truthy shorthand property.

{ type: 'Property',
  key:
   { type: 'Identifier',
     name: 'myfunc',
     range: [ 16, 22 ],
     loc: { start: [Object], end: [Object] },
     parentNode: [Circular],
     parentCollection: [ undefined ] },
  value:
   { type: 'FunctionExpression',
     id: null,
     params: [],
     defaults: [],
     body: { ... }, ... },
  kind: 'init',
  method: true,
  shorthand: false, // !!! here it is
  computed: false,
  parentNode: ...

Ref jscs-dev/node-jscs#1013

ES6 feature: Modules: Tracking Issue

Syntax:

  • imports:
ImportDeclaration :
  import ImportClause FromClause ;
  import ModuleSpecifier ;
ImportClause :
  ImportedDefaultBinding
  NameSpaceImport
  NamedImports
  ImportedDefaultBinding , NameSpaceImport
  ImportedDefaultBinding , NamedImports
ImportedDefaultBinding :
  ImportedBinding
NameSpaceImport :
  * as ImportedBinding
NamedImports :
  { }
  { ImportsList }
  { ImportsList , }
FromClause :
  from ModuleSpecifier
ImportsList :
  ImportSpecifier
  ImportsList , ImportSpecifier
ImportSpecifier :
  ImportedBinding
  IdentifierName as ImportedBinding
ModuleSpecifier :
  StringLiteral
ImportedBinding :
  BindingIdentifier
  • exports:
ExportDeclaration :
  export * FromClause ;
  export ExportClause FromClause ;
  export ExportClause ;
  export VariableStatement
  export Declaration
  export default HoistableDeclaration[Default]
  export default ClassDeclaration[Default]
  export default [lookahead โˆ‰ {function, class}] AssignmentExpression[In] ;
ExportClause :
  { }
  { ExportsList }
  { ExportsList , }
ExportsList :
  ExportSpecifier
  ExportsList , ExportSpecifier
ExportSpecifier :
  IdentifierName
  IdentifierName as IdentifierName

Spec:

Remaining Tasks:

Template Literal Delimiters do not appear in the token list

Ported from https://code.google.com/p/esprima/issues/detail?id=632

What steps will reproduce the problem?

  1. Go here: http://esprima.googlecode.com/git-history/harmony/demo/parse.html?code=var%20foo%20%3D%20%5B%60bar%20%24%7Bbaz%7D%60%5D%3B
  2. Click on the Tokens tab of the output

What is the expected output?

To see the ` token in the list of tokens.

What do you see instead?

They were not present.

What version of the product are you using? On what operating system? Which

browser?

the harmony branch

Add a directive flag to ExpressionStatement to indicate a directive prologue

In the current syntax tree, a directive such as "use strict" will appear as ExpressionStatement. A tool that consumes the tree and needs to be aware of the strict mode will have to perform an extra step to figure out whether such an ExpressionStatement is representing a directive or not.

In this proposal, a new flag directive is added to ExpressionStatement. The value is set to true for a directive prologue.

The current state:

> esprima.parse('"use strict"').body[0]
{ type: 'ExpressionStatement',
  expression: 
   { type: 'Literal',
     value: 'use strict',
     raw: '"use strict"' } }

If this proposal is implemented, it becomes:

> esprima.parse('"use strict"').body[0]
{ type: 'ExpressionStatement',
  expression: 
   { type: 'Literal',
     value: 'use strict',
     raw: '"use strict"' },
  directive: true }

Additional resources:

Do not call skipComment when peeking for line terminators

When peeking for line terminators, we are calling skipComment and test if the lineNumber has changes. This is in fact unnecessary because the white space region we scanned through is a region we scanned already earlier. A flag can be added to indicate if there is a new line between index and the beginning of lookahead.

ES6 feature: Rest Parameters: tracking Issue

Syntax:

FormalParameterList[Yield,GeneratorParameter] :
  FunctionRestParameter[?Yield]
  FormalsList[?Yield, ?GeneratorParameter]
  FormalsList[?Yield, ?GeneratorParameter] , FunctionRestParameter[?Yield]
FunctionRestParameter[Yield] :
  BindingRestElement[?Yield]
BindingRestElement[Yield, GeneratorParameter] :
  [+GeneratorParameter] ... BindingIdentifier[Yield]
  [~GeneratorParameter] ... BindingIdentifier[?Yield]

Spec:

https://people.mozilla.org/~jorendorff/es6-draft.html#sec-functions-and-classes

Remaining Tasks:

  • Review and Test Token Generation
  • Review Error Messages
  • Arrow Function Rest Parameters
  • estree/estree#37

ES6 feature: Arrow Functions: tracking Issue

Syntax:

ArrowFunction[In, Yield] :
  ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]
ArrowParameters[Yield] :
  BindingIdentifier[?Yield]
  CoverParenthesizedExpressionAndArrowParameterList[?Yield]
ConciseBody[In] :
  [lookahead โ‰  { ] AssignmentExpression[?In]
  { FunctionBody }

Supplemental Syntax

When the production 
  ArrowParameters[Yield] : CoverParenthesizedExpressionAndArrowParameterList[?Yield]
is recognized the following grammar is used to refine the interpretation of
  CoverParenthesizedExpressionAndArrowParameterList :
ArrowFormalParameters[Yield, GeneratorParameter] :
  ( StrictFormalParameters[?Yield, ?GeneratorParameter] )

Spec:

https://people.mozilla.org/~jorendorff/es6-draft.html#sec-arrow-function-definitions

Remaining Tasks:

Range for object literal shorthand methods doesn't include params

What steps will reproduce the problem?

On a fresh checkout of the harmony branch:

// test.js
var esprima = require('./');

var source = [
    '({',
    '    method1(arg1) {},',
    '})'
].join('\n');

var ast = esprima.parse(source, { range: true });

console.log(ast.body[0].expression.properties[0]);
console.log(ast.body[0].expression.properties[0].value.params[0]);
$ node test.js
{ type: 'Property',
  key: { type: 'Identifier', name: 'method1', range: [ 7, 14 ] },
  value:
   { type: 'FunctionExpression',
     id: null,
     params: [ [Object] ],
     defaults: [],
     body: { type: 'BlockStatement', body: [], range: [Object] },
     rest: null,
     generator: false,
     expression: false,
     range: [ 21, 23 ] },
  kind: 'init',
  method: true,
  shorthand: false,
  computed: false,
  range: [ 7, 23 ] }
{ type: 'Identifier', name: 'arg1', range: [ 15, 19 ] }

What is the expected output?

I would expect the FunctionExpression's range to include the method's parameters as well as the body as in (arg1) {}.

It makes sense that the method's name is not included, as that is the Property's key and does not belong to the FunctionExpression.

What do you see instead?

The FunctionExpression's range includes only the body, {}, leading to a scenario in which a traversal starting at the FunctionExpression, range 21-23, would reach the parameter, whose range, 15-19, lies outside that of its parent.

(Migrated from https://code.google.com/p/esprima/issues/detail?id=625, as reported by @btmills)

Tolerate unclosed block comment

Consider the following test code (parsing in tolerant mode):

require('./esprima').parse('x /* foobar', { tolerant: true })

The current master branch will thrown an exception due to the error Line 1: Unexpected token ILLEGAL.

If this feature is implemented, it will return an AST because the unclosed block comment is tolerated. The error will be still listed in the errors array.

(Migrated from https://code.google.com/p/esprima/issues/detail?id=582, as reported by @mrennie)

Use test runner to execute the unit tests

Investigate the use of common test runner (Karma or Venus.js, or other candidates) to run the unit tests.

The benefits:

  • there is no need to write a special test runner
  • execute the tests on e.g. Sauce Labs
  • simplify the test fixture (individual test and expected result)

Transition to TryStatement single handler

To facilitate the transition of TryStatement from the old handlers to the new handler (see #1030), Esprima should produce both properties. Once all the major downstream tools have been ported to use the handler only, handlers can be safely removed in the next major version.

In the current master branch:

> require('./esprima').parse('try{}catch(e){}')
{ type: 'Program',
  body: 
   [ { type: 'TryStatement',
       block: [Object],
       guardedHandlers: [],
       handlers: [Object],
       finalizer: null } ] }

Once this transition step is implemented, it will look like:

> require('./esprima').parse('try{}catch(e){}')
{ type: 'Program',
  body: 
   [ { type: 'TryStatement',
       block: [Object],
       guardedHandlers: [],
       handlers: [Object],
       handler: [Object],
       finalizer: null } ] }

implement a pull request landing bot

Considering our complex commit message guide, having a bot actually land patches will reduce errors in commit messages and take the burden out of landing the patch. We should investigate if existing solutions are already out there that meet our requirements as a prereq.

TryStatement should use handler instead of handlers

The TryStatement node has changed according to estree/estree#1 from

interface TryStatement <: Statement {
    type: "TryStatement";
    block: BlockStatement;
    handlers: [ CatchClause ];
    guardedHandlers: [];
    finalizer: BlockStatement | null;
}

to

interface TryStatement <: Statement {
    type: "TryStatement";
    block: BlockStatement;
    handler: CatchClause | null;
    finalizer: BlockStatement | null;
}

The differences are:

  • handlers (an array of CatchClause) is changed to handler (a single CatchClause, if any)
  • guardedHandlers is gone

See also https://bugzilla.mozilla.org/show_bug.cgi?id=742612.

(Migrated from https://code.google.com/p/esprima/issues/detail?id=433)

Extend ExpressionStatement to indicate a directive prologue

In the current syntax tree, a directive such as "use strict" will appear as ExpressionStatement. A tool that consumes the tree and needs to be aware of the strict mode will have to perform an extra step to figure out whether such an ExpressionStatement is representing a directive or not.

In this proposal, a new flag directive is added to ExpressionStatement. The value is set to true for a directive prologue.

The current state:

> esprima.parse('"use strict"').body[0]
{ type: 'ExpressionStatement',
  expression: 
   { type: 'Literal',
     value: 'use strict',
     raw: '"use strict"' } }

If this proposal is implemented, it becomes:

> esprima.parse('"use strict"').body[0]
{ type: 'ExpressionStatement',
  expression: 
   { type: 'Literal',
     value: 'use strict',
     raw: '"use strict"' },
  directive: true }

Additional resources:

Enhance the comment-attaching algorithm

This algorithm currently tests if the comment "belongs" to an AST tree if the range of the AST covers the comment. This end up giving the following result:

The comment of

a  //x

is attached to the ExpressionStatement, but the comment of

a; //x

is attached to the FunctionBody.

It should be a parse error if a class static method contains a 'super'

From https://code.google.com/p/esprima/issues/detail?id=633:

@jeffmo says:

As of the latest version of the spec, it is no longer statically valid to have references to 'super' in static class methods:

https://people.mozilla.org/~jorendorff/es6-draft.html#sec-class-definitions-static-semantics-early-errors

Currently esprima will parse this without issue, but it should through a syntax error.
Clarification: It's only invalid to have super() call in any method...not just static methods.

(this is a recent constraint as of the Jan15 tc39 meeting)
Further clarification: super.whatever (member-expression-ish thing) appears to still be valid

ES6 feature: Generator: Tracking Issue

Syntax:

Per Rev 32 (Feb 2, 2015) of the draft spec, the relevant grammar is on Section 14.4 Generator Function Definitions:

GeneratorMethod[Yield] :
    * PropertyName[?Yield] ( StrictFormalParameters[Yield,GeneratorParameter] )  { GeneratorBody[Yield]  }

GeneratorDeclaration[Yield, Default] :
    function * BindingIdentifier[?Yield] ( FormalParameters[Yield, GeneratorParameter] ) { GeneratorBody[Yield] }
    [+Default] function * ( FormalParameters[Yield, GeneratorParameter] ) { GeneratorBody[Yield] }

GeneratorExpression :
    function * BindingIdentifier[Yield]opt ( FormalParameters[Yield,GeneratorParameter] ) { GeneratorBody[Yield] }

GeneratorBody[Yield] :
    FunctionBody[?Yield]

YieldExpression[In] :
    yield
    yield [no LineTerminator here] [Lexical goal InputElementRegExp] AssignmentExpression[?In, Yield]
    yield [no LineTerminator here] * [Lexical goal InputElementRegExp] AssignmentExpression[?In, Yield]

AssignmentExpression[In, Yield] :
    [+Yield] YieldExpression[?In]

Spec:

https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generator-function-definitions

Relevant AST interfaces (from https://github.com/estree/estree):

Functions:

extend interface Function {
    defaults: [ Expression ];
    rest: Identifier | null;
    generator: boolean;
}
interface ArrowExpression <: Function, Expression {
    type: "ArrowExpression";
    params: [ Pattern ];
    defaults: [ Expression ];
    rest: Identifier | null;
    body: BlockStatement | Expression;
    generator: boolean;
    expression: boolean;
}

YieldExpression:

interface YieldExpression <: Expression {
    type: "YieldExpression";
    argument: Expression | null;
}

See also:

Remaining Tasks:

  • Review V8 error messages on generator early error
  • Ensure the proper handling of yield* (old issue 617)

Destructuring Defaults

All of the following are valid ES6 and fail in current harmony:

  • function a({x = 10}) {}
  • function a({x = 10, y: { z = 10 }}) {}
  • ({x = 10}) => x
  • ({x = 10, y: { z = 10 }}) => [x,y]
  • [a=10] = 0
  • var {a = 10} = {}

Much more information about the expected implementation can be found here:
estree/estree#13

Unit Tests: break into much smaller files

We should take a page from espree here and break out the test files into much smaller pieces organized by the main language feature they are testing.

Right now it is unwieldily working with the giant file, and intimidating to newer contributors, like myself.

ES6 feature: Classes: tracking Issue

Syntax:

ClassDeclaration[Yield, Default] :
  class BindingIdentifier[?Yield] ClassTail[?Yield]
  [+Default] class ClassTail[?Yield]
ClassExpression[Yield,GeneratorParameter] :
  class BindingIdentifier[?Yield]opt ClassTail[?Yield,?GeneratorParameter]
ClassTail[Yield,GeneratorParameter] :
  [~GeneratorParameter] ClassHeritage[?Yield]opt { ClassBody[?Yield]opt }
  [+GeneratorParameter] ClassHeritageopt { ClassBodyopt }
ClassHeritage[Yield] :
  extends LeftHandSideExpression[?Yield]
ClassBody[Yield] :
  ClassElementList[?Yield]
ClassElementList[Yield] :
  ClassElement[?Yield]
  ClassElementList[?Yield] ClassElement[?Yield]
ClassElement[Yield] :
  MethodDefinition[?Yield]
  static MethodDefinition[?Yield]
  ;

Spec:

https://people.mozilla.org/~jorendorff/es6-draft.html#sec-class-definitions

Remaining Tasks:

  • Review and Test Token Generation
  • Review Error Messages

Arrow function: a line terminator should trigger a syntax error

(Migrated from https://code.google.com/p/esprima/issues/detail?id=591).

A line terminator before => should trigger an error.
Per Rev 32 (February 2, 2015) of the draft spec, Section 14.2, the grammar is:

ArrowFunction[In, Yield] :
  ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]

How to reproduce the bug:

esprima.parse("()\n=> 42;")

Current behavior: no error.
Expected behavior: a syntax error, e.g. "Illegal newline before arrow".

Tolerate missing ) for if/for/while

Consider the following test code (parsing in tolerant mode):

require('./esprima').parse('if(foo.bar === 1', { tolerant: true })

The current master branch will thrown an exception due to the error Line 1: Unexpected end of input.

If this feature is implemented, it will return an AST because the missing ) is tolerated. The error will be still listed in the errors array.

(Migrated from https://code.google.com/p/esprima/issues/detail?id=553, as reported by @mrennie)

Comment attachment should not imply storing syntax node location

To demonstrate the issue, run the following script:

var esprima = require('./esprima');
var code = '/* answer */ 42';
var tree = esprima.parse(code, { attachComment: true });
console.log(typeof tree.body[0].range);

The expected output is undefined. Since range option is not specified, it should default to false and hence every node will not have range property.

The current master branch produces the output object instead.

(Migrated from https://code.google.com/p/esprima/issues/detail?id=511)

ES6 feature: Destructuring: Tracking Issue

12.14.5 Destructuring Assignment

They are used in the left hand side of an assignment expression when = is the assignment operator, or at the LeftHandSideExpression position of a for-in or a for-of loop.

Referred to by:

  • 12.14.1 Static Semantics: Early Errors
  • 13.6.4.1 Static Semantics: Early Errors

Syntax:

AssignmentPattern[Yield] :
  ObjectAssignmentPattern[?Yield]
  ArrayAssignmentPattern[?Yield]

ObjectAssignmentPattern[Yield] :
  { }
  { AssignmentPropertyList[?Yield] }
  { AssignmentPropertyList[?Yield] , }

ArrayAssignmentPattern[Yield] :
  [ Elisionopt AssignmentRestElement[?Yield]opt ]
  [ AssignmentElementList[?Yield] ]
  [ AssignmentElementList[?Yield] , Elisionopt AssignmentRestElement[?Yield]opt ]

AssignmentPropertyList[Yield] :
  AssignmentProperty[?Yield]
  AssignmentPropertyList[?Yield] , AssignmentProperty[?Yield]

AssignmentElementList[Yield] :
  AssignmentElisionElement[?Yield]
  AssignmentElementList[?Yield] , AssignmentElisionElement[?Yield]

AssignmentElisionElement[Yield] :
  Elisionopt AssignmentElement[?Yield]

AssignmentProperty[Yield] :
  IdentifierReference[?Yield] Initializer[In,?Yield]opt
  PropertyName : AssignmentElement[?Yield]

AssignmentElement[Yield] :
  DestructuringAssignmentTarget[?Yield] Initializer[In,?Yield]opt

AssignmentRestElement[Yield] :
  ... DestructuringAssignmentTarget[?Yield]

DestructuringAssignmentTarget[Yield] :
  LeftHandSideExpression[?Yield]

Spec:

Destructuring Assignment: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-destructuring-assignment

Relevant AST interfaces (from https://github.com/estree/estree): (TBD)

Early Errors:

AssignmentProperty : IdentifierReference Initializeropt
  • It is a Syntax Error if IsValidSimpleAssignmentTarget of IdentifierReference is false.
DestructuringAssignmentTarget : LeftHandSideExpression
  • It is a Syntax Error if LeftHandSideExpression is either an ObjectLiteral or an ArrayLiteral and if the lexical token sequence matched by LeftHandSideExpression cannot be parsed with no tokens left over using AssignmentPattern as the goal symbol.
  • It is a Syntax Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and IsValidSimpleAssignmentTarget(LeftHandSideExpression) is false.

13.2.3 Destructuring Binding Patterns

BindingPatterns are used in LexicalBindings, VariableDeclarations, ForBindings and CatchParameters. BindingElement is also used in FormalParameters. A BindingElement is either a BindingPattern or a BindingIdentifier, optionally followed by a Initializer.

Syntax

BindingPattern[Yield,GeneratorParameter] :
  ObjectBindingPattern[?Yield,?GeneratorParameter]
  ArrayBindingPattern[?Yield,?GeneratorParameter]

ObjectBindingPattern[Yield,GeneratorParameter] :
  { }
  { BindingPropertyList[?Yield,?GeneratorParameter] }
  { BindingPropertyList[?Yield,?GeneratorParameter] , }

ArrayBindingPattern[Yield,GeneratorParameter] :
  [ Elisionopt BindingRestElement[?Yield, ?GeneratorParameter]opt ]
  [ BindingElementList[?Yield, ?GeneratorParameter] ]
  [ BindingElementList[?Yield, ?GeneratorParameter] , Elisionopt BindingRestElement[?Yield, ?GeneratorParameter]opt ]

BindingPropertyList[Yield,GeneratorParameter] :
  BindingProperty[?Yield, ?GeneratorParameter]
  BindingPropertyList[?Yield, ?GeneratorParameter] , BindingProperty[?Yield, ?GeneratorParameter]

BindingElementList[Yield,GeneratorParameter] :
  BindingElisionElement[?Yield, ?GeneratorParameter]
  BindingElementList[?Yield, ?GeneratorParameter] , BindingElisionElement[?Yield, ?GeneratorParameter]

BindingElisionElement[Yield,GeneratorParameter] :
  Elisionopt BindingElement[?Yield, ?GeneratorParameter]

BindingProperty[Yield,GeneratorParameter] :
  SingleNameBinding[?Yield, ?GeneratorParameter]
  PropertyName[?Yield, ?GeneratorParameter] : BindingElement[?Yield, ?GeneratorParameter]

BindingElement[Yield,GeneratorParameter] :
  SingleNameBinding[?Yield, ?GeneratorParameter]
  [+GeneratorParameter] BindingPattern[?Yield,GeneratorParameter] Initializer[In]opt
  [~GeneratorParameter] BindingPattern[?Yield] Initializer[In, ?Yield]opt

SingleNameBinding [Yield, GeneratorParameter] :
  [+GeneratorParameter] BindingIdentifier[Yield] Initializer[In]opt
  [~GeneratorParameter] BindingIdentifier[?Yield] Initializer[In, ?Yield]opt

BindingRestElement[Yield, GeneratorParameter] :
  [+GeneratorParameter] ... BindingIdentifier[Yield]
  [~GeneratorParameter] ... BindingIdentifier[?Yield]

Spec

Destructuring Binding Patterns: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-destructuring-binding-patterns

Relevant AST interfaces (from https://github.com/estree/estree): (TBD)

SpiderMonkey AST

interface ObjectPattern <: Pattern {
    type: "ObjectPattern";
    properties: [ { key: Literal | Identifier, value: Pattern } ];
}

interface ArrayPattern <: Pattern {
    type: "ArrayPattern";
    elements: [ Pattern | null ];
}

Shift AST

typedef (ObjectBinding or ArrayBinding or BindingIdentifier or MemberExpression) Binding;


interface BindingWithDefault : Node {
  attribute (ObjectBinding or ArrayBinding or BindingIdentifier) binding;
  attribute Expression init;
};

interface BindingIdentifier : Node {
  attribute Identifier identifier;
};

interface ArrayBinding : Node {
  attribute (Binding or BindingWithDefault)?[] elements;
  attribute BindingIdentifier? restElement;
};

interface ObjectBinding : Node {
  attribute BindingProperty[] properties;
};

interface BindingProperty : Node { };

interface BindingPropertyIdentifier : BindingProperty {
  attribute BindingIdentifier identifier;
  attribute Expression? init;
};

interface BindingPropertyProperty : BindingProperty {
  attribute PropertyName name;
  attribute (Binding or BindingWithDefault) binding;
};


interface PropertyName : Node { };

interface ComputedPropertyName : PropertyName {
  attribute Expression value;
};

interface StaticPropertyName : PropertyName {
  attribute string value;
};

Related Tasks:

ES6: `as` in token list listed as "Identifier"

While working through adding tokens to the harmonymoduletest file, I've stumbled on something that I'm not sure is a bug, but seems off: In all import and export statements, as is listed as an "Identifier", when it seems like it should be a "Keyword".

The spec doesn't seem to list it as a keyword, but the syntax section of export (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-exports) seems like, given the export/import context, it should be one.

arrowExpression vs ArrowFunctionExpression

From @RReverser in https://code.google.com/p/esprima/issues/detail?id=567

What steps will reproduce the problem?

  1. Parse 'x => 1' with esprima.parse to ast variable.
  2. Check out type of ast.body[0].expression.

What is the expected output?
'ArrowExpression' (as stated on https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API page)

What do you see instead?
'ArrowFunctionExpression'

I suppose this is by design, but would be great to fix either MDN wiki page or Esprima's output type so all the AST tools developers could follow the same specification and expect same results.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.