public static void Init() { engineScript = Selection.activeGameObject.GetComponent<ScriptEngine> (); EngineWindow window = (EngineWindow)EditorWindow.GetWindow(typeof(EngineWindow)); window.Show (); window.minSize = new Vector2(800.0f, 220.0f); }
/// <summary> /// Initializes a new instance of the PythonPlugin class /// </summary> /// <param name="filename"></param> /// <param name="engine"></param> /// <param name="watcher"></param> internal PythonPlugin(string filename, ScriptEngine engine, FSWatcher watcher) { // Store filename Filename = filename; PythonEngine = engine; this.watcher = watcher; }
private static object __STUB__Next(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is SetIterator)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'next' is not generic."); return ((SetIterator)thisObj).Next(); }
static ScriptEngine CreateScriptEngineWithCoffeeScriptLoaded() { var engine = new ScriptEngine(); engine.Execute(Properties.Resources.coffeescript); engine.Execute("function compile(c) { return CoffeeScript.compile(c); }"); return engine; }
private static object __GETTER__ByteLength(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is ArrayBufferInstance)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'get byteLength' is not generic."); return ((ArrayBufferInstance)thisObj).ByteLength; }
public TestRuntime(Driver/*!*/ driver, TestCase/*!*/ testCase) { _driver = driver; _testName = testCase.Name; if (_driver.SaveToAssemblies) { Environment.SetEnvironmentVariable("DLR_AssembliesFileName", _testName); } var runtimeSetup = ScriptRuntimeSetup.ReadConfiguration(); LanguageSetup languageSetup = null; foreach (var language in runtimeSetup.LanguageSetups) { if (language.TypeName == typeof(RubyContext).AssemblyQualifiedName) { languageSetup = language; break; } } runtimeSetup.DebugMode = _driver.IsDebug; languageSetup.Options["InterpretedMode"] = _driver.Interpret; languageSetup.Options["Verbosity"] = 2; languageSetup.Options["Compatibility"] = testCase.Compatibility; _env = Ruby.CreateRuntime(runtimeSetup); _engine = Ruby.GetEngine(_env); _context = Ruby.GetExecutionContext(_engine); }
private static object __GETTER__ToStringTag(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is SetIterator)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'get [Symbol.toStringTag]' is not generic."); return ((SetIterator)thisObj).ToStringTag; }
public override void Execute(ScriptEngine engine, ScriptScope scope) { if (!string.IsNullOrEmpty(Path)) { engine.ExecuteFile(Path, scope); } }
/// <summary> /// Init the py interpreter /// </summary> public static void Initialize() { pyEngine = Python.CreateEngine(); // Create an engine to access IronPython objOps = pyEngine.CreateOperations(); // Performing tasks with the script scope = pyEngine.CreateScope(); // Default scope for executing the script var paths = pyEngine.GetSearchPaths().ToList(); //paths.Add(PluginEngine.PluginsPyPath); paths.Add(Path.Combine(Folders.ScriptsDirectory, "lib")); if (!string.IsNullOrEmpty(TESVSnip.UI.Services.Options.Value.IronPythonDirectory)) paths.Add(Path.Combine(TESVSnip.UI.Services.Options.Value.IronPythonDirectory, "lib")); pyEngine.SetSearchPaths(paths); var runtime = pyEngine.Runtime; runtime.LoadAssembly(Assembly.GetExecutingAssembly()); runtime.LoadAssembly(typeof(TESVSnip.Framework.TypeConverter).Assembly); runtime.LoadAssembly(typeof(TESVSnip.Domain.Model.BaseRecord).Assembly); runtime.LoadAssembly(typeof(String).Assembly); runtime.LoadAssembly(typeof(IronPython.Hosting.Python).Assembly); runtime.LoadAssembly(typeof(System.Dynamic.DynamicObject).Assembly); watcher = new FileSystemWatcher { Path = Path.GetFullPath(Path.GetDirectoryName(RendererPyPath)), Filter = Path.GetFileNameWithoutExtension(RendererPyPath) + ".*", IncludeSubdirectories = false }; watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; watchedFiles.Add(Path.GetFullPath(RendererPyPath)); watchedFiles.Add(Path.ChangeExtension(RendererPyPath, ".css")); Reload(); }
public static ICollection<string> ReadAllTasks(string path) { var list = new List<string>(); if (path.EndsWith(".ts")) { path = path.Replace(".ts", ".js").Replace(".coffee",".js"); } if (!File.Exists(path)) { return list; } // executes the gulpfile with some little additions :) try { var engine = new ScriptEngine(); engine.Execute(Resources.gulpInit); engine.ExecuteFile(path); // reads the evaluated tasks ArrayInstance names = (ArrayInstance)engine.Evaluate("tasks"); foreach (var elem in names.ElementValues) { list.Add((string)elem); } } catch (Exception) { list.Add("Cannot parse gulpfile"); } return list.Distinct().ToList(); }
public override string ToString(ScriptEngine engine) { string msg = engine.Pad() + "Return" + Environment.NewLine; engine.IndentationLevel += ScriptEngine.PaddingIncrement; msg += engine.Pad() + "LHS:" + Environment.NewLine; { engine.IndentationLevel += ScriptEngine.PaddingIncrement; for (int i = 0; i < _lhs.Count; i++) { msg += _lhs[i].ToString(engine); } engine.IndentationLevel -= ScriptEngine.PaddingIncrement; } msg += engine.Pad() + "RHS:" + Environment.NewLine; { engine.IndentationLevel += ScriptEngine.PaddingIncrement; for (int i = 0; i < _rhs.Count; i++) { msg += _rhs[i].ToString(engine); } engine.IndentationLevel -= ScriptEngine.PaddingIncrement; } engine.IndentationLevel -= ScriptEngine.PaddingIncrement; return msg; }
public TestRuntime(Driver/*!*/ driver, TestCase/*!*/ testCase) { _driver = driver; _testName = testCase.Name; if (testCase.Options.NoRuntime) { return; } if (_driver.SaveToAssemblies) { Environment.SetEnvironmentVariable("DLR_AssembliesFileName", _testName); } var runtimeSetup = ScriptRuntimeSetup.ReadConfiguration(); var languageSetup = runtimeSetup.AddRubySetup(); runtimeSetup.DebugMode = _driver.IsDebug; runtimeSetup.PrivateBinding = testCase.Options.PrivateBinding; languageSetup.Options["NoAdaptiveCompilation"] = _driver.NoAdaptiveCompilation; languageSetup.Options["Verbosity"] = 2; languageSetup.Options["Compatibility"] = testCase.Options.Compatibility; _runtime = Ruby.CreateRuntime(runtimeSetup); _engine = Ruby.GetEngine(_runtime); _context = Ruby.GetExecutionContext(_engine); }
/// <summary> /// Creates a new FunctionContext instance. /// </summary> /// <param name="engine"> The script engine. </param> /// <param name="scope"> The function scope. </param> /// <param name="functionName"> The name of the function. </param> /// <param name="argumentNames"> The names of the arguments. </param> /// <param name="body"> The source code for the body of the function. </param> /// <param name="options"> Options that influence the compiler. </param> public FunctionMethodGenerator(ScriptEngine engine, DeclarativeScope scope, string functionName, IList<string> argumentNames, string body, CompilerOptions options) : base(engine, scope, new StringScriptSource(body), options) { this.Name = functionName; this.ArgumentNames = argumentNames; this.BodyText = body; }
internal void HookUpScript(string scriptLanguage) { if (scriptLanguage == null) { // TODO: Need to revise this, we need to use the InvariantContext here probably // but it can't actually do calls yet. _scriptEngine = _defaultEngine; return; } _scriptEngine = EngineHelper.GetScriptEngineByName(scriptLanguage); _defaultEngine = _defaultEngine ?? _scriptEngine; _templateControlVirtualPath = VirtualPathUtility.ToAbsolute(_templateControl.AppRelativeVirtualPath); // First, look for a code behind file named <pagename>.aspx.<ext>, where 'ext' is the extension // for the page's language _inlineScript = false; IList<string> extensions = _scriptEngine.Setup.FileExtensions; foreach (string extension in extensions) { _scriptVirtualPath = _templateControlVirtualPath + extension; if (HookUpScriptFile()) { return; } } // Then, look for inline script _inlineScript = true; _scriptVirtualPath = _templateControlVirtualPath; HookUpScriptFile(); }
public ResponseInstance(ScriptEngine engine, HttpListenerResponse response) : base(engine) { this.Response = response; this.PopulateFields(); this.PopulateFunctions(); }
public DLREngine(LanguageSettings language, TextWriter output) { Language = language; Output = output; DLREngineFactory factory = new DLREngineFactory(); Engine = factory.CreateEngine(language); }
private static object __STUB__ValueOf(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is SymbolInstance)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'valueOf' is not generic."); return ((SymbolInstance)thisObj).ValueOf(); }
/// <summary> /// Creates a new ClrStaticTypeWrapper object. /// </summary> /// <param name="engine"> The associated script engine. </param> /// <param name="type"> The CLR type to wrap. </param> /// <param name="flags"> <c>BindingFlags.Static</c> to populate static methods; /// <c>BindingFlags.Instance</c> to populate instance methods. </param> private ClrStaticTypeWrapper(ScriptEngine engine, Type type) : base(engine, GetPrototypeObject(engine, type)) { this.WrappedType = type; // Pick up the public constructors, if any. var constructors = type.GetConstructors(); if (constructors.Length > 0) this.constructBinder = new ClrBinder(constructors); else { // The built-in primitive types do not have constructors, but we still want to // allow their construction since there is no way to construct them otherwise. // Pretend that a constructor does exist. switch (Type.GetTypeCode(type)) { case TypeCode.Int32: this.constructBinder = new ClrBinder(ReflectionHelpers.Convert_ToInt32_Double); break; } } this.FastSetProperty("name", type.Name); if (this.constructBinder != null) this.FastSetProperty("length", this.constructBinder.FunctionLength); // Populate the fields, properties and methods. PopulateMembers(this, type, BindingFlags.Static); }
private static void Main() { try { PyEngine = Python.CreateEngine(); NtrClient = new NtrClient(); ScriptHelper = new ScriptHelper(); GlobalScope = PyEngine.CreateScope(); GlobalScope.SetVariable("nc", ScriptHelper); LoadConfig(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); GCmdWindow = new CmdWindow(); Dc = new DebugConsole(); Application.Run(GCmdWindow); } catch (Exception e) { BugReporter br = new BugReporter(e, "Program exception"); MessageBox.Show( @"WARNING - NTRDebugger has encountered an error" + Environment.NewLine + @"This error is about to crash the program, please send the generated" + Environment.NewLine + @"Error log to imthe666st!" + Environment.NewLine + Environment.NewLine + @"Sorry for the inconvinience -imthe666st" ); } }
public JSBlockType(ScriptEngine engine, string name) : base(engine) { this.PopulateFunctions(); this.name = name; }
public PythonScriptReader() { _engine = Python.CreateEngine(); _escope = _engine.CreateScope(); var reader = new StreamReader(new FileStream(@"Scripts\Script.py", FileMode.Open, FileAccess.Read)); string scriptText = reader.ReadToEnd(); reader.Close(); _engine.Execute(scriptText, _escope); if (!_escope.TryGetVariable("GeneratorFunc", out _randomGenerator)) { MessageBox.Show("Error Occurred in Executing python script! - GeneratorFunc", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("userDefinedFunc", out _userDefinedMethod)) { MessageBox.Show("Error Occurred in Executing python script! - userDefinedFunc", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("LifeSpanMapper", out _lifeTimeMapper)) { MessageBox.Show("Error Occurred in Executing python script! - LifeSpanMapper", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("DelayMapper", out _delayTimeMapper)) { MessageBox.Show("Error Occurred in Executing python script! - DelayMapper", "Error"); throw new Exception("Error Occurred in Executing python script!"); } }
private static object __STUB__Call(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is MapConstructor)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'Call' is not generic."); return ((MapConstructor)thisObj).Call(); }
private static List<PropertyNameAndValue> GetDeclarativeProperties(ScriptEngine engine) { return new List<PropertyNameAndValue>(4) { new PropertyNameAndValue(engine.Symbol.Species, new PropertyDescriptor(new ClrStubFunction(engine.FunctionInstancePrototype, "get [Symbol.species]", 0, __GETTER__Species), null, PropertyAttributes.Configurable)), }; }
public override Token Build(Token lastToken, ScriptEngine engine, Script script, ref SourceCode sourceCode) { while ((++sourceCode).SpecialChar) { } if (sourceCode.Peek() != '{') { sourceCode.Throw(String.Format("Error parsing a 'do' statement, expected a '{' but got '{0}' instead.", sourceCode.Peek())); } List<List<List<Token>>> code = engine.BuildLongTokens(ref sourceCode, ref script, new[] {'}'}); if (!sourceCode.SeekToNext("while")) { sourceCode.Throw("Error parsing a 'do' statement, was expecting a 'while' after the { } block."); } if (!sourceCode.SeekToNext('(')) { sourceCode.Throw("Error parsing a 'do' statement, was expecting a '(' after 'while'."); } List<List<Token>> exitCondition = engine.BuildTokensAdvanced(ref sourceCode, ref script, new[] {')'}); return new DoWhileToken(code, exitCondition); }
/// <summary> /// Creates a new JavaScriptException instance. /// </summary> /// <param name="name"> The name of the error, e.g "RangeError". </param> /// <param name="message"> A description of the error. </param> /// <param name="lineNumber"> The line number in the source file the error occurred on. </param> /// <param name="sourcePath"> The path or URL of the source file. Can be <c>null</c>. </param> public JavaScriptException(ScriptEngine engine, string name, string message, int lineNumber, string sourcePath) : base(string.Format("{0}: {1}", name, message)) { this.ErrorObject = CreateError(engine, name, message); this.LineNumber = lineNumber; this.SourcePath = sourcePath; }
internal Meta(ScriptEngine engine, ModelInstance instance) : base(engine, engine.Object.InstancePrototype) { this.PopulateFunctions(); this.instance = instance; this.typeWrapper = new TypeWrapper(engine, instance.Type); }
public RequireJsCompiler(TextWriter consoleOut, string currentDirectory) { _jsEngine = new ScriptEngine(); _jsEngine.CompatibilityMode = CompatibilityMode.ECMAScript3; _jsEngine.Evaluate(LoadResource("require.js")); _jsEngine.Evaluate(LoadResource("json2.js")); _jsEngine.Evaluate(LoadResource(@"adapt\rhino.js")); _jsEngine.Evaluate("require(" + new JavaScriptSerializer().Serialize(new { baseUrl = ResourceBaseUrl }) + ");"); _fs = new NativeFS(_jsEngine, currentDirectory); _jsEngine.SetGlobalValue("YUNoFS", _fs); _path = new NativePath(_jsEngine, currentDirectory); _jsEngine.SetGlobalValue("YUNoPath", _path); _ioAdapter = new IOAdapter(_jsEngine, consoleOut); _jsEngine.SetGlobalFunction("load", (Action<string>)_ioAdapter.load); _jsEngine.SetGlobalValue("ioe", _ioAdapter); _jsEngine.SetGlobalValue("IsRunningYUNoAMD", true); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "env.js", @"build\jslib\env.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "yunoamd/args.js", @"build\jslib\yunoamd\args.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "build.js", @"build\build.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "print.js", @"build\jslib\yunoamd\print.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "fs.js", @"build\jslib\yunoamd\fs.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "path.js", @"build\jslib\yunoamd\path.js"); SetupModuleFromResource(RequireJsCompiler.ResourceBaseUrl + "file.js", @"build\jslib\node\file.js"); }
private static object __GETTER__Species(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is MapConstructor)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'get [Symbol.species]' is not generic."); return ((MapConstructor)thisObj).Species; }
private static object __STUB__ToLocaleString(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is NumberInstance)) throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'toLocaleString' is not generic."); return ((NumberInstance)thisObj).ToLocaleString(); }
private void initRuby() { ScriptRuntimeSetup runtimeSetup = ScriptRuntimeSetup.ReadConfiguration(); var languageSetup = IronRuby.RubyHostingExtensions.AddRubySetup(runtimeSetup); runtimeSetup.DebugMode = false; runtimeSetup.PrivateBinding = false; runtimeSetup.HostType = typeof(RhoHost); languageSetup.Options["NoAdaptiveCompilation"] = false; languageSetup.Options["CompilationThreshold"] = 0; languageSetup.Options["Verbosity"] = 2; m_runtime = IronRuby.Ruby.CreateRuntime(runtimeSetup); m_engine = IronRuby.Ruby.GetEngine(m_runtime); m_context = (RubyContext)Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(m_engine); m_context.ObjectClass.SetConstant("RHO_WP7", 1); m_context.Loader.LoadAssembly("RhoRubyLib", "rho.rubyext.rubyextLibraryInitializer", true, true); System.Collections.ObjectModel.Collection<string> paths = new System.Collections.ObjectModel.Collection<string>(); paths.Add("lib"); paths.Add("apps/app"); m_engine.SetSearchPaths(paths); }
public WindowObject(ScriptEngine engine) : base(engine.Global) { this.PopulateFunctions(); }
public object CsCodeAssembler_Should_Compile_And_Return_Valid_Assembly_Test(string codeBlockName, string codeBlock, string codeBlockReferences) { //ARRANGE IntPtr windowHandle = new IntPtr(); StringBuilder sb_script_core = new StringBuilder(""); var class_name = codeBlockName; //<<--alias for clarity var function_name = "{CLASS}.Run".Replace("{CLASS}", class_name); var code = ""; var code_template = @" //============================================================================= //=={CODEBLOCKNAME} - Unit Test //============================================================================= using System; using System.Drawing; namespace Includes { public interface ITriggerLogic { bool Run(IntPtr windowHandle); } //------------------------------------------------------------------------- public class TriggerLogic : ITriggerLogic { private bool _bln_result = true; private string _error = ""ok""; private string _diagnostics = """"; public TriggerLogic() {;} public bool Result{get{return(_bln_result);}} public string LastError{get{return(_error);}} public string DiagnosticsMessage{get{return(_diagnostics);}} public bool Run(IntPtr windowHandle) { try { {CODEBLOCK} } catch(Exception error) { _error = ""TriggerLogic: fail - {ERROR}."".Replace(""{ERROR}"", error.Message); } return(Result); } } }"; /* * execute VHP's (variable hardpoints), allows us to add token handling to the code builder, can be a one-liner, * but is clearer broken down. Note: order is important. */ code = code_template.Replace("{CODEBLOCK}", codeBlock); code = code.Replace("{CODEBLOCKNAME}", codeBlockName); code = code.Replace("{REFERENCES}", Includes.VoiceBotSupportClasses.Constants.default_references); sb_script_core.Append(code); //ACT var assembly_library_code = ScriptEngine.CsCodeAssembler(windowHandle, codeBlockName, sb_script_core.ToString(), codeBlockReferences); //ASSERT assembly_library_code.ShouldNotBeNull(); return(assembly_library_code != null); }
public object CallFunction_Should_Compile_And_Invoke_Method_And_Return_True_Test(string codeBlockName, string codeBlock, string codeBlockReferences) { //ARRANGE IntPtr windowHandle = new IntPtr(); StringBuilder sb_script_core = new StringBuilder(""); var obj_parameters_array = new object[] { windowHandle }; var class_name = codeBlockName; //<<--alias for clarity var function_name = "Run"; var fullFunction_name = "{CLASS}.{FUNCTION}".Replace("{CLASS}", class_name).Replace("{FUNCTION}", function_name); var code = ""; var fullname = "Includes." + class_name; //var bln_ignore_case = false; var code_template = @" //============================================================================= //=={CODEBLOCKNAME} - Unit Test //============================================================================= using System; using System.Drawing; namespace Includes { public interface ITriggerLogic { bool Run(IntPtr windowHandle); } //------------------------------------------------------------------------- public class TriggerLogic : ITriggerLogic { private bool _bln_result = true; private string _error = ""ok""; private string _diagnostics = """"; public TriggerLogic() {;} public bool Result{get{return(_bln_result);}} public string LastError{get{return(_error);}} public string DiagnosticsMessage{get{return(_diagnostics);}} public bool Run(IntPtr windowHandle) { try { {CODEBLOCK} } catch(Exception error) { _error = ""TriggerLogic: fail - {ERROR}."".Replace(""{ERROR}"", error.Message); } return(Result); } } }"; /* * execute VHP's (variable hardpoints), allows us to add token handling to the code builder, can be a one-liner, * but is clearer broken down. Note: order is important. */ code = code_template.Replace("{CODEBLOCK}", codeBlock); code = code.Replace("{CODEBLOCKNAME}", codeBlockName); code = code.Replace("{REFERENCES}", Includes.VoiceBotSupportClasses.Constants.default_references); sb_script_core.Append(code); var assembly_library_code = ScriptEngine.CsCodeAssembler(windowHandle, codeBlockName, sb_script_core.ToString(), codeBlockReferences); var classInstance = assembly_library_code.CreateInstance(fullname); var type_instance_type = classInstance.GetType(); var method_info = type_instance_type.GetMethods().Where(m => m.Name == function_name).FirstOrDefault(); //ACT object obj_return = method_info.Invoke(classInstance, obj_parameters_array); //ASSERT //<MSTest>Assert.IsTrue((bool)obj_return);//<<--expected object for this test is a bool true for the logic:'_bln_result = ("UnitTest" + "Passes" == "UnitTestPasses");' obj_return.ShouldNotBeNull();//<<--expected object for this test is a bool true for the logic:'_bln_result = ("UnitTest" + "Passes" == "UnitTestPasses");' return(obj_return); }
public object CreateClassInstance_Should_Return_Class_Instance_Test(string codeBlockName, string codeBlock, string codeBlockReferences) { //ARRANGE IntPtr windowHandle = new IntPtr(); StringBuilder sb_script_core = new StringBuilder(""); var obj_parameters_array = new object[] { }; var class_name = codeBlockName; //<<--alias for clarity var function_name = "{CLASS}.Run".Replace("{CLASS}", class_name); var code = ""; var fullname = "Includes." + class_name; var bln_ignore_case = false; var code_template = @" //============================================================================= //=={CODEBLOCKNAME} - Unit Test //============================================================================= using System; using System.Drawing; namespace Includes { public interface ITriggerLogic { bool Run(IntPtr windowHandle); } //------------------------------------------------------------------------- public class TriggerLogic : ITriggerLogic { private bool _bln_result = true; private string _error = ""ok""; private string _diagnostics = """"; public TriggerLogic() {;} public bool Result{get{return(_bln_result);}} public string LastError{get{return(_error);}} public string DiagnosticsMessage{get{return(_diagnostics);}} public bool Run(IntPtr windowHandle) { try { {CODEBLOCK} } catch(Exception error) { _error = ""TriggerLogic: fail - {ERROR}."".Replace(""{ERROR}"", error.Message); } return(Result); } } }"; /* * execute VHP's (variable hardpoints), allows us to add token handling to the code builder, can be a one-liner, * but is clearer broken down. Note: order is important. */ code = code_template.Replace("{CODEBLOCK}", codeBlock); code = code.Replace("{CODEBLOCKNAME}", codeBlockName); code = code.Replace("{REFERENCES}", Includes.VoiceBotSupportClasses.Constants.default_references); sb_script_core.Append(code); System.Reflection.BindingFlags flags = (BindingFlags.Public | BindingFlags.Instance); var assembly_library_code = ScriptEngine.CsCodeAssembler(windowHandle, codeBlockName, sb_script_core.ToString(), codeBlockReferences); dynamic obj_class = (dynamic)ScriptEngine.CreateClassInstance(assembly_library_code, class_name, obj_parameters_array); //ACT var classInstance = assembly_library_code.CreateInstance(fullname, bln_ignore_case, flags, null, obj_parameters_array, null, new object[] { }); //ASSERT //<MSTest>Assert.IsNotNull(classInstance); classInstance.ShouldNotBeNull(); return(classInstance != null); }
public PythonService(PythonContext /*!*/ context, ScriptEngine /*!*/ engine) { Assert.NotNull(context, engine); _context = context; _engine = engine; }
public void TestInitialize() { engine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging); engine.AddHostObject("host", host = new ExtendedHostFunctions()); }
/// <summary> /// Creates a new proxy instance. /// </summary> /// <param name="engine"> The script engine. </param> /// <param name="target"> A target object to wrap with Proxy. It can be any sort of object, /// including a native array, a function, or even another proxy. </param> /// <param name="handler"> An object whose properties are functions that define the /// behavior of the proxy when an operation is performed on it. </param> internal ProxyFunction(ScriptEngine engine, FunctionInstance target, ObjectInstance handler) : base(engine) { this.target = target; this.handler = handler; }
public void TestInitialize() { engine = new V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging); engine.AddHostObject("clr", HostItemFlags.GlobalMembers, new HostTypeCollection("mscorlib", "System", "System.Core")); engine.AddHostObject("host", new HostFunctions()); }
public SPContentTypeListConstructor(ScriptEngine engine) : base(engine.Function.InstancePrototype, "SPContentTypeList", new SPContentTypeListInstance(engine, null)) { }
public RubyEngineManager() { _scriptEngine = IronRuby.Ruby.CreateEngine(); }
public ProjectState(ScriptEngine pythonEngine) { _pythonEngine = pythonEngine; _projectEntries = new List <ProjectEntry>(); _modules = new Dictionary <string, ModuleReference>(); _modulesByFilename = new Dictionary <string, ModuleInfo>(StringComparer.OrdinalIgnoreCase); _itemCache = new Dictionary <object, object>(); var pythonContext = HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext; _codeContextCls = new ModuleContext(new PythonDictionary(), pythonContext).GlobalContext; _codeContextCls.ModuleContext.ShowCls = true; _codeContext = new ModuleContext( new PythonDictionary(), HostingHelpers.GetLanguageContext(_pythonEngine) as PythonContext ).GlobalContext; InitializeBuiltinModules(); // TODO: Use reflection-only! _references = new List <KeyValuePair <Assembly, TopNamespaceTracker> >(); AddAssembly(LoadAssemblyInfo(typeof(string).Assembly)); AddAssembly(LoadAssemblyInfo(typeof(Debug).Assembly)); // cached for quick checks to see if we're a call to clr.AddReference SpecializeFunction("clr", "AddReference", (n, unit, args) => AddReference(n, null)); SpecializeFunction("clr", "AddReferenceByPartialName", (n, unit, args) => AddReference(n, ClrModule.LoadAssemblyByPartialName)); SpecializeFunction("clr", "AddReferenceByName", (n, unit, args) => AddReference(n, null)); SpecializeFunction("clr", "AddReferenceToFile", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFile(_codeContext, s))); SpecializeFunction("clr", "AddReferenceToFileAndPath", (n, unit, args) => AddReference(n, (s) => ClrModule.LoadAssemblyFromFileWithPath(_codeContext, s))); try { SpecializeFunction("wpf", "LoadComponent", LoadComponent); } catch (KeyNotFoundException) { // IronPython.Wpf.dll isn't available... } SpecializeFunction("__builtin__", "range", (n, unit, args) => unit.DeclaringModule.GetOrMakeNodeVariable(n, (nn) => new RangeInfo(ClrModule.GetPythonType(typeof(List)), unit.ProjectState).SelfSet)); SpecializeFunction("__builtin__", "min", ReturnUnionOfInputs); SpecializeFunction("__builtin__", "max", ReturnUnionOfInputs); _builtinModule = (BuiltinModule)Modules["__builtin__"].Module; _propertyObj = GetBuiltin("property"); _classmethodObj = GetBuiltin("classmethod"); _staticmethodObj = GetBuiltin("staticmethod"); _typeObj = GetBuiltin("type"); _intType = GetBuiltin("int"); _stringType = (BuiltinClassInfo)GetBuiltin("str"); _objectSet = new HashSet <Namespace>(new[] { GetBuiltin("object") }); _setType = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Set); _rangeFunc = GetBuiltin("range"); _frozensetType = GetBuiltin("frozenset"); _functionType = GetNamespaceFromObjects(TypeCache.Function); _generatorType = (BuiltinClassInfo)GetNamespaceFromObjects(DynamicHelpers.GetPythonTypeFromType(typeof(PythonGenerator))); _dictType = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Dict); _boolType = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.Boolean); _noneInst = (ConstantInfo)GetNamespaceFromObjects(new object[] { null }); _listType = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.List); _tupleType = (BuiltinClassInfo)GetNamespaceFromObjects(TypeCache.PythonTuple); _queue = new Queue <AnalysisUnit>(); _docProvider = CodeContext.LanguageContext.GetService <DocumentationProvider>(); }
public void Initialize(ScriptEngine engine) { m_ScriptEngine = engine; }
/// <summary> /// Creates a global scope. /// </summary> /// <param name="engine"> The associated script engine. </param> /// <returns> A new RuntimeScope instance. </returns> public static RuntimeScope CreateGlobalScope(ScriptEngine engine) { return(new RuntimeScope(engine)); }
public PublishingCacheConstructor(ScriptEngine engine) : base(engine.Function.InstancePrototype, "PublishingCache", new PublishingCacheInstance(engine.Object.InstancePrototype)) { this.PopulateFunctions(); }
public Script(String name) { this.Name = name; this.counters = new Dictionary <String, Int32>(); counters.Add("print", 0); counters.Add("text", 0); counters.Add("emote", 0); counters.Add("private", 0); counters.Add("website", 0); counters.Add("html", 0); this.engine = new ScriptEngine(); //ENUMERATIONS engine.Global.DefineProperty("AresId", new PropertyDescriptor(new Objects.Enum(this, typeof(AresId)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Language", new PropertyDescriptor(new Objects.Enum(this, typeof(Language)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Country", new PropertyDescriptor(new Objects.Enum(this, typeof(Country)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Gender", new PropertyDescriptor(new Objects.Enum(this, typeof(Gender)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("AdminLevel", new PropertyDescriptor(new Objects.Enum(this, typeof(AdminLevel)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("CaptchaEvent", new PropertyDescriptor(new Objects.Enum(this, typeof(CaptchaEvent)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("RejectReason", new PropertyDescriptor(new Objects.Enum(this, typeof(RejectReason)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("ClientFeatures", new PropertyDescriptor(new Objects.Enum(this, typeof(ClientFeatures)), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("ServerFeatures", new PropertyDescriptor(new Objects.Enum(this, typeof(ServerFeatures)), PropertyAttributes.Sealed), true); // INSTANCE CLASSES - NOT ENUMERATED engine.Global.DefineProperty("Error", new PropertyDescriptor(new Objects.Error.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Collection", new PropertyDescriptor(new Objects.Collection.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("List", new PropertyDescriptor(new Objects.List.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("ReadOnlyList", new PropertyDescriptor(new Objects.ReadOnlyList.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Monitor", new PropertyDescriptor(new Objects.Monitor.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("RoomStats", new PropertyDescriptor(new Objects.RoomStats.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("HttpRequest", new PropertyDescriptor(new Objects.HttpRequest.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Hashlink", new PropertyDescriptor(new Objects.Hashlink.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("ChannelHash", new PropertyDescriptor(new Objects.ChannelHash.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("Avatar", new PropertyDescriptor(new Objects.Avatar.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("FloodRule", new PropertyDescriptor(new Objects.FloodRule.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("EncodingInstance", new PropertyDescriptor(new Objects.EncodingInstance.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("UserId", new PropertyDescriptor(new Objects.UserId.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("User", new PropertyDescriptor(new Objects.User.Constructor(this), PropertyAttributes.Sealed), true); engine.Global.DefineProperty("UserRecord", new PropertyDescriptor(new Objects.UserRecord.Constructor(this), PropertyAttributes.Sealed), true); // GLOBAL (STATIC) CLASSES this.room = new Room(this, Jurassic.Self.Server); engine.SetGlobalFunction("user", new Func <Object, User>(room.FindUser)); engine.SetGlobalFunction("print", new Action <Object, Object>(room.SendAnnounce)); engine.Global.DefineProperty("user", new PropertyDescriptor(Engine.Global["user"], PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("print", new PropertyDescriptor(Engine.Global["print"], PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Channels", new PropertyDescriptor(new Objects.Channels(this, Jurassic.Self.Server.Channels), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("File", new PropertyDescriptor(new Objects.File(this), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Script", new PropertyDescriptor(new Objects.Script(this), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Encoding", new PropertyDescriptor(new Objects.Encoding(this, true), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Base64", new PropertyDescriptor(new Objects.Base64(this), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Hashlinks", new PropertyDescriptor(new Objects.Hashlinks(this), PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); engine.Global.DefineProperty("Room", new PropertyDescriptor(room, PropertyAttributes.Sealed | PropertyAttributes.Enumerable), true); foreach (var embedded in Jurassic.Embedded) { engine.Global.DefineProperty( embedded.Key, new PropertyDescriptor(embedded.Value.Create(this), embedded.Value.Attributes), true); } Eval(default_script.ToString()); }
public TnTF() { engine = Python.CreateEngine(); scope = engine.CreateScope(); ScriptWorkMode = Core.Connectors.ScriptWorkMode.List; }
public Nitrassic.Library.Array Split(ScriptEngine engine, string input) { return(Split(engine, input, uint.MaxValue)); }
/// <summary> /// Creates a new RuntimeScope instance. /// </summary> /// <param name="engine"> The script engine this scope is associated with. </param> /// <param name="parent"> The parent scope, or <c>null</c> if this is the root scope. </param> /// <param name="scopeType"></param> /// <param name="varNames"></param> /// <param name="letNames"></param> /// <param name="constNames"></param> internal RuntimeScope(ScriptEngine engine, RuntimeScope parent, ScopeType scopeType, string[] varNames, string[] letNames, string[] constNames) { this.Engine = engine ?? throw new ArgumentNullException(nameof(engine)); this.Parent = parent; this.ScopeType = scopeType; if (varNames != null && scopeType != ScopeType.TopLevelFunction && scopeType != ScopeType.EvalStrict) { var scope = this; while (scope != null && scope.ScopeObject == null && scope.ScopeType != ScopeType.TopLevelFunction && scopeType != ScopeType.EvalStrict) { scope = scope.Parent; } if (scope != null) { if (scope.ScopeType == ScopeType.TopLevelFunction || scopeType == ScopeType.EvalStrict) { foreach (var name in varNames) { if (!scope.values.ContainsKey(name)) { scope.values[name] = new LocalValue { Value = Undefined.Value, Flags = LocalFlags.Deletable } } } ; } else { var attributes = scopeType == ScopeType.Eval ? PropertyAttributes.FullAccess : PropertyAttributes.Enumerable | PropertyAttributes.Writable; foreach (var name in varNames) { scope.ScopeObject.InitializeMissingProperty(name, attributes); } } } varNames = null; } if (varNames != null || letNames != null || constNames != null) { values = new Dictionary <string, LocalValue>( (varNames != null ? varNames.Length : 0) + (letNames != null ? letNames.Length : 0) + (constNames != null ? constNames.Length : 0)); } if (varNames != null) { foreach (string variableName in varNames) { values[variableName] = new LocalValue { Value = Undefined.Value } } ; } if (letNames != null) { foreach (string variableName in letNames) { values[variableName] = new LocalValue(); } } if (constNames != null) { foreach (string variableName in constNames) { values[variableName] = new LocalValue { Flags = LocalFlags.ReadOnly } } ; } }
public JavaScriptExecutor() { JSEngine = new ScriptEngine(); }
public void Unload() { this.room = null; this.engine = null; }
public static ArrayInstance From(ScriptEngine engine, ObjectInstance iterable) { return(From(engine, iterable, null, null)); }
public HttpWebResponseConstructor(ScriptEngine engine) : base(engine.Function.InstancePrototype, "HttpWebResponse", new HttpWebResponseInstance(engine.Object.InstancePrototype)) { }
public SPWorkflowTemplateConstructor(ScriptEngine engine) : base(engine.Function.InstancePrototype, "SPWorkflowTemplate", new SPWorkflowTemplateInstance(engine.Object.InstancePrototype)) { PopulateFunctions(); }
private static object __STUB__ToString(ScriptEngine engine, object thisObj, object[] args) { return(ToString(thisObj)); }
/// <summary>Constructs the ScriptRan script event.</summary> /// <param name="system">The relevant command system.</param> public ScriptRanPreScriptEvent(ScriptEngine system) : base(system, "scriptranpreevent", true) { }
public static ArrayInstance Of(ScriptEngine engine, params object[] elements) { return(engine.Array.New(elements)); }
public JSUser(ScriptEngine eng) : base(eng.Function.InstancePrototype, "User", new Objects.JSUser(eng)) { }
public JsonDocumentConstructor(ScriptEngine engine) : base( engine.Function.InstancePrototype, "JsonDocument", new JsonDocumentInstance(engine.Object.InstancePrototype)) { }
public ScriptApi(ScriptEngine engine, string extensionId, ExtensionManifest manifest) { _engine = engine; _extensionId = extensionId; _manifest = manifest; }
/// <summary> /// Creates a new DeclarativeScope instance. /// </summary> /// <param name="declaredVariableCount"> The number of variables declared in this scope. </param> internal DeclarativeScope(ScriptEngine engine, int declaredVariableCount) : base(engine) { this.variables = new Dictionary <string, Variable>(declaredVariableCount); this.CanDeclareVariables = false; }