GithubHelp home page GithubHelp logo

sebastienros / esprima-dotnet Goto Github PK

View Code? Open in Web Editor NEW
410.0 26.0 76.0 17.63 MB

Esprima .NET (BSD license) is a .NET port of the esprima.org project. It is a standard-compliant ECMAScript parser (also popularly known as JavaScript).

License: BSD 3-Clause "New" or "Revised" License

C# 97.49% JavaScript 2.51% Batchfile 0.01%

esprima-dotnet's People

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

esprima-dotnet's Issues

Consider renaming EsprimaVisitor to AstVisitor

Consider renaming EsprimaVisitor to AstVisitor because the project name of Esprima in EsprimaVisitor doesn't really say anything about the type and AstVisitor is more representative of exactly what it is.

I can submit a PR to do the rename if it makes sense.

Attach leading and trailing comments to AST nodes

Input

Parse the following code:

// leading
a // trailing

with turned on Comment = true option in ParserOptions:

var program = parser.ParseProgram(source, new ParserOptions(source) { Comment = true; });

After that, serialize the result AST with JsonConvert.

Expected

Leading and trailing should be attached to AST nodes. Check it on Esprima.org.

{
    "type": "Program",
    "body": [
        {
            "type": "ExpressionStatement",
            "expression": {
                "type": "Identifier",
                "name": "a",
                "trailingComments": [
                    {
                        "type": "Line",
                        "value": " trailing",
                        "range": [
                            13,
                            24
                        ]
                    }
                ]
            },
            "leadingComments": [
                {
                    "type": "Line",
                    "value": " leading",
                    "range": [
                        0,
                        10
                    ]
                }
            ]
        }
    ],
    "sourceType": "script"
}

Actual

Comments are completely skipped.

{
  "Type": "Program",
  "Body": [
    {
      "Type": "ExpressionStatement",
      "Expression": {
        "Type": "Identifier",
        "Name": "a",
        "Loc": {}
      },
      "Loc": {}
    }
  ],
  "SourceType": "script",
  "Loc": {}
}

AST API has inconsistencies

The AST API currently contains a few inconsistencies, fixing which would go a long way to polish things up for 1.0.

The majority of the AST appears to be read-only except in a few select cases, most of which seem to be unused (or are/were supporting Jint?). The biggest read-write structure seems to be List<> but List<> is not designed to be exposed in the public API surface of a class library anyway. I suggest rendering the entire public AST data structures read-only for sake of consistency, if not for other benefits that may stem from that like naturally thread-safe structures due to their immutability.

There is also mixed use of fields and properties. It would seem best to consistently expose properties.

The table below shows all node classes of the AST with fields and properties. It shows the mixed use of the two. I've also highlighted read-write properties/fields with an asterisk (*), which would need review to make the AST immutable.

Type Fields Properties
ArrayExpression Elements
ArrayPattern Elements
ArrowFunctionExpression Id, Params, Body, Generator, Expression, HoistingScope*
ArrowParameterPlaceHolder Params
AssignmentExpression Operator, Left, Right
AssignmentPattern Left, Right*
BinaryExpression Operator, Left, Right
BlockStatement Body
BreakStatement Label
CallExpression Callee, Arguments, Cached*, CanBeCached*, CachedArguments*
CatchClause Param, Body
ClassBody Body
ClassDeclaration Id, SuperClass, Body
ClassExpression Id, SuperClass, Body
ConditionalExpression Test, Consequent, Alternate
ContinueStatement Label
Directive Directiv
DoWhileStatement Body, Test
ExportAllDeclaration Source
ExportDefaultDeclaration Declaration
ExportNamedDeclaration Declaration, Specifiers, Source
ExportSpecifier Exported, Local
ExportStatement Expression
ExpressionStatement Expression
ForInStatement Left, Right, Body, Each
ForOfStatement Left, Right, Body
ForStatement Init, Test, Update, Body
FunctionDeclaration Id, Params, Body, Generator, Expression, HoistingScope, Strict
FunctionExpression Id, Params, Body, Generator, Expression, HoistingScope, Strict
Identifier Name
IfStatement Test, Consequent, Alternate
ImportDeclaration Specifiers, Source
ImportDefaultSpecifier Local
ImportNamespaceSpecifier Local
ImportSpecifier Local, Imported
LabeledStatement Label, Body
Literal NumericValue, Regex, Value, Raw, TokenType, CachedValue* StringValue, BooleanValue, RegexValue
MetaProperty Meta, Property
MethodDefinition Static
NewExpression Callee, Arguments
Node Type*, Range*, Location*
ObjectExpression Properties
ObjectPattern Properties
Program Body, SourceType HoistingScope, Strict
Property Method, Shorthand
RestElement Argument
ReturnStatement Argument
SequenceExpression Expressions*
SpreadElement Argument
Statement LabelSet*
SwitchCase Test, Consequent
SwitchStatement Discriminant, Cases
TaggedTemplateExpression Tag, Quasi
TemplateElement Value, Tail
TemplateLiteral Quasis, Expressions
ThrowStatement Argument
TryStatement Block, Handler, Finalizer
UnaryExpression Operator, Argument Prefix*
VariableDeclaration Declarations, Kind
VariableDeclarator Id, Init
WhileStatement Test, Body
WithStatement Object, Body
YieldExpression Argument, Delegate

ArgumentOutOfRangeException for scripts with multiline strings

With the latest 2.0.0-beta1303

The following valid JS code:

var str = 'test \
d'+'test \
test'+'f';

will throw ArgumentOutOfRangeException while parsing with Loc=true option

var code = "var str = 'test \\\nd'+'test \\\ntest'+'f';";

var parser = new JavaScriptParser(code, new ParserOptions {Loc = true});
parser.Invoking(_ => parser.ParseScript())
	.Should().NotThrow(); // TODO: this fails

parser = new JavaScriptParser(code);
parser.Invoking(_ => parser.ParseScript())
	.Should().NotThrow();

ArgumentOutOfRangeException parsing class member declared using Symbol

Exception of type 'System.ArgumentOutOfRangeException' was thrown.
Parameter name: Type
Actual value was MemberExpression.

Exception generated when I tried to parse node.js node_modules folder (to test parser-dependent application).
Original file: node_modules\npm\node_modules\@npmcli\arborist\lib\edge.js from node.js distribution

edge.zip

Offending lines (looks like failure on method name parse):

  [util.inspect.custom] () {
    return this.toJSON()
  }

JavaScriptParser.ParseProgram throws on empty file with comments and Loc = true

// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * Correct interpretation of single line comments
 *
 * @path ch07/7.4/S7.4_A1_T2.js
 * @description Simple test, create empty comment: ///
 */

//CHECK#1
///

Parsing the above file with this parser:

var parser = new JavaScriptParser(source, new ParserOptions
{
    Loc = true
});

Throws this exception:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.

Because a Location was initialised with start and end equal to (12, 0).

I believe the solution to this is modifying the Location constructor to allow the end to be equal to the start (but not precede it). I'll create a PR to reflect that, but I'd appreciate it if anyone can comment on whether the correct behaviour would be that start and end would equal (0, 0).

Parser Events

I am using this parser currently and master branch code's hoisting scope is very useful as it saves one additional pass. I am surprised why it is removed in next update. Setting up hoisting in parsing stage will remove two passes in code execution/generation phase.

After reading comments on jquery/esprima#1603 , I see that you are planning to make this project more compatible with esprima, but is it possible to introduce Compiler Events where hoisting and syntax errors can be done while parsing? This will save one additional pass.

So you can leave Parser compatible with Esprima but allow some sort of hooks/events to incorporate additional checks while parsing. I see "action" parameter for parser, but there is no way to store anything with the node, using Dictionary to keep map of node and its values would be too slow.

If you can provide a property bag for node, that would be helpful.

Incorrect parse tree during several destructing assignment statements parsing

Input

var [ a, , b ] = list
[ b, a ] = [ a, b ]

Expected

Parse tree should contain two statements:

{
  "Type": "Program",
  "Body": [
    {
      "Type": "VariableDeclaration",
      "Declarations": [
        {
          "Type": "VariableDeclarator",
          "Id": {
            "Type": "ArrayPattern",
            "Elements": [
              {
                "Type": "Identifier",
                "Name": "a",
                "Loc": {}
              },
              null,
              {
                "Type": "Identifier",
                "Name": "b",
                "Loc": {}
              }
            ],
            "Loc": {}
          },
          "Init": {
            "Type": "Identifier",
            "Name": "list",
            "Loc": {}
          },
          "Loc": {}
        }
      ],
      "Kind": "var",
      "Loc": {}
    },
    {
      "Type": "ExpressionStatement",
      "Expression": {
        "Left": {
          "Type": "ArrayPattern",
          "Elements": [
            {
              "Type": "Identifier",
              "Name": "b",
              "Loc": {}
            },
            {
              "Type": "Identifier",
              "Name": "a",
              "Loc": {}
            }
          ],
          "Loc": {}
        },
        "Right": {
          "Type": "ArrayExpression",
          "Elements": [
            {
              "Type": "Identifier",
              "Name": "a",
              "Loc": {}
            },
            {
              "Type": "Identifier",
              "Name": "b",
              "Loc": {}
            }
          ],
          "Loc": {}
        },
        "Loc": {}
      },
      "Loc": {}
    }
  ],
  "SourceType": "script",
  "Loc": {}
}

Just add semicolon ; to the end of the first line to get the correct output:

var [ a, , b ] = list;
[ b, a ] = [ a, b ]

Actual

Code parsed to the following parse tree with nonexistent MemberExpression and only a single declaration:

{
  "Type": "Program",
  "Body": [
    {
      "Type": "VariableDeclaration",
      "Declarations": [
        {
          "Type": "VariableDeclarator",
          "Id": {
            "Type": "ArrayPattern",
            "Elements": [
              {
                "Type": "Identifier",
                "Name": "a",
                "Loc": {}
              },
              null,
              {
                "Type": "Identifier",
                "Name": "b",
                "Loc": {}
              }
            ],
            "Loc": {}
          },
          "Init": {
            "Left": {
              "Type": "MemberExpression",
              "Object": {
                "Type": "Identifier",
                "Name": "list",
                "Loc": {}
              },
              "Property": {
                "Type": "SequenceExpression",
                "Expressions": [
                  {
                    "Type": "Identifier",
                    "Name": "b",
                    "Loc": {}
                  },
                  {
                    "Type": "Identifier",
                    "Name": "a",
                    "Loc": {}
                  }
                ],
                "Loc": {}
              },
              "Computed": true,
              "Loc": {}
            },
            "Right": {
              "Type": "ArrayExpression",
              "Elements": [
                {
                  "Type": "Identifier",
                  "Name": "a",
                  "Loc": {}
                },
                {
                  "Type": "Identifier",
                  "Name": "b",
                  "Loc": {}
                }
              ],
              "Loc": {}
            },
            "Loc": {}
          },
          "Loc": {}
        }
      ],
      "Kind": "var",
      "Loc": {}
    }
  ],
  "SourceType": "script",
  "Loc": {}
}

AST Visitor - wrong order?

In the Visit of the For Statement, the Update is Visited before the Body.

Is this intended?

I need to change that if I want to use the Visitor to write back Javascript.

break out of a loop fails when a function is declared inside the labelled loop

Using Jint version 3.0.0-beta-1598

Encountered when experimenting with calling a custom React renderer from Jint, it seems like if you declare a function inside of a while loop which is labeled, then trying to do a break

var jsengine = new Jint.Engine()
jsengine.Execute("breakout: while(true) { function test() {} break breakout }")

results in Esprima.ParserException: 'Line 1: Undefined label "breakout"'

However the following works without error, so breaking by label itself seems supported, just that the function results in it losing track of the label:

jsengine.Execute("breakout: while(true) { while(true) break breakout }")

Comments are not handled at all?

Consider the following javascript code:

// c

I'm trying to get all comments with the following code:

var parserOptions = new ParserOptions(source) { Comment = true, Tokens = true };
var scanner = new Scanner(source, parserOptions);
var comments = scanner.ScanComments();

But getting an empty comments collection.

The following code also does not work (from Esprima.Sample):

do
{
    scanner.ScanComments();
    token = scanner.Lex();
    tokens.Add(token);
} while (token.Type != TokenType.EOF);

Returns only a single empty token:

[
  {
    "Type": 1,
    "Start": 4,
    "End": 4,
    "LineNumber": 1,
    "Location": {}
  }
]

How can I handle them?

TitleCase property names in serialized ast

JsonConvert.SerializeObject(tokens, Formatting.Indented) for an Exprima.Ast.Program results in JSON that has capitalized property names, (like "Type": " "VariableDeclaration"). In my case, this was a problem, because I was re-writing the source with esgodegen, which expects camelcase property names, and got tripped up. So, I used:

var astJson =JsonConvert.SerializeObject(program, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

I couldn't quickly find the ESTree spec, so I'm not sure if it specified that property names should be camelcase. But I assume that they are largely expected to be, since that's the usual json convention.

The Program, and various nodes, should probably get a [DataContract] with [DataMemeber] attributes, which specify camelcase property names.

ExportStatement has the wrong type or even a thing?

It seems awfully suspicious that ExportStatement has a node type of ExpressionStatement:

public class ExportStatement : Statement
{
public readonly Expression Expression;
public ExportStatement(Expression expression)
{
Type = Nodes.ExpressionStatement;
Expression = expression;
}
}

Is this correct? Is ExportStatement even a thing? Neither do I see it appear in the Exports section of the ESTree spec nor do I see it defined in Esprima's definitions of nodes:

export class ExportAllDeclaration {
    readonly type: string;
    readonly source: Literal;
    constructor(source: Literal) {
        this.type = Syntax.ExportAllDeclaration;
        this.source = source;
    }
}

export class ExportDefaultDeclaration {
    readonly type: string;
    readonly declaration: ExportableDefaultDeclaration;
    constructor(declaration: ExportableDefaultDeclaration) {
        this.type = Syntax.ExportDefaultDeclaration;
        this.declaration = declaration;
    }
}

export class ExportNamedDeclaration {
    readonly type: string;
    readonly declaration: ExportableNamedDeclaration | null;
    readonly specifiers: ExportSpecifier[];
    readonly source: Literal | null;
    constructor(declaration: ExportableNamedDeclaration | null, specifiers: ExportSpecifier[], source: Literal | null) {
        this.type = Syntax.ExportNamedDeclaration;
        this.declaration = declaration;
        this.specifiers = specifiers;
        this.source = source;
    }
}

export class ExportSpecifier {
    readonly type: string;
    readonly exported: Identifier;
    readonly local: Identifier;
    constructor(local: Identifier, exported: Identifier) {
        this.type = Syntax.ExportSpecifier;
        this.exported = exported;
        this.local = local;
    }
}

System.NullReferenceException when scanning comments in v1.0.1270

The code

   var scanner = new Scanner("var foo=1; /* \"330413500\" */", new ParserOptions {Comment = true, Loc = true});
   Token token;
   do
   {
       foreach (var comment in scanner.ScanComments())
           Console.WriteLine($"{comment.Start}-{comment.End}");
       token = scanner.Lex();
   } while (token.Type != TokenType.EOF);

works with Esprima v1.0.1258 (prints 11-28) and doesn't work with v1.0.1270 where the exception is thrown:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Esprima.Scanner.SkipMultiLineComment() in C:\projects\esprima-dotnet\src\Esprima\Scanner.cs:line 317
   at Esprima.Scanner.ScanCommentsInternal() in C:\projects\esprima-dotnet\src\Esprima\Scanner.cs:line 425
   at Esprima.Scanner.ScanComments() in C:\projects\esprima-dotnet\src\Esprima\Scanner.cs:line 383
   at ConsoleApp1.Program.Main(String[] args) in C:\sandbox\EsprimaCheck\ConsoleApp1\Program.cs:line 15

InvalidCastException during parsing syntax with class inheritance

I tried to parse the file Classes.js from examples directory of JavaScript ANTLR grammar.

But got the following exception in ParseClassDeclaration method:

System.InvalidCastException: 'Unable to cast object of type 'Esprima.Ast.CallExpression' to type 'Esprima.Ast.PropertyKey'.'

Specifically, the following string causes the exception:

class Rectangle extends aggregation(Shape, Colored, ZCoord) {}

Such syntax is definitely correct (copied from http://es6-features.org/#ClassInheritanceFromExpressions). Moreover even if incorrect that error should not be thrown. It broke the parsing process.

The similar issues with EnhancedObjectProperties.js.

net45 support

Hi,

we want to use esprima and jint in an net45 project. Can we add net45 suppoort?
I can send a PR.

Regards
Michael

Parse from JSON?

I'm looking to build a GUI builder for conditions and simple statements. It seems like I would want to make the GUI build up an ES tree and persist that tree for when I need to go back and re-populate the visual builder UI. I don't want to create my own tree model from scratch so I'd like to be able to serialize the model to JSON which I can do using ToJsonString, but it doesn't appear that there is a way to parse that JSON back into the ES tree models. Is that correct? Any ideas on how I would go about doing this?

To Javascript

Would it be possible to add a function that serialize it to javascript instead of JSON?

Removing Json.NET dependency

Currently necessary to run the tests. A solution is to create another project that is intended for serialization (Json and scripts) that would contain the rendering logic instead of decorating the AST with Json.NET attributes.

JavaScriptParser.ParseProgram throws ArgumentOutOfRangeException

JavaScriptParser.ParseProgram sometimes throws ArgumentOutOfRangeException (this is different from the ArgumentOutOfRangeException found in sebastienros/jint#571). Here is the complete C# program for reproducing the issue:

using Esprima;

namespace esprima.Run
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var parser = new JavaScriptParser("Fu>\\u{ddee}\\u{dn");
      parser.ParseProgram();
    }
  }
}

The stack trace:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Private.CoreLib.dll: 'A valid UTF32 value is between 0x000000 and 0x10ffff, inclusive, and should not include surrogate codepoint values (0x00d800 ~ 0x00dfff).'
   at System.Char.ConvertFromUtf32(Int32 utf32)
   at Esprima.Scanner.GetComplexIdentifier()
   at Esprima.Scanner.ScanIdentifier()
   at Esprima.JavaScriptParser.NextToken()
   at Esprima.JavaScriptParser.ParseBinaryExpression()
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseConditionalExpression()
   at Esprima.JavaScriptParser.ParseAssignmentExpression()
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction)
   at Esprima.JavaScriptParser.ParseExpression()
   at Esprima.JavaScriptParser.ParseLabelledStatement()
   at Esprima.JavaScriptParser.ParseStatement()
   at Esprima.JavaScriptParser.ParseStatementListItem()
   at Esprima.JavaScriptParser.ParseProgram(Boolean strict)

Found via SharpFuzz.

Get parameters from FunctionDeclaration

I Found a error at FunctionDeclaration.cs

public ref readonly NodeList<Expression> Params => ref _parameters;

The Params is readonly and so can't be used does we have another way to use it?

I found a alternative solution but this is a littel bit too complicated

function test( param1, param2 )

0 = test
1 = param1

< NodeList<IStatementListItem > .Where(e => e.Type == Nodes.FunctionDeclaration).ToList().ForEach(e => {
                Console.WriteLine((e.ChildNodes.ToList()[2] as dynamic).Name);  //returns param2
  });

Can you make it easier to use?

Implement convenient ToString() methods for nodes and locations

Or use DebuggerDisplay attribute instead. It makes the debug process more clear.

Also, I suggest using the following output line-column based format for Location:

  • [l,c) - if start position equals to the end position.
  • [l,c1..c2) - if start line equals to the end line, but columns are different.
  • [l1..l2,c) - if start line differs from the end, but columns are the same.
  • [l1,c1..l2,c2) - common format.

And the following for index-based (Roslyn-like):

  • [i) - if start position equals to the end position.
  • [i1..i2) - includes the first position but excludes the latest one.

Write AST back to Script

Is there a Method to write the AST back to a script?

I want to use the library to minimize scripts direct in my c# webserver. So I want to parse to AST, optmize the AST and write it back to a script.

Help wanted to get multiple syntax errors from a script

I am wondering whether it is possible to get multiple parsing errors from this library. Currently, I am using a try-catch block to catch the ParserException, which gives me only a single error. I looked into the original esprima project at this link:

https://esprima.org/demo/validate.html

With the predefined example:

return 42; // should be inside a function

function f() {
  'use strict';

  var x = 042;

  with (z) {}
}

The validator generates 3 errors.

Could someone help on this? Thanks.

Use System.Span

Opening for tracking. My masterpiece where Slice tries to match common keywords will come much simpler. This will affect a lot of public API by having ReadOnlySpan instead of string, but all should become quite alloc-free.

Undefined label

Hello!

During parsing of the typescript-combined.js file the following error occurs:

Esprima.ParserException: Line 34409: Undefined label "outer"
   at Esprima.JavaScriptParser.ThrowError(String messageFormat, Object[] values) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 4156
   at Esprima.JavaScriptParser.ParseContinueStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2717
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3041
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2028
   at Esprima.JavaScriptParser.ParseSwitchCase() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2823
   at Esprima.JavaScriptParser.ParseSwitchStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2850
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3062
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2028
   at Esprima.JavaScriptParser.ParseBlock() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2052
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3014
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 474
   at Esprima.JavaScriptParser.ParseForStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2692
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3050
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2028
   at Esprima.JavaScriptParser.ParseBlock() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2052
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3014
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 474
   at Esprima.JavaScriptParser.ParseForStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2692
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3050
   at Esprima.JavaScriptParser.ParseLabelledStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2888
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3031
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2034
   at Esprima.JavaScriptParser.ParseFunctionSourceElements() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3118
   at Esprima.JavaScriptParser.ParseFunctionExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3412
   at Esprima.JavaScriptParser.ParsePrimaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 638
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1351
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseUpdateExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1486
   at Esprima.JavaScriptParser.ParseUnaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1535
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseExponentiationExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1545
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseBinaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1655
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseConditionalExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1722
   at Esprima.JavaScriptParser.ParseAssignmentExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1870
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 474
   at Esprima.JavaScriptParser.ParseVariableDeclaration(Boolean& inFor) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2373
   at Esprima.JavaScriptParser.ParseVariableDeclarationList(Boolean& inFor) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2388
   at Esprima.JavaScriptParser.ParseVariableStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2404
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3071
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2028
   at Esprima.JavaScriptParser.ParseFunctionSourceElements() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3118
   at Esprima.JavaScriptParser.ParseFunctionDeclaration(Boolean identifierIsOptional) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3330
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2018
   at Esprima.JavaScriptParser.ParseFunctionSourceElements() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3118
   at Esprima.JavaScriptParser.ParseFunctionDeclaration(Boolean identifierIsOptional) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3330
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2018
   at Esprima.JavaScriptParser.ParseFunctionSourceElements() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3118
   at Esprima.JavaScriptParser.ParseFunctionDeclaration(Boolean identifierIsOptional) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3330
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2018
   at Esprima.JavaScriptParser.ParseFunctionSourceElements() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3118
   at Esprima.JavaScriptParser.ParseFunctionExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3412
   at Esprima.JavaScriptParser.ParsePrimaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 638
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1351
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseUpdateExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1486
   at Esprima.JavaScriptParser.ParseUnaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1535
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseExponentiationExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1545
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseBinaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1655
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseConditionalExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1722
   at Esprima.JavaScriptParser.ParseAssignmentExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1870
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseGroupExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1140
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParsePrimaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 600
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseLeftHandSideExpressionAllowCall() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1351
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseUpdateExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1486
   at Esprima.JavaScriptParser.ParseUnaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1535
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseExponentiationExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1545
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseBinaryExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1655
   at Esprima.JavaScriptParser.InheritCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 497
   at Esprima.JavaScriptParser.ParseConditionalExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1722
   at Esprima.JavaScriptParser.ParseAssignmentExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1870
   at Esprima.JavaScriptParser.IsolateCoverGrammar[T](Func`1 parseFunction) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 474
   at Esprima.JavaScriptParser.ParseExpression() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 1964
   at Esprima.JavaScriptParser.ParseExpressionStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2424
   at Esprima.JavaScriptParser.ParseStatement() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 3018
   at Esprima.JavaScriptParser.ParseStatementListItem() in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 2034
   at Esprima.JavaScriptParser.ParseProgram(Boolean strict) in C:\temp\TestEsprima\Esprima\JavascriptParser.cs:line 162

Parser from the Jint version 2.X correctly processed this code. ChakraCore and V8 can also parse this code correctly.

ParserException: 'Unexpected token ILLEGAL' on nested templates

output += `${table(
            messages.map(message => {
                let messageType;

                if (message.fatal || message.severity === 2) {
                    messageType = chalk.red("error");
                    summaryColor = "red";
                } else {
                    messageType = chalk.yellow("warning");
                }

                return [
                    "",
                    message.line || 0,
                    message.column || 0,
                    messageType,
                    message.message.replace(/([^ ])\.$/u, "$1"),
                    chalk.dim(message.ruleId || "")
                ];
            }),
            {
                align: ["", "r", "l"],
                stringLength(str) {
                    return stripAnsi(str).length;
                }
            }
        ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`;

eslint\lib\cli-engine\formatters\stylish.js
stylish.zip

Tokens of JavaScriptParser should be public

Is it possible to open the Tokens Array of the JavaScriptParser to be public available?

And, if I have part of the Tokens in a Sublist, is it possible to get the syntax of this
subset out of the tokens again?

e.g. i have a list of 20 tokens, then I get the tokens at Position 5-10 and want to get the
syntax out of it.

Optional catch binding not supported

catch statement without expression variable clause leads to parse exception:

Esprima.ParserException: 'Line 535: Unexpected token {'

Code (@eslint\eslintrc\lib\config-array-factory.js ):

 static getPathToConfigFileInDirectory(directoryPath) {
        for (const filename of configFilenames) {
            const filePath = path.join(directoryPath, filename);

            if (fs.existsSync(filePath)) {
                if (filename === "package.json") {
                    try {
                        loadPackageJSONConfigFile(filePath);
                        return filePath;
                    } catch { /* ignore */ }
                } else {
                    return filePath;
                }
            }
        }
        return null;
    }

config-array-factory.zip

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.