예제 #1
0
        public DynValue ExecuteAndReturn(string expr, dynamic invoker)
        {
            if (Disabled)
            {
                return(DynValue.Nil);
            }

            try
            {
                Compiled.Globals["utility"] = typeof(HybrasylUtility);
                Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                Compiled.Globals.Set("parent", GetUserDataValue(invoker));
                return(Compiled.DoString(expr));
            }
            catch (Exception ex)
            {
                Game.ReportException(ex);
                var error_msg = HumanizeException(ex);
                GameLog.ScriptingError("Execute: Error executing expression {expr} in {FileName} (associate {associate}, invoker {invoker}): {Message}",
                                       expr, FileName, Associate?.Name ?? "none", invoker?.Name ?? "none", error_msg);
                //Disabled = true;
                CompilationError = ex.ToString();
                return(DynValue.Nil);
            }
        }
예제 #2
0
        public IEnumerable <IDebugEvent> Solve (Compiled.Goal [] goalDefs)
        {
            // Instantiate the goals.
            var queryArgumentInstantiator = new ArgumentInstantiator();
            var goals = InstantiateGoals (goalDefs, queryArgumentInstantiator);

            frame = new Frame (goals, null, new BoundVariableSet (), queryArgumentInstantiator.Variables);

// ReSharper disable ConditionIsAlwaysTrueOrFalse
            while (frame != null)
// ReSharper restore ConditionIsAlwaysTrueOrFalse
            {
                if (frame.GoalsProven == frame.Goals.Length)
                {
                    // No more goals to prove or it's a fact.
                    System.Diagnostics.Debug.Assert (frame.Goals.All (g => g.CurrentFrame != null));

                    if (frame.Parent == null)
                    {
                        yield return new Solution (frame);

                        foreach (var e in GoToLastChoicePoint ()) 
                            yield return e;
                    }
                    else
                    {
                        // go on and prove the next parent goal.
                        frame = frame.Parent;
                        frame.GoalsProven++;
                    }

                    continue;
                }

                var goal = frame.Goals [frame.GoalsProven];

                // Check that the same goal is not on the stack to prevent infinite loops.
                if (AlreadyOnTheStack (goal))
                {
                    foreach (var e in Backtrack ()) 
                        yield return e;
                }
                else
                {
                    var newFrame = goal.GetNextFrame ();

                    if (newFrame == null)
                    {
                        foreach (var e in Backtrack ()) 
                            yield return e;
                    }
                    else
                    {
                        yield return new Enter (newFrame);

                        frame = newFrame; // decend the tree
                    }
                }
            }
        }
예제 #3
0
파일: Script.cs 프로젝트: Jinori/server
        /// <summary>
        /// Load the script from disk and execute it.
        /// </summary>
        /// <param name="onLoad">Whether or not to execute OnLoad() if it exists in the script.</param>
        /// <returns>boolean indicating whether the script was reloaded or not</returns>
        public bool Run(bool onLoad = true)
        {
            try
            {
                Compiled.Globals["Gender"]      = UserData.CreateStatic <Xml.Gender>();
                Compiled.Globals["LegendIcon"]  = UserData.CreateStatic <LegendIcon>();
                Compiled.Globals["LegendColor"] = UserData.CreateStatic <LegendColor>();
                Compiled.Globals["Class"]       = UserData.CreateStatic <Xml.Class>();
                Compiled.Globals["utility"]     = typeof(HybrasylUtility);
                Compiled.Globals.Set("world", UserData.Create(Processor.World));
                Compiled.Globals.Set("logger", UserData.Create(new ScriptLogger(Name)));
                Compiled.Globals.Set("this_script", DynValue.NewString(Name));
                Compiled.DoFile(FullPath);
                if (onLoad)
                {
                    ExecuteFunction("OnLoad");
                }
            }
            catch (Exception ex) when(ex is InterpreterException)
            {
                GameLog.ScriptingError("{Function}: Error executing script {FileName}: {Message}",
                                       MethodBase.GetCurrentMethod().Name, FileName,
                                       (ex as InterpreterException).DecoratedMessage);
                Disabled         = true;
                CompilationError = ex.ToString();
                LastRuntimeError = (ex as InterpreterException).DecoratedMessage;
                return(false);
            }

            return(true);
        }
예제 #4
0
파일: Script.cs 프로젝트: Jinori/server
        /// <summary>
        /// Execute a Lua expression in the context of an associated world object.
        /// Primarily used for dialog callbacks.
        /// </summary>
        /// <param name="expr">The javascript expression, in string form.</param>
        /// <param name="invoker">The invoker (caller).</param>
        /// <param name="source">Optionally, the source of the script call, invocation or dialog</param>
        /// <returns></returns>
        public bool Execute(string expr, dynamic invoker, dynamic source = null)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                Compiled.Globals["utility"] = typeof(HybrasylUtility);
                Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                if (source != null)
                {
                    Compiled.Globals.Set("source", GetUserDataValue(source));
                }

                // We pass Compiled.Globals here to make sure that the updated table (with new variables) makes it over
                LastReturnValue = Compiled.DoString(expr, Compiled.Globals);
            }
            catch (Exception ex) when(ex is InterpreterException)
            {
                GameLog.ScriptingError("{Function}: Error executing expression {expr} in {FileName} (invoker {Invoker}): {Message}",
                                       MethodBase.GetCurrentMethod().Name, expr, FileName, invoker.Name,
                                       (ex as InterpreterException).DecoratedMessage);
                //Disabled = true;
                CompilationError = ex.ToString();
                LastRuntimeError = (ex as InterpreterException).DecoratedMessage;
                return(false);
            }
            return(true);
        }
예제 #5
0
 /// <summary>
 /// Returns true if the text matches the pattern.
 /// </summary>
 /// <param name="text">Text to be matched with the pattern.</param>
 /// <returns>True if the text matches the pattern.</returns>
 public bool IsMatch(string text)
 {
     Positions = FixedParts.Select(e => text.IndexOf(e, ComparisonType)).ToArray();
     if (Positions.Any(i => i < 0))
     {
         return(false);
     }
     if (Compiled.First().IsFixed&& !text.StartsWith(FixedParts[0], ComparisonType))
     {
         return(false);
     }
     if (Compiled.Last().IsFixed&& !text.EndsWith(FixedParts[FixedParts.Length - 1], ComparisonType))
     {
         return(false);
     }
     for (int i = 0, l = -1, n = Positions.Length; i < n; i++)
     {
         if (Positions[i] <= l)
         {
             return(false);
         }
         l = Positions[i];
     }
     return(true);
 }
예제 #6
0
        public bool ExecuteFunction(string functionName, dynamic invoker)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                if (HasFunction(functionName))
                {
                    Compiled.Globals["utility"] = typeof(HybrasylUtility);
                    Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                    Compiled.Call(Compiled.Globals[functionName]);
                }
                else
                {
                    //GameLog.ScriptingWarning("ExecuteFunction: function {fn} in {FileName} did not exist",
                    //    functionName, FileName);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Game.ReportException(ex);
                var error_msg = HumanizeException(ex);
                GameLog.ScriptingError("ExecuteFunction: Error executing function {fn} in {FileName} (associate {associate}, invoker {invoker}): {Message}",
                                       functionName, FileName, Associate?.Name ?? "none", invoker?.Name ?? "none", error_msg);
                CompilationError = error_msg;
                return(false);
            }

            return(true);
        }
예제 #7
0
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  leftToken  = currentToken.Value;
            string leftName   = leftToken.value;
            Token  rightToken = currentToken.Next.Next.Value;
            string rightName  = rightToken.value;

            //Compile left of +
            //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken);

            //simple assignment
            if (currentToken.Next.Next.Next.Value.type == TokenType.Endstatement)
            {
                //Temp variable for right
                if (rightToken.type == TokenType.Number)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, rightToken));
                }
                else if (rightToken.type == TokenType.Variable)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.VARIABLETORETURN, rightName));
                }
                currentToken = currentToken.Next.Next.Next.Next;
            }
            else
            {
                currentToken = currentToken.Next.Next;
                CompiledStatement cs  = CompilerFactory.Instance.CreateCompiledStatement(currentToken);
                NodeLinkedList    nll = cs.compile(ref currentToken);
                Compiled.Add(nll);
                currentToken = currentToken.Next;
            }
            Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, leftName));
            return(Compiled);
        }
예제 #8
0
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  leftToken  = currentToken.Value;
            string leftName   = leftToken.value;
            Token  rightToken = currentToken.Next.Next.Value;
            string rightName  = rightToken.value;

            //Compile left of +
            //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken);

            //Temp variable for left
            if (leftToken.type == TokenType.Number)
            {
                leftName = CompiledStatement.getUniqueId();
                Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, leftToken));
                Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, leftName));
            }

            //Temp variable for right
            if (rightToken.type == TokenType.Number)
            {
                rightName = CompiledStatement.getUniqueId();
                Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, rightToken));
                Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, rightName));
            }
            currentToken = currentToken.Next;

            if (currentToken.Value.type == TokenType.Multiply)
            {
                Compiled.Add(new FunctionCallNode("Multiply", leftName, rightName));
            }

            currentToken = currentToken.Next.Next;
            return(Compiled);
        }
예제 #9
0
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  valueToken = currentToken.Next.Next.Value;
            string valueName  = valueToken.value;

            //Compile left of +
            //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken);

            currentToken = currentToken.Next.Next;
            try
            {
                CompiledStatement cs  = CompilerFactory.Instance.CreateCompiledStatement(currentToken);
                NodeLinkedList    nll = cs.compile(ref currentToken);
                Compiled.Add(nll);
            }
            catch
            {
                if (valueToken.type == TokenType.Number)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, valueToken));
                }
                else if (valueToken.type == TokenType.Variable)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.VARIABLETORETURN, valueName));
                }
                currentToken = currentToken.Next;
            }

            Compiled.Add(new FunctionCallNode("Print"));

            currentToken = currentToken.Next.Next;
            return(Compiled);
        }
예제 #10
0
파일: Script.cs 프로젝트: Jinori/server
        public bool ExecuteFunction(string functionName)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                if (HasFunction(functionName))
                {
                    Compiled.Globals["utility"] = typeof(HybrasylUtility);
                    Compiled.Call(Compiled.Globals[functionName]);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex) when(ex is InterpreterException)
            {
                GameLog.ScriptingError("{Function}: Error executing script function {ScriptFunction} in {FileName}: {Message}",
                                       MethodBase.GetCurrentMethod().Name, functionName, FileName,
                                       (ex as InterpreterException).DecoratedMessage);
                CompilationError = ex.ToString();
                return(false);
            }

            return(true);
        }
예제 #11
0
        /// <summary>
        /// Execute a Lua expression in the context of an associated world object.
        /// Primarily used for dialog callbacks.
        /// </summary>
        /// <param name="expr">The javascript expression, in string form.</param>
        /// <param name="invoker">The invoker (caller).</param>
        /// <param name="source">Optionally, the source of the script call, invocation or dialog</param>
        /// <returns></returns>
        public bool Execute(string expr, dynamic invoker, dynamic source = null)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                Compiled.Globals["utility"] = typeof(HybrasylUtility);
                Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                if (source != null)
                {
                    Compiled.Globals.Set("source", GetUserDataValue(source));
                }

                // We pass Compiled.Globals here to make sure that the updated table (with new variables) makes it over
                LastReturnValue = Compiled.DoString(expr, Compiled.Globals);
            }
            catch (Exception ex)
            {
                Game.ReportException(ex);
                var error_msg = HumanizeException(ex);
                GameLog.ScriptingError("Execute: Error executing expression {expr} in {FileName} (associate {associate}, invoker {invoker}, source {source}): {Message}",
                                       expr, FileName, Associate?.Name ?? "none", invoker?.Name ?? "none", source?.Name ?? "none", error_msg);
                //Disabled = true;
                CompilationError = ex.ToString();
                LastRuntimeError = error_msg;
                return(false);
            }
            return(true);
        }
예제 #12
0
        public void New(string template, string expected)
        {
            var sut = new Compiled(template);

            var res = sut.Expand(Params);

            Assert.AreEqual(expected, res);
        }
예제 #13
0
        public Macro(string name, string macro)
        {
            Name      = name;
            AreErrors = false;
            var compiler = new CompileCsMacro();

            Compiled      = compiler.Compile(macro);
            AreErrors     = compiler.Error != "";
            MacroDelegate = null;
            if (AreErrors)
            {
                Errors = compiler.Tokens.Where(t => t.TokenType == TokenType.Error).Select(t => t.Value).Append("--")
                         .Append(compiler.Error).ToArray();
                return;
            }

            var options = ScriptOptions.Default
                          .AddReferences(GetReferences().ToArray())
                          .AddImports(GetImports().ToArray());
            var script = CSharpScript.Create <bool>(Compiled, globalsType: typeof(T), options: options);

            try
            {
                MacroDelegate = script.CreateDelegate();
            }
            catch (CompilationErrorException cex)
            {
                var compiledlines = Compiled.Split('\n');
                var er            = new List <string>();
                er.Add("Macro C# syntax error:");
                er.Add(cex.Message);
                foreach (var d in cex.Diagnostics)
                {
                    er.Add(d.GetMessage());
                    var lp    = d.Location.GetLineSpan();
                    var lines = compiledlines.Skip(lp.StartLinePosition.Line)
                                .Take(lp.EndLinePosition.Line - lp.StartLinePosition.Line + 1);
                    er.AddRange(lines);
                }

                Errors = er.ToArray();
                throw new Exception(string.Join(Environment.NewLine, Errors));
            }
            catch (Exception ex)
            {
                var er = new List <string>();
                er.Add("Macro C# syntax error:");
                er.Add(ex.Message);
                var ie = ex.InnerException;
                while (ie != null)
                {
                    er.Add(ie.Message);
                    ie = ie.InnerException;
                }
                Errors = er.ToArray();
                throw new Exception(string.Join(Environment.NewLine, Errors));
            }
        }
예제 #14
0
        /// <summary>
        /// Create the necessary output folders
        /// </summary>
        private void Create()
        {
            _Logger.Log(string.Format(Messages.Msg_PreparingDeployFoldersAndFilesForStaging, FolderNameConstants.DEPLOY));

            // __DEPLOY__ should already exist by this point
            Compiled.CreateRootOnly();
            Staging.CreateFolders();
            Final.CreateFolders();
        }
예제 #15
0
            protected override string OnCompile(string file)
            {
                Compiled?.Invoke(this, file);

                var compiledFile = Path.GetTempFileName();

                File.WriteAllText(compiledFile, nameof(MockCompiler));

                return(compiledFile);
            }
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  leftToken = currentToken.Value;
            string leftName  = leftToken.value;

            currentToken = currentToken.Next;
            Token operatorToken = currentToken.Value;

            currentToken = currentToken.Next;
            Token  rightToken = currentToken.Value;
            string rightName  = rightToken.value;

            if (leftToken.type == TokenType.Number)
            {
                leftName = CompiledStatement.getUniqueId();
                Compiled.Add(new DirectFunctionCallNode("ConstantToReturn", leftToken.value));
                Compiled.Add(new DirectFunctionCallNode("ReturnToVariable", leftName));
            }

            if (rightToken.type == TokenType.Number)
            {
                rightName = CompiledStatement.getUniqueId();
                Compiled.Add(new DirectFunctionCallNode("ConstantToReturn", leftToken.value));
                Compiled.Add(new DirectFunctionCallNode("ReturnToVariable", rightName));
            }

            switch (operatorToken.type)
            {
            case TokenType.Equals:
                Compiled.Add(new FunctionCallNode("AreEqual", leftName, rightName));
                break;

            case TokenType.SmallerThan:
                Compiled.Add(new FunctionCallNode("IsSmaller", leftName, rightName));
                break;

            case TokenType.Largerthan:
                Compiled.Add(new FunctionCallNode("IsLarger", leftName, rightName));
                break;

            case TokenType.SmallerOrEqualThan:
                Compiled.Add(new FunctionCallNode("IsSmallerOrEqual", leftName, rightName));
                break;

            case TokenType.LargerOrEqualThan:
                Compiled.Add(new FunctionCallNode("IsLargerOrEqual", leftName, rightName));
                break;

            default:
                break;
            }
            currentToken = currentToken.Next;
            return(Compiled);
        }
예제 #17
0
        public static IEnumerable <Runtime.ISolutionTreeNode> Solve (Compiled.Program program, out Tracer tracer, params AST.Goal [] goals)
        {
            var engine = new Runtime.Engine ();

            tracer = new Tracer();
            //engine.NewGoal += tracer.Engine_NewGoal;
            //engine.Unified += tracer.Engine_Unified;
            //engine.Failed  += tracer.Engine_Failed;

            return Compiler.Solve (engine, goals, program);
        }
예제 #18
0
 /// <summary>
 /// Creates text matching pattern similar to SQL LIKE.
 /// </summary>
 /// <param name="pattern">Pattern string.</param>
 /// <param name="comparisonType">One of the enumeration values that determines how this string and value are compared.</param>
 public TextPattern(string pattern, StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase)
 {
     if (String.IsNullOrEmpty(pattern))
     {
         throw new ArgumentException("Pattern cannot be empty.");
     }
     Pattern        = pattern;
     ComparisonType = comparisonType;
     Compiled       = Compile(Pattern).ToArray();
     FixedParts     = Compiled.Where(i => i.IsFixed).Select(i => i.Value).ToArray();
 }
예제 #19
0
        /// <summary>Ensures each globals FieldInfo and each functions MethodInfo is correct.</summary>
        public void CollectMethods()
        {
            // Get all the fields and methods from the main type:
            Type type = Compiled.GetType(EngineName + "_EntryPoint");

            if (GlobalSection_ != null)
            {
                FieldInfo[] globalFields = type.GetFields();

                // Quick ref to globals array:
                GlobalVariable[] globals = GlobalSection_.Globals;

                // For each global..
                for (int i = 0; i < globalFields.Length; i++)
                {
                    // Get the ID from the name:
                    string name = globalFields[i].Name;

                    if (name.StartsWith("global_"))
                    {
                        // Get the index as a number:
                        int index = int.Parse(name.Substring(7));

                        // Apply the fieldInfo:
                        globals[index].Field = globalFields[i];
                    }
                }
            }

            if (TypeSection_ != null)
            {
                FuncType[] methods = TypeSection_.Types;

                // Get all the methods:
                MethodInfo[] availableMethods = type.GetMethods();

                for (int i = 0; i < availableMethods.Length; i++)
                {
                    // Get the ID from the name:
                    string name = availableMethods[i].Name;

                    if (name.StartsWith("Func_"))
                    {
                        // Get the index as a number:
                        int index = int.Parse(name.Substring(5));

                        // Apply the MethodInfo:
                        methods[index].Signature_ = availableMethods[i];
                    }
                }
            }
        }
예제 #20
0
        public void New(string template)
        {
            var expander = new Compiled(template).Compile();

            var st = Stopwatch.StartNew();

            for (var i = 0; i < _iterations; ++i)
            {
                expander.Expand(Standards.Params);
            }

            st.Stop();
            Console.WriteLine(st.Elapsed);
            Assert.Less(st.Elapsed, _limit);
        }
예제 #21
0
        public bool ExecuteFunction(string functionName)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                if (HasFunction(functionName))
                {
                    Compiled.Globals["utility"] = typeof(HybrasylUtility);
                    // Provide extra information when running spawn/load to aid in debugging
                    if (functionName == "OnSpawn" || functionName == "OnLoad")
                    {
                        string assoc = null;
                        if (Associate != null)
                        {
                            assoc = $"{Associate.Type}";
                            if (!string.IsNullOrEmpty(Associate.Name))
                            {
                                assoc = $"{assoc} {Associate.Name}";
                            }
                            assoc = $"{assoc}: {Associate.LocationDescription}";
                        }
                        GameLog.ScriptingInfo($"{FileName}: (associate is {assoc ?? "none"}), executing {functionName}");
                    }
                    Compiled.Call(Compiled.Globals[functionName]);
                }
                else
                {
                    //GameLog.ScriptingWarning("ExecuteFunction: function {fn} in {FileName} did not exist",
                    //    functionName, FileName);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Game.ReportException(ex);
                var error_msg = HumanizeException(ex);
                GameLog.ScriptingError("ExecuteFunction: Error executing function {fn} in {FileName} (associate {associate}): {Message}",
                                       functionName, FileName, Associate?.Name ?? "none", error_msg);
                CompilationError = error_msg;
                return(false);
            }

            return(true);
        }
예제 #22
0
        public void ProcessRequest(HttpContext context)
        {
            if (lp == null)
            {
                lp = Helpers.Provider as IronSchemeLanguageProvider;
                se = lp.GetEngine();
                RuntimeExtensions.Eval("(library-path (cons {0} (library-path)))", context.Server.MapPath("~/lib"));
                compiled.Clear();
            }

            if (!File.Exists(context.Request.PhysicalPath))
            {
                if (context.Request.AppRelativeCurrentExecutionFilePath == "~/process-routes.ss")
                {
                    if (process_routes == null)
                    {
                        Callable     eval = Builtins.SymbolValue(SymbolTable.StringToObject("eval-r6rs")) as Callable;
                        StringReader r    = new StringReader("(eval 'process-request (environment '(ironscheme web routing)))");

                        process_routes = eval.Call(Builtins.Read(r)) as Callable;
                    }
                    process_routes.Call();
                }
                else
                {
                    context.Response.StatusCode = 404;
                }
                return;
            }


            Compiled cc;

            lock (GLOBALLOCK)
            {
                if (!compiled.TryGetValue(context.Request.PhysicalPath, out cc) || cc.Time < File.GetLastWriteTime(context.Request.PhysicalPath) || cc.Closure == null)
                {
                    Callable ccc = se.Evaluate(string.Format("(compile->closure \"{0}\")", context.Request.PhysicalPath.Replace('\\', '/'))) as Callable;
                    cc         = new Compiled();
                    cc.Time    = DateTime.Now;
                    cc.Closure = ccc;

                    compiled[context.Request.PhysicalPath] = cc;
                }
            }

            cc.Closure.Call();
        }
예제 #23
0
        Frame Unify (Compiled.Clause clause)
        {
            var boundVariables = new BoundVariableSet ();
            var argumentInstantiator = new ArgumentInstantiator ();

            var clauseHeadArguments = clause.Head.Arguments.Select (a => a.Accept(argumentInstantiator)).ToArray();

            if (boundVariables.ZipUnify (Arguments, clauseHeadArguments))
            {
                Goal [] goals = EngineInternals.InstantiateGoals (clause.Body, argumentInstantiator);

                return new Frame (goals, this, boundVariables, argumentInstantiator.Variables);
            }

            return null;
        }
예제 #24
0
    public void ProcessRequest(HttpContext context)
    {
      if (lp == null)
      {
        lp = Helpers.Provider as IronSchemeLanguageProvider;
        se = lp.GetEngine();
        compiled.Clear();
      }

      if (!File.Exists(context.Request.PhysicalPath))
      {
        if (context.Request.AppRelativeCurrentExecutionFilePath == "~/process-routes.ss")
        {
          if (process_routes == null)
          {
            Callable eval = Builtins.SymbolValue(SymbolTable.StringToObject("eval-r6rs")) as Callable;
            StringReader r = new StringReader("(eval 'process-request (environment '(ironscheme web routing)))");

            process_routes = eval.Call(Builtins.Read(r)) as Callable;
          }
          process_routes.Call();
        }
        else
        {
          context.Response.StatusCode = 404;
        }
        return;
      }


      Compiled cc;

      lock (GLOBALLOCK)
      {
        if (!compiled.TryGetValue(context.Request.PhysicalPath, out cc) || cc.Time < File.GetLastWriteTime(context.Request.PhysicalPath) || cc.Closure == null)
        {
          Callable ccc = se.Evaluate(string.Format("(compile->closure \"{0}\")", context.Request.PhysicalPath.Replace('\\', '/'))) as Callable;
          cc = new Compiled();
          cc.Time = DateTime.Now;
          cc.Closure = ccc;

          compiled[context.Request.PhysicalPath] = cc;
        }
      }

      cc.Closure.Call();
    }
예제 #25
0
        public TResults Execute <TResults>(string className, string methodName, params object[] parameters)
        {
            if (Compiled != null)
            {
                Compiled.Execute(Scope);
            }
            else
            {
                Source.Execute(Scope);
            }
            var classObj      = Scope.GetVariable(className);
            var classInstance = Operations.Call(classObj);
            var classMethod   = Operations.GetMember(classInstance, methodName);
            var results       = (TResults)Operations.Call(classMethod, parameters);

            return(results);
        }
예제 #26
0
        public static void ExpressionSchemaToBinary(List <String> DataDirs, String BinaryPath)
        {
            var ExpressionSchema = GetExpressionSchema();
            var eal = new ExpressionAssemblyLoader(ExpressionSchema);

            foreach (var DataDir in DataDirs)
            {
                foreach (var tf in Directory.EnumerateFiles(DataDir, "*.tree", SearchOption.AllDirectories))
                {
                    eal.LoadAssembly(tf);
                }
            }
            var a  = eal.GetResult();
            var bs = BinarySerializerWithString.Create();

            Byte[] Compiled;
            using (var ms = Streams.CreateMemoryStream())
            {
                bs.Write(a, ms);
                ms.Position = 0;
                Compiled    = ms.Read((int)(ms.Length));
            }
            if (File.Exists(BinaryPath))
            {
                Byte[] Original;
                using (var fs = Streams.OpenReadable(BinaryPath))
                {
                    Original = fs.Read((int)(fs.Length));
                }
                if (Compiled.SequenceEqual(Original))
                {
                    return;
                }
            }
            var BinaryDir = FileNameHandling.GetFileDirectory(BinaryPath);

            if (BinaryDir != "" && !Directory.Exists(BinaryDir))
            {
                Directory.CreateDirectory(BinaryDir);
            }
            using (var fs = Streams.CreateWritable(BinaryPath))
            {
                fs.Write(Compiled);
            }
        }
예제 #27
0
 public virtual MetadataReference ToMetadataReference()
 {
     try
     {
         return(MetadataReference.CreateFromFile(Compiled.Location));
     }
     catch (Exception)
     {
         try
         {
             return(MetadataReference.CreateFromImage(Compiled.SerializeBinary()));
         }
         catch (Exception)
         {
             throw;
         }
     }
 }
예제 #28
0
        /// <summary>
        /// Load the script from disk, recompile it into bytecode, and execute it.
        /// </summary>
        /// <returns>boolean indicating whether the script was reloaded or not</returns>
        public bool Load()
        {
            string scriptText;

            try
            {
                scriptText = File.ReadAllText(Path);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Couldn't open script {0}: {1}", Path, e.ToString());
                Disabled         = true;
                CompilationError = e.ToString();
                return(false);
            }

            scriptText = //HybrasylScriptProcessor.RestrictStdlib
                         HybrasylScriptProcessor.HybrasylImports + scriptText;

            Source =
                Processor.Engine.CreateScriptSourceFromString(scriptText);

            Name = System.IO.Path.GetFileName(Path).ToLower();

            try
            {
                Compile();
                Compiled.Execute(Scope);
                Disabled = false;
            }
            catch (Exception e)
            {
                var pythonFrames    = PythonOps.GetDynamicStackFrames(e);
                var exceptionString = Processor.Engine.GetService <ExceptionOperations>().FormatException(e);
                Logger.ErrorFormat("script {0} encountered error, Python stack follows", Path);
                Logger.ErrorFormat("{0}", exceptionString);
                Disabled         = true;
                CompilationError = exceptionString;
                return(false);
            }
            return(true);
        }
예제 #29
0
        /// <summary>
        /// Execute the script in the passed scope.
        /// </summary>
        /// <param name="scope">The ScriptScope the script will execute in.</param>
        public void ExecuteScript(WorldObject caller = null)
        {
            dynamic resolvedCaller;

            if (caller != null)
            {
                if (caller is User)
                {
                    resolvedCaller = new HybrasylUser(caller as User);
                }
                else
                {
                    resolvedCaller = new HybrasylWorldObject(caller);
                }
                Scope.SetVariable("npc", resolvedCaller);
            }

            Scope.SetVariable("world", Processor.World);
            Compiled.Execute(Scope);
        }
예제 #30
0
파일: Script.cs 프로젝트: Jinori/server
        public DynValue ExecuteAndReturn(string expr, dynamic invoker)
        {
            if (Disabled)
            {
                return(DynValue.Nil);
            }

            try
            {
                Compiled.Globals["utility"] = typeof(HybrasylUtility);
                Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                return(Compiled.DoString(expr));
            }
            catch (Exception ex) when(ex is InterpreterException)
            {
                GameLog.ScriptingError("{Function}: Error executing expression: {expr} in {FileName} (invoker {Invoker}): {Message}",
                                       MethodBase.GetCurrentMethod().Name, expr, FileName, invoker.Name,
                                       (ex as InterpreterException).DecoratedMessage);
                //Disabled = true;
                CompilationError = ex.ToString();
                return(DynValue.Nil);
            }
        }
예제 #31
0
        public IEnumerable <ISolutionTreeNode> Solve (Compiled.Goal [] goalDefs)
        {
            solution = null;

            if (Start != null)
            {
                Start ();
            }

            var engine = new EngineInternals ();

            foreach (var @event in engine.Solve (goalDefs))
            {
                @event.Accept (this);

                if (solution != null)
                {
                    yield return solution.Tree;

                    solution = null;
                }
            }
        }
예제 #32
0
파일: Script.cs 프로젝트: Jinori/server
        public bool ExecuteFunction(string functionName, dynamic invoker, dynamic source, dynamic scriptItem = null)
        {
            if (Disabled)
            {
                return(false);
            }

            try
            {
                if (HasFunction(functionName))
                {
                    Compiled.Globals["utility"] = typeof(HybrasylUtility);
                    Compiled.Globals.Set("invoker", GetUserDataValue(invoker));
                    Compiled.Globals.Set("source", GetUserDataValue(source));
                    if (scriptItem != null)
                    {
                        Compiled.Globals.Set("item", GetUserDataValue(scriptItem));
                    }
                    Compiled.Call(Compiled.Globals[functionName]);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex) when(ex is InterpreterException)
            {
                GameLog.ScriptingError("{Function}: Error executing function {ScriptFunction} in {FileName} (invoker {Invoker}): {Message}",
                                       MethodBase.GetCurrentMethod().Name, functionName, FileName, invoker.Name,
                                       (ex as InterpreterException).DecoratedMessage);
                //Disabled = true;
                CompilationError = ex.ToString();
                return(false);
            }
            return(true);
        }
예제 #33
0
        /// <summary>
        /// Load the script from disk and execute it.
        /// </summary>
        /// <param name="onLoad">Whether or not to execute OnLoad() if it exists in the script.</param>
        /// <returns>boolean indicating whether the script was reloaded or not</returns>
        public bool Run(bool onLoad = true)
        {
            try
            {
                Compiled.Globals["Gender"]      = UserData.CreateStatic <Xml.Gender>();
                Compiled.Globals["LegendIcon"]  = UserData.CreateStatic <LegendIcon>();
                Compiled.Globals["LegendColor"] = UserData.CreateStatic <LegendColor>();
                Compiled.Globals["Class"]       = UserData.CreateStatic <Xml.Class>();
                Compiled.Globals["utility"]     = typeof(HybrasylUtility);
                Compiled.Globals.Set("world", UserData.Create(Processor.World));
                Compiled.Globals.Set("logger", UserData.Create(new ScriptLogger(Name)));
                Compiled.Globals.Set("this_script", DynValue.NewString(Name));
                // Load file into RawSource so we have access to it later
                RawSource = File.ReadAllText(FullPath);
                Compiled.DoFile(FullPath);
                if (onLoad)
                {
                    GameLog.ScriptingInfo($"Loading: {Path.GetFileName(FullPath)}");
                    ExecuteFunction("OnLoad");
                }
            }
            catch (Exception ex)
            {
                Game.ReportException(ex);
                var error_msg = HumanizeException(ex);
                GameLog.ScriptingError("Run: Error executing script {FileName} (associate {assoc}): {Message}",
                                       FileName, Associate?.Name ?? "none", error_msg);

                Disabled         = true;
                CompilationError = ex.ToString();
                LastRuntimeError = error_msg;
                return(false);
            }

            return(true);
        }
예제 #34
0
        private static async Task <Compiled> CompileAsync(string code)
        {
            string[]               lines             = code.Split('\n');
            List <string>          actualLines       = new List <string>();
            List <string>          dependenciesNames = new List <string>();
            List <CSLogicProvider> assemblies        = new List <CSLogicProvider>();

            foreach (var l in lines)
            {
                string trimmed = l.Trim();
                if (trimmed.StartsWith("#reference"))
                {
                    //# reference shared
                    trimmed = trimmed.Remove(0, 10).Trim();
                    dependenciesNames.Add(trimmed);
                    var t = AsyncFactory(trimmed);
                    assemblies.Add(await t);
                }
                else
                {
                    actualLines.Add(l);
                }
            }
            code = string.Join("\n", actualLines);

            Assembly assembly = null;

            byte[] binary = null;
            await Task.Run(() =>
            {
                //https://stackoverflow.com/questions/137933/what-is-the-best-scripting-language-to-embed-in-a-c-sharp-desktop-application
                // Create a code provider
                // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)
                // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that
                // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)
                Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
                // Setup our options
                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable = false;                 // we want a Dll (or "Class Library" as its called in .Net)
                options.GenerateInMemory   = false;


                //			Directory.CreateDirectory("logicAssemblies");
                //			options.OutputAssembly = Path.Combine("logicAssemblies",assemblyName+".dll");

                //options.TreatWarningsAsErrors = true;
                // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
                // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
                // thus they can only do the things you want them to.
                // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
                // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another
                // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
                // the "script"
                options.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location);
                options.ReferencedAssemblies.Add(typeof(VectorMath.Vec3).Assembly.Location);
                options.ReferencedAssemblies.Add(typeof(EntityChange.Abstract).Assembly.Location);
                options.ReferencedAssemblies.Add(typeof(Base.Box).Assembly.Location);
                foreach (var a in assemblies)
                {
                    options.ReferencedAssemblies.Add(a.Assembly.Location);
                }

                var result = csProvider.CompileAssemblyFromSource(options, code);
                if (result.Errors.HasErrors)
                {
                    throw new CompilationException("Unable to compile logic: " + result.Errors[0]);
                }
                assembly = result.CompiledAssembly;
                binary   = File.ReadAllBytes(result.PathToAssembly);
                lock (loadedAssemblies)
                    loadedAssemblies[new BinaryKey(binary)] = assembly;
                //foreach (var f in result.TempFiles)
                //{
                //	System.Console.WriteLine(f);
                //	File.Delete(f.ToString());
                //}
                //if (result.Errors.HasWarnings)
                //Log.Message("Warning while loading logic '" + ScriptName + "': " + FirstWarning);
            });

            Compiled rs = new Compiled();

            rs.assembly         = assembly;
            rs.compiledAssembly = binary;
            rs.dependencies     = new Dependency[assemblies.Count];
            for (int i = 0; i < assemblies.Count; i++)
            {
                var a = assemblies[i];
                rs.dependencies[i] = new Dependency(dependenciesNames[i], Task.Run(() => a));
            }
            return(rs);
        }
예제 #35
0
// ReSharper disable ParameterTypeCanBeEnumerable.Global
        internal static Goal [] InstantiateGoals (Compiled.Goal [] goalDefs, ArgumentInstantiator argumentInstantiator)
// ReSharper restore ParameterTypeCanBeEnumerable.Global
        {
            return goalDefs.Select (goalDef => CreateGoal (argumentInstantiator, goalDef)).ToArray ();
        }
예제 #36
0
        private static void AssertExternalPredicateSolutionIsCorrect (AST.Goal goal, Compiled.Program program)
        {
            var solutions = Helper.GetSolutions (goal, program);

            var variables = solutions.Single();

            Assert.AreEqual ("john", ((Runtime.Atom) variables ["X"]).Name);
        }
예제 #37
0
 public static IEnumerable <Runtime.ISolutionTreeNode> Solve (AST.Goal goal, Compiled.Program program)
 {
     return Compiler.Solve (new Runtime.Engine (), new [] {goal}, program);
 }
예제 #38
0
        private static Goal CreateGoal (ArgumentInstantiator visitor, Compiled.Goal goalDef)
        {
            var arguments = goalDef.Arguments.Select(a => a.Accept(visitor)).ToArray();

            var predicate = goalDef.Predicate;

            var goal = predicate.Accept (new GoalInstantiator ());

            goal.Arguments = arguments;
            goal.Definition = goalDef;

            goal.Restart ();

            return goal;
        }
예제 #39
0
 public IEnumerable <IDebugEvent> Run (Compiled.Program program)
 {
     return Solve (program.GetStartupGoal ());
 }
예제 #40
0
 public IEnumerable <ISolutionTreeNode> Run (Compiled.Program program)
 {
     return Solve (program.GetStartupGoal ());
 }
예제 #41
0
 private void OnCompiled(CompileEventArgs e)
 {
     Compiled?.Invoke(this, e);
 }
예제 #42
0
        public static IEnumerable <Dictionary <string, Runtime.IConcreteValue>> GetSolutions (AST.Goal goal, Compiled.Program program)
        {
            var solutions = Solve (goal, program);

            return solutions.Select(GetTopLevelVariables);
        }
예제 #43
0
        public static IEnumerable <Runtime.ISolutionTreeNode> Solve (Runtime.Engine engine, AST.Goal [] goals, Compiled.Program program)
        {
            Compiled.Goal[] compiledGoals = Compile (goals, program.predicatesByName);

            return engine.Solve (compiledGoals);
        }
예제 #44
0
 public PrologGoal (Compiled.PrologPredicate predicate)
 {
     this.predicate = predicate;
 }