Exemplo n.º 1
0
        public ExpressionScriptProvided Resolve(
            string name,
            int numParameters)
        {
            var key = new NameAndParamNum(name, numParameters);

            // try self-originated protected types first
            ExpressionScriptProvided localExpr = _locals.Scripts.Get(key);
            if (localExpr != null) {
                return localExpr;
            }

            try {
                var expression = _path.GetAnyModuleExpectSingle(
                    new NameAndParamNum(name, numParameters),
                    _moduleUses);
                if (expression != null) {
                    if (!_isFireAndForget &&
                        !NameAccessModifierExtensions.Visible(
                        expression.First.Visibility,
                        expression.First.ModuleName,
                        _moduleName)) {
                        return null;
                    }

                    _moduleDependencies.AddPathScript(key, expression.Second);
                    return expression.First;
                }
            }
            catch (PathException e) {
                throw CompileTimeResolverUtil.MakePathAmbiguous(PathRegistryObjectType.SCRIPT, name, e);
            }

            return null;
        }
Exemplo n.º 2
0
        public void Verify(ExpressionScriptProvided expressionScript)
        {
            try
            {
                using (var engine = new JScriptEngine())
                {
                    ExposeTypesToEngine(engine);

                    engine.AddHostObject("host", new XHostFunctions());
                    engine.AddHostObject("debug", new DebugFunctions(this));

                    var writer = new StringWriter();
                    WritePolyfills(writer);
                    writer.WriteLine("var __result = function() {");
                    writer.WriteLine(expressionScript.Expression);
                    writer.WriteLine("};");

                    engine.Execute(writer.ToString());
                }
            }
            catch (ScriptEngineException ex)
            {
                throw new ExprValidationException(ex.Message, ex);
            }
        }
Exemplo n.º 3
0
        public void Verify(ExpressionScriptProvided script)
        {
#if X86 || X64
#else
            throw new UnsupportedOperationException("noesis engine is not supported outside of x86 and x64 builds");
#endif
        }
Exemplo n.º 4
0
 public void RegisterScript(
     string scriptName,
     int numParams,
     ExpressionScriptProvided meta)
 {
     _moduleScripts.Put(new NameAndParamNum(scriptName, numParams), meta);
 }
Exemplo n.º 5
0
        public void AddScript(ExpressionScriptProvided item)
        {
            if (scripts == null) {
                scripts = new Dictionary<string, ExpressionScriptProvided>();
            }

            scripts.Put(item.Name, item);
        }
Exemplo n.º 6
0
        public Func <ScriptArgs, Object> Compile(ExpressionScriptProvided expressionScript)
        {
#if true
            var script = new StringScriptSource(expressionScript.Expression);
            return(args => ExecuteWithScriptArgs(script, args));
#else
            throw new UnsupportedOperationException("jurassic engine is not supported outside of x86 and x64 builds");
#endif
        }
Exemplo n.º 7
0
        public void Verify(ExpressionScriptProvided expressionScript)
        {
#if true
            var script = new StringScriptSource(expressionScript.Expression);
            ScopeTestHelper.AssertNotNull(script);
#else
            throw new UnsupportedOperationException("jurassic engine is not supported outside of x86 and x64 builds");
#endif
        }
Exemplo n.º 8
0
 public ExprNodeScript(
     string defaultDialect,
     ExpressionScriptProvided script,
     IList<ExprNode> parameters)
 {
     _defaultDialect = defaultDialect;
     Script = script ?? throw new ArgumentException("script cannot be null", nameof(script));
     Parameters = parameters;
 }
Exemplo n.º 9
0
            internal CodeCompileUnit GenerateCode(string typeName, ExpressionScriptProvided script, StringCollection imports)
            {
                var compileUnit = new CodeCompileUnit();

                var typeDecl = new CodeTypeDeclaration(typeName);

                typeDecl.IsClass        = true;
                typeDecl.TypeAttributes = TypeAttributes.Public;
                typeDecl.BaseTypes.Add(typeof(ScriptBase));

                var scriptMainMember = new CodeMemberMethod();

                scriptMainMember.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                scriptMainMember.Name       = "ScriptMain";
                scriptMainMember.Parameters.Add(
                    new CodeParameterDeclarationExpression(typeof(ScriptArgs), "args"));
                scriptMainMember.ReturnType = new CodeTypeReference(typeof(object));

                foreach (var parameter in script.ParameterNames)
                {
                    var variableDeclarationStatement = new CodeVariableDeclarationStatement();
                    variableDeclarationStatement.Type           = new CodeTypeReference(typeof(object));
                    variableDeclarationStatement.Name           = parameter;
                    variableDeclarationStatement.InitExpression = new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("args"),
                        "GetParameter",
                        new CodePrimitiveExpression(parameter)
                        );

                    scriptMainMember.Statements.Add(variableDeclarationStatement);
                }

                scriptMainMember.Statements.Add(
                    new CodeSnippetExpression(script.Expression));

                typeDecl.Members.Add(scriptMainMember);

                var nspace = new CodeNamespace();

                // add the default namespaces
                foreach (string import in DefaultNamespaces)
                {
                    nspace.Imports.Add(new CodeNamespaceImport(import));
                }
                // add requested imports
                foreach (string import in imports)
                {
                    nspace.Imports.Add(new CodeNamespaceImport(import));
                }

                compileUnit.Namespaces.Add(nspace);
                nspace.Types.Add(typeDecl);

                return(compileUnit);
            }
Exemplo n.º 10
0
        public void VerifyScript(string dialect, ExpressionScriptProvided script)
        {
            var scriptingEngine = _scriptingEngines.Get(dialect);

            if (scriptingEngine == null)
            {
                throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect + "' for script '" + script.Name + "'");
            }

            scriptingEngine.Verify(script);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Compiles the specified language prefix.
        /// </summary>
        /// <param name="dialect">The language prefix.</param>
        /// <param name="script">The script.</param>
        /// <returns></returns>
        public Func <ScriptArgs, Object> Compile(string dialect, ExpressionScriptProvided script)
        {
            var scriptingEngine = _scriptingEngines.Get(dialect);

            if (scriptingEngine == null)
            {
                throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect + "' for script '" + script.Name + "'");
            }

            return(scriptingEngine.Compile(script));
        }
Exemplo n.º 12
0
        public void RegisterScript(
            string scriptName,
            int numParameters,
            ExpressionScriptProvided meta)
        {
            var key = new NameAndParamNum(scriptName, numParameters);
            if (scripts.ContainsKey(key)) {
                throw new IllegalStateException("Script already found '" + key + "'");
            }

            scripts.Put(key, meta);
        }
Exemplo n.º 13
0
 public static void VerifyCompilerScript(ExpressionScriptProvided script, string dialect)
 {
     try
     {
         CreateCodeProvider(dialect);
     }
     catch (TypeLoadException e)
     {
         throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect +
                                           "' for script '" + script.Name + "'");
     }
 }
Exemplo n.º 14
0
        public void NewScript(ExpressionScriptProvided detail)
        {
            if (!detail.Visibility.IsModuleProvidedAccessModifier()) {
                throw new IllegalStateException("Invalid visibility for contexts");
            }

            var key = new NameAndParamNum(detail.Name, detail.ParameterNames.Length);
            var existing = Scripts.Get(key);
            if (existing != null) {
                throw new IllegalStateException("Duplicate script has been encountered for name '" + key + "'");
            }

            Scripts.Put(key, detail);
        }
Exemplo n.º 15
0
        private object ExecuteWithScriptArgs(ExpressionScriptProvided expressionScript, ScriptArgs args)
        {
            using (var engine = new Microsoft.ClearScript.Windows.JScriptEngine())
            {
                var primitives             = new ExpandoObject();
                var primitivesAsDictionary = (IDictionary <string, object>)primitives;

                foreach (var binding in args.Bindings)
                {
                    if (IsPrimitive(binding.Value))
                    {
                        primitivesAsDictionary.Add(binding.Key, binding.Value);
                    }
                    else
                    {
                        engine.AddHostObject(binding.Key, binding.Value);
                    }
                }

                ExposeTypesToEngine(engine);

                engine.AddHostObject("__variables", primitives);
                engine.AddHostObject("host", new XHostFunctions());
                engine.AddHostObject("debug", new DebugFunctions(this));

                var writer = new StringWriter();
                WritePolyfills(writer);
                writer.WriteLine("var __result = (function() {");

                foreach (var binding in primitivesAsDictionary)
                {
                    writer.WriteLine("var {0} = __variables.{0};", binding.Key);
                }

                writer.WriteLine(expressionScript.Expression);
                writer.WriteLine("})();");

                engine.Execute(writer.ToString());

                var result = engine.Script.__result;
                if ((result is VoidResult) || (result is Undefined))
                {
                    return(null);
                }

                return(result);
            }
        }
Exemplo n.º 16
0
        public String AddExpressionOrScript(CreateExpressionDesc expressionDesc)
        {
            using (_iLock.Acquire())
            {
                if (expressionDesc.Expression != null)
                {
                    ExpressionDeclItem expression = expressionDesc.Expression;
                    String             name       = expression.Name;
                    if (_globalExpressions.ContainsKey(name))
                    {
                        throw new ExprValidationException("Expression '" + name + "' has already been declared");
                    }
                    _globalExpressions.Put(name, expression);
                    return(name);
                }
                else
                {
                    ExpressionScriptProvided newScript = expressionDesc.Script;
                    String name = newScript.Name;

                    List <ExpressionScriptProvided> scripts = _globalScripts.Get(name);
                    if (scripts != null)
                    {
                        foreach (ExpressionScriptProvided script in scripts)
                        {
                            if (script.ParameterNames.Count == newScript.ParameterNames.Count)
                            {
                                throw new ExprValidationException(
                                          "Script '" + name +
                                          "' that takes the same number of parameters has already been declared");
                            }
                        }
                    }
                    else
                    {
                        scripts = new List <ExpressionScriptProvided>(2);
                        _globalScripts.Put(name, scripts);
                    }
                    scripts.Add(newScript);

                    return(name);
                }
            }
        }
Exemplo n.º 17
0
        private object ExecuteWithScriptArgs(ExpressionScriptProvided expressionScript, ScriptArgs args)
        {
#if X86 || X64
            using (var context = new JavascriptContext())
            {
                foreach (var binding in args.Bindings)
                {
                    context.SetParameter(binding.Key, binding.Value);
                }

                context.SetParameter("clr", new ClrBinding());
                context.SetParameter("print", new Action <object>(value => Console.Out.WriteLine(value)));
                context.SetParameter("render", new Action <object>(value => value.Render()));
                return(context.Run(expressionScript.Expression));
            }
#else
            throw new UnsupportedOperationException("noesis engine is not supported outside of x86 and x64 builds");
#endif
        }
Exemplo n.º 18
0
        private static ExpressionScriptProvided FindScript(String name, int parameterCount, ICollection <ExpressionScriptProvided> scriptsByName)
        {
            if (scriptsByName == null || scriptsByName.IsEmpty())
            {
                return(null);
            }
            ExpressionScriptProvided nameMatchedScript = null;

            foreach (ExpressionScriptProvided script in scriptsByName)
            {
                if (script.Name.Equals(name) && script.ParameterNames.Count == parameterCount)
                {
                    return(script);
                }
                if (script.Name.Equals(name))
                {
                    nameMatchedScript = script;
                }
            }
            return(nameMatchedScript);
        }
Exemplo n.º 19
0
        private static void ValidateScript(
            ExpressionScriptProvided script,
            string defaultDialect,
            ScriptCompiler scriptCompiler)
        {
            var dialect = script.OptionalDialect ?? defaultDialect;

            if (dialect == null)
            {
                throw new ExprValidationException(
                          "Failed to determine script dialect for script '" +
                          script.Name +
                          "', please configure a default dialect or provide a dialect explicitly");
            }

            scriptCompiler.VerifyScript(dialect, script);

#if false
            ExpressionScriptCompiled compiledBuf = JSR223Helper
                                                   .VerifyCompileScript(script.Name, script.Expression, dialect);

            script.CompiledBuf = compiledBuf;
#endif

            if (script.ParameterNames.Length != 0)
            {
                var parameters = new HashSet <String>();
                foreach (var param in script.ParameterNames)
                {
                    if (parameters.Contains(param))
                    {
                        throw new ExprValidationException(
                                  "Invalid script parameters for script '" + script.Name + "', parameter '" + param + "' is defined more then once");
                    }

                    parameters.Add(param);
                }
            }
        }
Exemplo n.º 20
0
 public Func <ScriptArgs, Object> Compile(ExpressionScriptProvided expressionScript)
 {
     return(args => ExecuteWithScriptArgs(expressionScript, args));
 }
Exemplo n.º 21
0
 public Func <ScriptArgs, object> Compile(ExpressionScriptProvided expressionScript)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 22
0
 public void AddScript(ExpressionScriptProvided item)
 {
     Scripts.Add(item);
 }
Exemplo n.º 23
0
 public ExprNodeScript(String defaultDialect, ExpressionScriptProvided script, IList <ExprNode> parameters)
 {
     _defaultDialect = defaultDialect;
     Script          = script;
     Parameters      = parameters;
 }
Exemplo n.º 24
0
        public static Pair <ExpressionDeclItem, ExpressionScriptProvided> WalkExpressionDecl(
            EsperEPL2GrammarParser.ExpressionDeclContext ctx,
            IList <String> scriptBodies,
            IDictionary <ITree, ExprNode> astExprNodeMap,
            CommonTokenStream tokenStream)
        {
            var name = ctx.name.Text;

            if (ctx.alias != null)
            {
                if (ctx.alias.Text.ToLower().Trim() != "alias")
                {
                    throw ASTWalkException.From("For expression alias '" + name + "' expecting 'alias' keyword but received '" + ctx.alias.Text + "'");
                }
                if (ctx.columnList() != null)
                {
                    throw ASTWalkException.From("For expression alias '" + name + "' expecting no parameters but received '" + tokenStream.GetText(ctx.columnList()) + "'");
                }
                if (ctx.expressionDef() != null && ctx.expressionDef().expressionLambdaDecl() != null)
                {
                    throw ASTWalkException.From("For expression alias '" + name + "' expecting an expression without parameters but received '" + tokenStream.GetText(ctx.expressionDef().expressionLambdaDecl()) + "'");
                }
                if (ctx.expressionDef().stringconstant() != null)
                {
                    throw ASTWalkException.From("For expression alias '" + name + "' expecting an expression but received a script");
                }
                var exprNode = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0];
                var alias    = ctx.name.Text;
                var decl     = new ExpressionDeclItem(alias, Collections.GetEmptyList <String>(), exprNode, true);
                return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(decl, null));
            }

            if (ctx.expressionDef().stringconstant() != null)
            {
                var expressionText = scriptBodies[0];
                scriptBodies.RemoveAt(0);
                var parameters         = ASTUtil.GetIdentList(ctx.columnList());
                var optionalReturnType = ctx.classIdentifier() == null
                    ? null
                    : ASTUtil.UnescapeClassIdent(ctx.classIdentifier());
                var optionalReturnTypeArray = ctx.array != null;
                var optionalDialect         = ctx.expressionDialect() == null ? null : ctx.expressionDialect().d.Text;
                var script = new ExpressionScriptProvided(
                    name, expressionText, parameters,
                    optionalReturnType, optionalReturnTypeArray, optionalDialect);
                return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(null, script));
            }

            var ctxexpr = ctx.expressionDef();
            var inner   = ASTExprHelper.ExprCollectSubNodes(ctxexpr.expression(), 0, astExprNodeMap)[0];

            var parametersNames = Collections.GetEmptyList <string>();
            var lambdactx       = ctxexpr.expressionLambdaDecl();

            if (ctxexpr.expressionLambdaDecl() != null)
            {
                parametersNames = ASTLibFunctionHelper.GetLambdaGoesParams(lambdactx);
            }

            var expr = new ExpressionDeclItem(name, parametersNames, inner, false);

            return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(expr, null));
        }
Exemplo n.º 25
0
        /// <summary>
        /// Compiles the code.
        /// </summary>
        /// <param name="expressionScript">The expression script.</param>
        /// <returns></returns>
        public Func <ScriptArgs, Object> Compile(ExpressionScriptProvided expressionScript)
        {
            var compilerInfo = CreateCompilerInfo(Language);

            var options = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;
            options.MainClass          = MainClass;

            // add (and load) assemblies specified by user
            foreach (var assemblyFile in References)
            {
                try
                {
                    // load the assembly into current AppDomain to ensure it is
                    // available when executing the emitted assembly
                    var asm = Assembly.LoadFrom(assemblyFile);

                    // Log the assembly being added to the CompilerParameters
                    Log.Debug("Adding assembly {0}", asm.GetName().Name);

                    // add the location of the loaded assembly
                    if (!string.IsNullOrEmpty(asm.Location))
                    {
                        options.ReferencedAssemblies.Add(asm.Location);
                    }
                }
                catch (Exception ex)
                {
                    throw new ExprValidationException("unable to load assembly: " + assemblyFile, ex);
                }
            }

            var imports = new StringCollection();

            foreach (var import in Imports)
            {
                imports.Add(import);
            }

            // generate the code
            var compileUnit = compilerInfo.GenerateCode(RootClassName, expressionScript, imports);

            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            compilerInfo.Provider.GenerateCodeFromCompileUnit(compileUnit, stringWriter, null);
            string code = stringWriter.ToString();

            Log.Debug("Generated script: {0}", code);

            var results = compilerInfo.Provider.CompileAssemblyFromDom(options, compileUnit);

            if (results.Errors.Count > 0)
            {
                // Console.WriteLine(results.Errors.Cast<CompilerError>().Select(e => e.ErrorText).Aggregate((a, b) => a + "," + b));
                throw new ScriptCompilationException("failed to compile script", results.Errors.Cast <CompilerError>().ToList());
            }

            var compiled = results.CompiledAssembly;

            var mainClass = RootClassName;

            if (!string.IsNullOrEmpty(MainClass))
            {
                mainClass += "+" + MainClass;
            }

            var mainType = compiled.GetType(mainClass);

            if (mainType == null)
            {
                throw new ScriptCompilationException(
                          "failed to compile script: unable to find main type");
            }

            var entry = mainType.GetMethod("ScriptMain");

            // check for task or function definitions.
            if (entry == null)
            {
                throw new ScriptCompilationException(
                          "failed to compile script: ScriptMain() not defined");
            }

            if (!entry.IsStatic)
            {
                throw new ScriptCompilationException(
                          "failed to compile script: ScriptMain() not defined as static");
            }

            var entryParams = entry.GetParameters();

            if (entryParams.Length != 1)
            {
                throw new ScriptCompilationException(
                          "failed to compile script: ScriptMain() should have only one parameter");
            }

            if (entryParams[0].ParameterType.FullName != typeof(ScriptArgs).FullName)
            {
                throw new ScriptCompilationException(
                          string.Format("failed to compile script: ScriptMain() takes one member of type {0}, should have only one parameter of type {1}",
                                        entryParams[0].ParameterType.FullName, typeof(ScriptArgs).FullName));
            }

            if (entry.ReturnType.FullName != typeof(Object).FullName)
            {
                throw new ScriptCompilationException(
                          string.Format("failed to compile script: ScriptMain() must return value of type {0}",
                                        typeof(Object).FullName));
            }

            return(args =>
            {
                try
                {
                    return entry.Invoke(null, new object[] { args });
                }
                catch (Exception ex)
                {
                    Log.Warn("exception thrown during script execution", ex);
                    throw;
                }
            });
        }
Exemplo n.º 26
0
 /// <summary>
 /// Verifies the specified script.
 /// </summary>
 /// <param name="script">The script.</param>
 public void Verify(ExpressionScriptProvided script)
 {
 }
Exemplo n.º 27
0
        public static MyPair WalkExpressionDecl(
            EsperEPL2GrammarParser.ExpressionDeclContext ctx,
            IList<string> scriptBodies,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            CommonTokenStream tokenStream)
        {
            var name = ctx.name.Text;

            if (ctx.alias != null)
            {
                if (!ctx.alias.Text.ToLowerInvariant().Trim().Equals("alias"))
                {
                    throw ASTWalkException.From(
                        "For expression alias '" + name + "' expecting 'alias' keyword but received '" + ctx.alias.Text + "'");
                }

                if (ctx.columnList() != null)
                {
                    throw ASTWalkException.From(
                        "For expression alias '" + name + "' expecting no parameters but received '" + tokenStream.GetText(ctx.columnList()) + "'");
                }

                if (ctx.expressionDef() != null && ctx.expressionDef().expressionLambdaDecl() != null)
                {
                    throw ASTWalkException.From(
                        "For expression alias '" + name + "' expecting an expression without parameters but received '" +
                        tokenStream.GetText(ctx.expressionDef().expressionLambdaDecl()) + "'");
                }

                if (ctx.expressionDef().stringconstant() != null)
                {
                    throw ASTWalkException.From("For expression alias '" + name + "' expecting an expression but received a script");
                }

                var node = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0];
                var alias = ctx.name.Text;
                var expressionUnmap = StatementSpecMapper.Unmap(node);
                var decl = new ExpressionDeclItem(alias, new string[0], true);
                decl.OptionalSoda = expressionUnmap;
                return new MyPair(decl, null);
            }

            if (ctx.expressionDef().stringconstant() != null)
            {
                var expressionText = scriptBodies.DeleteAt(0);
                var parameters = ASTUtil.GetIdentList(ctx.columnList());
                var optionalReturnType = ctx.classIdentifier() == null ? null : ASTUtil.UnescapeClassIdent(ctx.classIdentifier());
                var optionalReturnTypeArray = ctx.array != null;
                var optionalDialect = ctx.expressionDialect() == null ? null : ctx.expressionDialect().d.Text;
                var optionalEventTypeName = ASTTypeExpressionAnnoHelper.ExpectMayTypeAnno(ctx.typeExpressionAnnotation(), tokenStream);
                var script = new ExpressionScriptProvided(
                    name, expressionText, parameters.ToArray(),
                    optionalReturnType, optionalReturnTypeArray, optionalEventTypeName, optionalDialect);
                return new MyPair(null, script);
            }

            var ctxexpr = ctx.expressionDef();
            var inner = ASTExprHelper.ExprCollectSubNodes(ctxexpr.expression(), 0, astExprNodeMap)[0];

            IList<string> parametersNames = new EmptyList<string>();
            var lambdactx = ctxexpr.expressionLambdaDecl();
            if (ctxexpr.expressionLambdaDecl() != null)
            {
                parametersNames = ASTLambdaHelper.GetLambdaGoesParams(lambdactx);
            }

            var expression = StatementSpecMapper.Unmap(inner);
            var expr = new ExpressionDeclItem(name, parametersNames.ToArray(), false);
            expr.OptionalSoda = expression;
            return new MyPair(expr, null);
        }