Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            var text   = File.ReadAllText(args[0]);
            var parser = new JavaScriptParser(text);

            parser.ParseProgram();
        }
Ejemplo n.º 2
0
        public void ProgramShouldBeStrict()
        {
            var parser  = new JavaScriptParser("'use strict'; function p() {}");
            var program = parser.ParseProgram();

            Assert.True(program.Strict);
        }
Ejemplo n.º 3
0
        private string CompileScriptInternal(string sourceCode)
        {
            if (String.IsNullOrWhiteSpace(sourceCode))
            {
                return(null);
            }

            if (TypeScriptProgram == null)
            {
                var tsLib  = GetFromResources("typescript.min.js");
                var parser = new JavaScriptParser(tsLib, EsprimaOptions);

                TypeScriptProgram = parser.ParseProgram();
            }



            var _engine = new Engine();

            _engine.Execute(TypeScriptProgram);



            _engine.SetValue("src", sourceCode);


            var transpileOtions = "{\"compilerOptions\": {\"target\":\"ES5\"}}";

            var output = _engine.Execute($"ts.transpileModule(src, {transpileOtions})", EsprimaOptions).GetCompletionValue().AsObject();

            return(output.Get("outputText").AsString());
        }
Ejemplo n.º 4
0
        public void ProgramShouldNotBeStrict()
        {
            var parser  = new JavaScriptParser("function p() {}");
            var program = parser.ParseProgram();

            Assert.False(program.Strict);
        }
Ejemplo n.º 5
0
        public static void Bench(string script)
        {
            var repeat  = 120;
            var exclude = 10;

            var filename = $"../../test/Esprima.Tests/Fixtures/3rdparty/{script}.js";
            var content  = File.ReadAllText(filename);

            var sw      = new Stopwatch();
            var results = new List <long>();

            for (var i = 0; i < repeat; i++)
            {
                var parser = new JavaScriptParser(content);
                sw.Restart();

                parser.ParseProgram();
                results.Add(sw.ElapsedMilliseconds);
            }

            var average = results
                          .OrderBy(x => x)
                          .Skip(exclude)
                          .Take(repeat - exclude * 2)
                          .Average();

            Console.WriteLine("{0} ({2}KB): {1} ms", script, Math.Round(average, 1), content.Length / 1024);
        }
Ejemplo n.º 6
0
        public ParserException[] ParseCode(string code)
        {
            this.code = code;
            var syntaxErrors = new List <ParserException>();
            var errorHandler = new ErrorHandler {
                Tolerant = true
            };
            var parser = new JavaScriptParser(code, new ParserOptions {
                SourceType   = SourceType.Script,
                Tolerant     = true,
                ErrorHandler = errorHandler
            });

            try {
                program = parser.ParseProgram();
            } catch (ParserException error) {
                syntaxErrors.Add(error);
            } catch (Exception e) {
                syntaxErrors.Add(
                    new ParserException(
                        new ParseError(
                            $"Parser error ({e.Message})",
                            errorHandler.Source,
                            0,
                            new Position(0, 0)
                            )
                        )
                    );
            }
            syntaxErrors.AddRange(errorHandler.Errors);
            return(syntaxErrors.ToArray());
        }
Ejemplo n.º 7
0
        private static void Parse(string source)
        {
            var parser  = new JavaScriptParser(source);
            var program = parser.ParseProgram();

            Console.WriteLine(JsonConvert.SerializeObject(program, Formatting.Indented));
        }
Ejemplo n.º 8
0
        public void FunctionShouldBeStrict()
        {
            var parser   = new JavaScriptParser("function p() {'use strict'; return false;}");
            var program  = parser.ParseProgram();
            var function = program.Body.First().As <FunctionDeclaration>();

            Assert.True(function.Strict);
        }
Ejemplo n.º 9
0
        public void FunctionShouldBeStrictInProgramStrict()
        {
            var parser   = new JavaScriptParser("'use strict'; function p() {}");
            var program  = parser.ParseProgram();
            var function = program.Body.Skip(1).First().As <FunctionDeclaration>();

            Assert.True(function.Strict);
        }
Ejemplo n.º 10
0
        public void FunctionShouldNotBeStrict()
        {
            var parser   = new JavaScriptParser("function p() {}");
            var program  = parser.ParseProgram();
            var function = program.Body.First().As <FunctionDeclaration>();

            Assert.False(function.Strict);
        }
Ejemplo n.º 11
0
        private static void Parse(string source, TextWriter output)
        {
            var parser  = new JavaScriptParser(source);
            var program = parser.ParseProgram();

            program.WriteJson(output);
            Console.WriteLine();
        }
Ejemplo n.º 12
0
 public void ParseProgram()
 {
     for (int i = 0; i < N; ++i)
     {
         var parser = new JavaScriptParser(Script);
         parser.ParseProgram();
     }
 }
Ejemplo n.º 13
0
        private static Program ParseModuleContent(ModuleData module)
        {
            var parser = new JavaScriptParser(module.Content, new ParserOptions {
                Loc = true, Range = true, SourceType = SourceType.Module, Tolerant = true
            });

            try { return(parser.ParseProgram()); }
            catch (Exception ex) { throw EcmaScriptErrorHelper.ParsingModuleFileFailed(module.FilePath, GetFileProviderHint(module.File), ex); }
        }
Ejemplo n.º 14
0
        public void LabelSetShouldPointToStatement()
        {
            var parser           = new JavaScriptParser("here: Hello();");
            var program          = parser.ParseProgram();
            var labeledStatement = program.Body.First().As <LabeledStatement>();
            var body             = labeledStatement.Body;

            Assert.Equal(labeledStatement.Label, body.LabelSet);
        }
Ejemplo n.º 15
0
        public void CanVisitIfWithNoElse()
        {
            var parser  = new JavaScriptParser("if (true) { p(); }");
            var program = parser.ParseProgram();

            EsprimaVisitor visitor = new EsprimaVisitor();

            visitor.VisitProgram(program);
        }
Ejemplo n.º 16
0
        public void CanVisitForOfStatement()
        {
            var parser  = new JavaScriptParser(@"for (var elem of list) { }");
            var program = parser.ParseProgram();

            EsprimaVisitor visitor = new EsprimaVisitor();

            visitor.VisitProgram(program);
        }
Ejemplo n.º 17
0
        public void CanVisitForWithNoTest()
        {
            var parser  = new JavaScriptParser(@"for (var a = []; ; ) { }");
            var program = parser.ParseProgram();

            EsprimaVisitor visitor = new EsprimaVisitor();

            visitor.VisitProgram(program);
        }
Ejemplo n.º 18
0
        public void HoistingScopeShouldWork()
        {
            var parser  = new JavaScriptParser(@"
                function p() {}
                var x;");
            var program = parser.ParseProgram();

            Assert.NotEmpty(program.HoistingScope.FunctionDeclarations);
            Assert.NotEmpty(program.HoistingScope.VariableDeclarations);
        }
Ejemplo n.º 19
0
        public void CommentsAreParsed()
        {
            int            count  = 0;
            Action <INode> action = node => count++;
            var            parser = new JavaScriptParser("// this is a comment", new ParserOptions(), action);

            parser.ParseProgram();

            Assert.Equal(1, count);
        }
Ejemplo n.º 20
0
        public C2Addon ReadEdittimeJs(string source)
        {
            c2addon = new C2Addon();
            var     parser  = new JavaScriptParser(source);
            var     program = parser.ParseProgram();
            var     json    = program.ToJsonString();
            dynamic ast     = JObject.Parse(json);

            return(TraverseJavascriptTree(ast));
        }
Ejemplo n.º 21
0
        public void ShouldParseLocation()
        {
            var options = new ParserOptions
            {
                Loc = true
            };
            var parser = new JavaScriptParser("// End on second line\r\n", options);

            var program = parser.ParseProgram();
        }
Ejemplo n.º 22
0
        public string ParseAndFormat(string source, ParserOptions options)
        {
            var          parser  = new JavaScriptParser(source, options);
            var          program = parser.ParseProgram();
            const string indent  = "  ";

            return(program.ToJsonString(AstJson.Options.Default
                                        .WithIncludingLineColumn(true)
                                        .WithIncludingRange(true),
                                        indent));
        }
Ejemplo n.º 23
0
        private HashSet <CollectionName> ExecuteCodeAndCollectReferencedCollections(string code)
        {
            var javascriptParser = new JavaScriptParser(code, DefaultParserOptions);
            var program          = javascriptParser.ParseProgram();

            _engine.ExecuteWithReset(program);
            var loadVisitor = new EsprimaReferencedCollectionVisitor();

            loadVisitor.Visit(program);
            return(loadVisitor.ReferencedCollection);
        }
Ejemplo n.º 24
0
        public void CanVisitDefaultSwitchCase()
        {
            var parser  = new JavaScriptParser(@"switch(foo) {
    default:
        p();
        break;
}");
            var program = parser.ParseProgram();

            EsprimaVisitor visitor = new EsprimaVisitor();

            visitor.VisitProgram(program);
        }
Ejemplo n.º 25
0
        public void CanVisitSwitchCase()
        {
            var parser  = new JavaScriptParser(@"switch(foo) {
    case 'A':
        p();
        break;
}");
            var program = parser.ParseProgram();

            AstVisitor visitor = new AstVisitor();

            visitor.Visit(program);
        }
Ejemplo n.º 26
0
        public void FunctionShouldBeStrictInStrictFunction()
        {
            var parser  = new JavaScriptParser("function p() {'use strict'; function q() { return; } return; }");
            var program = parser.ParseProgram();
            var p       = program.Body.First().As <FunctionDeclaration>();
            var q       = p.Body.As <BlockStatement>().Body.Skip(1).First().As <FunctionDeclaration>();

            Assert.Equal("p", p.Id.Name);
            Assert.Equal("q", q.Id.Name);

            Assert.True(p.Strict);
            Assert.True(q.Strict);
        }
Ejemplo n.º 27
0
        public ObjectInstance Construct(JsValue[] arguments)
        {
            var    argCount = arguments.Length;
            string p        = "";
            string body     = "";

            if (argCount == 1)
            {
                body = TypeConverter.ToString(arguments[0]);
            }
            else if (argCount > 1)
            {
                var firstArg = arguments[0];
                p = TypeConverter.ToString(firstArg);
                for (var k = 1; k < argCount - 1; k++)
                {
                    var nextArg = arguments[k];
                    p += "," + TypeConverter.ToString(nextArg);
                }

                body = TypeConverter.ToString(arguments[argCount - 1]);
            }

            IFunction function;

            try
            {
                var functionExpression = "function f(" + p + ") { " + body + "}";
                var parser             = new JavaScriptParser(functionExpression, ParserOptions);
                function = (IFunction)parser.ParseProgram().Body[0];
            }
            catch (ParserException)
            {
                ExceptionHelper.ThrowSyntaxError(_engine);
                return(null);
            }

            var functionObject = new ScriptFunctionInstance(
                Engine,
                function,
                LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment),
                function.Strict
                )
            {
                Extensible = true
            };

            return(functionObject);
        }
Ejemplo n.º 28
0
        public Program Parse(string script)
        {
            var key = Key(script);

            if (!memoryCache.TryGetValue <Program>(key, out var program))
            {
                var parser = new JavaScriptParser(script, DefaultParserOptions);

                program = parser.ParseProgram();

                memoryCache.Set(key, program, Expiration);
            }

            return(program);
        }
Ejemplo n.º 29
0
        private HashSet <CollectionName> ExecuteCodeAndCollectReferencedCollections(string code, string additionalSources)
        {
            var javascriptParser = new JavaScriptParser(code, DefaultParserOptions);
            var program          = javascriptParser.ParseProgram();

            _engine.ExecuteWithReset(program);
            var loadVisitor = new EsprimaReferencedCollectionVisitor();

            if (string.IsNullOrEmpty(additionalSources) == false)
            {
                loadVisitor.Visit(new JavaScriptParser(additionalSources, DefaultParserOptions).ParseProgram());
            }

            loadVisitor.Visit(program);
            return(loadVisitor.ReferencedCollection);
        }
        public IEnumerable <string> Match(string script, IEnumerable <Field> available)
        {
            var parser = new JavaScriptParser(script, new ParserOptions()
            {
                Tokens = true
            });

            return(parser.ParseProgram()
                   .DescendantNodesAndSelf()
                   .Where(n => n.Type == Nodes.Identifier)
                   .Select(n => n.As <Identifier>())
                   .Select(i => i.Name)
                   .Intersect(available.Select(f => f.Alias))
                   .Distinct()
                   .ToArray());
        }