public void Test1() { var expression = @"var result = '#'; if (CustomerAddress1.length > 3) { result = 'https://maps.google.com/maps?q=' + CustomerAddress1 + ' ' + CustomerCity + ', ' + CustomerState + ' ' + CustomerZip; } else { if (Latitude != 0) { result = 'https://maps.google.com/maps?q=' + Latitude + ',' + Longitude; } } result;"; var parser = new Jint.Parser.JavaScriptParser(); var result = parser.Parse(expression); var expected = new[] { "result", "CustomerAddress1", "length", "CustomerCity", "CustomerState", "CustomerZip", "Latitude", "Longitude" }; var program = parser.Parse(expression, new Jint.Parser.ParserOptions { Tokens = true }); var actual = program.Tokens .Where(o => o.Type == Jint.Parser.Tokens.Identifier) .Select(o => o.Value.ToString()) .Distinct() .ToArray(); Assert.AreEqual(expected, actual); }
private List <ProgramError> CompileJavascript(ProgramBlock program) { List <ProgramError> errors = new List <ProgramError>(); Jint.Parser.JavaScriptParser jp = new Jint.Parser.JavaScriptParser(false); //Jint.Parser.ParserOptions po = new Jint.Parser.ParserOptions(); try { jp.Parse(program.ScriptCondition); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "TC" }); } } } // try { jp.Parse(program.ScriptSource); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "CR" }); } } } return(errors); }
public List<ProgramError> Compile() { List<ProgramError> errors = new List<ProgramError>(); Jint.Parser.JavaScriptParser jp = new Jint.Parser.JavaScriptParser(false); //Jint.Parser.ParserOptions po = new Jint.Parser.ParserOptions(); try { jp.Parse(programBlock.ScriptCondition); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "TC" }); } } } // try { jp.Parse(programBlock.ScriptSource); } catch (Exception e) { // TODO: parse error message if (e.Message.Contains(":")) { string[] error = e.Message.Split(':'); string message = error[1]; if (message != "hg is not defined") // TODO: find a better solution for this { int line = int.Parse(error[0].Split(' ')[1]); errors.Add(new ProgramError() { Line = line, ErrorMessage = message, CodeBlock = "CR" }); } } } return errors; }
public static string ExpToJS(String exp) { string buffer = ""; var parser = new Jint.Parser.JavaScriptParser(); var program = parser.Parse(exp, new Jint.Parser.ParserOptions { Tokens = true }); foreach (var ex in program.Body) { var expr = ex as ExpressionStatement; if (expr.Expression is BinaryExpression) { buffer = visitBinary(expr.Expression as BinaryExpression); } else if (expr.Expression is LogicalExpression) { buffer = visitLogical(expr.Expression as LogicalExpression); } else if (expr.Expression is UnaryExpression) { buffer = visitUnary(expr.Expression as UnaryExpression); } else if (expr.Expression is Literal) { buffer = visitLiteral(expr.Expression as Literal); } else if (expr.Expression is Identifier) { buffer = visitIdentifier(expr.Expression as Identifier); } } buffer = "{\"type\":\"Program\",\"body\":[{\"type\":\"ExpressionStatement\",\"expression\":{" + buffer + "}}],\"sourceType\":\"script\"}"; return(buffer); }
public void CollectionHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CollectionTesting); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List <string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = true, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
/// <summary> /// Get a string of function declarations delimited by semicolons. /// </summary> /// <param name="script"></param> /// <returns></returns> public string GetFunctionDeclarations(string script) { string declarations = ""; if (script != null) { var parser = new Jint.Parser.JavaScriptParser(); var program = parser.Parse(script); if (program.FunctionDeclarations.Any()) { declarations = ":"; program.FunctionDeclarations.ToList().ForEach((declaration) => { declarations += declaration.Id.Name + ":"; }); } if (program.VariableDeclarations.Any()) { declarations = (declarations.Length == 0) ? ":" : declarations; program.VariableDeclarations.ToList().ForEach((declaration) => { declarations += declaration.Declarations.First().Id.Name + ":"; }); } } return(declarations); }
public void BasicGenerationWithOptions() { //Generate a basic javascript model from a C# class var modelType = typeof(AddressInformation); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List <string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = false, OutputNamespace = "models", IncludeEqualsFunction = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void ArrayTypeHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(ArrayTypeTest); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List<string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = false, OutputNamespace = "models" }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void EqualsDictionaryHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CollectionTesting); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List <string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = true, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true, IncludeEqualsFunction = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" + $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" + $"var result = p1.$equals(p2);"; var jsEngine = new Jint.Engine().Execute(strToExecute); var res = (bool)jsEngine.GetValue("result").ToObject(); Assert.IsTrue(res); var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" + $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test2' }} }});\r\n" + $"var result = p1.$equals(p2);"; var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual); var resNotEqual = (bool)jsEngineNotEqual.GetValue("result").ToObject(); Assert.IsFalse(resNotEqual); }
public void CustomFunctionHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CollectionTesting); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List <string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = true, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true, CustomFunctionProcessors = new List <Action <StringBuilder, IEnumerable <PropertyBag>, JsGeneratorOptions> >() { (builder, bags, arg3) => { builder.AppendLine($"\tthis.helloWorld = function () {{"); builder.AppendLine("\t\tconsole.log('hello');"); builder.AppendLine("\t}"); } } }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); Assert.IsTrue(outputJs.Contains("this.helloWorld")); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public virtual ExpressionTree <SyntaxNode> Parse(string script) { if (script == null) { throw new ArgumentNullException(nameof(script)); } var parser = new Jint.Parser.JavaScriptParser(); try { return(new ExpressionTree <SyntaxNode>(parser.Parse(script))); } catch (Exception ex) { var first = string.Join(string.Empty, script.Take(512).ToArray()); throw new TestException($"Failed to parse JavaScript content ({first}...): {ex}", ex); } }
public void BasicGeneration() { //Generate a basic javascript model from a C# class var modelType = typeof(AddressInformation); var outputJs = JsGenerator.Generate(new[] { modelType }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void RecursiveTypeGenerationLegacy() { //Generate a basic javascript model from a C# class var modelType = typeof(RecursiveTest); var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle"); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void BasicGenerationLegacy() { //Generate a basic javascript model from a C# class var modelType = typeof (AddressInformation); var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle"); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public static List <Jint.Parser.Ast.FunctionDeclaration> ListRequireJsFuncs(string requireJsBlock) { Jint.Parser.JavaScriptParser parser = new Jint.Parser.JavaScriptParser(); var prog = parser.Parse(requireJsBlock); if (prog != null && prog.Body.Count() > 0) { var item = prog.Body.First(); if (item is Jint.Parser.Ast.ExpressionStatement) { var expres = item as Jint.Parser.Ast.ExpressionStatement; if (expres.Expression is Jint.Parser.Ast.CallExpression) { var call = expres.Expression as Jint.Parser.Ast.CallExpression; if (call != null && call.Arguments.Count() == 2) { var requireargu = call.Arguments[1]; if (requireargu != null && requireargu is Jint.Parser.Ast.FunctionExpression) { var requireFunc = requireargu as Jint.Parser.Ast.FunctionExpression; if (requireFunc != null) { return(requireFunc.FunctionDeclarations.ToList()); } } } } } } return(new List <Jint.Parser.Ast.FunctionDeclaration>()); }
public void BasicGenerationLegacy() { //Generate a basic javascript model from a C# class var modelType = typeof(AddressInformation); #pragma warning disable 618 var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle"); #pragma warning restore 618 Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
protected override IPrecompiledScript InnerPrecompile(string code, string documentName) { OriginalProgram program; string uniqueDocumentName = _documentNameManager.GetUniqueName(documentName); lock (_executionSynchronizer) { try { var parserOptions = new OriginalParserOptions { Source = uniqueDocumentName }; var parser = new OriginalParser(); program = parser.Parse(code, parserOptions); } catch (OriginalParserException e) { throw WrapParserException(e); } } return(new JintPrecompiledScript(program)); }
public void CamelCaseHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CamelCaseTest); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List<string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = false, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); Program res = null; try { res = js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } var classExpression = res.Body.First().As<ExpressionStatement>(); var functionDefinition = classExpression.Expression.As<AssignmentExpression>().Right.As<FunctionExpression>() .Body.As<BlockStatement>() .Body; var firstMemberDefinition = functionDefinition.Skip(1) .Take(1) .First() .As<ExpressionStatement>() .Expression.As<AssignmentExpression>(); var memberName = firstMemberDefinition.Left.As<MemberExpression>().Property.As<Identifier>().Name; Assert.IsTrue(memberName == "wktPolygon"); var secondMemberDefinition = functionDefinition.Skip(2) .Take(1) .First() .As<ExpressionStatement>() .Expression.As<AssignmentExpression>(); var secondMemberName = secondMemberDefinition.Left.As<MemberExpression>().Property.As<Identifier>().Name; Assert.IsTrue(secondMemberName == "alreadyUnderscored"); var thirdMemberDefinition = functionDefinition.Skip(3) .Take(1) .First() .As<ExpressionStatement>() .Expression.As<AssignmentExpression>(); var thirdMemberName = thirdMemberDefinition.Left.As<MemberExpression>().Property.As<Identifier>().Name; Assert.IsTrue(thirdMemberName == "regularCased"); }
public void RecursiveTypeGenerationLegacy() { //Generate a basic javascript model from a C# class var modelType = typeof (RecursiveTest); #pragma warning disable 618 var outputJs = JsGenerator.GenerateJsModelFromTypeWithDescendants(modelType, true, "castle"); #pragma warning restore 618 Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void EqualsHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(AddressInformation); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List<string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = true, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true, IncludeEqualsFunction = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" + $"var p2 = new models.AddressInformation({{ name: 'Test' }});\r\n" + $"var result = p1.$equals(p2);"; var jsEngine = new Jint.Engine().Execute(strToExecute); var res = (bool)jsEngine.GetValue("result").ToObject(); Assert.IsTrue(res); var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" + $"var p2 = new models.AddressInformation({{ name: 'Test2' }});\r\n" + $"var result = p1.$equals(p2);"; var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual); var resNotEqual = (bool)jsEngineNotEqual.GetValue("result").ToObject(); Assert.IsFalse(resNotEqual); }
public void UnexpectedStateHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(AttributeInformationTest); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = null, CamelCase = true, IncludeMergeFunction = false, OutputNamespace = "models", RespectDataMemberAttribute = false, RespectDefaultValueAttribute = false }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }
public void CamelCaseHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CamelCaseTest); var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List <string>() { "Dto" }, CamelCase = true, IncludeMergeFunction = false, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); var js = new Jint.Parser.JavaScriptParser(); Program res = null; try { res = js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } var classExpression = res.Body.First().As <ExpressionStatement>(); var functionDefinition = classExpression.Expression.As <AssignmentExpression>().Right.As <FunctionExpression>() .Body.As <BlockStatement>() .Body; var firstMemberDefinition = functionDefinition.Skip(1) .Take(1) .First() .As <ExpressionStatement>() .Expression.As <AssignmentExpression>(); var memberName = firstMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name; Assert.IsTrue(memberName == "wktPolygon"); var secondMemberDefinition = functionDefinition.Skip(2) .Take(1) .First() .As <ExpressionStatement>() .Expression.As <AssignmentExpression>(); var secondMemberName = secondMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name; Assert.IsTrue(secondMemberName == "alreadyUnderscored"); var thirdMemberDefinition = functionDefinition.Skip(3) .Take(1) .First() .As <ExpressionStatement>() .Expression.As <AssignmentExpression>(); var thirdMemberName = thirdMemberDefinition.Left.As <MemberExpression>().Property.As <Identifier>().Name; Assert.IsTrue(thirdMemberName == "regularCased"); }
public void CustomFunctionHandling() { //Generate a basic javascript model from a C# class var modelType = typeof(CollectionTesting); var outputJs = JsGenerator.Generate(new[] {modelType}, new JsGeneratorOptions() { ClassNameConstantsToRemove = new List<string>() {"Dto"}, CamelCase = true, IncludeMergeFunction = true, OutputNamespace = "models", RespectDataMemberAttribute = true, RespectDefaultValueAttribute = true, CustomFunctionProcessors = new List<Action<StringBuilder, IEnumerable<PropertyBag>, JsGeneratorOptions>>() { (builder, bags, arg3) => { builder.AppendLine($"\tthis.helloWorld = function () {{"); builder.AppendLine("\t\tconsole.log('hello');"); builder.AppendLine("\t}"); } } }); Assert.IsTrue(!string.IsNullOrEmpty(outputJs)); Assert.IsTrue(outputJs.Contains("this.helloWorld")); var js = new Jint.Parser.JavaScriptParser(); try { js.Parse(outputJs); } catch (Exception ex) { Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message); } }