public static IEnumerable<dynamic> ProcessScript(ScriptInfo scriptInfo, IEnumerable<ClassTemplateInfo> dataClassesInfo, Func<Type, object> deserializeToType) { var modelType = LoadModelTypesAppDomain(dataClassesInfo); // INFO: Configure Roslyn Script Engine var scriptEngine = ConfigureScriptEngine(scriptInfo, modelType.Assembly); // INFO: Read input data for Model of runtime types var models = LoadModelData(deserializeToType, modelType); Submission<object> submission; // INFO: Create Roslyn Script Submission var submissionModel = CreateSubmission(scriptInfo, modelType, scriptEngine, out submission); // INFO: Process all inputs return models .Select(model => { CopyPropertiesToSubmissionModel(modelType, submissionModel, model); return submission.Execute(); }) .ToList(); }
public SensorManager() { sensorBridge.SensorDataAvailable += new EventHandler<SensorDataEventArgs>(sensorBridge_SensorDataAvailable); // add some common assemblies ScriptRuntime runtime = scriptEngine.Runtime; runtime.LoadAssembly(Assembly.GetExecutingAssembly()); runtime.LoadAssembly(typeof(string).Assembly); runtime.LoadAssembly(typeof(Uri).Assembly); runtime.LoadAssembly(typeof(System.Diagnostics.Trace).Assembly); // enumerate the scripts, and prepare the scopes and sources foreach (string script in Directory.GetFiles(SensorMonitorDirectory, "*.py")) { try { ScriptInfo info = new ScriptInfo(); info.CompiledCode = scriptEngine.CreateScriptSourceFromFile(script).Compile(); info.ScriptScope = scriptEngine.CreateScope(); sensorScripts.Add(script, info); } catch (Exception ex) { ExceptionOperations eo; eo = scriptEngine.GetService<ExceptionOperations>(); string error = eo.FormatException(ex); Trace.WriteLine(String.Format("Initialising SensorMonitors:: {0}", error)); } } }
private static ScriptEngine ConfigureScriptEngine(ScriptInfo scriptInfo, Assembly modelAssembly) { var scriptEngine = new ScriptEngine(); scriptEngine.AddReference(modelAssembly); scriptInfo.Assemblies.ToList().ForEach(scriptEngine.AddReference); scriptInfo.Namespaces.ToList().ForEach(scriptEngine.ImportNamespace); return scriptEngine; }
public PublishingManager() { // add some common assemblies ScriptRuntime runtime = scriptEngine.Runtime; runtime.LoadAssembly(Assembly.GetExecutingAssembly()); runtime.LoadAssembly(typeof(string).Assembly); runtime.LoadAssembly(typeof(Uri).Assembly); runtime.LoadAssembly(typeof(System.Xml.XmlDocument).Assembly); runtime.LoadAssembly(typeof(System.Diagnostics.Trace).Assembly); // enumerate the scripts, and prepare the scopes and sources foreach (string scriptPath in Directory.GetFiles(PublishingMonitorDirectory, "*.py")) { try { ScriptInfo info = new ScriptInfo(); info.ScriptPath = scriptPath; info.CompiledCode = scriptEngine.CreateScriptSourceFromFile(scriptPath).Compile(); info.ScriptScope = scriptEngine.CreateScope(); // execute it to run any initialization code in the publisher info.CompiledCode.Execute(info.ScriptScope); // get the topics that the publisher wants to be notified of. Func<IEnumerable<string>> GetTopics = info.ScriptScope.GetVariable<Func<IEnumerable<string>>>("GetTopics"); // get the publish function provided by the publisher, the MQTT client will directly invoke it for us. Func<string, object, bool> Publish = info.ScriptScope.GetVariable<Func<string, object, bool>>("Publish"); IEnumerable<string> topics = GetTopics(); foreach (var topic in topics) { MqttClientManager.Subscribe(topic, Nmqtt.MqttQos.AtMostOnce, Publish); } info.Topics.AddRange(topics); PublishingScripts.Add(scriptPath, info); } catch (Exception ex) { ExceptionOperations eo; eo = scriptEngine.GetService<ExceptionOperations>(); string error = eo.FormatException(ex); Trace.WriteLine(String.Format("Initialising Publishers:: {0}", error)); } } }
public SqlHarvester(SqlScripterFactory factory, ScriptInfo scriptInfo, string outputDirectory, int index) { if (scriptInfo == null) { throw new ArgumentException("scriptInfo"); } if (factory == null) { throw new ArgumentException("factory"); } this.index = index; sqlScripter = factory.CreateInstance(scriptInfo); this.scriptInfo = scriptInfo; file = GetFile(outputDirectory); Stream stream = file.Open(FileMode.Create, FileAccess.Write, FileShare.Read); writer = new StreamWriter(stream); }
public static ScriptInfo GetScriptInfo(string url) { ScriptInfo info = new ScriptInfo(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url)); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); info.Owner = response.GetResponseHeader("X-SecondLife-Owner-Name"); info.Region = response.GetResponseHeader("X-SecondLife-Region"); info.Server = response.GetResponseHeader("Server"); } catch { } return info; }
public CommandProcessorBase CreateCommandProcessor(Command command) { string cmdText = command.CommandText; CommandInfo commandInfo = null; bool useLocalScope = command.UseLocalScope; if (command.IsScript) //CommandText contains a script block. Parse it { command.ScriptBlockAst = Parser.ParseInput(cmdText); } //either we parsed something like "& { foo; bar }", or the CommandText was a script and was just parsed if (command.ScriptBlockAst != null) { commandInfo = new ScriptInfo("", command.ScriptBlockAst.GetScriptBlock(), useLocalScope ? ScopeUsages.NewScope : ScopeUsages.CurrentScope); } else //otherwise it's a real command (cmdlet, script, function, application) { commandInfo = FindCommand(cmdText, useLocalScope); } // make sure we only create a valid command processor if it's a valid command commandInfo.Validate(); switch (commandInfo.CommandType) { case CommandTypes.Application: return new ApplicationProcessor((ApplicationInfo)commandInfo); case CommandTypes.Cmdlet: return new CommandProcessor(commandInfo as CmdletInfo); case CommandTypes.Script: case CommandTypes.ExternalScript: case CommandTypes.Function: return new ScriptBlockProcessor(commandInfo as IScriptBlockInfo, commandInfo); default: throw new NotImplementedException("Invalid command type"); } }
private bool InternalSet(ScriptInfo script) { bool isStatic = !CodeDomUtils.AreMemberAttributesSet(script.TypeDeclaration, MemberAttributes.Final); if (isStatic && !CodeDomUtils.AreMemberAttributesSet(script.TypeDeclaration, MemberAttributes.Static)) { isStatic = !CollectionUtils.Contains( CodeObjectMetaData.GetFields(script.TypeDeclaration).Values, delegate(CodeMemberField memberField) { return (!CodeDomUtils.AreMemberAttributesSet(memberField, MemberAttributes.Const)); }); if (isStatic) { isStatic = !CollectionUtils.Contains( script.Dependencies.Values, delegate(ScriptInfo dependencyScript) { return (!dependencyScript.IsInvalid && !InternalSet(dependencyScript)); }); } MemberAttributes attribute = (isStatic ? MemberAttributes.Static : MemberAttributes.Final); CodeDomUtils.SetMemberAttributes(script.TypeDeclaration, attribute); foreach (CodeTypeMember typeMember in script.TypeDeclaration.Members) { if (!(typeMember is CodeTypeDeclaration || (typeMember is CodeMemberField && CodeDomUtils.AreMemberAttributesSet(typeMember, MemberAttributes.Const)))) { CodeDomUtils.SetMemberAttributes(typeMember, attribute); } } } return isStatic; }
////////////////////////////////////////////////////////////////////////// public static string[] GetClassProperties(string NativeClass) { if(ClassProps==null) { ClassProps = new Dictionary<string, string[]>(); try { string XmlDocsPath = ""; using (RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"Software\DEAD:CODE\Wintermute Tools\Settings")) { XmlDocsPath = Key.GetValue("ToolsPath", "").ToString(); }; XmlDocsPath = Path.Combine(XmlDocsPath, "wme_docs_core_en.xml"); if (File.Exists(XmlDocsPath)) { ScriptInfo Info = new ScriptInfo(); if (Info.ReadXml(XmlDocsPath)) { foreach (ScriptObject Obj in Info.Objects) { if (Obj.NativeClass == null || Obj.NativeClass == string.Empty) continue; List<string> Attrs = new List<string>(Obj.Attributes.Count); foreach (ScriptAttribute Attr in Obj.Attributes) { Attrs.Add(Attr.Name); } ClassProps[Obj.NativeClass] = Attrs.ToArray(); } } } } catch { } } if (ClassProps.ContainsKey(NativeClass)) return ClassProps[NativeClass]; else return null; }
public PromptManager(ScriptInfo pScriptInfo) { scriptInfo = pScriptInfo; language = scriptInfo.ScriptLanguage.ToString(); languageSuffix = language.Substring(0, 2); rootPromptsFolder = Path.Combine(scriptInfo.RbrRoot, PromptConstants.ROOT_FOLDER); standardPromptsFolder = Path.Combine(rootPromptsFolder, PromptConstants.STANDARD); standardPromptsFolder = Path.Combine(standardPromptsFolder, language); servicePromptsFolder = Path.Combine(rootPromptsFolder, scriptInfo.ServiceName); if (!Directory.Exists(servicePromptsFolder)) { Directory.CreateDirectory(servicePromptsFolder); } servicePromptsFolder = Path.Combine(servicePromptsFolder, language); if (!Directory.Exists(servicePromptsFolder)) { Directory.CreateDirectory(servicePromptsFolder); } }
///Makes and returns a closed generic ScriptInfo for targetType out of an existing ScriptInfo public static ScriptInfo MakeGenericInfo(this ScriptInfo info, Type targetType, string subCategory = null, int priorityShift = 0) { if (info == null || !info.originalType.IsGenericTypeDefinition) { return(null); } info = info.GetBaseInfo(); var genericArg = info.originalType.GetGenericArguments().First(); if (targetType.IsAllowedByGenericArgument(genericArg)) { var genericType = info.originalType.MakeGenericType(targetType); var genericCategory = info.category + subCategory; var genericName = info.name.Replace("(T)", string.Format("({0})", targetType.FriendlyName())); var newInfo = new ScriptInfo(genericType, genericName, genericCategory, info.priority + priorityShift); newInfo.originalType = info.originalType; newInfo.originalName = info.originalName; newInfo.originalCategory = info.originalCategory; return(newInfo); } return(null); }
public string GetAllScript(ProxyScriptType type) { lock (CachedScripts) { var cacheKey = type + "_all"; if (!CachedScripts.ContainsKey(cacheKey)) { var script = new StringBuilder(); var dynamicControllers = _dynamicApiControllerManager.GetAll().Where(ci => ci.IsProxyScriptingEnabled); foreach (var dynamicController in dynamicControllers) { var proxyGenerator = CreateProxyGenerator(type, dynamicController, false); script.AppendLine(proxyGenerator.Generate()); script.AppendLine(); } CachedScripts[cacheKey] = new ScriptInfo(script.ToString()); } return(CachedScripts[cacheKey].Script); } }
public static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { VarName varName = new VarName(); MoveInfo moveInfo = new MoveInfo(parentInfo); int startIndex = parentInfo.CurrentIndex; int length; // find members and arrayIndexers IElement next = null; do { length = (moveInfo.CurrentIndex + 1) - startIndex; next = moveInfo.FindNextBlack(SearchDirection.LeftToRight); }while (next != null && (ArrayIndexer.Check(moveInfo, parsingInfo, scriptInfo) || DataMember.Check(moveInfo, parsingInfo, scriptInfo))); varName.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, varName); }
public static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { Vector vec = new Vector(); ParenthesesGroup group = (ParenthesesGroup)parentInfo.Current; MoveInfo groupInfo = new MoveInfo(group, SearchTree.ContentBlock, 0, parentInfo); for (int i = 0; i < 3; i++) { Expression exp = Expression.Parse(groupInfo, parsingInfo, scriptInfo); IElement next = groupInfo.FindNextBlack(SearchDirection.LeftToRight); if ((i < 2 && !next.IsTT(TokenType.Comma)) || (i == 2 && next != null)) { throw new SyntaxException("Could not parse vector " + (i + 1) + " expression", parentInfo.GetErrorInfo()); } if (i != 2) // move behind , { groupInfo.Move(SearchDirection.LeftToRight); } } int startIndex = parentInfo.CurrentIndex; int length = 1; MoveInfo moveInfo = new MoveInfo(parentInfo); moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (moveInfo.Current != null && ArrayIndexer.Check(moveInfo, parsingInfo, scriptInfo)) { length = (moveInfo.CurrentIndex + 1) - startIndex; } vec.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, vec); }
private ScriptInfo InternalAdd(string scriptString, string scriptKey, JSRuntime runtime) { Debug.Assert(scriptKey != null, "Invalid scriptKey, should be string"); ScriptInfo script = null; if (!Scripts.TryGetValue(scriptKey, out script)) { script = Scripts.GetOrAdd(scriptKey, key => { Debug.WriteLine("Script precompilation cache {0} [miss]", key); JSRuntime.Instance = runtime; var scriptInfo = new ScriptInfo(key, scriptString); scriptInfo.LexTask = System.Threading.Tasks.Task.Factory.StartNew(state => { var taskState = state as JSTaskState <ScriptInfo>; var info = taskState.GetState(); var timer = JSRuntime.StartTimer(true, "JS/PreLoad/" + key); info.Metadata = taskState.RuntimeInstance.LoadScriptStringMetadata(info.Text); if (Instance.Configuration.EnableParallelJit) { info.Metadata.JitSpeculatively(ref mdr.DFunctionSignature.EmptySignature); } else if (Instance.Configuration.EnableParallelAnalyze) { info.Metadata.Analyze(); //Will launch the rest itself. } JSRuntime.StopTimer(timer); }, new JSTaskState <ScriptInfo>(scriptInfo)); return(scriptInfo); }); } else { Debug.WriteLine("Script precompilation cache {0} [hit]", scriptKey); } return(script); }
private static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { ReturnStatement returnStatement = new ReturnStatement(); MoveInfo moveInfo = new MoveInfo(parentInfo); IElement tryExp = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryExp == null) { throw new SyntaxException("Missing directive ';'?", parentInfo.GetErrorInfo()); } // expression defined if (!tryExp.IsTT(TokenType.SemiColon)) { Expression exp = Expression.Parse(moveInfo, parsingInfo, scriptInfo, false, false, true); if (exp == null) { throw new SyntaxException("Could not parse return expression", parentInfo.GetErrorInfo()); } moveInfo.FindNextBlack(SearchDirection.LeftToRight); } // terminal if (moveInfo.Current == null || !moveInfo.Current.IsTT(TokenType.SemiColon)) { throw new SyntaxException("Missing directive ';'?", parentInfo.GetErrorInfo()); } // build int startIndex = parentInfo.CurrentIndex; int length = (moveInfo.CurrentIndex + 1) - startIndex; returnStatement.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, returnStatement); }
private static void Test(Language language, CodeDomProvider provider) { MigrationSettings settings = new MigrationSettings(); settings.VSProjectName = "ClassLibrary1"; settings.Namespace = "ClassLibrary1"; settings.Language = language; MigrationContext context = new MigrationContext( settings, null, null, null, null, provider, null, null, new EmptyOperationStatus(), null); context.LocalizedStrings.Add("One", "Uno"); context.References.Add("AxSLXControls, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL", @"AxSLXControls.dll"); context.References.Add(typeof (Form).Assembly.GetName().Name, null); Plugin plugin = new Plugin(); plugin.Family = "Test"; plugin.Name = "Class1"; plugin.Blob.Data = new byte[0]; ScriptInfo script = new ScriptInfo(plugin); context.Scripts.Add("0", script); MigrationContextHolderService holder = new MigrationContextHolderService(); holder.Context = context; VSProjectService p = new VSProjectService(); p.ContextHolder = holder; p.Generate(); }
private static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { DefaultSwitchStatement defaultSwitch = new DefaultSwitchStatement(); MoveInfo moveInfo = new MoveInfo(parentInfo); // terminal IElement tryTerminal = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryTerminal == null || !tryTerminal.IsTT(TokenType.Colon)) { throw new SyntaxException("Missing directive ':'?", parentInfo.GetErrorInfo()); } // statements IElement nextStatement = moveInfo.FindNextBlack(SearchDirection.LeftToRight); while (nextStatement != null) // end of switch { if (CaseSwitchStatement.Check(moveInfo, parsingInfo, scriptInfo, false) || DefaultSwitchStatement.Check(moveInfo, parsingInfo, scriptInfo, false)) { break; } Statement.Check(moveInfo, parsingInfo, scriptInfo); nextStatement = moveInfo.FindNextBlack(SearchDirection.LeftToRight); } // build int startIndex = parentInfo.CurrentIndex; int length = (moveInfo.CurrentIndex) - startIndex; defaultSwitch.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, defaultSwitch); }
private static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { WhileStatement whileStatement = new WhileStatement(); MoveInfo moveInfo = new MoveInfo(parentInfo); // expression IElement expGroupTry = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (expGroupTry == null || !(expGroupTry is ParenthesesGroup)) { throw new SyntaxException("Could not find while expression", parentInfo.GetErrorInfo()); } ParenthesesGroup expGroup = (ParenthesesGroup)expGroupTry; MoveInfo expGroupInfo = new MoveInfo(expGroup, SearchTree.ContentBlock, 0, parentInfo); Expression exp = Expression.Parse(expGroupInfo, parsingInfo, scriptInfo); if (exp == null || expGroupInfo.FindNextBlack(SearchDirection.LeftToRight) != null) { throw new SyntaxException("Could not parse while expression", parentInfo.GetErrorInfo()); } // statement moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (!Statement.Check(moveInfo, parsingInfo, scriptInfo)) { throw new SyntaxException("Could not parse while statement", parentInfo.GetErrorInfo()); } // build int startIndex = parentInfo.CurrentIndex; int length = (moveInfo.CurrentIndex + 1) - startIndex; whileStatement.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, whileStatement); }
public static bool Check(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { if (parentInfo.Current.IsTT(TokenType.ADD) || parentInfo.Current.IsTT(TokenType.SUB)) { MoveInfo moveInfo = new MoveInfo(parentInfo); IElement next = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (next != null && next.IsTT(TokenType.Number)) // +5 { MoveInfo prevInfo = new MoveInfo(parentInfo); IElement prev = prevInfo.FindNextBlack(SearchDirection.RightToLeft); if (prev == null || !(prev is ExpressionOperand)) // +5 | 5 + +5 { ParseSigned(parentInfo, parsingInfo, scriptInfo); return(true); } } } else if (parentInfo.Current.IsTT(TokenType.Number)) { ParseUnsigned(parentInfo, parsingInfo, scriptInfo); return(true); } return(false); }
public static void ParseRegion(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { MoveInfo moveInfo = new MoveInfo(parentInfo); List <IElement> content = new List <IElement>(); content.Add(moveInfo.Current); content.Add(moveInfo.Move(SearchDirection.LeftToRight)); moveInfo.Move(SearchDirection.LeftToRight); int nameStart = moveInfo.CurrentIndex; IElement end = moveInfo.Find(SearchDirection.LeftToRight, SearchVisibility.Unvisible, IsRegionEnd); if (end == null) { throw new SyntaxException("Bad region syntax", parentInfo.GetErrorInfo()); } content.AddRange(moveInfo.CurrentElements.GetRange(nameStart, moveInfo.CurrentIndex - nameStart)); IBlock region = new PreProcessorRegion(content); parentInfo.Replace(moveInfo.CurrentIndex - parentInfo.CurrentIndex, region); }
/// <summary> /// Performs PHP inclusion on a specified script. /// </summary> /// <param name="relativeSourcePath"> /// Path to the target script source file relative to the application source root /// (see <c>Configuration.Application.Compiler.SourceRoot</c>. /// </param> /// <param name="script"> /// Script type (i.e. type called <c>Default</c> representing the target script) or any type from /// the assembly where the target script is contained (useful for multi-script assemblies, where script types are /// not directly available from C# as they have mangled names). In the latter case, the script type is searched in the /// assembly using value of <paramref name="relativeSourcePath"/>. /// </param> /// <returns>The value returned by the global code of the target script.</returns> /// <remarks> /// <para> /// The inclusion inheres in adding the target to the list of included scripts on the current script context /// (see <c>ScriptContext.Scripts</c> and in a call to the global code of the target script. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">Request context has been disposed.</exception> /// <exception cref="ArgumentNullException"><paramref name="relativeSourcePath"/> or <paramref name="script"/> are <B>null</B> references.</exception> /// <exception cref="ArgumentException">Script type cannot be resolved.</exception> /// <exception cref="InvalidScriptAssemblyException">The target assembly is not a valid Phalanger compiled assembly.</exception> internal object IncludeScript(string /*!*/ relativeSourcePath, ScriptInfo /*!*/ script) { //if (type == null) // throw new ArgumentNullException("type"); if (relativeSourcePath == null) { throw new ArgumentNullException("relativeSourcePath"); } if (script == null) { throw new ArgumentException("script"); } FullPath source_root = Configuration.Application.Compiler.SourceRoot; PhpSourceFile source_file = new PhpSourceFile( new FullPath(source_root), new FullPath(Path.Combine(source_root, relativeSourcePath))); // the first script becomes the main one: if (MainScriptFile == null) { DefineMainScript(script, source_file); } return(GuardedCall((ScriptInfo scriptInfo) => { //return PhpScript.InvokeMainHelper( // (Type)scriptType, return scriptInfo.Main( this, null, // no local variables null, // no object context null, // no class context true); }, script, true)); }
/// <summary> /// Gets all the mods and patches them. /// </summary> private void worker_DoWork(object sender, DoWorkEventArgs e) { _errorLevel = ErrorLevel.NoError; //Gets the list of mods ItemCollection modCollection = null; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { modCollection = ModsListBox.Items; })); SetStatusLabelAsync("Gathering mods..."); //Gets the list of mods that have been checked. List <LessMod> modsToPatch = new List <LessMod>(); foreach (var x in modCollection) { CheckBox box = (CheckBox)x; bool isBoxChecked = false; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { isBoxChecked = box.IsChecked ?? false; })); if (isBoxChecked) { modsToPatch.Add(_lessMods[box]); } } string lolLocation = null; bool overwrite = true; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { lolLocation = LocationTextbox.Text; })); if (IsGarena) { MessageBox.Show("Garena detected! Please note that you must uninstall LESs before patching your LoL with Garena." + Environment.NewLine + "Otherwise, your Garena LoL patcher will complain hard and we are not responsible for it ;)."); Uri lolRootLocation = new Uri(lolLocation); lolRootLocation = new Uri(lolRootLocation.LocalPath.Replace(lolRootLocation.Segments.Last(), String.Empty)); // Get LoL latest patched date String versionLocation = Path.Combine(lolRootLocation.LocalPath, "lol.version"); if (File.Exists(versionLocation)) { // Store the date in another file. It will be used in LESs removing. File.Copy(versionLocation, Path.Combine(lolRootLocation.LocalPath, "LESs_recent.version"), true); } if (Directory.Exists(Path.Combine(lolLocation, "LESsBackup"))) { MessageBoxResult diagRst = MessageBox.Show("We found that you already have backup files. Overwriting it may result in you losing your original files." + Environment.NewLine + "Would you like to overwrite your old files?", "You already have backup files", MessageBoxButton.YesNo); if (diagRst == MessageBoxResult.No) { overwrite = false; } } } Dictionary <string, SwfFile> swfs = new Dictionary <string, SwfFile>(); Stahpwatch = Stopwatch.StartNew(); foreach (var lessMod in modsToPatch) { Debug.Assert(lessMod.Patches.Length > 0); SetStatusLabelAsync("Patching mod: " + lessMod.Name); foreach (var patch in lessMod.Patches) { if (!swfs.ContainsKey(patch.Swf)) { string fullPath = Path.Combine(lolLocation, patch.Swf); //Backup the SWF string CurrentLocation = ""; string[] FileLocation = patch.Swf.Split('/'); foreach (string s in FileLocation.Take(FileLocation.Length - 1)) { CurrentLocation = Path.Combine(CurrentLocation, s); if (IsGarena) { if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", CurrentLocation))) { Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", CurrentLocation)); } if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", patch.Swf))) { if (overwrite) { File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", patch.Swf)); } } } else { if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation))) { Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation)); } if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf))) { File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf)); } } } swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath)); } SwfFile swf = swfs[patch.Swf]; List <DoAbcTag> tags = swf.GetDoAbcTags(); bool classFound = false; foreach (var tag in tags) { //check if this tag contains our script ScriptInfo si = tag.GetScriptByClassName(patch.Class); //check next tag if it doesn't if (si == null) { continue; } ClassInfo cls = si.GetClassByClassName(patch.Class); classFound = true; Assembler asm; switch (patch.Action) { case "replace_trait": //replace trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); TraitInfo newTrait = asm.Assemble() as TraitInfo; int traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); bool classTrait = false; if (traitIndex < 0) { traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); classTrait = true; } if (traitIndex < 0) { throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class)); } if (classTrait) { cls.Traits[traitIndex] = newTrait; } else { cls.Instance.Traits[traitIndex] = newTrait; } break; case "replace_cinit": //replace class constructor asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.ClassInit = asm.Assemble() as MethodInfo; break; case "replace_iinit": //replace instance constructor asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.Instance.InstanceInit = asm.Assemble() as MethodInfo; break; case "add_class_trait": //add new class trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); if (traitIndex < 0) { cls.Traits.Add(newTrait); } else { cls.Traits[traitIndex] = newTrait; } break; case "add_instance_trait": //add new instance trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); if (traitIndex < 0) { cls.Instance.Traits.Add(newTrait); } else { cls.Instance.Traits[traitIndex] = newTrait; } break; case "remove_class_trait": throw new NotImplementedException(); case "remove_instance_trait": throw new NotImplementedException(); default: throw new NotSupportedException("Unknown Action \"" + patch.Action + "\" in mod " + lessMod.Name); } } if (!classFound) { _errorLevel = ErrorLevel.UnableToPatch; throw new ClassNotFoundException(string.Format("Class {0} not found in file {1}", patch.Class, patch.Swf)); } } } //return; foreach (var patchedSwf in swfs) { try { SetStatusLabelAsync("Applying mods: " + patchedSwf.Key); string swfLoc = Path.Combine(lolLocation, patchedSwf.Key); SwfFile.WriteFile(patchedSwf.Value, swfLoc); } catch { _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow; if (Debugger.IsAttached) { throw; } } } Stahpwatch.Stop(); }
public ScriptProcessor(ScriptInfo scriptInfo) : base(scriptInfo) { }
protected IMohidTask LoadScript(FileName script_file_path) { ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == script_file_path.FullPath; }); if (si != null) { si.Interface.Reset(); return si.Interface; } else { ScriptCompiler sc = new ScriptCompiler(); Assembly ass; try { ass = sc.Compile(script_file_path); } catch (Exception ex) { throw new Exception("Error when trying to compile " + script_file_path.FullPath + ". The message returned was " + ex.Message); } si = new ScriptInfo(); si.ScriptFile = script_file_path; si.Interface = (IMohidTask)sc.FindScriptInterface("IMohidTask", ass); scripts.Add(si); return si.Interface; } }
private static ScriptInfo ParseConfig(string text) { var si = new ScriptInfo(); var lines = text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); var mode = ParseMode.None; var players = new List <PlayerInfo>(); int lastTeam = -1; foreach (var s in lines) { string line = s.Trim(); if (line.StartsWith("[player", StringComparison.InvariantCultureIgnoreCase)) { mode = ParseMode.Player; var m = Regex.Match(line, "\\[player([0-9]+)", RegexOptions.IgnoreCase); if (m.Success) { int id = int.Parse(m.Groups[1].Value); var pi = new PlayerInfo(id); players.Add(pi); } else { throw new ApplicationException("Error parsing " + scriptName); } } else if (line.StartsWith("[team", StringComparison.InvariantCultureIgnoreCase)) { mode = ParseMode.Team; var m = Regex.Match(line, "\\[team([0-9]+)", RegexOptions.IgnoreCase); if (m.Success) { lastTeam = int.Parse(m.Groups[1].Value); } else { throw new ApplicationException("Error parsing " + scriptName); } } else { var m = Regex.Match(line, "([^=]+)=([^;]+)"); if (m.Success) { string var = m.Groups[1].Value; string val = m.Groups[2].Value; if (mode == ParseMode.Player) { if (String.Compare(var, "team", true) == 0) { players[players.Count - 1].Team = int.Parse(val); } else if (String.Compare(var, "spectator", true) == 0) { players[players.Count - 1].IsSpectator = (val == "1"); } else if (String.Compare(var, "name", true) == 0) { players[players.Count - 1].Name = val; if (players[players.Count - 1].Id == 0) { si.Host = val; } } } else if (mode == ParseMode.Team) { if (String.Compare(var, "allyteam", true) == 0) { for (int i = 0; i < players.Count; ++i) { if (players[i].Team == lastTeam) { players[i].Ally = int.Parse(val); } } } } } } } foreach (var pi in players) { if (!pi.IsSpectator) { var pp = new ScriptInfo.PlayerPair(pi.Ally, pi.Name); si.Players.Add(pp); } } return(si); }
public static List <ScriptInfo> GetScriptInfosOfType(Type baseType) { if (cachedInfos == null) { cachedInfos = new Dictionary <Type, List <ScriptInfo> >(); } List <ScriptInfo> infosResult; if (cachedInfos.TryGetValue(baseType, out infosResult)) { return(infosResult.ToList()); } infosResult = new List <ScriptInfo>(); var subTypes = GetAssemblyTypes(baseType); if (baseType.IsGenericTypeDefinition) { subTypes = new List <Type> { baseType }; } foreach (var subType in subTypes) { if (subType.IsDefined(typeof(DoNotListAttribute), true) || subType.IsDefined(typeof(ObsoleteAttribute), true)) { continue; } if (subType.IsAbstract) { continue; } var isGeneric = subType.IsGenericTypeDefinition && subType.GetGenericArguments().Length == 1; var scriptName = subType.FriendlyName().SplitCamelCase(); var scriptCategory = string.Empty; var scriptPriority = 0; var nameAttribute = subType.RTGetAttribute <NameAttribute>(true); if (nameAttribute != null) { scriptPriority = nameAttribute.priority; scriptName = nameAttribute.name; if (isGeneric && !scriptName.EndsWith("<T>")) { scriptName += " (T)"; } } var categoryAttribute = subType.RTGetAttribute <CategoryAttribute>(true); if (categoryAttribute != null) { scriptCategory = categoryAttribute.category; } var info = new ScriptInfo(subType, scriptName, scriptCategory, scriptPriority); info.originalType = subType; info.originalName = scriptName; info.originalCategory = scriptCategory; //add the generic types based on constrains and prefered types list if (isGeneric) { var exposeAsBaseDefinition = subType.RTIsDefined <ExposeAsDefinition>(true); if (!exposeAsBaseDefinition) { var typesToWrap = UserTypePrefs.GetPreferedTypesList(true); foreach (var t in typesToWrap) { infosResult.Add(info.MakeGenericInfo(t, string.Format("/{0}/{1}", info.name, t.NamespaceToPath()))); infosResult.Add(info.MakeGenericInfo(typeof(List <>).MakeGenericType(t), string.Format("/{0}/{1}{2}", info.name, UserTypePrefs.LIST_MENU_STRING, t.NamespaceToPath()), -1)); infosResult.Add(info.MakeGenericInfo(typeof(Dictionary <,>).MakeGenericType(typeof(string), t), string.Format("/{0}/{1}{2}", info.name, UserTypePrefs.DICT_MENU_STRING, t.NamespaceToPath()), -2)); } continue; } } infosResult.Add(info); } infosResult = infosResult .Where(s => s != null) .OrderBy(s => s.GetBaseInfo().name) .OrderBy(s => s.GetBaseInfo().priority * -1) .OrderBy(s => s.GetBaseInfo().category) .ToList(); cachedInfos[baseType] = infosResult; return(infosResult); }
internal static bool RunScript(IWin32Window owner, GitModule aModule, ScriptInfo scriptInfo, RevisionGrid revisionGrid) { string originalCommand = scriptInfo.Command; string argument = scriptInfo.Arguments; string command = OverrideCommandWhenNecessary(originalCommand); var allSelectedRevisions = new List<GitRevision>(); GitRevision selectedRevision = null; GitRevision currentRevision = null; var selectedLocalBranches = new List<GitRef>(); var selectedRemoteBranches = new List<GitRef>(); var selectedRemotes = new List<string>(); var selectedBranches = new List<GitRef>(); var selectedTags = new List<GitRef>(); var currentLocalBranches = new List<GitRef>(); var currentRemoteBranches = new List<GitRef>(); var currentRemote = ""; var currentBranches = new List<GitRef>(); var currentTags = new List<GitRef>(); foreach (string option in Options) { if (string.IsNullOrEmpty(argument) || !argument.Contains(option)) continue; if (option.StartsWith("{c") && currentRevision == null) { currentRevision = GetCurrentRevision(aModule, revisionGrid, currentTags, currentLocalBranches, currentRemoteBranches, currentBranches, currentRevision); if (currentLocalBranches.Count == 1) currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", currentLocalBranches[0].Name)); else { currentRemote = aModule.GetCurrentRemote(); if (string.IsNullOrEmpty(currentRemote)) currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", askToSpecify(currentLocalBranches, "Current Revision Branch"))); } } else if (option.StartsWith("{s") && selectedRevision == null && revisionGrid != null) { allSelectedRevisions = revisionGrid.GetSelectedRevisions(); allSelectedRevisions.Reverse(); // Put first clicked revisions first selectedRevision = CalculateSelectedRevision(revisionGrid, selectedRemoteBranches, selectedRemotes, selectedLocalBranches, selectedBranches, selectedTags); } string remote; string url; switch (option) { case "{sHashes}": argument = argument.Replace(option, string.Join(" ", allSelectedRevisions.Select(revision => revision.Guid).ToArray())); break; case "{sTag}": if (selectedTags.Count == 1) argument = argument.Replace(option, selectedTags[0].Name); else if (selectedTags.Count != 0) argument = argument.Replace(option, askToSpecify(selectedTags, "Selected Revision Tag")); else argument = argument.Replace(option, ""); break; case "{sBranch}": if (selectedBranches.Count == 1) argument = argument.Replace(option, selectedBranches[0].Name); else if (selectedBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedBranches, "Selected Revision Branch")); else argument = argument.Replace(option, ""); break; case "{sLocalBranch}": if (selectedLocalBranches.Count == 1) argument = argument.Replace(option, selectedLocalBranches[0].Name); else if (selectedLocalBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedLocalBranches, "Selected Revision Local Branch")); else argument = argument.Replace(option, ""); break; case "{sRemoteBranch}": if (selectedRemoteBranches.Count == 1) argument = argument.Replace(option, selectedRemoteBranches[0].Name); else if (selectedRemoteBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedRemoteBranches, "Selected Revision Remote Branch")); else argument = argument.Replace(option, ""); break; case "{sRemote}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); argument = argument.Replace(option, remote); break; case "{sRemoteUrl}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote)); argument = argument.Replace(option, url); break; case "{sRemotePathFromUrl}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote)); argument = argument.Replace(option, GetRemotePath(url)); break; case "{sHash}": argument = argument.Replace(option, selectedRevision.Guid); break; case "{sMessage}": argument = argument.Replace(option, selectedRevision.Message); break; case "{sAuthor}": argument = argument.Replace(option, selectedRevision.Author); break; case "{sCommitter}": argument = argument.Replace(option, selectedRevision.Committer); break; case "{sAuthorDate}": argument = argument.Replace(option, selectedRevision.AuthorDate.ToString()); break; case "{sCommitDate}": argument = argument.Replace(option, selectedRevision.CommitDate.ToString()); break; case "{cTag}": if (currentTags.Count == 1) argument = argument.Replace(option, currentTags[0].Name); else if (currentTags.Count != 0) argument = argument.Replace(option, askToSpecify(currentTags, "Current Revision Tag")); else argument = argument.Replace(option, ""); break; case "{cBranch}": if (currentBranches.Count == 1) argument = argument.Replace(option, currentBranches[0].Name); else if (currentBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentBranches, "Current Revision Branch")); else argument = argument.Replace(option, ""); break; case "{cLocalBranch}": if (currentLocalBranches.Count == 1) argument = argument.Replace(option, currentLocalBranches[0].Name); else if (currentLocalBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentLocalBranches, "Current Revision Local Branch")); else argument = argument.Replace(option, ""); break; case "{cRemoteBranch}": if (currentRemoteBranches.Count == 1) argument = argument.Replace(option, currentRemoteBranches[0].Name); else if (currentRemoteBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentRemoteBranches, "Current Revision Remote Branch")); else argument = argument.Replace(option, ""); break; case "{cHash}": argument = argument.Replace(option, currentRevision.Guid); break; case "{cMessage}": argument = argument.Replace(option, currentRevision.Message); break; case "{cAuthor}": argument = argument.Replace(option, currentRevision.Author); break; case "{cCommitter}": argument = argument.Replace(option, currentRevision.Committer); break; case "{cAuthorDate}": argument = argument.Replace(option, currentRevision.AuthorDate.ToString()); break; case "{cCommitDate}": argument = argument.Replace(option, currentRevision.CommitDate.ToString()); break; case "{cDefaultRemote}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } argument = argument.Replace(option, currentRemote); break; case "{cDefaultRemoteUrl}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote)); argument = argument.Replace(option, url); break; case "{cDefaultRemotePathFromUrl}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote)); argument = argument.Replace(option, GetRemotePath(url)); break; case "{UserInput}": using (SimplePrompt Prompt = new SimplePrompt()) { Prompt.ShowDialog(); argument = argument.Replace(option, Prompt.UserInput); } break; case "{WorkingDir}": argument = argument.Replace(option, aModule.WorkingDir); break; } } command = ExpandCommandVariables(command,aModule); if (!scriptInfo.RunInBackground) FormProcess.ShowDialog(owner, command, argument, aModule.WorkingDir, null, true); else { if (originalCommand.Equals("{openurl}", StringComparison.CurrentCultureIgnoreCase)) Process.Start(argument); else aModule.RunExternalCmdDetached(command, argument); } return !scriptInfo.RunInBackground; }
internal void Bake() { scriptInfo = new ScriptInfo(ScriptTypeBuilder.CreateType(), null); //FastReflect(); }
private static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { ForStatement forStatement = new ForStatement(); MoveInfo moveInfo = new MoveInfo(parentInfo); // expGroup IElement tryExpGroup = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryExpGroup == null || !(tryExpGroup is ParenthesesGroup)) { throw new SyntaxException("Could not find for expressions", parentInfo.GetErrorInfo()); } ParenthesesGroup expGroup = (ParenthesesGroup)tryExpGroup; MoveInfo expGroupInfo = new MoveInfo(expGroup, SearchTree.ContentBlock, 0, parentInfo); // initializer IElement tryInitializer = expGroupInfo.Find(SearchDirection.LeftToRight, SearchVisibility.Visible); if (tryInitializer == null) { throw new SyntaxException("Could not parse for initializer", parentInfo.GetErrorInfo()); } if (!tryInitializer.IsTT(TokenType.SemiColon)) { if (!ExpressionStatement.Check(expGroupInfo, parsingInfo, scriptInfo, false)) { throw new SyntaxException("Could not parse for initializer", parentInfo.GetErrorInfo()); } expGroupInfo.FindNextBlack(SearchDirection.LeftToRight); } if (expGroupInfo.Current == null || !expGroupInfo.Current.IsTT(TokenType.SemiColon)) { throw new SyntaxException("Missing for first directive ';'?", parentInfo.GetErrorInfo()); } // expression IElement tryExpression = expGroupInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryExpression == null) { throw new SyntaxException("Could not parse for expression", parentInfo.GetErrorInfo()); } if (!tryExpression.IsTT(TokenType.SemiColon)) { Expression exp = Expression.Parse(expGroupInfo, parsingInfo, scriptInfo); if (exp == null) { throw new SyntaxException("Could not parse for expression", parentInfo.GetErrorInfo()); } expGroupInfo.FindNextBlack(SearchDirection.LeftToRight); } if (expGroupInfo.Current == null || !expGroupInfo.Current.IsTT(TokenType.SemiColon)) { throw new SyntaxException("Missing for second directive ';'?", parentInfo.GetErrorInfo()); } // iterator IElement tryIterator = expGroupInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryIterator != null) { if (!ExpressionStatement.Check(expGroupInfo, parsingInfo, scriptInfo, false)) { throw new SyntaxException("Could not parse for iterator", parentInfo.GetErrorInfo()); } IElement end = expGroupInfo.FindNextBlack(SearchDirection.LeftToRight); if (end != null) { throw new SyntaxException("Could not parse for iterator", parentInfo.GetErrorInfo()); } } // statement moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (!Statement.Check(moveInfo, parsingInfo, scriptInfo)) { throw new SyntaxException("Could not parse for statement", parentInfo.GetErrorInfo()); } // build int startIndex = parentInfo.CurrentIndex; int length = (moveInfo.CurrentIndex + 1) - startIndex; forStatement.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.Replace(length, forStatement); }
private void Persist(ScriptInfo script) { _assemblyReferenceGatherer.Gather(script.TypeDeclaration); CodeGeneratorOptions generatorOptions = new CodeGeneratorOptions(); generatorOptions.VerbatimOrder = true; string nameSpacePrefix = (string.IsNullOrEmpty(_context.Settings.Namespace) ? null : _context.Settings.Namespace + "."); CodeNamespace nameSpace = new CodeNamespace(nameSpacePrefix + script.NamespaceName); nameSpace.Types.Add(script.TypeDeclaration); _namespaceFactorizer.Factorize(nameSpace); string outputDirectory = (string.IsNullOrEmpty(_context.Settings.OutputDirectory) ? script.NamespaceName : Path.Combine(_context.Settings.OutputDirectory, script.NamespaceName)); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } string fileName = string.Format("{0}.{1}", script.ClassName, _context.CodeProvider.FileExtension); using (TextWriter writer = new StreamWriter(Path.Combine(outputDirectory, fileName))) { _context.CodeProvider.GenerateCodeFromNamespace(nameSpace, writer, generatorOptions); } }
private void ParseNew(ScriptInfo script) { if (!_context.Scripts.ContainsKey(script.PrefixedFullName)) { _context.Scripts.Add(script.PrefixedFullName, script); } _dependencyBuilder.Build(script); Parse(script); }
private void Build(ScriptInfo script) { _staticSetter.Set(script); _returnValueCorrector.Correct(script.TypeDeclaration); _stringLocalizer.Localize(script.TypeDeclaration); }
public void Parse(ScriptInfo script) { try { script.TypeDeclaration = _parser.Parse(script.Code); } catch (ParserException ex) { LogError(ex.Message); script.IsInvalid = true; } if (script.TypeDeclaration != null) { script.TypeDeclaration.Name = script.ClassName; CodeObjectMetaData.SetNamespaceName(script.TypeDeclaration, script.NamespaceName); _propertySetValueCorrector.Correct(script.TypeDeclaration); _propertyPartConsolidator.Consolidate(script.TypeDeclaration); _createObjectStrongTyper.Process(script.TypeDeclaration); _nestedClassConstructorCorrector.Process(script.TypeDeclaration); _identifierDiscoverer.Process(script.TypeDeclaration); } }
/// <summary> /// Resolves script corresponding to given parameters. /// </summary> /// <param name="path">Requested script path, absolute or relative in PHP manner.</param> /// <param name="root_path">The application root path. All scripts are relative to this directory.</param> /// <param name="include_path">List of include paths (absolute or relative) to search in. Can be <c>null</c>.</param> /// <param name="working_dir">Current working directory to search in after <paramref name="include_path"/>. Also <c>.</c> and <c>..</c> are relative to this directory.</param> /// <param name="script_dir">The directory of the currently executing script. Normalized. Can be <c>null</c>. Is relative to <paramref name="root_path"/>.</param> /// <returns>Script descriptor or empty an invalid script in case path inclusion cannot be resolved.</returns> public static ScriptInfo ResolveInclude(string path, string root_path, string[] include_path, string working_dir, string script_dir) { // check arguments Debug.Assert(root_path != null); ScriptInfo script = default(ScriptInfo); if (string.IsNullOrEmpty(path)) { return(script); } // 0. rooted path -> resolved if (Path.IsPathRooted(path)) { // normalize, check it is within root_path path = NormalizeSlashes(Path.GetFullPath(path)); if (path.StartsWith(root_path)) { script = GetDeclaredScript(path.Substring(root_path.Length + 1)); // TODO: script may be not loaded yet but exists physically, check it exists and compile } return(script); } // 1. ".." or "." are always relative to working_dir -> resolved if (path[0] == '.' && path.Length >= 2) { // ./ if (PathUtils.IsDirectorySeparator(path[1])) { return(ResolveRelativeScript(working_dir, path.Substring(2), root_path, working_dir)); } // ../ if (path[1] == '.' && path.Length >= 3 && PathUtils.IsDirectorySeparator(path[2])) { return(ResolveRelativeScript(Path.GetDirectoryName(working_dir), path.Substring(3), root_path, working_dir)); } } // 2. repeat for combinations with include_path if (include_path != null) { for (int i = 0; i < include_path.Length; i++) { script = ResolveRelativeScript(include_path[i], path, root_path, working_dir); if (script.IsValid) { return(script); } } } // 3. working_dir script = ResolveRelativeScript(working_dir, path, root_path, working_dir); if (script.IsValid) { return(script); } // 4. script_dir if (script_dir != null) { script = ResolveInclude(Path.Combine(root_path, script_dir, path), root_path, null, null, null); if (script.IsValid) { return(script); } } // return(script); }
private static CommandProcessorBase CreateCommandProcessorForScript(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) { sessionState = sessionState ?? (scriptInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState); CommandProcessorBase base2 = GetScriptAsCmdletProcessor(scriptInfo, context, useNewScope, true, sessionState); if (base2 != null) { return base2; } return new DlrScriptCommandProcessor(scriptInfo, context, useNewScope, sessionState); }
private void OnScriptInfoAdded(ScriptInfo scriptInfo) { ScriptNames = _scriptAccess.GetScriptNames(); ScriptName = scriptInfo.Name; }
////////////////////////////////////////////////////////////////////////// private void OnIntegrate(object sender, EventArgs e) { string ScitePath = Path.Combine(WmeUtils.ToolsPath, "scite"); if (!Directory.Exists(ScitePath)) Directory.CreateDirectory(ScitePath); string[] Extensions = ParentForm.GetExtensions(); string Extensions2 = ""; foreach (string Ext in Extensions) { if (Extensions2 != "") Extensions2 += ";"; Extensions2 += "*." + Ext; } // generate syntax file try { // read XML docs ScriptInfo Info = new ScriptInfo(); Info.ReadXml(WmeUtils.XmlDocsPath); string KwdFile = Path.Combine(ScitePath, "wme_kwd.properties"); using (StreamWriter sw = new StreamWriter(KwdFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("file.patterns.script=" + Extensions2); sw.WriteLine("filter.script=WME Scripts|$(file.patterns.script)|"); sw.WriteLine(); WordHolder wh; // keywords sw.WriteLine("keywords.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (string Keyword in ScriptTokenizer.Keywords) { wh.AddWord(Keyword); } sw.WriteLine(wh.GetWords()); // methods sw.WriteLine("keywords2.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { int Brace = Header.IndexOf("("); if (Brace >= 0) { wh.AddWord(Header.Substring(0, Brace).Trim()); } } } } sw.WriteLine(wh.GetWords()); // attributes sw.WriteLine("keywords4.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) continue; wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWords()); } // tools string ToolsFile = Path.Combine(ScitePath, "wme_tools.properties"); using (StreamWriter sw = new StreamWriter(ToolsFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("command.compile.$(file.patterns.script)=\"" + WmeUtils.CompilerPath + "\" -script \"$(FilePath)\" -format scite"); sw.WriteLine("command.help.$(file.patterns.script)=reference!" + Path.Combine(WmeUtils.ToolsPath, "wme.chm")); sw.WriteLine("command.help.subsystem.$(file.patterns.script)=4"); sw.WriteLine("api.$(file.patterns.script)=" + Path.Combine(WmeUtils.ToolsPath, "SciTE\\wme.api")); } // api string ApiFile = Path.Combine(ScitePath, "wme.api"); using (StreamWriter sw = new StreamWriter(ApiFile, false, Encoding.Default)) { WordHolder wh; wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { wh.AddWord(Header + Method.Desc); } } } foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) continue; wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWordsApi()); } } catch { } }
/// <summary> /// Gets all the mods and patches them. /// </summary> private void worker_DoWork(object sender, DoWorkEventArgs e) { _errorLevel = ErrorLevel.NoError; //Gets the list of mods ItemCollection modCollection = null; string lolLocation = null; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { modCollection = ModsListBox.Items; lolLocation = LocationTextbox.Text; })); SetStatusLabelAsync("Gathering mods..."); //Gets the list of mods that have been checked. List <LessMod> modsToPatch = new List <LessMod>(); foreach (var x in modCollection) { CheckBox box = (CheckBox)x; bool isBoxChecked = false; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { isBoxChecked = box.IsChecked ?? false; })); if (isBoxChecked) { modsToPatch.Add(_lessMods[box]); } } Dictionary <string, SwfFile> swfs = new Dictionary <string, SwfFile>(); timer = Stopwatch.StartNew(); foreach (var lessMod in modsToPatch) { Debug.Assert(lessMod.Patches.Length > 0); SetStatusLabelAsync("Patching mod: " + lessMod.Name); foreach (var patch in lessMod.Patches) { if (!swfs.ContainsKey(patch.Swf)) { string fullPath = Path.Combine(lolLocation, patch.Swf); //Backup the SWF string CurrentLocation = ""; string[] FileLocation = patch.Swf.Split('/', '\\'); foreach (string s in FileLocation.Take(FileLocation.Length - 1)) { CurrentLocation = Path.Combine(CurrentLocation, s); if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation))) { Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, CurrentLocation)); } } if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf))) { File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", INTENDED_VERSION, patch.Swf)); } swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath)); } SwfFile swf = swfs[patch.Swf]; List <DoAbcTag> tags = swf.GetDoAbcTags(); bool classFound = false; foreach (var tag in tags) { //check if this tag contains our script ScriptInfo si = tag.GetScriptByClassName(patch.Class); //check next tag if it doesn't if (si == null) { continue; } ClassInfo cls = si.GetClassByClassName(patch.Class); classFound = true; Assembler asm; switch (patch.Action) { case "replace_trait": //replace trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); TraitInfo newTrait = asm.Assemble() as TraitInfo; int traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); bool classTrait = false; if (traitIndex < 0) { traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); classTrait = true; } if (traitIndex < 0) { throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class)); } if (classTrait) { cls.Traits[traitIndex] = newTrait; } else { cls.Instance.Traits[traitIndex] = newTrait; } break; case "replace_cinit": //replace class constructor asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.ClassInit = asm.Assemble() as MethodInfo; break; case "replace_iinit": //replace instance constructor asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.Instance.InstanceInit = asm.Assemble() as MethodInfo; break; case "add_class_trait": //add new class trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); if (traitIndex < 0) { cls.Traits.Add(newTrait); } else { cls.Traits[traitIndex] = newTrait; } break; case "add_instance_trait": //add new instance trait (method) asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.Instance.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name); if (traitIndex < 0) { cls.Instance.Traits.Add(newTrait); } else { cls.Instance.Traits[traitIndex] = newTrait; } break; case "remove_class_trait": throw new NotImplementedException(); case "remove_instance_trait": throw new NotImplementedException(); default: throw new NotSupportedException("Unknown Action \"" + patch.Action + "\" in mod " + lessMod.Name); } } if (!classFound) { _errorLevel = ErrorLevel.UnableToPatch; throw new ClassNotFoundException(string.Format("Class {0} not found in file {1}", patch.Class, patch.Swf)); } } } //return; foreach (var patchedSwf in swfs) { try { SetStatusLabelAsync("Applying mods: " + patchedSwf.Key); string swfLoc = Path.Combine(lolLocation, patchedSwf.Key); SwfFile.WriteFile(patchedSwf.Value, swfLoc); } catch { _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow; if (Debugger.IsAttached) { throw; } } } timer.Stop(); }
public CommandProcessorBase CreateCommandProcessor(Command command) { string cmdName = command.CommandText; CommandInfo commandInfo = null; if (command.IsScript) { // TODO: take care of the script commands throw new NotImplementedException(this.ToString()); } if (commandInfo == null && _aliases.ContainsKey(cmdName)) { commandInfo = _aliases[cmdName].ReferencedCommand; } if (commandInfo == null && _cmdLets.ContainsKey(cmdName)) { commandInfo = _cmdLets[cmdName].First(); } if (commandInfo == null && _scripts.ContainsKey(cmdName)) { commandInfo = _scripts[cmdName]; } // TODO: if the command wasn't found should we treat is as a Script? if (commandInfo == null) { var parseTree = PowerShellGrammar.ParseInteractiveInput(command.CommandText); var statements = parseTree.EndBlock.Statements; if (statements.Count == 1 && statements.Single() is PipelineAst) { var pipelineAst = statements.Single() as PipelineAst; if (pipelineAst.PipelineElements.Count == 1 && pipelineAst.PipelineElements.Single() is CommandAst) { var commandAst = pipelineAst.PipelineElements.Single() as CommandAst; if (commandAst.CommandElements.Count == 1 && commandAst.CommandElements.Single() is StringConstantExpressionAst) { var stringAst = commandAst.CommandElements.Single() as StringConstantExpressionAst; if (File.Exists(stringAst.Value) && Path.GetExtension(stringAst.Value) == ".ps1") { // I think we should be using a ScriptFile parser, but this will do for now. commandInfo = new ScriptInfo(stringAst.Value, new ScriptBlock(PowerShellGrammar.ParseInteractiveInput(File.ReadAllText(stringAst.Value)))); } else { throw new Exception(string.Format("Command '{0}' not found.", cmdName)); } } } } if (commandInfo == null) commandInfo = new ScriptInfo("", new ScriptBlock(parseTree)); } if (commandInfo != null) { switch (commandInfo.CommandType) { case CommandTypes.Cmdlet: return new CommandProcessor(commandInfo as CmdletInfo); case CommandTypes.Function: // TODO: teat the function as a script break; case CommandTypes.Script: return new ScriptProcessor(commandInfo as ScriptInfo); } } throw new Exception(string.Format("Command '{0}' not found.", cmdName)); }
internal static void RunScript(IWin32Window owner, GitModule aModule, ScriptInfo scriptInfo, RevisionGrid revisionGrid) { string command = scriptInfo.Command; string argument = scriptInfo.Arguments; command = OverrideCommandWhenNecessary(command); GitRevision selectedRevision = null; GitRevision currentRevision = null; var selectedLocalBranches = new List<GitRef>(); var selectedRemoteBranches = new List<GitRef>(); var selectedRemotes = new List<string>(); var selectedBranches = new List<GitRef>(); var selectedTags = new List<GitRef>(); var currentLocalBranches = new List<GitRef>(); var currentRemoteBranches = new List<GitRef>(); var currentRemote = ""; var currentBranches = new List<GitRef>(); var currentTags = new List<GitRef>(); foreach (string option in Options) { if (string.IsNullOrEmpty(argument) || !argument.Contains(option)) continue; if (!option.StartsWith("{s") || selectedRevision != null) { currentRevision = GetCurrentRevision(aModule, revisionGrid, currentTags, currentLocalBranches, currentRemoteBranches, currentBranches, currentRevision, option); if (currentLocalBranches.Count == 1) currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", currentLocalBranches[0].Name)); else { currentRemote = aModule.GetCurrentRemote(); if (string.IsNullOrEmpty(currentRemote)) currentRemote = aModule.GetSetting(string.Format("branch.{0}.remote", askToSpecify(currentLocalBranches, "Current Revision Branch"))); } } else { selectedRevision = CalculateSelectedRevision(revisionGrid, selectedRemoteBranches, selectedRemotes, selectedLocalBranches, selectedBranches, selectedTags); } string remote; string url; switch (option) { case "{sTag}": if (selectedTags.Count == 1) argument = argument.Replace(option, selectedTags[0].Name); else if (selectedTags.Count != 0) argument = argument.Replace(option, askToSpecify(selectedTags, "Selected Revision Tag")); else argument = argument.Replace(option, ""); break; case "{sBranch}": if (selectedBranches.Count == 1) argument = argument.Replace(option, selectedBranches[0].Name); else if (selectedBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedBranches, "Selected Revision Branch")); else argument = argument.Replace(option, ""); break; case "{sLocalBranch}": if (selectedLocalBranches.Count == 1) argument = argument.Replace(option, selectedLocalBranches[0].Name); else if (selectedLocalBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedLocalBranches, "Selected Revision Local Branch")); else argument = argument.Replace(option, ""); break; case "{sRemoteBranch}": if (selectedRemoteBranches.Count == 1) argument = argument.Replace(option, selectedRemoteBranches[0].Name); else if (selectedRemoteBranches.Count != 0) argument = argument.Replace(option, askToSpecify(selectedRemoteBranches, "Selected Revision Remote Branch")); else argument = argument.Replace(option, ""); break; case "{sRemote}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); argument = argument.Replace(option, remote); break; case "{sRemoteUrl}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote)); argument = argument.Replace(option, url); break; case "{sRemotePathFromUrl}": if (selectedRemotes.Count == 0) { argument = argument.Replace(option, ""); break; } if (selectedRemotes.Count == 1) remote = selectedRemotes[0]; else remote = askToSpecify(selectedRemotes, "Selected Revision Remote"); url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, remote)); argument = argument.Replace(option, GetRemotePath(url)); break; case "{sHash}": argument = argument.Replace(option, selectedRevision.Guid); break; case "{sMessage}": argument = argument.Replace(option, selectedRevision.Message); break; case "{sAuthor}": argument = argument.Replace(option, selectedRevision.Author); break; case "{sCommitter}": argument = argument.Replace(option, selectedRevision.Committer); break; case "{sAuthorDate}": argument = argument.Replace(option, selectedRevision.AuthorDate.ToString()); break; case "{sCommitDate}": argument = argument.Replace(option, selectedRevision.CommitDate.ToString()); break; case "{cTag}": if (currentTags.Count == 1) argument = argument.Replace(option, currentTags[0].Name); else if (currentTags.Count != 0) argument = argument.Replace(option, askToSpecify(currentTags, "Current Revision Tag")); else argument = argument.Replace(option, ""); break; case "{cBranch}": if (currentBranches.Count == 1) argument = argument.Replace(option, currentBranches[0].Name); else if (currentBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentBranches, "Current Revision Branch")); else argument = argument.Replace(option, ""); break; case "{cLocalBranch}": if (currentLocalBranches.Count == 1) argument = argument.Replace(option, currentLocalBranches[0].Name); else if (currentLocalBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentLocalBranches, "Current Revision Local Branch")); else argument = argument.Replace(option, ""); break; case "{cRemoteBranch}": if (currentRemoteBranches.Count == 1) argument = argument.Replace(option, currentRemoteBranches[0].Name); else if (currentRemoteBranches.Count != 0) argument = argument.Replace(option, askToSpecify(currentRemoteBranches, "Current Revision Remote Branch")); else argument = argument.Replace(option, ""); break; case "{cHash}": argument = argument.Replace(option, currentRevision.Guid); break; case "{cMessage}": argument = argument.Replace(option, currentRevision.Message); break; case "{cAuthor}": argument = argument.Replace(option, currentRevision.Author); break; case "{cCommitter}": argument = argument.Replace(option, currentRevision.Committer); break; case "{cAuthorDate}": argument = argument.Replace(option, currentRevision.AuthorDate.ToString()); break; case "{cCommitDate}": argument = argument.Replace(option, currentRevision.CommitDate.ToString()); break; case "{cDefaultRemote}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } argument = argument.Replace(option, currentRemote); break; case "{cDefaultRemoteUrl}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote)); argument = argument.Replace(option, url); break; case "{cDefaultRemotePathFromUrl}": if (string.IsNullOrEmpty(currentRemote)) { argument = argument.Replace(option, ""); break; } url = aModule.GetPathSetting(string.Format(SettingKeyString.RemoteUrl, currentRemote)); argument = argument.Replace(option, GetRemotePath(url)); break; case "{UserInput}": using (SimplePrompt Prompt = new SimplePrompt()) { Prompt.ShowDialog(); argument = argument.Replace(option, Prompt.UserInput); } break; } } if (scriptInfo.ShowProgress) FormProcess.ShowDialog(owner, command, argument, aModule.WorkingDir, null, true); else aModule.RunExternalCmdDetached(command, argument); }
internal bool IsIncluded(ScriptInfo script) => script.IsValid && IsIncluded(script.Index);
public SpringConfigWatcherEventArgs(ScriptInfo scriptInfo) { ScriptInfo = scriptInfo; }
/// <summary> /// Declares script within runtime. The script will be available for inclusions. /// </summary> public static void DeclareScript(ScriptInfo script) => throw new NotImplementedException(); // ScriptsMap.DeclareScript( ... )
protected IMohidTask LoadLibrary(FileName library_file_path, string task_class) { ScriptInfo si = scripts.Find(delegate(ScriptInfo info) { return info.ScriptFile.FullPath == library_file_path.FullPath; }); if (si != null) { si.Interface.Reset(); return si.Interface; } else { Assembly ass; try { ass = Assembly.LoadFrom(library_file_path.FullPath); } catch (Exception ex) { throw new Exception("Error when trying to compile " + library_file_path.FullPath + ". The message returned was " + ex.Message); } si = new ScriptInfo(); si.ScriptFile = library_file_path; Type t = ass.GetType(task_class); if (t.GetInterface("IMohidTask", true) != null) si.Interface = (IMohidTask)ass.CreateInstance(t.FullName); scripts.Add(si); return si.Interface; } }
public virtual void Compile(MoveInfo treeInfo, ScriptInfo scriptInfo, CompilingInfo compilingInfo) { }
////////////////////////////////////////////////////////////////////////// private void OnIntegrate(object sender, EventArgs e) { string ScitePath = Path.Combine(WmeUtils.ToolsPath, "scite"); if (!Directory.Exists(ScitePath)) { Directory.CreateDirectory(ScitePath); } string[] Extensions = ParentForm.GetExtensions(); string Extensions2 = ""; foreach (string Ext in Extensions) { if (Extensions2 != "") { Extensions2 += ";"; } Extensions2 += "*." + Ext; } // generate syntax file try { // read XML docs ScriptInfo Info = new ScriptInfo(); Info.ReadXml(WmeUtils.XmlDocsPath); string KwdFile = Path.Combine(ScitePath, "wme_kwd.properties"); using (StreamWriter sw = new StreamWriter(KwdFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("file.patterns.script=" + Extensions2); sw.WriteLine("filter.script=WME Scripts|$(file.patterns.script)|"); sw.WriteLine(); WordHolder wh; // keywords sw.WriteLine("keywords.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (string Keyword in ScriptTokenizer.Keywords) { wh.AddWord(Keyword); } sw.WriteLine(wh.GetWords()); // methods sw.WriteLine("keywords2.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { int Brace = Header.IndexOf("("); if (Brace >= 0) { wh.AddWord(Header.Substring(0, Brace).Trim()); } } } } sw.WriteLine(wh.GetWords()); // attributes sw.WriteLine("keywords4.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) { continue; } wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWords()); } // tools string ToolsFile = Path.Combine(ScitePath, "wme_tools.properties"); using (StreamWriter sw = new StreamWriter(ToolsFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("command.compile.$(file.patterns.script)=\"" + WmeUtils.CompilerPath + "\" -script \"$(FilePath)\" -format scite"); sw.WriteLine("command.help.$(file.patterns.script)=reference!" + Path.Combine(WmeUtils.ToolsPath, "wme.chm")); sw.WriteLine("command.help.subsystem.$(file.patterns.script)=4"); sw.WriteLine("api.$(file.patterns.script)=" + Path.Combine(WmeUtils.ToolsPath, "SciTE\\wme.api")); } // api string ApiFile = Path.Combine(ScitePath, "wme.api"); using (StreamWriter sw = new StreamWriter(ApiFile, false, Encoding.Default)) { WordHolder wh; wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { wh.AddWord(Header + Method.Desc); } } } foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) { continue; } wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWordsApi()); } } catch { } }
public static FuncDefParam Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { FuncDefParam param = new FuncDefParam(); MoveInfo moveInfo = new MoveInfo(parentInfo); MoveInfo wordMoveInfo = moveInfo; IElement wordTry = moveInfo.Find(SearchDirection.LeftToRight, SearchVisibility.Visible); int startIndex = moveInfo.CurrentIndex; if (wordTry == null) { throw new SyntaxException("Could not parse FuncDef param", parentInfo.GetErrorInfo()); } if (wordTry is SQBracketGroup) { param._group = (SQBracketGroup)wordTry; param.Optional = true; MoveInfo bracketInfo = new MoveInfo((SQBracketGroup)wordTry, SearchTree.ContentBlock, 0, moveInfo); wordTry = bracketInfo.Find(SearchDirection.LeftToRight, SearchVisibility.Visible); wordMoveInfo = bracketInfo; } if (wordTry == null || !wordTry.IsTT(TokenType.Word)) { throw new SyntaxException("Could not parse FuncDef param", parentInfo.GetErrorInfo()); } VarName.Parse(wordMoveInfo, parsingInfo, scriptInfo); param.VarName = (VarName)wordMoveInfo.Current; param.Name = wordTry.ToString(); param.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, moveInfo.CurrentIndex - startIndex + 1)); parentInfo.Replace((moveInfo.CurrentIndex + 1) - startIndex, param); return(param); }
// HACK: all functions are currently stored as scripts. But I'm confused, so I don't know how to fix it. internal void SetFunction(/*FunctionInfo */ScriptInfo functionInfo) { this._scripts[functionInfo.Name] = functionInfo; }
public void GetItemInfo( string name, ScriptInfo returnMask, [Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] item, [Out] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] typeInfo) { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() name:" + ValidationHelper.ToString(name)); if (name == null) { throw new ArgumentNullException("name"); } if (name != c_ScriptHelperName) { throw new COMException(null, (int) HRESULT.TYPE_E_ELEMENTNOTFOUND); } if ((returnMask & ScriptInfo.IUnknown) != 0) { if (item == null) { throw new ArgumentNullException("item"); } GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Setting item."); item[0] = helper; } if ((returnMask & ScriptInfo.ITypeInfo) != 0) { if (typeInfo == null) { throw new ArgumentNullException("typeInfo"); } typeInfo[0] = IntPtr.Zero; } GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Done."); }
private static void Parse(MoveInfo parentInfo, ParsingInfo parsingInfo, ScriptInfo scriptInfo) { int startIndex = parentInfo.CurrentIndex; MoveInfo moveInfo = new MoveInfo(parentInfo); // modifier MemberAccess access; AccessModifier modifier = AccessModifier.GetModifier(moveInfo, out access); if (modifier != null) { startIndex = moveInfo.CurrentIndex; } // name moveInfo = new MoveInfo(parentInfo); IElement tryName = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (tryName == null || !tryName.IsTT(TokenType.Word)) { throw new SyntaxException("Could not find using name", parentInfo.GetErrorInfo()); } string name = tryName.ToString(); UsingDef usingDef = new UsingDef(moveInfo.Current.CharIndex, moveInfo.Current.CharLength, moveInfo.Current.LineIndex); // assign moveInfo.FindNextBlack(SearchDirection.LeftToRight); // = moveInfo.FindNextBlack(SearchDirection.LeftToRight); // behind = // expression Path pathTry = Path.Parse(moveInfo, parsingInfo, scriptInfo); if (pathTry == null) { throw new SyntaxException("Could not find using path", parentInfo.GetErrorInfo()); } // terminal IElement terminalTry = moveInfo.FindNextBlack(SearchDirection.LeftToRight); if (terminalTry == null || !(terminalTry.IsTT(TokenType.SemiColon))) { throw new SyntaxException("Missing directive ';'?", parentInfo.GetErrorInfo()); } int length = (moveInfo.CurrentIndex + 1) - startIndex; usingDef.AddChildren(parentInfo.CurrentElements.GetRange(startIndex, length)); parentInfo.MoveToIndex(startIndex); parentInfo.Replace(length, usingDef); // info // add const def to list parsingInfo.UsingDefList.Add(usingDef); /*if (scriptInfo.Constants.FindIndex(a => a.Name == name) != -1) * ErrorManager.Semantic("Constant '" + name + "' already defined", new ErrorInfo(parentInfo.ErrorInfo)); * else * {*/ UsingInfo usingInfo = new UsingInfo(scriptInfo.SF, name, pathTry.ToString(), access, usingDef); scriptInfo.AddUsing(usingInfo); usingDef._usingInfo = usingInfo; //} }
private static void DeserializeFromOldFormat(string inputString) { const string PARAM_SEPARATOR = "<_PARAM_SEPARATOR_>"; const string SCRIPT_SEPARATOR = "<_SCRIPT_SEPARATOR_>"; if (inputString.Contains(PARAM_SEPARATOR) || inputString.Contains(SCRIPT_SEPARATOR)) { Scripts = new BindingList<ScriptInfo>(); string[] scripts = inputString.Split(new string[] { SCRIPT_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < scripts.Length; i++) { string[] parameters = scripts[i].Split(new string[] { PARAM_SEPARATOR }, StringSplitOptions.None); ScriptInfo scriptInfo = new ScriptInfo(); scriptInfo.Name = parameters[0]; scriptInfo.Command = parameters[1]; scriptInfo.Arguments = parameters[2]; scriptInfo.AddToRevisionGridContextMenu = parameters[3].Equals("yes"); scriptInfo.Enabled = true; Scripts.Add(scriptInfo); } } }
public void SystemInitialize(ScriptInfo info) { _info = info; }
internal DlrScriptCommandProcessor(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState) : base(scriptInfo, context, useNewScope, sessionState) { this._input = new ArrayList(); this.Init(); }
public virtual void CheckSemantic(MoveInfo treeInfo, ScriptInfo scriptInfo, CheckingInfo checkingInfo) { }
/// <summary> /// /// </summary> /// <param name="scriptInfo"></param> public void SetScript(ScriptInfo scriptInfo) { ScriptInfo = scriptInfo; }
public XmlElement ToXML(XmlDocument doc, XmlElement elem, ScriptInfo si) { elem.SetAttribute("tokenType", Type.GetName()); elem.InnerText = StringContent; return(elem); }
private void btnSaveScript_Click(object sender, EventArgs e) { string scriptName = txtScriptName.Text; if (string.IsNullOrEmpty(scriptName)) { MessageBox.Show("Script name can't be empty.", Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } ScriptInfo scriptInfo = Scripts.FirstOrDefault(x => x.Name.Equals(scriptName, StringComparison.InvariantCultureIgnoreCase)); if (scriptInfo != null) { scriptInfo.Script = rtbInput.Text; scriptInfo.LineDelay = (int)nudLineDelay.Value; } else { scriptInfo = new ScriptInfo() { Name = scriptName, Script = rtbInput.Text, LineDelay = (int)nudLineDelay.Value }; Scripts.Add(scriptInfo); AddScript(scriptInfo); } }
private static void AddDefaultScripts() { ScriptInfo fetchAfterCommitScript = new ScriptInfo(); fetchAfterCommitScript.HotkeyCommandIdentifier = 9000; fetchAfterCommitScript.Name = "Fetch changes after commit"; fetchAfterCommitScript.Command = "git"; fetchAfterCommitScript.Arguments = "fetch"; fetchAfterCommitScript.AskConfirmation = true; fetchAfterCommitScript.OnEvent = ScriptEvent.AfterCommit; fetchAfterCommitScript.AddToRevisionGridContextMenu = false; fetchAfterCommitScript.Enabled = false; Scripts.Add(fetchAfterCommitScript); ScriptInfo updateSubmodulesAfterPullScript = new ScriptInfo(); updateSubmodulesAfterPullScript.HotkeyCommandIdentifier = 9001; updateSubmodulesAfterPullScript.Name = "Update submodules after pull"; updateSubmodulesAfterPullScript.Command = "git"; updateSubmodulesAfterPullScript.Arguments = "submodule update"; updateSubmodulesAfterPullScript.AskConfirmation = true; updateSubmodulesAfterPullScript.OnEvent = ScriptEvent.AfterPull; updateSubmodulesAfterPullScript.AddToRevisionGridContextMenu = false; updateSubmodulesAfterPullScript.Enabled = false; Scripts.Add(updateSubmodulesAfterPullScript); ScriptInfo userMenuScript = new ScriptInfo(); userMenuScript.HotkeyCommandIdentifier = 9002; userMenuScript.Name = "Example"; userMenuScript.Command = "c:\\windows\\system32\\calc.exe"; userMenuScript.Arguments = ""; userMenuScript.AskConfirmation = false; userMenuScript.OnEvent = ScriptEvent.ShowInUserMenuBar; userMenuScript.AddToRevisionGridContextMenu = false; userMenuScript.Enabled = false; Scripts.Add(userMenuScript); }
private void AddScript(ScriptInfo scriptInfo) { lvScripts.Items.Add(scriptInfo.Name).Tag = scriptInfo; }