### Setup JSModuleContext Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Creates a JSModuleContext with a root folder for global node_modules, then runs a script with a working directory and script path. The result contains exports. ```csharp var rootFolder = "... global folder to load node_modules from ... , set this to global npm installed"; var context = new JSModuleContext(rootFolder); var currentWorkingDirectory = ".... project folder.. that contains local node_modules"; var scriptPath = "... actual script location"; var result = await context.RunAsync(currentWorkingDirectory, scriptPath); // result contains exports.... ``` -------------------------------- ### new CLR Constructor - System.Random Example Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Creates a new instance of System.Random in JavaScript, calls its next() method, and asserts the result is a number. Demonstrates basic type conversion. ```javascript import clr from "clr"; var Random = clr.getClass("System.Random"); var r = new Random(); // this will create instance of `System.Random`. var n = r.next(); // this will call `Random.Next` method // n is `number` and not `System.Double`. assert(typeof n === 'number'); ``` -------------------------------- ### Getter and Setter Grammar Rules Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines getter and setter syntax using semantic predicates to match 'get' and 'set' keywords followed by a property name. ```ANTLR getter : {this.n("get")}? identifier propertyName ; ``` ```ANTLR setter : {this.n("set")}? identifier propertyName ; ``` -------------------------------- ### Construct and compile a Yantra expression Source: https://github.com/yantrajs/yantra/wiki/Expression-Compiler Constructs a simple addition expression using YExpression.Parameter, YExpression.Binary, and YExpression.Lambda, then compiles and invokes it. The example asserts that the compiled delegate returns 1 for (1,0) and 3 for (1,2). ```csharp var a = YExpression.Parameter(typeof(int)); var b = YExpression.Parameter(typeof(int)); var exp = YExpression.Lambda>("add", YExpression.Binary(a, YOperator.Add, b), new YParameterExpression[] { a, b }); var fx = exp.Compile(); Assert.AreEqual(1, fx(1, 0)); Assert.AreEqual(3, fx(1, 2)); ``` -------------------------------- ### clr.getClass - Get CLR Type Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Imports the 'clr' module and uses clr.getClass to get a CLR type, e.g., System.Int32, returning a type reference. ```javascript import clr from "clr"; var int32 = clr.getClass("System.Int32"); // this will return typeof(System.Int32); ``` -------------------------------- ### Create global function with context.CreateFunction Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Creates a global function 'add' that sums all arguments passed to it using the DoubleValue property and returns a JSNumber. This uses JSFunctionDelegate and the Arguments struct. ```csharp context["add"] = context.CreateFunction((in Arguments a) => { var result = 0.0; for(var i = 0; i { var uri = new Uri(a[0]?.ToString() ?? throw context.NewReferenceError("At least one parameter expected")); return new ClrProxy(uri); }, "createUri"); Console.WriteLine(context.Eval("var uri = createUri('https://yantrajs.com'); uri.host")); ``` -------------------------------- ### Keyword Grammar Rule Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Lists all keywords recognized by the parser, including reserved words and contextual keywords like 'async', 'await', 'from', and 'as'. ```ANTLR keyword : Break | Do | Instanceof | Typeof | Case | Else | New | Var | Catch | Finally | Return | Void | Continue | For | Switch | While | Debugger | Function | This | With | Default | If | Throw | Delete | In | Try | Class | Enum | Extends | Super | Const | Export | Import | Implements | let_ | Private | Public | Interface | Package | Protected | Static | Yield | Async | Await | From | As ; ``` ```ANTLR let_ : NonStrictLet | StrictLet ; ``` -------------------------------- ### JSContext Synchronous Eval with global function registration Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Creates a JSContext and registers a global 'add' function using JSFunction, then evaluates 'add(4,5)' synchronously with FastEval (no setTimeout/promise handling). ```csharp var context = new JSContext(); // create global function context["add"] = new JSFunction((in Arguments a) => { return new JSNumber( (a[0]?.IntValue ?? 0) + (a[1]?.IntValue ?? 0) ); }); var result = context.Eval("add(4,5)", "script.js"); ``` -------------------------------- ### JSContext Asynchronous Eval with Promise awaiting Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Evaluates async JavaScript in a context that has a SynchronizationContext, then awaits the resulting JSPromise task. Requires the SynchronizationContext to be present (e.g., UI thread). ```csharp var context = new JSContext(); var r = context.Eval("some async code", "script.js"); var result = await (r is JSPromise promise).Task; ``` -------------------------------- ### Identifier and Reserved Word Grammar Rules Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines identifier names, identifiers, and reserved words, including handling of 'let' and 'async' as non-strict identifiers. ```ANTLR identifierName : identifier | reservedWord ; ``` ```ANTLR identifier : Identifier | NonStrictLet | Async ; ``` ```ANTLR reservedWord : keyword | NullLiteral | BooleanLiteral ; ``` -------------------------------- ### JSContext ExecuteAsync and Execute for async code Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Executes asynchronous JavaScript code using ExecuteAsync, which runs synchronously with its own SynchronizationContext and resolves all setTimeout/setInterval/Promises. The Execute method provides a sync alternative. ```csharp var context = new JSContext(); var r = await context.ExecuteAsync("some async code", "script.js"); ``` ```csharp var context = new JSContext(); var r = context.Execute("some async code", "script.js"); ``` -------------------------------- ### Function Body and Source Elements Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for a function body as optional source elements, and source elements as one or more source elements. ```antlr functionBody : sourceElements? ; ``` ```antlr sourceElements : sourceElement+ ; ``` -------------------------------- ### Arguments and Argument Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for function call arguments, allowing optional trailing commas and spread arguments. ```antlr arguments : '('(argument (',' argument)* ','?)?')' ; ``` ```antlr argument : Ellipsis? (singleExpression | identifier) ; ``` -------------------------------- ### Property Name Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for property names, which can be identifiers, string literals, numeric literals, or computed expressions. ```antlr propertyName : identifierName | StringLiteral | numericLiteral | '[' singleExpression ']' ; ``` -------------------------------- ### Assignment Operator Grammar Rule Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Lists all assignment operators supported by the parser, including compound assignments and exponentiation assignment. ```ANTLR assignmentOperator : '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|=' | '**=' ; ``` -------------------------------- ### Property Assignment Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for property assignments in object literals, including computed properties, methods, getters, setters, and shorthand. ```antlr propertyAssignment : propertyName ':' singleExpression # PropertyExpressionAssignment | '[' singleExpression ']' ':' singleExpression # ComputedPropertyExpressionAssignment | Async? '*'? propertyName '(' formalParameterList? ')' '{' functionBody '}' # FunctionProperty | getter '(' ')' '{' functionBody '}' # PropertyGetter | setter '(' formalParameterArg ')' '{' functionBody '}' # PropertySetter | Ellipsis? singleExpression # PropertyShorthand ; ``` -------------------------------- ### Expression Sequence Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for a sequence of expressions separated by commas. ```antlr expressionSequence : singleExpression (',' singleExpression)* ; ``` -------------------------------- ### Anonymous Function Grammar Rules Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines anonymous function syntax including function declarations, async/generator functions, and arrow functions. Uses ANTLR grammar with alternatives for each form. ```ANTLR anoymousFunction : functionDeclaration # FunctionDecl | Async? Function '*'? '(' formalParameterList? ')' '{' functionBody '}' # AnoymousFunctionDecl | Async? arrowFunctionParameters '=>' arrowFunctionBody # ArrowFunction ; ``` ```ANTLR arrowFunctionParameters : identifier | '(' formalParameterList? ')' ; ``` ```ANTLR arrowFunctionBody : singleExpression | '{' functionBody '}' ; ``` -------------------------------- ### Array Literal and Element Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for array literals and their elements, allowing optional commas and ellipsis for spread elements. ```antlr arrayLiteral : ('[' elementList ']') ; ``` ```antlr elementList : ','* arrayElement? (','+ arrayElement)* ','* // Yes, everything is optional ; ``` ```antlr arrayElement : Ellipsis? singleExpression ; ``` -------------------------------- ### CSX Module Delegate Export Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Defines a CSX module delegate as `Task Module(JSModule module)`. This allows loading other JavaScript modules via `module.ImportAsync` and custom logic. Note that importing other CSX files is not supported by design. ```csharp #r "nuget: YantraJS.Core,1.0.18" using System; using System.Linq; using System.Threading.Tasks; using YantraJS.Core; using YantraJS.Core.Clr; static async Task Module(JSModule module) { // load some other JavaScript module var importedModule = await module.ImportAsync("other-module"); var importedFun = importedModule["namedImport"] // named export module.Exports["namedExport"] = JSNumber.Zero; // export * module.Export = new JSFunction((in Arguments a) => { // do something here... // a.This is `this` return JSUndefined.Value; }, "Function Description"); } return (JSModuleDelegate)Module; ``` -------------------------------- ### JavaScriptParser.g4 - Full ANTLR4 Grammar Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md The complete ANTLR4 grammar for parsing JavaScript. It defines the parser rules for program structure, statements, declarations, expressions, and more. This grammar is used with the JavaScriptLexer and extends JavaScriptParserBase. ```ANTLR4 parser grammar JavaScriptParser; options { tokenVocab=JavaScriptLexer; superClass=JavaScriptParserBase; } program : HashBangLine? sourceElements? EOF ; sourceElement : statement ; statement : block | variableStatement | importStatement | exportStatement | emptyStatement | classDeclaration | expressionStatement | ifStatement | iterationStatement | continueStatement | breakStatement | returnStatement | yieldStatement | withStatement | labelledStatement | switchStatement | throwStatement | tryStatement | debuggerStatement | functionDeclaration ; block : '{' statementList? '}' ; statementList : statement+ ; importStatement : Import importFromBlock ; importFromBlock : importDefault? (importNamespace | moduleItems) importFrom eos | StringLiteral eos ; moduleItems : '{' (aliasName ',')* (aliasName ','?)? '}' ; importDefault : aliasName ',' ; importNamespace : ('*' | identifierName) (As identifierName)? ; importFrom : From StringLiteral ; aliasName : identifierName (As identifierName)? ; exportStatement : Export (exportFromBlock | declaration) eos # ExportDeclaration | Export Default singleExpression eos # ExportDefaultDeclaration ; exportFromBlock : importNamespace importFrom eos | moduleItems importFrom? eos ; declaration : variableStatement | classDeclaration | functionDeclaration ; variableStatement : variableDeclarationList eos ; variableDeclarationList : varModifier variableDeclaration (',' variableDeclaration)* ; variableDeclaration : assignable ('=' singleExpression)? // ECMAScript 6: Array & Object Matching ; emptyStatement : SemiColon ; expressionStatement : {this.notOpenBraceAndNotFunction()}? expressionSequence eos ; ifStatement : If '(' expressionSequence ')' statement (Else statement)? ; iterationStatement : Do statement While '(' expressionSequence ')' eos # DoStatement | While '(' expressionSequence ')' statement # WhileStatement | For '(' (expressionSequence | variableDeclarationList)? ';' expressionSequence? ';' expressionSequence? ')' statement # ForStatement | For '(' (singleExpression | variableDeclarationList) In expressionSequence ')' statement # ForInStatement // strange, 'of' is an identifier. and this.p("of") not work in sometime. | For Await? '(' (singleExpression | variableDeclarationList) identifier{this.p("of")}? expressionSequence ')' statement # ForOfStatement ; varModifier // let, const - ECMAScript 6 : Var | let_ | Const ; continueStatement : Continue ({this.notLineTerminator()}? identifier)? eos ; breakStatement : Break ({this.notLineTerminator()}? identifier)? eos ; returnStatement : Return ({this.notLineTerminator()}? expressionSequence)? eos ; yieldStatement : Yield ({this.notLineTerminator()}? expressionSequence)? eos ; withStatement : With '(' expressionSequence ')' statement ; switchStatement : Switch '(' expressionSequence ')' caseBlock ; caseBlock : '{' caseClauses? (defaultClause caseClauses?)? '}' ; caseClauses : caseClause+ ; caseClause : Case expressionSequence ':' statementList? ; defaultClause : Default ':' statementList? ; labelledStatement : identifier ':' statement ; throwStatement : Throw {this.notLineTerminator()}? expressionSequence eos ; tryStatement : Try block (catchProduction finallyProduction? | finallyProduction) ; catchProduction : Catch ('(' assignable? ')')? block ; finallyProduction : Finally block ; debuggerStatement : Debugger eos ; functionDeclaration : Async? Function '*'? identifier '(' formalParameterList? ')' '{' functionBody '}' ; classDeclaration : Class identifier classTail ; classTail : (Extends singleExpression)? '{' classElement* '}' ; classElement : (Static | {this.n("static")}? identifier | Async)* (methodDefinition | assignable '=' objectLiteral ';') | emptyStatement | '#'? propertyName '=' singleExpression ; methodDefinition : '*'? '#'? propertyName '(' formalParameterList? ')' '{' functionBody '}' | '*'? '#'? getter '(' ')' '{' functionBody '}' | '*'? '#'? setter '(' formalParameterList? ')' '{' functionBody '}' ; formalParameterList : formalParameterArg (',' formalParameterArg)* (',' lastFormalParameterArg)? | lastFormalParameterArg ; formalParameterArg : assignable ('=' singleExpression)? // ECMAScript 6: Initialization ; ``` -------------------------------- ### CSX Module Export Type Source: https://github.com/yantrajs/yantra/wiki/JavaScript-Engine-Example Exports a C# type as a CSX module using `[Export]` and `[DefaultExport]` attributes. This is simpler than a module delegate but cannot import other JavaScript modules. ```csharp #r "nuget: YantraJS.Core,1.0.18" using System; using System.Linq; using YantraJS.Core; using YantraJS.Core.Clr; // Export attribute with parameter is considered as `*` [Export] // Named Export [Export("url")] // Default export [DefaultExport] public class JSUrl { private Uri uri; public JSUrl(in Arguments a) { this.uri = new Uri(a.Get1().ToString()); } public string Host => uri.Host; } ``` -------------------------------- ### Rest Parameter Grammar Rule Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines the grammar for a rest parameter in ECMAScript 6, which is an ellipsis followed by a single expression. ```antlr lastFormalParameterArg // ECMAScript 6: Rest Parameter : Ellipsis singleExpression ; ``` -------------------------------- ### Literal Grammar Rules Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines literal types including null, boolean, string, template string, regular expression, numeric, and bigint literals. ```ANTLR literal : NullLiteral | BooleanLiteral | StringLiteral | TemplateStringLiteral | RegularExpressionLiteral | numericLiteral | bigintLiteral ; ``` ```ANTLR numericLiteral : DecimalLiteral | HexIntegerLiteral | OctalIntegerLiteral | OctalIntegerLiteral2 | BinaryIntegerLiteral ; ``` ```ANTLR bigintLiteral : BigDecimalIntegerLiteral | BigHexIntegerLiteral | BigOctalIntegerLiteral | BigBinaryIntegerLiteral ; ``` -------------------------------- ### End of Statement (eos) Grammar Rule Source: https://github.com/yantrajs/yantra/blob/main/YantraJS.Core/FastParser/Parser.md Defines end-of-statement detection using semicolon, EOF, or semantic predicates for line terminator or closing brace. ```ANTLR eos : SemiColon | EOF | {this.lineTerminatorAhead()}? | {this.closeBrace()}? ; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.