Giter VIP home page Giter VIP logo

esprima's Introduction

jQuery — New Wave JavaScript

Meetings are currently held on the matrix.org platform.

Meeting minutes can be found at meetings.jquery.org.

Contribution Guides

In the spirit of open source software development, jQuery always encourages community code contribution. To help you get started and before you jump into writing code, be sure to read these important contribution guidelines thoroughly:

  1. Getting Involved
  2. Core Style Guide
  3. Writing Code for jQuery Projects

References to issues/PRs

GitHub issues/PRs are usually referenced via gh-NUMBER, where NUMBER is the numerical ID of the issue/PR. You can find such an issue/PR under https://github.com/jquery/jquery/issues/NUMBER.

jQuery has used a different bug tracker - based on Trac - in the past, available under bugs.jquery.com. It is being kept in read only mode so that referring to past discussions is possible. When jQuery source references one of those issues, it uses the pattern trac-NUMBER, where NUMBER is the numerical ID of the issue. You can find such an issue under https://bugs.jquery.com/ticket/NUMBER.

Environments in which to use jQuery

  • Browser support
  • jQuery also supports Node, browser extensions, and other non-browser environments.

What you need to build your own jQuery

To build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. Earlier versions might work, but are not supported.

For Windows, you have to download and install git and Node.js.

macOS users should install Homebrew. Once Homebrew is installed, run brew install git to install git, and brew install node to install Node.js.

Linux/BSD users should use their appropriate package managers to install git and Node.js, or build from source if you swing that way. Easy-peasy.

How to build your own jQuery

First, clone the jQuery git repo.

Then, enter the jquery directory, install dependencies, and run the build script:

cd jquery
npm install
npm run build

The built version of jQuery will be placed in the dist/ directory, along with a minified copy and associated map file.

Build all jQuery release files

To build all variants of jQuery, run the following command:

npm run build:all

This will create all of the variants that jQuery includes in a release, including jquery.js, jquery.slim.js, jquery.module.js, and jquery.slim.module.js along their associated minified files and sourcemaps.

jquery.module.js and jquery.slim.module.js are ECMAScript modules that export jQuery and $ as named exports are placed in the dist-module/ directory rather than the dist/ directory.

Building a Custom jQuery

The build script can be used to create a custom version of jQuery that includes only the modules you need.

Any module may be excluded except for core. When excluding selector, it is not removed but replaced with a small wrapper around native querySelectorAll (see below for more information).

Build Script Help

To see the full list of available options for the build script, run the following:

npm run build -- --help

Modules

To exclude a module, pass its path relative to the src folder (without the .js extension) to the --exclude option. When using the --include option, the default includes are dropped and a build is created with only those modules.

Some example modules that can be excluded or included are:

  • ajax: All AJAX functionality: $.ajax(), $.get(), $.post(), $.ajaxSetup(), .load(), transports, and ajax event shorthands such as .ajaxStart().

  • ajax/xhr: The XMLHTTPRequest AJAX transport only.

  • ajax/script: The <script> AJAX transport only; used to retrieve scripts.

  • ajax/jsonp: The JSONP AJAX transport only; depends on the ajax/script transport.

  • css: The .css() method. Also removes all modules depending on css (including effects, dimensions, and offset).

  • css/showHide: Non-animated .show(), .hide() and .toggle(); can be excluded if you use classes or explicit .css() calls to set the display property. Also removes the effects module.

  • deprecated: Methods documented as deprecated but not yet removed.

  • dimensions: The .width() and .height() methods, including inner- and outer- variations.

  • effects: The .animate() method and its shorthands such as .slideUp() or .hide("slow").

  • event: The .on() and .off() methods and all event functionality.

  • event/trigger: The .trigger() and .triggerHandler() methods.

  • offset: The .offset(), .position(), .offsetParent(), .scrollLeft(), and .scrollTop() methods.

  • wrap: The .wrap(), .wrapAll(), .wrapInner(), and .unwrap() methods.

  • core/ready: Exclude the ready module if you place your scripts at the end of the body. Any ready callbacks bound with jQuery() will simply be called immediately. However, jQuery(document).ready() will not be a function and .on("ready", ...) or similar will not be triggered.

  • deferred: Exclude jQuery.Deferred. This also excludes all modules that rely on Deferred, including ajax, effects, and queue, but replaces core/ready with core/ready-no-deferred.

  • exports/global: Exclude the attachment of global jQuery variables ($ and jQuery) to the window.

  • exports/amd: Exclude the AMD definition.

  • selector: The full jQuery selector engine. When this module is excluded, it is replaced with a rudimentary selector engine based on the browser's querySelectorAll method that does not support jQuery selector extensions or enhanced semantics. See the selector-native.js file for details.

Note: Excluding the full selector module will also exclude all jQuery selector extensions (such as effects/animatedSelector and css/hiddenVisibleSelectors).

AMD name

You can set the module name for jQuery's AMD definition. By default, it is set to "jquery", which plays nicely with plugins and third-party libraries, but there may be cases where you'd like to change this. Pass it to the --amd parameter:

npm run build -- --amd="custom-name"

Or, to define anonymously, leave the name blank.

npm run build -- --amd
File name and directory

The default name for the built jQuery file is jquery.js; it is placed under the dist/ directory. It's possible to change the file name using --filename and the directory using --dir. --dir is relative to the project root.

npm run build -- --slim --filename="jquery.slim.js" --dir="/tmp"

This would create a slim version of jQuery and place it under tmp/jquery.slim.js.

ECMAScript Module (ESM) mode

By default, jQuery generates a regular script JavaScript file. You can also generate an ECMAScript module exporting jQuery as the default export using the --esm parameter:

npm run build -- --filename=jquery.module.js --esm
Factory mode

By default, jQuery depends on a global window. For environments that don't have one, you can generate a factory build that exposes a function accepting window as a parameter that you can provide externally (see README of the published package for usage instructions). You can generate such a factory using the --factory parameter:

npm run build -- --filename=jquery.factory.js --factory

This option can be mixed with others like --esm or --slim:

npm run build -- --filename=jquery.factory.slim.module.js --factory --esm --slim --dir="/dist-module"

Custom Build Examples

Create a custom build using npm run build, listing the modules to be excluded. Excluding a top-level module also excludes its corresponding directory of modules.

Exclude all ajax functionality:

npm run build -- --exclude=ajax

Excluding css removes modules depending on CSS: effects, offset, dimensions.

npm run build -- --exclude=css

Exclude a bunch of modules (-e is an alias for --exclude):

npm run build -- -e ajax/jsonp -e css -e deprecated -e dimensions -e effects -e offset -e wrap

There is a special alias to generate a build with the same configuration as the official jQuery Slim build:

npm run build -- --filename=jquery.slim.js --slim

Or, to create the slim build as an esm module:

npm run build -- --filename=jquery.slim.module.js --slim --esm

Non-official custom builds are not regularly tested. Use them at your own risk.

Running the Unit Tests

Make sure you have the necessary dependencies:

npm install

Start npm start to auto-build jQuery as you work:

npm start

Run the unit tests with a local server that supports PHP. Ensure that you run the site from the root directory, not the "test" directory. No database is required. Pre-configured php local servers are available for Windows and Mac. Here are some options:

Essential Git

As the source code is handled by the Git version control system, it's useful to know some features used.

Cleaning

If you want to purge your working directory back to the status of upstream, the following commands can be used (remember everything you've worked on is gone after these):

git reset --hard upstream/main
git clean -fdx

Rebasing

For feature/topic branches, you should always use the --rebase flag to git pull, or if you are usually handling many temporary "to be in a github pull request" branches, run the following to automate this:

git config branch.autosetuprebase local

(see man git-config for more information)

Handling merge conflicts

If you're getting merge conflicts when merging, instead of editing the conflicted files manually, you can use the feature git mergetool. Even though the default tool xxdiff looks awful/old, it's rather useful.

The following are some commands that can be used there:

  • Ctrl + Alt + M - automerge as much as possible
  • b - jump to next merge conflict
  • s - change the order of the conflicted lines
  • u - undo a merge
  • left mouse button - mark a block to be the winner
  • middle mouse button - mark a line to be the winner
  • Ctrl + S - save
  • Ctrl + Q - quit

QUnit Reference

Test methods

expect( numAssertions );
stop();
start();

Note: QUnit's eventual addition of an argument to stop/start is ignored in this test suite so that start and stop can be passed as callbacks without worrying about their parameters.

Test assertions

ok( value, [message] );
equal( actual, expected, [message] );
notEqual( actual, expected, [message] );
deepEqual( actual, expected, [message] );
notDeepEqual( actual, expected, [message] );
strictEqual( actual, expected, [message] );
notStrictEqual( actual, expected, [message] );
throws( block, [expected], [message] );

Test Suite Convenience Methods Reference (See test/data/testinit.js)

Returns an array of elements with the given IDs

q( ... );

Example:

q("main", "foo", "bar");

=> [ div#main, span#foo, input#bar ]

Asserts that a selection matches the given IDs

t( testName, selector, [ "array", "of", "ids" ] );

Example:

t("Check for something", "//[a]", ["foo", "bar"]);

Fires a native DOM event without going through jQuery

fireNative( node, eventType )

Example:

fireNative( jQuery("#elem")[0], "click" );

Add random number to url to stop caching

url( "some/url" );

Example:

url("index.html");

=> "data/index.html?10538358428943"


url("mock.php?foo=bar");

=> "data/mock.php?foo=bar&10538358345554"

Run tests in an iframe

Some tests may require a document other than the standard test fixture, and these can be run in a separate iframe. The actual test code and assertions remain in jQuery's main test files; only the minimal test fixture markup and setup code should be placed in the iframe file.

testIframe( testName, fileName,
  function testCallback(
      assert, jQuery, window, document,
	  [ additional args ] ) {
	...
  } );

This loads a page, constructing a url with fileName "./data/" + fileName. The iframed page determines when the callback occurs in the test by including the "/test/data/iframeTest.js" script and calling startIframeTest( [ additional args ] ) when appropriate. Often this will be after either document ready or window.onload fires.

The testCallback receives the QUnit assert object created by testIframe for this test, followed by the global jQuery, window, and document from the iframe. If the iframe code passes any arguments to startIframeTest, they follow the document argument.

Questions?

If you have any questions, please feel free to ask on the Developing jQuery Core forum or in #jquery on libera.

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

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)

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:

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

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:

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)

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)

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)

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: `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.

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.

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".

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: 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: 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

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.

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

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)

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)

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.

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:

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.

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:

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

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.

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 } ] }

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.