public Parser(Lexer lex) { lexer = lex; tokens = lexer.TokenList; FunctionTable = new FunctionTable(); SymbolTable = new SymbolTableIndex(); }
public RPN_CalculatorEngine() { curr_state = ParserState.ParserState_Ok; op_stack = new Stack<CalculatorToken>(32); output_queue = new Stack<CalculatorToken>(32); func_table_ = new FunctionTable(); input_string = null; input_iter = 0; input_end_marker = 0; }
public void ShouldAddFunctionWithType() { FunctionTable table = new FunctionTable(); table.AddFunction("test", typeof(TestFunction)); Assert.AreEqual<int>(1, table.Count()); Assert.IsTrue(table.Contains("test")); Assert.AreEqual<string>("test", table.First().Key); Assert.AreEqual<Type>(typeof(TestFunction), table.First().Value); }
public override ITable Evaluate(IQueryContext context) { var childTable = Child.Evaluate(context); var funTable = new FunctionTable(childTable, Functions, Names, context); // If no columns then it is implied the whole table is the group. if (ColumnNames == null) { funTable = funTable.AsGroup(); } else { funTable = funTable.CreateGroupMatrix(ColumnNames); } return funTable.MergeWith(GroupMaxColumn); }
public Runnable GetScript(Instruction[] instructions, int secondIndex) { var stream = new InstrucStream(instructions); var function = new Function(Function.MainName, 0); var dofunction = new Function("Do", secondIndex); var ftable = new FunctionTable { { Function.MainName, function }, { "Do", dofunction} }; return new Runnable(stream, ftable); }
static public void RegisterType(string TypeName, CreateNewEntityOfType TypeGenerator, CreateNewXMLSerializerOfType XMLGenerator) { if (TypeNameToFunctionTable == null) { TypeNameToFunctionTable = new Dictionary <string, FunctionTable>(); } if (TypeNameToFunctionTable.ContainsKey(TypeName)) { TypeNameToFunctionTable[TypeName] = new FunctionTable(TypeGenerator, XMLGenerator, TypeNameToFunctionTable[TypeName].NewEditorBox); } else { TypeNameToFunctionTable.Add(TypeName, new FunctionTable(TypeGenerator, XMLGenerator, null)); } }
static public void RegisterEditorType(string TypeName, CreateEditorBoxForType InNewEditorBox) { if (TypeNameToFunctionTable == null) { TypeNameToFunctionTable = new Dictionary <string, FunctionTable>(); } if (TypeNameToFunctionTable.ContainsKey(TypeName)) { TypeNameToFunctionTable[TypeName] = new FunctionTable(TypeNameToFunctionTable[TypeName].NewEntity, TypeNameToFunctionTable[TypeName].NewXMLSerializer, InNewEditorBox); } else { TypeNameToFunctionTable.Add(TypeName, new FunctionTable(null, null, InNewEditorBox)); } }
public void Compile_TableImport_UndersizedTable() { var module = new Module(); module.Types.Add(new WebAssemblyType { Returns = new[] { WebAssemblyValueType.Int32 }, Parameters = new[] { WebAssemblyValueType.Int32 } }); module.Imports.Add(new Import.Table("Test", "Test", 1)); module.Functions.Add(new Function { }); module.Exports.Add(new Export { Name = "Test", }); module.Elements.Add(new Element(0, 0)); module.Codes.Add(new FunctionBody { Code = new Instruction[] { new LocalGet(0), new End() }, }); var table = new FunctionTable(0, 1); Assert.AreEqual(0u, table.Length); var compiled = module.ToInstance <CompilerTestBase <int> >( new ImportDictionary { { "Test", "Test", table }, }); Assert.AreEqual(1u, table.Length); var rawDelegate = table[0]; Assert.IsNotNull(rawDelegate); Assert.IsInstanceOfType(rawDelegate, typeof(Func <int, int>)); var nativeDelegate = (Func <int, int>)rawDelegate !; Assert.AreEqual(0, nativeDelegate(0)); Assert.AreEqual(5, nativeDelegate(5)); }
public override ITable Evaluate(IRequest context) { var childTable = Child.Evaluate(context); var funTable = new FunctionTable(childTable, Functions, Names, context); // If no columns then it is implied the whole table is the group. if (ColumnNames == null) { funTable = funTable.AsGroup(); } else { funTable = funTable.CreateGroupMatrix(ColumnNames); } return(funTable.MergeWith(GroupMaxColumn)); }
public void ShouldReturnEnumerator() { FunctionTable table = new FunctionTable(); table.AddFunction <TestFunction>("test"); int count = 0; IEnumerator enumerator = ((IEnumerable)table).GetEnumerator(); while (enumerator.MoveNext()) { count++; } Assert.AreEqual <int>(1, count); }
public override ITable Evaluate(IQueryContext context) { ITable childTable = Child.Evaluate(context); var dbContext = (DatabaseQueryContext)context; var funTable = new FunctionTable((Table)childTable, functionList, nameList, dbContext); // If no columns then it is implied the whole table is the group. if (columns == null) { funTable.SetWholeTableAsGroup(); } else { funTable.CreateGroupMatrix(columns); } return(funTable.MergeWithReference(groupMaxColumn)); }
private IOperator BuildFunction(string exp, Token token) { var nametk = token.childs[0]; var namestr = exp.Substring(nametk.range.begin, nametk.range.end - nametk.range.begin); if (FunctionTable.TryGetValue(namestr, out Func <double[], double> func)) { var argsLen = token.childs.Count - 1; IOperator[] ops = new IOperator[argsLen]; for (int i = 0; i < argsLen; i++) { ops[i] = BuildExp(exp, token.childs[i + 1]); } return(new OpFun(ops, func)); } return(null); }
public void AddDeclarations(IEnumerable <Declaration> aDeclarations) { foreach (var decl in aDeclarations) { if (DeclarationsToIgnore.Contains(decl.Name)) { continue; } //== "sp_uint64" || decl.Name == "bool" || decl.Name == "byte") continue; if (decl.Kind == "typedef") { StructCType structType = decl.CType as StructCType; EnumCType enumType = decl.CType as EnumCType; FunctionCType functionType = decl.CType as FunctionCType; if (structType != null) { if (structType.Fields == null) { HandleTable.Add(decl.Name); } else { StructTable.Add(decl.Name, structType); } } else if (enumType != null) { EnumTable.Add(decl.Name, enumType); } else if (functionType != null) { FunctionTypedefTable.Add(decl.Name, functionType); } } else if (decl.Kind == "instance") { FunctionCType funcType = decl.CType as FunctionCType; if (funcType == null) { continue; } FunctionTable.Add(decl.Name, funcType); } } }
static void Main(string[] args) { using (var tr = new System.IO.FileStream(@"helloworld.wasm", System.IO.FileMode.Open)) { var module = new Module(); module.Types.Add(new WebAssemblyType { Returns = new[] { WebAssemblyValueType.Int32 }, Parameters = new[] { WebAssemblyValueType.Int32 } }); module.Imports.Add(new Import.Table { Module = "Test", Field = "Test", Definition = new Table { ElementType = ElementType.FunctionReference, ResizableLimits = new ResizableLimits(1) } }); module.Functions.Add(new Function { }); module.Exports.Add(new Export { Name = "Test", }); module.Elements.Add(new Element { Elements = new uint[] { 0 }, InitializerExpression = new Instruction[] { new Int32Constant(0), new End(), }, }); module.Codes.Add(new FunctionBody { Code = new Instruction[] { new LocalGet(0), new End() }, }); var table = new FunctionTable(1); module.ToInstance <CompilerTestBase <int> >( new ImportDictionary { { "Test", "Test", table }, }); } }
public void InterpreterGetFunctionProperty() { SymbolTable _SymbolTable = new SymbolTable(); FunctionTable functionTable = new FunctionTable(); var parser = new Parser(new Lexer(new InputStream(@" var id=0; var msg =''; var tst = 0; msg = System.DateTime.Now; "))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public NonlinearEquationDescription CompileEquations(string text) { compilerErrors = new List <ErrorMessage>(); constants = new Dictionary <string, double>(); variables = new Dictionary <string, int>(); variableNames = new List <string>(); initialValues = new List <double>(); FunctionTable.Init(); AntlrInputStream inputStream = new AntlrInputStream(text); EquationGrammarLexer eqLexer = new EquationGrammarLexer(inputStream); eqLexer.RemoveErrorListeners(); ErrorListener <int> lexerListener = new ErrorListener <int>(); eqLexer.AddErrorListener(lexerListener); CommonTokenStream commonTokenStream = new CommonTokenStream(eqLexer); EquationGrammarParser eqParser = new EquationGrammarParser(commonTokenStream); ErrorListener <IToken> parserListener = new ErrorListener <IToken>(); eqParser.RemoveErrorListeners(); eqParser.AddErrorListener(parserListener); EquationGrammarParser.CompileUnitContext eqContext = eqParser.compileUnit(); compilerErrors = lexerListener.GetErrors(); if (compilerErrors.Count > 0) { throw new CompilerException(compilerErrors, "Ошибки лексера"); } compilerErrors = parserListener.GetErrors(); if (compilerErrors.Count > 0) { throw new CompilerException(compilerErrors, "Ошибки парсера"); } GrammarVisitor visitor = new GrammarVisitor(); ASTNode root = visitor.VisitCompileUnit(eqContext); /*EquationGrammarVisitor visitor = new EquationGrammarVisitor(); * ASTNode root = visitor.VisitCompileUnit(expContext); * var rootSimple = Compiler.ASTCompiler.validate(root); * rootSimple = Compiler.ASTCompiler.simplify(rootSimple); * return compileASTExpression(rootSimple);*/ return(CompileEquations((RootNode)root)); }
public void Compile_TableImport_ExistingFunction() { var module = new Module(); module.Types.Add(new WebAssemblyType { Returns = new[] { WebAssemblyValueType.Int32 }, Parameters = new[] { WebAssemblyValueType.Int32 } }); module.Imports.Add(new Import.Table("Test", "Test", 1)); module.Functions.Add(new Function { }); module.Exports.Add(new Export { Name = "Test", }); module.Codes.Add(new FunctionBody { Code = new Instruction[] { new LocalGet(0), new Int32Constant(0), new CallIndirect(0), new End() }, }); var table = new FunctionTable(1); var calls = 0; table[0] = new Func <int, int>(value => { calls++; return(value + 1); }); var compiled = module.ToInstance <CompilerTestBase <int> >( new ImportDictionary { { "Test", "Test", table }, }); Assert.AreEqual(0, calls); Assert.AreEqual(3, compiled.Exports.Test(2)); Assert.AreEqual(1, calls); }
public void InterpreterDoWhile() { SymbolTable _SymbolTable = new SymbolTable(); FunctionTable functionTable = new FunctionTable(); var parser = new Parser(new Lexer(new InputStream(@"a = 1; b=0; do { b+=2; a++; }while(a<5)"))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public void InterpreterSetFunction() { scriptea.Test.AlanTst = "que onda"; SymbolTable _SymbolTable = new SymbolTable(); FunctionTable functionTable = new FunctionTable(); var parser = new Parser(new Lexer(new InputStream(@" var id=0; var msg =''; var tst = 0; msg = System.DateTime.Now; scriptea.Test.AlanTst = 'hola que ondas'; "))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public override void Interpret(SymbolTable table, FunctionTable functionTable) { do { try { foreach (var statementNode in CodeNode) { statementNode.Interpret(table, functionTable); } } catch (BreakException) { return; } catch (ContinueException) { } } while (EvaluationNode.Evaluate(table)); }
public void InterpreterFor() { FunctionTable functionTable = new FunctionTable(); SymbolTable _SymbolTable = new SymbolTable(); var parser = new Parser(new Lexer(new InputStream(@"var a=0; for(id=0;id<10;id++) { if(id>5) a+=3; id++; }"))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public static ITable[] ExecuteStatements(this IRequest request, params IStatement[] statements) { if (statements == null) { throw new ArgumentNullException("statements"); } if (statements.Length == 0) { throw new ArgumentException(); } var results = new ITable[statements.Length]; for (int i = 0; i < statements.Length; i++) { var statement = statements[i]; var context = new ExecutionContext(request); if (statement is IPreparableStatement) { statement = ((IPreparableStatement)statement).Prepare(request); } statement.Execute(context); ITable result; if (context.HasResult) { result = context.Result; } else { result = FunctionTable.ResultTable(request, 0); } results[i] = result; } return(results); }
public ExprDBFunction(FunctionTable paramFunctionTable) { this.fTable = paramFunctionTable; if (!string.ReferenceEquals(paramFunctionTable.Language, null)) { this.jsLanguage = paramFunctionTable.Language.Equals("JS"); } if (paramFunctionTable.FunctionArgumentList == null) { paramFunctionTable.FunctionArgumentList = new List <object>(); } foreach (FunctionArgumentTable functionArgumentTable in paramFunctionTable.FunctionArgumentList) { if (functionArgumentTable.Type.Equals("datatype.image") || functionArgumentTable.Type.Equals("datatype.calcvalue")) { this.constArguments.Add(functionArgumentTable); continue; } this.inputArguments.Add(functionArgumentTable); } }
public void Compile_TableImport_ExportedImport() { var module = new Module(); module.Imports.Add(new Import.Table("Test", "Test", 1)); module.Exports.Add(new Export { Name = nameof(ExportedTable.Table), Kind = ExternalKind.Table, }); var table = new FunctionTable(0); var exportedTable = module.ToInstance <ExportedTable>( new ImportDictionary { { "Test", "Test", table }, }) .Exports .Table; Assert.AreSame(table, exportedTable); }
public override void Interpret(SymbolTable table, FunctionTable functionTable) { try { foreach (var statementNode in TryCode) { statementNode.Interpret(table, functionTable); } } catch (System.Exception e) { table.AddSymbol(ExceptionID.Name, e); var _catch = (CatchNode)CatchBlockCode; _catch.Interpret(table, functionTable); } var _finally = (FinallyNode)FinallyCode; if (_finally.FinallyCode != null) { _finally.Interpret(table, functionTable); } }
public Implicit.DAEIDescription CompileDAEImplicit(string text) { compilerErrors = new List <ErrorMessage>(); parameters = new Dictionary <string, double>(); constants = new Dictionary <string, double>(); variables = new Dictionary <string, Variable>(); FunctionTable.Init(); //variables.Add("t", new Variable { Name = "t", InitialValue = 0.0, Initialized = true, VarType = Variable.Type.Algebraic, Count = 0 }); AntlrInputStream inputStream = new AntlrInputStream(text); DAEImplicitGrammarLexer eqLexer = new DAEImplicitGrammarLexer(inputStream); eqLexer.RemoveErrorListeners(); ErrorListener <int> lexerListener = new ErrorListener <int>(); eqLexer.AddErrorListener(lexerListener); CommonTokenStream commonTokenStream = new CommonTokenStream(eqLexer); DAEImplicitGrammarParser eqParser = new DAEImplicitGrammarParser(commonTokenStream); ErrorListener <IToken> parserListener = new ErrorListener <IToken>(); eqParser.RemoveErrorListeners(); eqParser.AddErrorListener(parserListener); DAEImplicitGrammarParser.CompileUnitContext eqContext = eqParser.compileUnit(); compilerErrors = lexerListener.GetErrors(); if (compilerErrors.Count > 0) { throw new CompilerException(compilerErrors, "Ошибки лексера"); } compilerErrors = parserListener.GetErrors(); if (compilerErrors.Count > 0) { throw new CompilerException(compilerErrors, "Ошибки парсера"); } DAEImplicitGrammarVisitor visitor = new DAEImplicitGrammarVisitor(); ASTNode root = visitor.VisitCompileUnit(eqContext); return(CompileDAEImplicit((RootNode)root)); }
/// <summary> /// Extend the XPath2 FunctionTable with 'base64encode' function to encode a string to base64 string. /// </summary> /// <param name="functionTable">The function table.</param> public static void AddBase64Encode(this FunctionTable functionTable) { string Base64EncodeDelegate(XPath2Context context, IContextProvider provider, object[] args) { string value = CoreFuncs.CastToStringExactOne(context, args[0]); Encoding encoding = args.Length == 2 ? ParseEncodingFromArg(context, args[1]) : Encoding.UTF8; try { return(Convert.ToBase64String(encoding.GetBytes(value))); } catch (Exception ex) { throw new XPath2Exception("InvalidFormat", ex); } } // base64encode with default UTF-8 encoding functionTable.Add(XmlReservedNs.NsXQueryFunc, "base64encode", 1, XPath2ResultType.String, Base64EncodeDelegate); // base64encode with specified encoding functionTable.Add(XmlReservedNs.NsXQueryFunc, "base64encode", 2, XPath2ResultType.String, Base64EncodeDelegate); }
static void Main(string[] args) { FunctionTable.LoadData(); Analyse analyse = new Analyse(); //analyse.Files.Add(@"F:\Games\Call Of Cthulhu DCoTE\Testing\0.bin"); //analyse.Files.Add(@"F:\Games\Call Of Cthulhu DCoTE\Testing\1.bin"); //analyse.Files.Add(@"F:\Games\Call Of Cthulhu DCoTE\Testing\2.bin"); //analyse.Files.Add(@"F:\Games\Call Of Cthulhu DCoTE\Testing\3.bin"); //analyse.Files.Add(@"F:\Games\Call Of Cthulhu DCoTE\Testing\4.bin"); //analyse.Files.Add(args[0]); if (args.Length > 1) { analyse.SaveAsNew = (args[1] != "asold"); analyse.BuildNew = (args[1] == "buildnew"); } analyse.NewBase = 605; //1AE = 430 //25D = 605 //2F8 = 760 if (args.Length > 2) { short parseShort = 0; short.TryParse(args[2], out parseShort); analyse.NewBase = parseShort; } ParsedContent parsedContent = analyse.AnalyseFile(args[0]); analyse.PostAnalysis(parsedContent); Console.WriteLine("Finished."); //Console.ReadLine(); }
private Expression.Expression ConvertFunction(FunctionNode node) { if (FunctionTable.IsValidFunction(node.FunctionName)) { //check number of arguments FunctionEntry entry = FunctionTable.GetFunctionEntry(node.FunctionName); if (entry.ArgNumber != node.Arguments.Count) { compilerErrors.Add(new ErrorMessage($"{entry.ArgNumber.ToString()} аргументов ожидалось в функции \"{node.FunctionName}", node.Line, node.Position)); return(null); } List <Expression.Expression> arguments = new List <Expression.Expression>(); foreach (var argument in node.Arguments) { arguments.Add(ConvertToExpression(argument)); } return(new Function(entry, arguments)); } else { compilerErrors.Add(new ErrorMessage($"Неизвестная функция \"{node.FunctionName}\"", node.Line, node.Position)); return(null); } }
public void InterpreterTry() { SymbolTable _SymbolTable = new SymbolTable(); FunctionTable functionTable = new FunctionTable(); var parser = new Parser(new Lexer(new InputStream(@" var id=0; var msg =''; try { id = f; } catch(err) { msg = err; id=44; }"))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public void InterpreterSwitch() { SymbolTable _SymbolTable = new SymbolTable(); FunctionTable functionTable = new FunctionTable(); var parser = new Parser(new Lexer(new InputStream(@" var id=1; var count = 3; switch(id) { case 1: count++; break; case 2: if(true) count--; }"))); parser.StartINTerminal = new StatementList(); var _result = (List <StatementNode>)parser.Parse(); foreach (var statementNode in _result) { statementNode.Interpret(_SymbolTable, functionTable); } }
public Runnable(InstrucStream instStream, FunctionTable fTable, SymbolTable symbolTable) { Setup(instStream, fTable, symbolTable); }
public Runnable(InstrucStream instStream, FunctionTable fTable) { Setup(instStream, fTable, null); }
private void Setup(InstrucStream instStream, FunctionTable fTable, SymbolTable symbolTable) { stream = instStream; functionTable = fTable; if (functionTable.ContainsKey(Function.MainName)) { mainFunction = functionTable[Function.MainName]; } ScriptSymbolTable = SymbolTable.CreateFor(symbolTable); RuntimeStack = new RuntimeStack(); ParamStack = new ParamStack(); }
public override void Interpret(SymbolTable table, FunctionTable functionTable) { throw new System.NotImplementedException(); }
public static ITable ResultTable(IQueryContext context, SqlExpression expression) { var exp = new [] { expression }; var names = new[] { "result" }; var table = new FunctionTable(exp, names, context); return new SubsetColumnTable(table, new int[0], new []{new ObjectName("result") }); }
public TableGroupResolver(FunctionTable table) { Table = table; GroupId = -1; }
private void ResetAll(Options options) { Heap = new Heap(); //Rmem = new RuntimeMemory(Heap); Configurations = new Dictionary <string, object>(); ResetRuntimeCore(); Validity.AssertExpiry(); Options = options; Compilers = new Dictionary <Language, Compiler>(); ClassIndex = Constants.kInvalidIndex; FunctionTable = new FunctionTable(); Langverify = new LangVerify(); watchFunctionScope = Constants.kInvalidIndex; watchSymbolList = new List <SymbolNode>(); watchBaseOffset = 0; GlobOffset = 0; GlobHeapOffset = 0; BaseOffset = 0; GraphNodeUID = 0; CodeBlockIndex = 0; RuntimeTableIndex = 0; CodeBlockList = new List <CodeBlock>(); CompleteCodeBlockList = new List <CodeBlock>(); DSExecutable = new Executable(); AssocNode = null; // TODO Jun/Luke type system refactoring // Initialize the globalClass table and type system ClassTable = new ClassTable(); TypeSystem = new TypeSystem(); TypeSystem.SetClassTable(ClassTable); ProcNode = null; ProcTable = new ProcedureTable(Constants.kGlobalScope); //Initialize the function pointer table FunctionPointerTable = new FunctionPointerTable(); //Initialize the dynamic string table and dynamic function table DynamicVariableTable = new DynamicVariableTable(); DynamicFunctionTable = new DynamicFunctionTable(); startPC = Constants.kInvalidIndex; deltaCompileStartPC = Constants.kInvalidIndex; if (options.SuppressBuildOutput) { // don't log any of the build related messages // just accumulate them in relevant containers with // BuildStatus object // BuildStatus = new BuildStatus(this, false, false, false); } else { BuildStatus = new BuildStatus(this, Options.BuildOptWarningAsError, null, Options.BuildOptErrorAsWarning); } SSASubscript = 0; SSASubscript_GUID = Guid.NewGuid(); ExpressionUID = 0; ModifierBlockUID = 0; ModifierStateSubscript = 0; ExprInterpreterExe = null; Options.RunMode = InterpreterMode.kNormal; assocCodegen = null; // Default execution log is Console.Out. ExecutionLog = Console.Out; DebuggerProperties = new DebugProperties(); ParsingMode = ParseMode.Normal; IsParsingPreloadedAssembly = false; IsParsingCodeBlockNode = false; ImportHandler = null; deltaCompileStartPC = 0; builtInsLoaded = false; ForLoopBlockIndex = Constants.kInvalidIndex; GraphNodeCallList = new List <GraphNode>(); newEntryPoint = Constants.kInvalidIndex; }
public static void RegisterType(string TypeName, CreateNewEntityOfType TypeGenerator, CreateNewXMLSerializerOfType XMLGenerator) { if(TypeNameToFunctionTable == null) { TypeNameToFunctionTable = new Dictionary<string, FunctionTable>(); } if(TypeNameToFunctionTable.ContainsKey(TypeName)) { TypeNameToFunctionTable[TypeName] = new FunctionTable(TypeGenerator, XMLGenerator, TypeNameToFunctionTable[TypeName].NewEditorBox); } else { TypeNameToFunctionTable.Add(TypeName, new FunctionTable(TypeGenerator, XMLGenerator, null)); } }
public override ITable Evaluate(IQueryContext context) { var childTable = Child.Evaluate(context); var funTable = new FunctionTable(childTable, Functions, Names, context); return funTable.MergeWith(null); }
QilNode IXPathEnvironment.ResolveFunction(string prefix, string name, IList <QilNode> args, IFocus env) { Debug.Assert(!args.IsReadOnly, "Writable collection expected"); if (prefix.Length == 0) { FunctionInfo?func; if (FunctionTable.TryGetValue(name, out func)) { func.CastArguments(args, name, _f); switch (func.id) { case FuncId.Current: if (!_allowCurrent) { throw new XslLoadException(SR.Xslt_CurrentNotAllowed); } // NOTE: This is the only place where the current node (and not the context node) must be used return(((IXPathEnvironment)this).GetCurrent() !); case FuncId.Key: if (!_allowKey) { throw new XslLoadException(SR.Xslt_KeyNotAllowed); } return(CompileFnKey(args[0], args[1], env)); case FuncId.Document: return(CompileFnDocument(args[0], args.Count > 1 ? args[1] : null)); case FuncId.FormatNumber: return(CompileFormatNumber(args[0], args[1], args.Count > 2 ? args[2] : null)); case FuncId.UnparsedEntityUri: return(CompileUnparsedEntityUri(args[0])); case FuncId.GenerateId: return(CompileGenerateId(args.Count > 0 ? args[0] : env.GetCurrent() !)); case FuncId.SystemProperty: return(CompileSystemProperty(args[0])); case FuncId.ElementAvailable: return(CompileElementAvailable(args[0])); case FuncId.FunctionAvailable: return(CompileFunctionAvailable(args[0])); default: Debug.Fail($"{func.id} is present in the function table, but absent from the switch"); return(null); } } else { throw new XslLoadException(SR.Xslt_UnknownXsltFunction, Compiler.ConstructQName(prefix, name)); } } else { string ns = ResolvePrefixThrow(/*ignoreDefaultNs:*/ true, prefix); Debug.Assert(ns != null); if (ns == XmlReservedNs.NsMsxsl) { if (name == "node-set") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(CompileMsNodeSet(args[0])); } else if (name == "string-compare") { FunctionInfo.CheckArity(/*minArg:*/ 2, /*maxArg:*/ 4, name, args.Count); return(_f.InvokeMsStringCompare( /*x: */ _f.ConvertToString(args[0]), /*y: */ _f.ConvertToString(args[1]), /*lang: */ 2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty), /*options:*/ 3 < args.Count ? _f.ConvertToString(args[3]) : _f.String(string.Empty) )); } else if (name == "utc") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(_f.InvokeMsUtc(/*datetime:*/ _f.ConvertToString(args[0]))); } else if (name == "format-date" || name == "format-time") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 3, name, args.Count); return(_f.InvokeMsFormatDateTime( /*datetime:*/ _f.ConvertToString(args[0]), /*format: */ 1 < args.Count ? _f.ConvertToString(args[1]) : _f.String(string.Empty), /*lang: */ 2 < args.Count ? _f.ConvertToString(args[2]) : _f.String(string.Empty), /*isDate: */ _f.Boolean(name == "format-date") )); } else if (name == "local-name") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(_f.InvokeMsLocalName(_f.ConvertToString(args[0]))); } else if (name == "namespace-uri") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(_f.InvokeMsNamespaceUri(_f.ConvertToString(args[0]), env.GetCurrent() !)); } else if (name == "number") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(_f.InvokeMsNumber(args[0])); } } if (ns == XmlReservedNs.NsExsltCommon) { if (name == "node-set") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(CompileMsNodeSet(args[0])); } else if (name == "object-type") { FunctionInfo.CheckArity(/*minArg:*/ 1, /*maxArg:*/ 1, name, args.Count); return(EXslObjectType(args[0])); } } // NOTE: If you add any function here, add it to IsFunctionAvailable as well // Ensure that all node-set parameters are DocOrderDistinct for (int i = 0; i < args.Count; i++) { args[i] = _f.SafeDocOrderDistinct(args[i]); } if (_compiler.Settings.EnableScript) { XmlExtensionFunction?scrFunc = _compiler.Scripts.ResolveFunction(name, ns, args.Count, (IErrorHelper)this); if (scrFunc != null) { return(GenerateScriptCall(_f.QName(name, ns, prefix), scrFunc, args)); } } else { if (_compiler.Scripts.ScriptClasses.ContainsKey(ns)) { ReportWarning(SR.Xslt_ScriptsProhibited); return(_f.Error(_lastScope !.SourceLine, SR.Xslt_ScriptsProhibited)); } } return(_f.XsltInvokeLateBound(_f.QName(name, ns, prefix), args)); } }
public void ShouldReturnEnumerator() { FunctionTable table = new FunctionTable(); table.AddFunction<TestFunction>("test"); int count = 0; IEnumerator enumerator = ((IEnumerable)table).GetEnumerator(); while (enumerator.MoveNext()) count++; Assert.AreEqual<int>(1, count); }
private void ResetAll(Options options) { Heap = new Heap(); //Rmem = new RuntimeMemory(Heap); Configurations = new Dictionary <string, object>(); DllTypesToLoad = new List <System.Type>(); Options = options; Compilers = new Dictionary <Language, Compiler>(); ClassIndex = Constants.kInvalidIndex; FunctionTable = new FunctionTable(); watchFunctionScope = Constants.kInvalidIndex; watchSymbolList = new List <SymbolNode>(); watchBaseOffset = 0; GlobOffset = 0; GlobHeapOffset = 0; BaseOffset = 0; GraphNodeUID = 0; CodeBlockIndex = 0; RuntimeTableIndex = 0; CodeBlockList = new List <CodeBlock>(); CompleteCodeBlockList = new List <CodeBlock>(); CallsiteGuidMap = new Dictionary <Guid, int>(); AssocNode = null; // TODO Jun/Luke type system refactoring // Initialize the globalClass table and type system ClassTable = new ClassTable(); TypeSystem = new TypeSystem(); TypeSystem.SetClassTable(ClassTable); ProcNode = null; ProcTable = new ProcedureTable(Constants.kGlobalScope); // Initialize internal attributes internalAttributes = new InternalAttributes(ClassTable); //Initialize the function pointer table FunctionPointerTable = new FunctionPointerTable(); //Initialize the dynamic string table and dynamic function table DynamicVariableTable = new DynamicVariableTable(); DynamicFunctionTable = new DynamicFunctionTable(); watchStartPC = Constants.kInvalidIndex; deltaCompileStartPC = Constants.kInvalidIndex; BuildStatus = new BuildStatus(this, null, Options.BuildOptErrorAsWarning); SSAExpressionUID = 0; SSASubscript = 0; SSASubscript_GUID = Guid.NewGuid(); SSAExprUID = 0; ExpressionUID = 0; ExprInterpreterExe = null; Options.RunMode = InterpreterMode.Normal; assocCodegen = null; // Default execution log is Console.Out. ExecutionLog = Console.Out; DebuggerProperties = new DebugProperties(); ParsingMode = ParseMode.Normal; IsParsingPreloadedAssembly = false; IsParsingCodeBlockNode = false; ImportHandler = null; deltaCompileStartPC = 0; builtInsLoaded = false; ForLoopBlockIndex = Constants.kInvalidIndex; GraphNodeCallList = new List <GraphNode>(); InlineConditionalBodyGraphNodes = new Stack <List <GraphNode> >(); newEntryPoint = Constants.kInvalidIndex; }
public static void RegisterEditorType(string TypeName, CreateEditorBoxForType InNewEditorBox) { if(TypeNameToFunctionTable == null) { TypeNameToFunctionTable = new Dictionary<string, FunctionTable>(); } if(TypeNameToFunctionTable.ContainsKey(TypeName)) { TypeNameToFunctionTable[TypeName] = new FunctionTable(TypeNameToFunctionTable[TypeName].NewEntity, TypeNameToFunctionTable[TypeName].NewXMLSerializer, InNewEditorBox); } else { TypeNameToFunctionTable.Add(TypeName, new FunctionTable(null, null, InNewEditorBox)); } }