コード例 #1
1
ファイル: PythonSingleLayer.cs プロジェクト: prefab/code
        public PythonSingleLayer(PythonScriptHost host, string code, string name)
        {
            Name = name;
            Code = code;
            Host = host;

            string[] codeWithoutWhitespace = code.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string alltokens = "";

            foreach (string token in codeWithoutWhitespace)
            {
                alltokens += token;
            }

            _id = alltokens.GetHashCode().ToString();

            _scope = host.CreateScriptSource(code, name);

            if (_scope.ContainsVariable(_processannotations))
            {
                _processAnnotationsFunc = _scope.GetVariable(_processannotations);
            }

            if (_scope.ContainsVariable(_interpret))
            {
                _interpretFunc = _scope.GetVariable(_interpret);
            }
        }
コード例 #2
0
        public PythonSingleLayer(PythonScriptHost host, string code, string name)
        {
            Name = name;
            Code = code;
            Host = host;

            string[] codeWithoutWhitespace = code.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string   alltokens             = "";

            foreach (string token in codeWithoutWhitespace)
            {
                alltokens += token;
            }

            _id = alltokens.GetHashCode().ToString();

            _scope = host.CreateScriptSource(code, name);

            if (_scope.ContainsVariable(_processannotations))
            {
                _processAnnotationsFunc = _scope.GetVariable(_processannotations);
            }

            if (_scope.ContainsVariable(_interpret))
            {
                _interpretFunc = _scope.GetVariable(_interpret);
            }
        }
コード例 #3
0
ファイル: PythonScope.cs プロジェクト: RoadieRich/centipede
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool TryGetVariable <T>(string name, out T value)
        {
            bool exists = Scope.ContainsVariable(name);

            value = exists ? this.Scope.GetVariable <T>(name) : default(T);
            return(exists);
        }
コード例 #4
0
    void AddPort(string portName)
    {
        ComPort comPort = comPorts.GetPort(portName);

        if (comPort != null && !m_scope.ContainsVariable(portName))
        {
            Debug.Log(portName + " added to scope");
            m_scope.SetVariable(portName, comPort);
        }
    }
コード例 #5
0
 public void SetScope(Dictionary <string, object> variableCollection)
 {
     foreach (var kvp in variableCollection)
     {
         if (_scope.ContainsVariable(kvp.Key))
         {
             Log("An variable with the name" + kvp.Key + " already exists");
             return;
         }
         _scope.SetVariable(kvp.Key, kvp.Value);
     }
 }
コード例 #6
0
        public void UnqualifiedMultipleAssign()
        {
            ScriptScope scope = this.engine.CreateScope();

            this.engine.Execute <AType>("b:=a:=6", scope);

            Assert.IsTrue(scope.ContainsVariable(".a"), "Variable not found");
            Assert.AreEqual(AInteger.Create(6), scope.GetVariable <AType>(".a"), "Incorrect value assigned");

            Assert.IsTrue(scope.ContainsVariable(".b"), "Variable not found");
            Assert.AreEqual(AInteger.Create(6), scope.GetVariable <AType>(".b"), "Incorrect value assigned");
        }
コード例 #7
0
        public void ContextTest()
        {
            ScriptScope scope = this.engine.CreateScope();

            this.engine.Execute <AType>("a:=5\n$cx X\na:=6", scope);

            Assert.IsTrue(scope.ContainsVariable(".a"), "Variable not found");
            Assert.AreEqual(AInteger.Create(5), scope.GetVariable <AType>(".a"));

            Assert.IsTrue(scope.ContainsVariable("X.a"), "Variable not found");
            Assert.AreEqual(AInteger.Create(6), scope.GetVariable <AType>("X.a"));
        }
コード例 #8
0
        /// <summary>
        /// Find all import statements and import into scope.  If the type is already in the scope, this will be skipped.
        /// The ImportedTypes dictionary is
        /// </summary>
        /// <param name="code">The code to discover the import statements.</param>
        public void UpdateImportedTypes(string code)
        {
            // look all import statements
            var imports = FindBasicImportStatements(code)
                          .Union(FindTypeSpecificImportStatements(code))
                          .Union(FindAllTypeImportStatements(code));

            // try and load modules into python scope
            foreach (var import in imports)
            {
                if (_scope.ContainsVariable(import.Key))
                {
                    continue;
                }
                try
                {
                    _scope.Engine.CreateScriptSourceFromString(import.Value, SourceCodeKind.SingleStatement)
                    .Execute(this._scope);
                    var type = Type.GetType(import.Key);
                    this.ImportedTypes.Add(import.Key, type);
                }
                catch
                {
                    Console.WriteLine();
                }
            }
        }
コード例 #9
0
        public void ContainsVariable_BasicLookup()
        {
            ScriptScope scope = _testEng.CreateScope();

            scope.SetVariable("v1", 1);
            Assert.IsTrue(scope.ContainsVariable("v1"));
        }
コード例 #10
0
        public void ContainVariable_NameLengthGT256WithNonExistingName()
        {
            ScriptScopeDictionary global = new ScriptScopeDictionary();

            // Populate with some test data
            // string > 20
            string[] key           = { "test123456789ABCDEFGHIJ", "test2", "test3" };
            int      tExpectedVal1 = 1111;

            global[key[0]] = tExpectedVal1;
            int tExpectedVal2 = 2222;

            global[key[1]] = tExpectedVal2;

            int           BigValueToTestBeyond = 256;
            StringBuilder longStrTest          = new StringBuilder("test_var_");

            for (int i = 0; i < BigValueToTestBeyond + 1; i++)
            {
                longStrTest.Append(string.Format("{0}", i));
            }

            string tLongKey = longStrTest.ToString();

            // Validate that this key is longer then 256
            Assert.IsTrue(tLongKey.Length > BigValueToTestBeyond);

            // Get default scope with set values
            ScriptScope TestScope = _testEng.CreateScope(new ObjectDictionaryExpando(global));

            // Lookup Long key
            Assert.IsFalse(TestScope.ContainsVariable(tLongKey));
        }
コード例 #11
0
 void CallMethod(string methodName)
 {
     if (scope.ContainsVariable(methodName))
     {
         scope.GetVariable <System.Action>(methodName).Invoke();
     }
 }
コード例 #12
0
        public void RubyHosting1B()
        {
            ScriptScope scope = Engine.CreateScope();

            scope.SetVariable("SomeValue", 1);
            scope.SetVariable("other_value", 2);

            // Method names are unmangled for scope lookups.
            // "tmp" is defined in the top-level binding, which is associated with the scope:
            Engine.Execute("tmp = some_value + other_value", scope);

            // "tmp" symbol is extracted from scope's top-level binding and passed to the compiler as a compiler option
            // so that the parser treats it as a local variable.
            string tmpDefined = Engine.Execute <MutableString>("defined?(tmp)", scope).ToString();

            Assert(tmpDefined == "local-variable");

            // The code is eval'd against the existing top-level local scope created by the first execution.
            // tmp2 local is looked up dynamically:
            Engine.Execute("tmp2 = 10", scope);

            // result= is turned into a scope variable assignment in method_missing:
            Engine.Execute("self.result = tmp", scope);

            // If "scope" variable is not defined on "self" and in the DLR scope we alias it for "self":
            Engine.Execute("scope.result += tmp2", scope);

            int result = scope.GetVariable <int>("result");

            Assert(result == 13);

            // Ruby local variables are not exposed:
            Assert(scope.ContainsVariable("tmp") == false);
        }
コード例 #13
0
        public void ContainsVariable_NoDefaultEngineWrongCaseLookup()
        {
            ScriptScope scope = _runtime.CreateScope();

            // One case sensitive var
            scope.SetVariable("v1", 1);
            Assert.IsFalse(scope.ContainsVariable("V1"));
        }
コード例 #14
0
ファイル: PythonVM.cs プロジェクト: parhelia512/nginz
 public dynamic CreateInstance(string name, params object[] args)
 {
     if (!Scope.ContainsVariable(name))
     {
         this.Throw("Cannot find type: {0}", name);
     }
     return(Engine.Operations.CreateInstance(name, args));
 }
コード例 #15
0
 void InitMethod <T>(string methodName, ref T action)
 {
     action = default(T);
     if (m_scope.ContainsVariable(methodName))
     {
         action = m_scope.GetVariable <T> (methodName);
     }
 }
コード例 #16
0
        public void RemoveVariable_WrongCase()
        {
            ScriptScope scope = _PYEng.CreateScope();

            scope.SetVariable("V2", 4);

            Assert.IsFalse(scope.RemoveVariable("v2"));
            Assert.IsTrue((1 == scope.GetVariableCount()) && scope.ContainsVariable("V2"));
        }
コード例 #17
0
ファイル: PyEngine.cs プロジェクト: lionsguard/perenthia
        public static void Call(string className, string methodName, params object[] args)
        {
            ObjectOperations ops = _engine.Operations;

            if (_scope.ContainsVariable(className))
            {
                object @class   = _scope.GetVariable(className);
                object instance = ops.Call(@class);
                if (instance != null)
                {
                    if (ops.ContainsMember(instance, methodName))
                    {
                        object method = ops.GetMember(instance, methodName);
                        ops.Call(method, args);
                    }
                }
            }
        }
コード例 #18
0
        public void CreateScope_PassValidScope()
        {
            ScriptScopeDictionary dict = new ScriptScopeDictionary();

            dict["foo_1"] = 1000;
            dict["foo_2"] = 2000;

            ScriptScope linkedScope = _runtime.CreateScope(new ObjectDictionaryExpando(dict));

            linkedScope.SetVariable("foo_3", 3000);
            linkedScope.SetVariable("foo_4", 4000);

            Assert.IsTrue(linkedScope.IsValid());

            Assert.IsTrue(dict["foo_3"].Equals(3000));
            Assert.IsTrue(dict["foo_4"].Equals(4000));
            Assert.IsTrue(linkedScope.ContainsVariable("foo_1"));
            Assert.IsTrue(linkedScope.ContainsVariable("foo_2"));
        }
コード例 #19
0
        public void GlobalAssignExecuteUni()
        {
            ScriptScope scope    = this.engineUni.CreateScope();
            AType       expected = AInteger.Create(10);
            AType       result   = this.engineUni.Execute <AType>("`X E.* 'b:=10'", scope);

            Assert.IsTrue(scope.ContainsVariable("X.b"), "No variable found in global scope");
            Assert.AreEqual <AType>(expected, scope.GetVariable <AType>("X.b"), "Incorrect result in global variable");
            Assert.AreEqual <AType>(expected, result, "Incorrect result returned");
        }
コード例 #20
0
        private void InitScripting(string scriptName)
        {
            this.engine = Python.CreateEngine();
            this.engine.Runtime.LoadAssembly(typeof(string).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(DiagnosticMonitor).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(RoleEnvironment).Assembly);
            this.engine.Runtime.LoadAssembly(typeof(Microsoft.WindowsAzure.CloudStorageAccount).Assembly);

            this.scope = this.engine.CreateScope();
            engine.CreateScriptSourceFromFile(scriptName).Execute(scope);

            if (scope.ContainsVariable("start"))
                this.pyStart = scope.GetVariable<Func<bool>>("start");

            this.pyRun = scope.GetVariable<Action>("run");

            if (scope.ContainsVariable("stop"))
                this.pyStop = scope.GetVariable<Action>("stop");
        }
コード例 #21
0
        public void FunctionCallVariableLeakInfix()
        {
            ScriptScope scope = this.engine.CreateScope();

            this.engine.Execute <AType>("a{c}: { d:=1; c+1 }", scope);

            AType result = this.engine.Execute <AType>("a 1 ", scope);

            Assert.AreEqual <AType>(AInteger.Create(2), result, "Infix Function call made incorrect calculation");
            Assert.IsFalse(scope.ContainsVariable(".d"), "Variable should NOT exist");
        }
コード例 #22
0
 public object GetObject(string name)
 {
     if (_pyScope.ContainsVariable(name))
     {
         return(_pyScope.GetVariable(name));
     }
     else
     {
         return(null);
     }
 }
コード例 #23
0
        public void Compile_Statement_StatementBoundVar_Test()
        {
            ScriptScope scope = _runTime.CreateScope();

            //Bind a module variable in a statement and then reference it
            _testEng.CreateScriptSourceFromString("pythonvar='This is a python variable'", SourceCodeKind.Statements).Execute(scope);
            CompiledCode e1 = _testEng.CreateScriptSourceFromString("print pythonvar", SourceCodeKind.Statements).Compile();

            TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, "This is a python variable");
            Assert.IsTrue(scope.ContainsVariable("pythonvar"), "Bound variable isn't visible in the module dict");
        }
コード例 #24
0
        public void ExecuteReturnUni()
        {
            ScriptScope scope           = this.engineUni.CreateScope();
            AType       expected_return = AInteger.Create(10);
            AType       expected_a      = AInteger.Create(20);

            AType result = this.engineUni.Execute <AType>("E.* 'a:=20; :=10; b:=30'", scope);

            Assert.IsFalse(scope.ContainsVariable(".b"), "Variable '.b' found in global scope");
            Assert.AreEqual <AType>(expected_a, scope.GetVariable <AType>(".a"), "Incorrect result in global variable");
            Assert.AreEqual <AType>(expected_return, result, "Incorrect result returned");
        }
コード例 #25
0
        private void CreateScriptScope(string tokenName, CancelScriptToken token)
        {
            CreateScriptScope();

            // Add the token to the available elements list
            if (m_Scope.ContainsVariable(tokenName))
            {
                m_Scope.RemoveVariable(tokenName);
            }

            m_Scope.SetVariable(tokenName, token);
        }
コード例 #26
0
        //Attempts to get a variable in the script
        public dynamic getVariable(string name)
        {
            if(scope == null || name == null) return null;

            if(!scope.ContainsVariable(name))
            {
#if ENGINEDEBUG
                Trace.WriteLine(actor.actorName + "'s behavior does not contain " + name);
#endif
                return null;
            }

            dynamic val;
            bool success = scope.TryGetVariable(name, out val);

            if (success == false)
            {
                Trace.WriteLine("Failed to retrieve " + name + " from + " + actor.actorName + "'s behavior");
            }

            return val;
        }
コード例 #27
0
        public void CreateScriptSource_DifferentEncoding_Test()
        {
            List <ScriptSource> sources = CreateSourceListWithDifferentEncodings(_codeSnippets[CodeType.Valid1]);

            foreach (ScriptSource src in sources)
            {
                //Exec the code in a new scope
                ScriptScope scope = _runTime.CreateScope();
                Assert.AreEqual(null, src.Execute(scope));
                Assert.AreEqual(_codeSnippets[CodeType.Valid1], src.GetCode());

                //Verify the scope's contents after execution
                Assert.IsTrue(!scope.ContainsVariable("local"));
                Assert.IsTrue(!scope.ContainsVariable("local2"));
                Assert.IsTrue(scope.ContainsVariable("global2"));
                Assert.IsTrue(scope.ContainsVariable("increment"));
                Assert.AreEqual(4, scope.GetVariable <int>("global1"));

                //Add the identifier to the scope
                scope.SetVariable("srcid", src.Path);
            }

            DeleteTempFiles();
        }
コード例 #28
0
 public ExecutionVariable GetVariable(string v_name)
 {
     if (_variableScope.ContainsVariable(v_name))
     {
         var ev = new ExecutionVariable();
         ev.Name  = v_name;
         ev.Value = _variableScope.GetVariable(v_name);
         ev.Type  = ev.Value.GetType();
         return(ev);
     }
     else
     {
         return(null);
     }
 }
コード例 #29
0
        public static dynamic RunFunction(string key, string functionName, params dynamic[] arguments)
        {
            // Make sure the collection has a script for the specified key.
            if (_scriptLibrary.ContainsKey(key))
            {
                // Return the result of the function if the function exists.
                if (_scope.ContainsVariable(functionName))
                {
                    var function = _scope.GetVariable(functionName);
                    return(function(arguments));
                }
            }

            // Return null if the function could not be run.
            return(null);
        }
コード例 #30
0
        public void FunctionDyadicDoExecute()
        {
            AType expected = AInteger.Create(2);

            ScriptScope scope = this.engine.CreateScope();

            scope.SetVariable(".a", AInteger.Create(500));

            this.engine.Execute <AType>("f{}: { a:=10; `X eval ' (a:=2) do { drop a }'; a }", scope);

            AType result = this.engine.Execute <AType>("f{}", scope);

            Assert.IsFalse(scope.ContainsVariable("X.a"), "Variable is defined in context");
            Assert.AreEqual <AType>(AInteger.Create(500), scope.GetVariable <AType>(".a"), "Incorrect result in global variable");
            Assert.AreEqual <AType>(expected, result, "Incorrect result returned");
        }
コード例 #31
0
        public void FunctionInsideEval()
        {
            AType expected = AInteger.Create(101);

            ScriptScope scope = this.engine.CreateScope();

            scope.SetVariable(".h", 100);

            this.engine.Execute <AType>("f{}: { h:=-10; eval 'g{}: h + 1'; -2 }", scope);
            this.engine.Execute <AType>("f{}", scope);

            Assert.IsTrue(scope.ContainsVariable(".g"), "Function '.g' not defined");

            AType result = this.engine.Execute <AType>("g{}", scope);

            Assert.AreEqual <AType>(expected, result, "Function call made incorrect calculation");
        }
コード例 #32
0
        public override Dictionary <string, object> PollScopeForOutputs(List <string> OutputNames)
        {
            var outdict = new Dictionary <string, object>();

            foreach (var outname in OutputNames)
            {
                if (scope.ContainsVariable(outname))
                {
                    outdict[outname] = scope.GetVariable(outname);
                }
                else
                {
                    outdict[outname] = "No variable named" + outname + "was defined in the python code";
                }
            }
            return(outdict);
        }
コード例 #33
0
ファイル: PythonPlugin.cs プロジェクト: CypressCube/Oxide
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public void Load()
        {
            // Load the plugin
            string code = File.ReadAllText(Filename);
            Name = Path.GetFileNameWithoutExtension(Filename);
            Scope = PythonEngine.CreateScope();
            var source = PythonEngine.CreateScriptSourceFromString(code, Path.GetFileName(Filename), SourceCodeKind.Statements);
            var compiled = source.Compile();
            compiled.Execute(Scope);
            if (!Scope.ContainsVariable(Name)) throw new Exception("Plugin is missing main class");
            Class = PythonEngine.Operations.CreateInstance(Scope.GetVariable(Name));
            PythonEngine.Operations.SetMember(Class, "Name", Name);

            // Read plugin attributes
            if (!PythonEngine.Operations.ContainsMember(Class, "Title") || PythonEngine.Operations.GetMember<string>(Class, "Title") == null) throw new Exception("Plugin is missing title");
            if (!PythonEngine.Operations.ContainsMember(Class, "Author") || PythonEngine.Operations.GetMember<string>(Class, "Author") == null) throw new Exception("Plugin is missing author");
            if (!PythonEngine.Operations.ContainsMember(Class, "Version") || PythonEngine.Operations.GetMember(Class, "Version").GetType() != typeof(VersionNumber)) throw new Exception("Plugin is missing version");
            Title = PythonEngine.Operations.GetMember<string>(Class, "Title");
            Author = PythonEngine.Operations.GetMember<string>(Class, "Author");
            Version = PythonEngine.Operations.GetMember<VersionNumber>(Class, "Version");
            if (PythonEngine.Operations.ContainsMember(Class, "Description")) Description = PythonEngine.Operations.GetMember<string>(Class, "Description");
            if (PythonEngine.Operations.ContainsMember(Class, "ResourceId")) ResourceId = PythonEngine.Operations.GetMember<int>(Class, "ResourceId");
            HasConfig = PythonEngine.Operations.ContainsMember(Class, "HasConfig") && PythonEngine.Operations.GetMember<bool>(Class, "HasConfig") || PythonEngine.Operations.ContainsMember(Class, "LoadDefaultConfig");

            // Set attributes
            PythonEngine.Operations.SetMember(Class, "Plugin", this);

            Globals = PythonEngine.Operations.GetMemberNames(Class);

            foreach (var name in Globals)
            {
                object func;
                if (!PythonEngine.Operations.TryGetMember(Class, name, out func) || !PythonEngine.Operations.IsCallable(func) || !PythonEngine.Operations.ContainsMember(func, "__dict__")) continue;
                var dict = PythonEngine.Operations.GetMember<PythonDictionary>(func, "__dict__");
                if (dict.ContainsKey("isCommand"))
                {
                    var names = ((IList<object>) dict["name"]).Cast<string>().ToArray();
                    var perms = ((IList<object>) dict["permission"]).Cast<string>().ToArray();
                    if (names.Length == 0)
                    {
                        Interface.Oxide.LogWarning("Command is missing name: {0} from plugin: {1}! Skipping...", name, Name);
                        continue;
                    }
                    AddCovalenceCommand(names, perms, (cmd, type, caller, args) =>
                    {
                        PythonEngine.Operations.InvokeMember(Class, name, caller, args);
                        return true;
                    });
                }
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();
        }
コード例 #34
0
        /// <summary>
        /// Check to make sure that two seperate (i.e. not references to same memory) 
        /// ScriptScope objects are equivalent.
        /// 
        /// 1) If they are NOT pointing at the same memory.
        /// 2) If they have the same number of elements and each scope element is the
        ///    same then they are both equal
        internal static bool IsSimilarButNotSameAs(this ScriptScope callingScope, ScriptScope scope)
        {
            // if reference of same object in memory return false
            if (callingScope == scope) return false;

            foreach (string varName in callingScope.GetVariableNames()) {
                if (!scope.ContainsVariable(varName))
                    return false;
                if (scope.GetVariable(varName) != callingScope.GetVariable(varName))
                    return false;
            }

            return true;
        }