public ScriptEngine() { this.lexer = new ScriptLexer(); this.parser = new ScriptParser(); this.codeGenerator = new CodeGenerator(); this.codeCompiler = new CodeCompiler(); this.executionContext = new ScriptExecutionContext(); }
/// <summary> /// Tries to parse a script node. /// </summary> /// <param name="Parser">Custom parser.</param> /// <param name="Result">Parsed Script Node.</param> /// <returns>If successful in parsing a script node.</returns> public bool TryParse(ScriptParser Parser, out ScriptNode Result) { Result = null; try { List <ScriptNode> Columns; List <ScriptNode> ColumnNames; ScriptNode Top = null; string s; bool Distinct = false; s = Parser.PeekNextToken().ToUpper(); if (string.IsNullOrEmpty(s)) { return(false); } while (s == "TOP" || s == "DISTINCT") { switch (s) { case "TOP": Parser.NextToken(); Top = Parser.ParseNoWhiteSpace(); break; case "DISTINCT": Parser.NextToken(); Distinct = true; break; } s = Parser.PeekNextToken(); if (string.IsNullOrEmpty(s)) { return(false); } } if (s == "*") { Parser.NextToken(); Columns = null; ColumnNames = null; } else { Columns = new List <ScriptNode>(); ColumnNames = new List <ScriptNode>(); while (true) { ScriptNode Node = Parser.ParseNoWhiteSpace(); ScriptNode Name = null; Parser.SkipWhiteSpace(); s = Parser.PeekNextToken().ToUpper(); if (!string.IsNullOrEmpty(s) && s != "," && s != "FROM") { if (s == "AS") { Parser.NextToken(); } Name = Parser.ParseNoWhiteSpace(); s = Parser.PeekNextToken(); } else if (Node is VariableReference Ref) { Name = new ConstantElement(new StringValue(Ref.VariableName), Node.Start, Node.Length, Node.Expression); } else if (Node is NamedMember NamedMember) { Name = new ConstantElement(new StringValue(NamedMember.Name), Node.Start, Node.Length, Node.Expression); } Columns.Add(Node); ColumnNames.Add(Name); if (s != ",") { break; } Parser.NextToken(); } } s = Parser.NextToken().ToUpper(); if (s != "FROM") { return(false); } if (!TryParseSources(Parser, out SourceDefinition Source)) { return(false); } ScriptNode Where = null; s = Parser.PeekNextToken().ToUpper(); if (s == "WHERE") { Parser.NextToken(); Where = Parser.ParseOrs(); s = Parser.PeekNextToken().ToUpper(); } List <ScriptNode> GroupBy = null; List <ScriptNode> GroupByNames = null; ScriptNode Having = null; if (s == "GROUP") { Parser.NextToken(); if (Parser.NextToken().ToUpper() != "BY") { return(false); } GroupBy = new List <ScriptNode>(); GroupByNames = new List <ScriptNode>(); while (true) { ScriptNode Node = Parser.ParseNoWhiteSpace(); ScriptNode Name = null; Parser.SkipWhiteSpace(); s = Parser.PeekNextToken().ToUpper(); if (!string.IsNullOrEmpty(s) && s != "," && s != "HAVING" && s != "ORDER" && s != "OFFSET") { if (s == "AS") { Parser.NextToken(); } Name = Parser.ParseNoWhiteSpace(); s = Parser.PeekNextToken().ToUpper(); } else if (Node is VariableReference Ref) { Name = new ConstantElement(new StringValue(Ref.VariableName), Node.Start, Node.Length, Node.Expression); } else if (Node is NamedMember NamedMember) { Name = new ConstantElement(new StringValue(NamedMember.Name), Node.Start, Node.Length, Node.Expression); } GroupBy.Add(Node); GroupByNames.Add(Name); if (s != ",") { break; } Parser.NextToken(); } if (s == "HAVING") { Parser.NextToken(); Having = Parser.ParseOrs(); s = Parser.PeekNextToken().ToUpper(); } } else if (!(Columns is null)) { bool ImplicitGrouping = false; foreach (ScriptNode Column in Columns) { if (this.ContainsVectorFunction(Column)) { ImplicitGrouping = true; break; } } if (ImplicitGrouping) { GroupBy = new List <ScriptNode>(); GroupByNames = new List <ScriptNode>(); } } List <KeyValuePair <ScriptNode, bool> > OrderBy = null; if (s == "ORDER") { Parser.NextToken(); if (Parser.NextToken().ToUpper() != "BY") { return(false); } OrderBy = new List <KeyValuePair <ScriptNode, bool> >(); while (true) { ScriptNode Node = Parser.ParseNoWhiteSpace(); s = Parser.PeekNextToken().ToUpper(); if (s == "ASC") { Parser.NextToken(); OrderBy.Add(new KeyValuePair <ScriptNode, bool>(Node, true)); s = Parser.PeekNextToken().ToUpper(); } else if (s == "DESC") { Parser.NextToken(); OrderBy.Add(new KeyValuePair <ScriptNode, bool>(Node, false)); s = Parser.PeekNextToken().ToUpper(); } else { OrderBy.Add(new KeyValuePair <ScriptNode, bool>(Node, true)); } if (s != ",") { break; } Parser.NextToken(); } } ScriptNode Offset = null; if (s == "OFFSET") { Parser.NextToken(); Offset = Parser.ParseNoWhiteSpace(); } Result = new Select(Columns?.ToArray(), ColumnNames?.ToArray(), Source, Where, GroupBy?.ToArray(), GroupByNames?.ToArray(), Having, OrderBy?.ToArray(), Top, Offset, Distinct, Parser.Start, Parser.Length, Parser.Expression); return(true); } catch (Exception) { return(false); } }
public static void DrawSelectionText(Graphics graphics, ScriptFile scriptFile, ScriptMessage message, bool alternative = false) { Color fontColor = Color.FromArgb(255, 255, 255); Font font = scriptFile.Font; int left = 15; int top = 7; string[] lines = null; if (alternative) { lines = ScriptParser.TextToLines(message.ContentAlternative); } else { lines = ScriptParser.TextToLines(message.Content); } bool open = false; if (lines != null) { foreach (string line in lines) { if (line.StartsWith("%SEL:")) { open = true; continue; } if (line.StartsWith("%END:")) { open = false; continue; } if (open) { string[] splitted = line.Split(','); if (splitted.Length < 3) { continue; } string displayText = splitted[2]; for (int i = 0; i < displayText.Length; i++) { char character = displayText[i]; if (left >= 223 || top >= 159) { continue; } if (scriptFile.IsValidChar(character)) { i++; if (i == displayText.Length) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else if (scriptFile.IsValidChar(displayText[i])) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character, displayText[i]), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } } } } top += 16; left = 15; } } }
public void Format(ScriptFile script, bool ignoreMissing = true) { StringBuilder stringBuilder = new StringBuilder(); string[] lines = ScriptParser.TextToLines(Content); stringBuilder.AppendLine(lines[0]); for (int l = 1; l < lines.Length; l++) { string[] splitted = lines[l].Split(','); if (splitted.Length != 3) { throw new Exception("NO!"); } string displayText = splitted[2]; stringBuilder.Append(splitted[0] + "," + splitted[1] + ","); for (int i = 0; i < displayText.Length; i++) { bool pair = false; string neededSymbol = displayText[i].ToString(); if (i + 1 < displayText.Length) { if (script.IsValidChar(displayText[i + 1])) { neededSymbol += displayText[i + 1]; pair = true; } else { neededSymbol += " "; } } else { neededSymbol += " "; } bool found = false; foreach (FontCharacter fontCharacter in script.GeneratedFont) { if (fontCharacter.Symbol == neededSymbol) { byte[] bytes = BitConverter.GetBytes(fontCharacter.Index); stringBuilder.Append(_shiftJis.GetString(bytes)); found = true; if (pair) { i++; } break; } } if (!found) { if (!ignoreMissing) { MessageBox.Show("Couldn't find the needed symbol in the generated font.\nGenerate the font before formating!", "Format Error!"); return; } } } stringBuilder.Append("\r\n"); } Content = stringBuilder.ToString(); }
public ScriptTests() { battle = ViewPort.Tools.CodeTool.BattleScriptParser; }
/// <summary> /// Compiles C# script file. /// </summary> private string Compile(string scriptFileName) { bool generateExe = options.GetBool("buildExecutable"); bool localAssembliesUsed = false; string scriptDir = Path.GetDirectoryName(scriptFileName); string assemblyFileName = ""; //parse source file in order to find all referenced assemblies //ASSUMPTION: assembly name is the same as namespace + ".dll" //if script doesn't follow this assumption user will need to //specify assemblies explicitly ScriptParser parser = new ScriptParser(scriptFileName); if (parser.apartmentState != ApartmentState.Unknown) Thread.CurrentThread.SetApartmentState(parser.apartmentState); //ICodeCompiler compiler = (new CSharpCodeProvider()).CreateCompiler(); CodeDomProvider c = new CSharpCodeProvider(); CompilerParameters compileParams = new CompilerParameters(); compileParams.IncludeDebugInformation = options.GetBool("DBG"); compileParams.GenerateExecutable = generateExe; compileParams.GenerateInMemory = !generateExe; //some assemblies were referenced from command line if (options.IsSet("refAssemblies")) { foreach (string asmName in (string[]) options["refAssemblies"]) { string asmLocation = Path.Combine(scriptDir, asmName); if (File.Exists(asmLocation)) { compileParams.ReferencedAssemblies.Add(asmLocation); localAssembliesUsed = true; } } } AssemblyResolver.ignoreFileName = Path.GetFileNameWithoutExtension(scriptFileName) + ".dll"; foreach (string nmSpace in parser.ReferencedNamespaces) { //find local and global assemblies assuming assembly name is the same as a namespace foreach (string asmLocation in AssemblyResolver.FindAssembly(nmSpace, scriptDir)) { compileParams.ReferencedAssemblies.Add(asmLocation); if (!localAssembliesUsed) localAssembliesUsed = (Path.GetDirectoryName(asmLocation) == scriptDir); } } foreach (string asmName in parser.ReferencedAssemblies) //some assemblies were referenced from code { string asmLocation = Path.Combine(scriptDir, asmName); if (File.Exists(asmLocation)) { compileParams.ReferencedAssemblies.Add(asmLocation); localAssembliesUsed = true; } } if (options.IsSet("forceOutputAssembly")) { assemblyFileName = (string) options["forceOutputAssembly"]; } else { if (generateExe) assemblyFileName = Path.Combine(scriptDir, Path.GetFileNameWithoutExtension(scriptFileName) + ".exe"); else if (options.GetBool("useCompiled") || localAssembliesUsed) if (options.GetBool("DLLExtension")) assemblyFileName = Path.Combine(scriptDir, Path.GetFileNameWithoutExtension(scriptFileName) + ".dll"); else assemblyFileName = Path.Combine(scriptDir, scriptFileName + "c"); else assemblyFileName = Path.GetTempFileName(); } compileParams.OutputAssembly = assemblyFileName; if (generateExe && options.GetBool("buildWinExecutable")) compileParams.CompilerOptions = "/target:winexe"; if (File.Exists(assemblyFileName)) File.Delete(assemblyFileName); CompilerResults results = c.CompileAssemblyFromFile(compileParams, parser.FilesToCompile); if (results.Errors.Count != 0) { StringBuilder compileErr = new StringBuilder(); foreach (CompilerError err in results.Errors) { compileErr.Append(err.ToString()); } throw new Exception(compileErr.ToString()); } else { parser.DeleteImportedFiles(); if (!options.GetBool("DBG")) //pdb file might be needed for a debugger { string pdbFile = Path.Combine(Path.GetDirectoryName(assemblyFileName), Path.GetFileNameWithoutExtension(assemblyFileName) + ".pdb"); if (File.Exists(pdbFile)) File.Delete(pdbFile); } FileInfo scriptFile = new FileInfo(scriptFileName); FileInfo asmFile = new FileInfo(assemblyFileName); if (scriptFile != null && asmFile != null) { asmFile.LastWriteTime = scriptFile.LastWriteTime; asmFile.LastWriteTimeUtc = scriptFile.LastWriteTimeUtc; } } return assemblyFileName; }
public TokenInt(ScriptParser parser) : base(parser) { }
/// <summary> /// Loads all scripts from a directory /// </summary> private static void loadDirScripts(ref List<ScriptParser> scripts, string directory) { //Create lists of files to define for each bot type foreach (string dir in Directory.GetDirectories(directory)) { //For each cs file in this directory foreach (string f in Directory.GetFiles(dir, "*.cs", SearchOption.AllDirectories)) { //Attempt to compile it string[] dirpath = f.Split(new char[] { Path.DirectorySeparatorChar }); //Obtain the subdir path string path = null; for (int i = 0; i < dirpath.Length - 1; ++i) { //Look for scripts.. if (dirpath[i].Equals("scripts", StringComparison.CurrentCultureIgnoreCase)) //Start forming our path path = new string(' ', 0); else if (path != null) path += dirpath[i] + "\\"; } //Trim the last slash path = path.Trim(new char[] { '\\' }); //Parse the script and add to the dictionary ScriptParser parser = new ScriptParser(f, true); scripts.Add(parser); //Which bot type does this belong to? InvokerType scriptType = null; foreach (InvokerType bt in _invokerTypes) if (bt.scriptDir == path) { scriptType = bt; break; } //If it belongs to a specific type, add it if (scriptType != null) { parser.m_namespace = "D3Bloader." + scriptType.name; scriptType.scripts.Add(f); } } } }
public TokenString(ScriptParser parser) : base(parser) { }
public void LoadConfig(MainLoadingForm loadingForm) { Config.ObjectSlotManagerGui = new ObjectSlotManagerGui() { TabControl = tabControlMain, LockLabelsCheckbox = checkBoxObjLockLabels, FlowLayoutContainer = WatchVariablePanelObjects, SortMethodComboBox = comboBoxSortMethod, LabelMethodComboBox = comboBoxLabelMethod, SelectionMethodComboBox = comboBoxSelectionMethod, }; int statusNum = 0; // Read configuration loadingForm.UpdateStatus("Loading main configuration", statusNum++); XmlConfigParser.OpenConfig(@"Config/Config.xml"); XmlConfigParser.OpenSavedSettings(@"Config/SavedSettings.xml"); loadingForm.UpdateStatus("Loading Miscellaneous Data", statusNum++); loadingForm.UpdateStatus("Loading Object Data", statusNum++); loadingForm.UpdateStatus("Loading Object Associations", statusNum++); Config.ObjectAssociations = XmlConfigParser.OpenObjectAssoc(@"Config/ObjectAssociations.xml", Config.ObjectSlotManagerGui); loadingForm.UpdateStatus("Loading Mario Data", statusNum++); loadingForm.UpdateStatus("Loading Camera Data", statusNum++); loadingForm.UpdateStatus("Loading Actions Data", statusNum++); loadingForm.UpdateStatus("Loading Water Data", statusNum++); loadingForm.UpdateStatus("Loading Input Data", statusNum++); loadingForm.UpdateStatus("Loading Input Image Associations", statusNum++); _inputImageGuiList = XmlConfigParser.CreateInputImageAssocList(@"Config/InputImageAssociations.xml"); loadingForm.UpdateStatus("Loading File Data", statusNum++); loadingForm.UpdateStatus("Loading File Image Associations", statusNum++); XmlConfigParser.OpenFileImageAssoc(@"Config/FileImageAssociations.xml", _fileImageGui); loadingForm.UpdateStatus("Loading Area Data", statusNum++); loadingForm.UpdateStatus("Loading Quarter Frame Data", statusNum++); loadingForm.UpdateStatus("Loading Camera Hack Data", statusNum++); loadingForm.UpdateStatus("Loading Triangles Data", statusNum++); loadingForm.UpdateStatus("Loading Debug Data", statusNum++); loadingForm.UpdateStatus("Loading HUD Data", statusNum++); loadingForm.UpdateStatus("Loading Map Associations", statusNum++); Config.MapAssociations = XmlConfigParser.OpenMapAssoc(@"Config/MapAssociations.xml"); loadingForm.UpdateStatus("Loading Scripts", statusNum++); _scriptParser = XmlConfigParser.OpenScripts(@"Config/Scripts.xml"); loadingForm.UpdateStatus("Loading Hacks", statusNum++); _romHacks = XmlConfigParser.OpenHacks(@"Config/Hacks.xml"); loadingForm.UpdateStatus("Loading Mario Actions", statusNum++); TableConfig.MarioActions = XmlConfigParser.OpenActionTable(@"Config/MarioActions.xml"); TableConfig.MarioAnimations = XmlConfigParser.OpenAnimationTable(@"Config/MarioAnimations.xml"); TableConfig.TriangleInfo = XmlConfigParser.OpenTriangleInfoTable(@"Config/TriangleInfo.xml"); TableConfig.PendulumSwings = XmlConfigParser.OpenPendulumSwingTable(@"Config/PendulumSwings.xml"); TableConfig.RacingPenguinWaypoints = XmlConfigParser.OpenWaypointTable(@"Config/RacingPenguinWaypoints.xml"); TableConfig.KoopaTheQuick1Waypoints = XmlConfigParser.OpenWaypointTable(@"Config/KoopaTheQuick1Waypoints.xml"); TableConfig.KoopaTheQuick2Waypoints = XmlConfigParser.OpenWaypointTable(@"Config/KoopaTheQuick2Waypoints.xml"); TableConfig.TtmBowlingBallPoints = XmlConfigParser.OpenPointTable(@"Config/TtmBowlingBallPoints.xml"); TableConfig.MusicData = XmlConfigParser.OpenMusicTable(@"Config/MusicData.xml"); TableConfig.Missions = XmlConfigParser.OpenMissionTable(@"Config/Missions.xml"); TableConfig.CourseData = XmlConfigParser.OpenCourseDataTable(@"Config/CourseData.xml"); TableConfig.FlyGuyData = new FlyGuyDataTable(); TableConfig.WdwRotatingPlatformTable = new ObjectAngleTable(1120); TableConfig.ElevatorAxleTable = new ObjectAngleTable(400); loadingForm.UpdateStatus("Creating Managers", statusNum++); CreateManagers(); loadingForm.UpdateStatus("Finishing", statusNum); }
public TokenComment(ScriptParser parser) : base(parser) { }
public void Initialize() { List <string> list = new List <string>(); list.Add("Sounds/Chatters/"); list.Add("Sounds/TempSounds/Chatters/"); for (int i = 0; i < list.Count; i++) { foreach (AudioClip audioClip in Resources.LoadAll <AudioClip>(list[i])) { string key = audioClip.name.ToLower(); if (this.m_AllClips.ContainsKey(key)) { Debug.Log("[DialogsManager:Start] ERROR - duplicated clip names " + audioClip.name); } else { this.m_AllClips.Add(key, audioClip); } } } this.m_AudioSource = base.transform.GetComponentInChildren <AudioSource>(); this.m_AudioSource.rolloffMode = AudioRolloffMode.Linear; this.m_AudioSource.maxDistance = 10f; ScriptParser scriptParser = new ScriptParser(); scriptParser.Parse("WTSounds.txt", true); for (int k = 0; k < scriptParser.GetKeysCount(); k++) { Key key2 = scriptParser.GetKey(k); if (key2.GetName() == "Before") { string[] array2 = key2.GetVariable(0).SValue.Split(new char[] { ';' }); for (int l = 0; l < array2.Length; l++) { AudioClip audioClip2 = Resources.Load <AudioClip>("Sounds/WT/" + array2[l]); if (!audioClip2) { audioClip2 = Resources.Load <AudioClip>("Sounds/TempSounds/WT/" + array2[l]); } if (!audioClip2) { DebugUtils.Assert("Can't find sound - " + array2[l], true, DebugUtils.AssertType.Info); } else { this.m_WTBeforeSounds.Add(audioClip2); } } } else if (key2.GetName() == "After") { string[] array3 = key2.GetVariable(0).SValue.Split(new char[] { ';' }); for (int m = 0; m < array3.Length; m++) { AudioClip audioClip3 = Resources.Load <AudioClip>("Sounds/WT/" + array3[m]); if (!audioClip3) { audioClip3 = Resources.Load <AudioClip>("Sounds/TempSounds/WT/" + array3[m]); } if (!audioClip3) { DebugUtils.Assert("Can't find sound - " + array3[m], true, DebugUtils.AssertType.Info); } else { this.m_WTAfterSounds.Add(audioClip3); } } } } this.LoadScript(false); }
public void Populate() { Merges = new List <MergeDescriptor.Merge>(); var statementParser = new MergeStatementParser(); var parser = new ScriptParser(statementParser, _path); parser.Parse(); foreach (var mergeStatement in statementParser.Merges) { if (!(mergeStatement.MergeSpecification.Target is NamedTableReference)) { Log.WriteInfo("Error Parsing Merge Statement, Target is not a NamedTableReference"); continue; } var name = (mergeStatement.MergeSpecification.Target as NamedTableReference).SchemaObject; var table = _tables.Get().FirstOrDefault(p => p.Name.EqualsName(name)); if (table == null) { Log.WriteInfo( "Error Parsing Merge Statement, Could not find table name ({0}) in the TableRepository", name.BaseIdentifier.Value); continue; } if (!(mergeStatement.MergeSpecification.TableReference is InlineDerivedTable)) { Log.WriteInfo("Error Parsing Merge Statement, Could not find InlineDerivedTable"); continue; } var merge = new MergeDescriptor.Merge(); merge.CustommMerger = mergeStatement; merge.Name = name.ToIdentifier(); merge.Data = GetDataFromMerge(mergeStatement, table); if (null == merge.Data) { continue; //can't do anything with this } merge.Data.AcceptChanges(); merge.ScriptDescriptor = new InScriptDescriptor(mergeStatement.StartOffset, mergeStatement.FragmentLength, _path); merge.Statement = mergeStatement; merge.Table = table; bool hasSearchKeys = false; var searchCondition = mergeStatement.MergeSpecification.SearchCondition as BooleanComparisonExpression; if (null != searchCondition) { var col = searchCondition.FirstExpression as ColumnReferenceExpression; if (col != null) { var searchColName = col.MultiPartIdentifier.Identifiers.Last(); if (searchColName.Value == "???") { hasSearchKeys = false; } else { hasSearchKeys = true; } } } merge.Option = new MergeOptions( mergeStatement.MergeSpecification.ActionClauses.Any(p => p.Condition == MergeCondition.Matched), mergeStatement.MergeSpecification.ActionClauses.Any( p => p.Condition == MergeCondition.NotMatchedByTarget), mergeStatement.MergeSpecification.ActionClauses.Any( p => p.Condition == MergeCondition.NotMatchedBySource) , hasSearchKeys ); Merges.Add(merge); } }
public static void Main(string[] args) { if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))) { Console.WriteLine(usage); } else if (args.Length == 1) { try { scriptFile = ResolveScriptFile(args[0]); string tempDir = Path.Combine(Path.GetDirectoryName(scriptFile), Path.GetFileNameWithoutExtension(scriptFile)); if (Directory.Exists(tempDir)) { try { Directory.Delete(tempDir, true); } catch (Exception e) { throw new Exception("Cannot clean destination folder "+tempDir+"\n"+e.Message); } } Directory.CreateDirectory(tempDir); ScriptParser parser = new ScriptParser(scriptFile); foreach (string file in parser.FilesToCompile) //contains scriptFile + imported { IsolateFile(file, tempDir, Path.GetDirectoryName(scriptFile)); } foreach (string name in parser.ReferencedAssemblies) foreach (string file in AssemblyResolver.FindAssembly(name, SearchDirs)) if (file.IndexOf("assembly\\GAC") == -1 && file.IndexOf("assembly/GAC") == -1) File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true); foreach (string name in parser.ReferencedNamespaces) foreach (string file in AssemblyResolver.FindAssembly(name, SearchDirs)) if (file.IndexOf("assembly\\GAC") == -1 && file.IndexOf("assembly/GAC") == -1) File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true); Console.WriteLine("Script "+Path.GetFileName(scriptFile)+" is isolated to folder: "+ new DirectoryInfo(tempDir).FullName); } catch(Exception ex) { Console.WriteLine(ex.Message); } } else if (args[1].ToLower() == @"/vs7" || args[1].ToLower() == @"/vs8") { string scriptFile = args[0]; if (!File.Exists(scriptFile) && !scriptFile.EndsWith(".cs") && File.Exists(scriptFile+".cs")) scriptFile = scriptFile+".cs"; scriptFile = Path.GetFullPath(scriptFile); string scHomeDir = Environment.GetEnvironmentVariable("CSSCRIPT_DIR"); if (args[1].ToLower() == @"/vs7") RunScript("\"" + Path.Combine(scHomeDir, @"lib\DebugVS7.1.cs ") + "\" /prj \""+scriptFile+"\""); else RunScript("\"" + Path.Combine(scHomeDir, @"lib\DebugVS8.0.cs ") + "\" /prj \"" + scriptFile + "\""); } }
public TokenLeftBracket(ScriptParser parser) : base(parser) { }
public void ExecuteSimpleScript() { var script = @" var myjson = { 'blabla':'oops', 'yep':'yep', 'format':{ 'text'='{{' } }; var a = 10; var b = 2017-01-02; #recognized as date type var b2 = @2017-01-02; #evaluated as 2017 sub 1 sub 2 var c = day(b) + a; if(c > 10, return (c), return (-1)); #the following works as well: if(c > 10, ( return(c) #note that return is a custom function, defined in the SyntaxExtension ); else( return (-1) ); ); "; var parser = new ScriptParser <SyntaxExtension>(strict: true); var context = new SyntaxExtension(); var fn = parser.Compile <SyntaxExtension, int>(script); fn(context); Assert.AreEqual(12, context.Result); // the following works because the context still is around, and strict is true // (strict: any identifier that that cannot be resolved as a member nor variable declaration is assumed to be a late-context-bound variable, it is attempted to be resolved during execution) // (not strict: any identifier that that cannot be resolved as a member nor variable declaration is assumed to be a string value) var script2 = "return(a);"; fn = parser.Compile <SyntaxExtension, int>(script2); fn(context); Assert.AreEqual(10, context.Result); fn = parser.Compile <SyntaxExtension, int>("return(b2)"); fn(context); Assert.AreEqual(2017 - 1 - 2, context.Result); // now lets create a new context context = new SyntaxExtension(); try { // we expect an exception here, because the variable belongs to another context fn(context); throw new Exception("Exception expected"); } catch (XPressionException ex) { Debug.WriteLine(ex.FullMessage); } // non strict (= default) example parser = new ScriptParser <SyntaxExtension>(strict: false); context = new SyntaxExtension(); fn = parser.Compile <SyntaxExtension, int>("return(a)"); fn(context); Assert.AreEqual("a", context.Result); // non strict is convenient in url queries, where using quotes often is annoying }
public void FulltextOrderingTest() { ScriptParser parser = new ScriptParser(); parser.Parse("CREATE FULLTEXT CATALOG Fulltext AS DEFAULT"); parser.Parse(@"CREATE TABLE Searching ( SearchingID int NOT NULL, SearchText varchar(max), MoreText varchar(max), LastUpdate timestamp )"); parser.Parse("CREATE UNIQUE CLUSTERED INDEX PK_Searching ON dbo.Searching(SearchingID)"); parser.Parse(@"CREATE FULLTEXT INDEX ON Searching( SearchText, MoreText ) KEY INDEX PK_Searching ON Fulltext WITH CHANGE_TRACKING AUTO"); Assert.AreEqual(1, parser.Database.Tables.Count); Assert.AreEqual(1, parser.Database.Tables[0].Indexes.Count); Assert.AreEqual(1, parser.Database.FulltextIndexes.Count); ScriptSet scripts = parser.Database.CreateDiffScripts(new Database()); scripts.Sort(); Assert.AreEqual(4, scripts.Count); Assert.AreEqual(ScriptType.Table, scripts[0].Type); Assert.AreEqual(ScriptType.ClusteredIndex, scripts[1].Type); Assert.AreEqual(ScriptType.FulltextCatalog, scripts[2].Type); Assert.AreEqual(ScriptType.FulltextIndex, scripts[3].Type); ExecuteScripts(scripts); ScriptParser database = ParseDatabase(); ScriptSet difference = parser.Database.CreateDiffScripts(database.Database); Assert.AreEqual(0, difference.Count, RunOptions.Current.Logger.ToString()); parser = new ScriptParser(); parser.Parse(@"CREATE TABLE Searching ( SearchingID int NOT NULL, SearchText varchar(max), MoreText varchar(max), LastUpdate timestamp )"); parser.Parse("CREATE UNIQUE CLUSTERED INDEX PK_Searching ON dbo.Searching(SearchingID)"); parser.Parse(@"CREATE FULLTEXT INDEX ON Searching( MoreText, --swap the order SearchText ) KEY INDEX PK_Searching ON Fulltext WITH CHANGE_TRACKING AUTO"); Assert.AreEqual(1, parser.Database.Tables.Count); Assert.AreEqual(1, parser.Database.Tables[0].Indexes.Count); Assert.AreEqual(1, parser.Database.FulltextIndexes.Count); difference = parser.Database.CreateDiffScripts(database.Database); difference.Sort(); Assert.AreEqual(0, difference.Count); }
private string GetScript() { var parser = new ScriptParser(this.Path); return(parser.Get()); }
public void FulltextViewTest() { ScriptParser parser = new ScriptParser(); parser.Parse("CREATE FULLTEXT CATALOG Fulltext AS DEFAULT"); parser.Parse(@"CREATE TABLE Searching ( SearchingID int PRIMARY KEY, SearchText varchar(max) )"); parser.Parse(@"CREATE VIEW SearchView WITH SCHEMABINDING AS SELECT SearchingID, SearchText FROM dbo.Searching"); parser.Parse("CREATE UNIQUE CLUSTERED INDEX IX_SearchView ON SearchView(SearchingID)"); parser.Parse(@"CREATE FULLTEXT INDEX ON SearchView( SearchText LANGUAGE English ) KEY INDEX IX_SearchView ON Fulltext WITH CHANGE_TRACKING AUTO"); Assert.AreEqual(1, parser.Database.Tables.Count); Assert.AreEqual(1, parser.Database.FulltextIndexes.Count); Assert.AreEqual(1, parser.Database.Views.Count); ScriptSet scripts = parser.Database.CreateDiffScripts(new Database()); scripts.Sort(); Assert.AreEqual(6, scripts.Count); Assert.AreEqual(ScriptType.Table, scripts[0].Type); Assert.AreEqual(ScriptType.View, scripts[1].Type); Assert.AreEqual(ScriptType.PrimaryKey, scripts[2].Type); Assert.AreEqual(ScriptType.ClusteredIndex, scripts[3].Type); Assert.AreEqual(ScriptType.FulltextCatalog, scripts[4].Type); Assert.AreEqual(ScriptType.FulltextIndex, scripts[5].Type); ExecuteScripts(scripts); ScriptParser database = ParseDatabase(); ScriptSet difference = parser.Database.CreateDiffScripts(database.Database); Assert.AreEqual(0, difference.Count, RunOptions.Current.Logger.ToString()); parser = new ScriptParser(); parser.Parse(@"CREATE TABLE Searching ( SearchingID int PRIMARY KEY, Foo int, SearchText varchar(max) )"); parser.Parse(@"CREATE VIEW SearchView WITH SCHEMABINDING AS SELECT SearchingID, SearchText FROM dbo.Searching"); parser.Parse("CREATE UNIQUE CLUSTERED INDEX IX_SearchView ON SearchView(SearchingID)"); parser.Parse(@"CREATE FULLTEXT INDEX ON SearchView( SearchText LANGUAGE English ) KEY INDEX IX_SearchView ON Fulltext WITH CHANGE_TRACKING AUTO"); Assert.AreEqual(1, parser.Database.Tables.Count); Assert.AreEqual(1, parser.Database.FulltextIndexes.Count); Assert.AreEqual(1, parser.Database.Views.Count); difference = parser.Database.CreateDiffScripts(database.Database); difference.Sort(); Assert.AreEqual(11, difference.Count); Assert.AreEqual(ScriptType.DropFulltextIndex, difference[0].Type); Assert.AreEqual(ScriptType.DropPrimaryKey, difference[1].Type); Assert.AreEqual(ScriptType.DropClusteredIndex, difference[2].Type); Assert.AreEqual(ScriptType.DropView, difference[3].Type); Assert.AreEqual(ScriptType.TableSaveData, difference[4].Type); Assert.AreEqual(ScriptType.Table, difference[5].Type); Assert.AreEqual(ScriptType.View, difference[6].Type); Assert.AreEqual(ScriptType.PrimaryKey, difference[7].Type); Assert.AreEqual(ScriptType.ClusteredIndex, difference[8].Type); Assert.AreEqual(ScriptType.TableRestoreData, difference[9].Type); Assert.AreEqual(ScriptType.FulltextIndex, difference[10].Type); ExecuteScripts(difference); database = ParseDatabase(); difference = parser.Database.CreateDiffScripts(database.Database); Assert.AreEqual(0, difference.Count, RunOptions.Current.Logger.ToString()); }
public Expression Parse(ScriptParser parser, Expression left, ScriptToken token) { var name = parser.Take(ScriptTokenType.Identifier); return(new FieldExpression(left, name)); }
static public Project GenerateProjectFor(string script) { // Debug.Assert(false); // ******************************************************************************************** // * Extremely important to keep the project building algorithm in sync with CSExecutor.Compile // ******************************************************************************************** var project = new Project { Script = script }; var searchDirs = new List <string>(); searchDirs.Add(Path.GetDirectoryName(script)); var globalConfig = GetGlobalConfigItems(); var defaultSearchDirs = globalConfig.dirs; var defaultRefAsms = globalConfig.asms; var defaultNamespaces = globalConfig.namespaces; searchDirs.AddRange(defaultSearchDirs); ScriptParser parser; using (var currDir = new CurrentDirGuard()) { Environment.CurrentDirectory = Path.GetDirectoryName(script); parser = new ScriptParser(script, searchDirs.ToArray(), false); } CSExecutor.options.preCompilers = parser.Precompilers .Select(x => FileParser.ResolveFile(x, CSExecutor.options.searchDirs)) .AddItem(CSExecutor.options.preCompilers) .JoinBy(","); PrecompilationContext precompiling = CSSUtils.Precompile(script, parser.FilesToCompile.Distinct(), CSExecutor.options); // search dirs could be also defined in the script var probingDirs = searchDirs.Concat(parser.SearchDirs) .Where(x => !string.IsNullOrEmpty(x)) .Distinct() .ToArray(); var sources = parser.SaveImportedScripts().ToList(); //this will also generate auto-scripts and save them sources.Insert(0, script); //if (parser.Packages.Any() && NotifyClient != null) //{ // NotifyClient("Processing NuGet packages..."); //} project.Files = sources.Distinct().Select <string, string>(Utils.PathNormaliseSeparators).ToArray(); project.Refs = parser.AgregateReferences(probingDirs, defaultRefAsms, defaultNamespaces) .Map(Utils.PathNormaliseSeparators, Utils.EnsureAsmExtension) .ToArray(); project.Refs = project.Refs.ConcatWith(precompiling.NewReferences); project.Files = project.Files.ConcatWith(precompiling.NewIncludes); project.SearchDirs = probingDirs.Select <string, string>(Utils.PathNormaliseSeparators).ToArray(); return(project); }
public Runtime(Type debugMainType = null, params string[] args) { _debugMainType = debugMainType; Config = new Config(args); if (args.Length == 0) { if (Debugging) { Log.Warn(Tr.Get("Runtime.DebugNoMainScript")); } else { var error = Tr.Get("Runtime.NoArgs"); Log.Fatal(error, this); throw new ArgumentException(error, nameof(args)); } } else { try { _mainScript = new FileInfo(args[0]); } catch { } if (_mainScript != null && _mainScript.Exists) { RootPath = _mainScript.Directory; Directory.SetCurrentDirectory(RootPath.FullName); ScriptParser.ParseSetDirectives(_mainScript, (key, value) => Config[key] = value); } else { if (Debugging) { Log.Warn(Tr.Get("Runtime.DebugNoMainScript")); } else { var error = Tr.Get("Runtime.MainScriptMissing", _mainScript?.FullName ?? args[0]); Log.Fatal(error, this); throw new FileNotFoundException(error); } } } if (Config.LogToFile && Log.SetLogFile(new FileInfo(Config.LogFilename), Config.LogAppend)) { Log.ShowConsoleOutput = Config.LogToConsole; } if (Enum.TryParse(Config.ConsoleLogLevel, true, out LogLevels logLevel)) { Log.ConsoleLogLevel = logLevel; } else { Log.Warn(Tr.Get("Runtime.UnknownLogLevel", Config.ConsoleLogLevel)); } if (Enum.TryParse(Config.FileLogLevel, true, out logLevel)) { Log.FileLogLevel = logLevel; } else { Log.Warn(Tr.Get("Runtime.UnknownLogLevel", Config.FileLogLevel)); } Tr.LoadFiles(new DirectoryInfo(Config.TranslationPath)); AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += AssemblyResolve; var pathList = Config.AssemblyPath.Split(','); foreach (var path in pathList) { var di = new DirectoryInfo(path.Trim()); if (di.Exists) { _assemblyDirectories.Add(di); } } _assemblyDirectories.Add(new DirectoryInfo(Path.GetDirectoryName(MsCoreLib.Location))); var domainAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in domainAssemblies) { if (assembly != MsCoreLib) { _referencedAssemblies.Add(assembly); } } ReferenceAssembly(GetType().Assembly); ReferenceAssembly(typeof(System.Net.IPNetwork).Assembly); ReferenceAssembly(typeof(YamlDotNet.Core.IEmitter).Assembly); }
public TokenBool(ScriptParser parser) : base(parser) { }
public void TableUpdateTest() { ScriptSet initScripts = new ScriptSet(); initScripts.Add(new Script("CREATE TABLE foo( a varchar(10), b varchar(10))", "Foo", ScriptType.Table)); initScripts.Add(new Script(@"INSERT INTO foo(a,b) VALUES('X', 'Y') INSERT INTO foo(a,b) VALUES('A','B')", "FooData", ScriptType.TableData)); ExecuteScripts(initScripts); ScriptSet updateScripts = new ScriptSet(); updateScripts.Add(new Script("CREATE TABLE foo( a varchar(10))", "Foo", ScriptType.Table)); updateScripts.Add(new Script( @"INSERT INTO foo(a) VALUES('X') INSERT INTO foo(a) VALUES('Y') INSERT INTO dbo.foo(a) VALUES('Z') insert into dbo.foo(a) values('yabba')", "FooData", ScriptType.TableData)); ScriptParser parsedScripts = new ScriptParser(); parsedScripts.RetrieveParsableObjects(updateScripts); Assert.AreEqual(0, updateScripts.Count); ScriptParser parsedDatabase = ParseDatabase(); GetData(parsedDatabase.Database, parsedScripts.Database.GetTablesWithData()); updateScripts.Add(parsedScripts.Database.CreateDiffScripts(parsedDatabase.Database)); Assert.AreEqual(5, updateScripts.Count); updateScripts.Sort(); Assert.AreEqual(@"DELETE FROM [dbo].[foo] WHERE [a] = 'X' AND [b] = 'Y' DELETE FROM [dbo].[foo] WHERE [a] = 'A' AND [b] = 'B' ", updateScripts[0].Text); Assert.AreEqual(ScriptType.TableRemoveData, updateScripts[0].Type); Assert.AreEqual(@"EXEC sp_rename '[dbo].[foo]', 'Tmp__foo', 'OBJECT'", updateScripts[1].Text); Assert.AreEqual(ScriptType.TableSaveData, updateScripts[1].Type); Assert.AreEqual(@"CREATE TABLE [dbo].[foo]( [a] [varchar](10) NULL ) GO", updateScripts[2].Text); Assert.AreEqual(ScriptType.Table, updateScripts[2].Type); Assert.AreEqual(@"INSERT INTO [dbo].[foo]([a]) VALUES('X') INSERT INTO [dbo].[foo]([a]) VALUES('Y') INSERT INTO [dbo].[foo]([a]) VALUES('Z') INSERT INTO [dbo].[foo]([a]) VALUES('yabba') ", updateScripts[3].Text); Assert.AreEqual(ScriptType.TableData, updateScripts[3].Type); ExecuteScripts(updateScripts); ScriptParser currentDatabase = ParseDatabase(); GetData(currentDatabase.Database, parsedScripts.Database.GetTablesWithData()); ScriptSet difference = parsedScripts.Database.CreateDiffScripts(currentDatabase.Database); Assert.AreEqual(0, difference.Count, RunOptions.Current.Logger.ToString()); }
public void SetScript(string script) { this.Script = script; commands = ScriptParser.ParseCommandStrings(script); }
static void Main(string[] args) { if (args.Length < 1) { OutputUsage(); return; } string mode = args[0]; string rdrfile; string inofile = null; switch (mode) { case "/trans": case "/write": rdrfile = args[1]; if (args.Length > 2) { inofile = args[2]; } break; default: rdrfile = args[0]; inofile = null; break; } PluginManager pluginManager = new PluginManager(); var plugin = PluginManager.Load(typeof(Program).Assembly) as PNamespacePlugin; pluginManager.AddStandard(plugin); string rdrName = Path.GetFileNameWithoutExtension(rdrfile); string rdrDir = Path.GetDirectoryName(rdrfile); if (inofile == null) { string inoDir = Path.Combine(rdrDir, rdrName); Directory.CreateDirectory(inoDir); inofile = Path.Combine(inoDir, rdrName + ".ino"); } else { } string inoFN = Path.GetFileName(inofile); //共通設定の読み込み string settingConfig = "settings.json"; string json; if (File.Exists(settingConfig)) { json = File.ReadAllText(settingConfig); } else { json = ""; } Settings setting = JsonConvert.DeserializeObject <Settings>(json); //個別設定の読み込み string settingConfig2 = Path.Combine(rdrDir, rdrName + ".json"); if (File.Exists(settingConfig2)) { string json2 = File.ReadAllText(settingConfig2); Settings setting2 = JsonConvert.DeserializeObject <Settings>(json2); if (setting2.SensorPort != null) { setting.SensorPort = setting2.SensorPort; } if (setting2.ServomotorPort != null) { setting.ServomotorPort = setting2.ServomotorPort; } if (setting2.DCMotorPort != null) { setting.DCMotorPort = setting2.DCMotorPort; } } ScriptParser parser = new ScriptParser(false); ProduireFile rdr = parser.ParseFrom(rdrfile, pluginManager); var compiler = new StuduinoCodeGenerator(); compiler.Settings = setting; if (!compiler.Compile(rdr, inofile)) { Console.WriteLine("変換に失敗しました。"); return; } if (mode != "/trans") { //転送 string temp = Path.GetTempPath(); string build_dir = Path.Combine(temp, @"rdr_arduino_build"); string cache_dir = Path.Combine(temp, @"rdr_arduino_cache"); Directory.CreateDirectory(build_dir); Directory.CreateDirectory(cache_dir); string code = File.ReadAllText("board.bat"); code = code.Replace("{Arduino_dir}", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Arduino\")); code = code.Replace("{lib_dir}", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Arduino\libraries")); code = code.Replace("{ino_file}", inofile); code = code.Replace("{comport}", setting.ComPort); code = code.Replace("{build_dir}", build_dir); code = code.Replace("{cache_dir}", cache_dir); code = code.Replace("{inoFileName}", inoFN); File.WriteAllText("compile.bat", code, Encoding.Default); Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += p_OutputDataReceived; p.ErrorDataReceived += P_ErrorDataReceived; p.StartInfo.FileName = "compile.bat"; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); Directory.Delete(build_dir, true); Directory.Delete(cache_dir, true); Console.WriteLine("完了しました。"); } else { Console.WriteLine("成功しました!"); } }
private void ParseFile(string script_name) { ScriptParser scriptParser = new ScriptParser(); scriptParser.Parse("Player/" + script_name, true); for (int i = 0; i < scriptParser.GetKeysCount(); i++) { Key key = scriptParser.GetKey(i); if (key.GetName() == "MaxStamina") { this.m_MaxStamina = key.GetVariable(0).FValue; } else if (key.GetName() == "Stamina") { this.m_Stamina = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxEnergy") { this.m_MaxEnergy = key.GetVariable(0).FValue; } else if (key.GetName() == "Energy") { this.m_Energy = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxHP") { this.m_MaxHP = key.GetVariable(0).FValue; } else if (key.GetName() == "HP") { this.m_HP = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxNutritionFat") { this.m_MaxNutritionFat = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFat") { this.m_NutritionFat = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxNutritionCarbo") { this.m_MaxNutritionCarbo = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbo") { this.m_NutritionCarbo = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxNutritionProtein") { this.m_MaxNutritionProteins = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProtein") { this.m_NutritionProteins = key.GetVariable(0).FValue; } else if (key.GetName() == "MaxHydration") { this.m_MaxHydration = key.GetVariable(0).FValue; } else if (key.GetName() == "Hydration") { this.m_Hydration = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaConsumptionWalkPerSecond") { this.m_StaminaConsumptionWalkPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaConsumptionRunPerSecond") { this.m_StaminaConsumptionRunPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaConsumptionDepletedPerSecond") { this.m_StaminaConsumptionDepletedPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaRegenerationPerSecond") { this.m_StaminaRegenerationPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaDepletedLevel") { this.m_StaminaDepletedLevel = key.GetVariable(0).FValue; } else if (key.GetName() == "StaminaDecrease") { this.m_StaminaDecreaseMap.Add((int)Enum.Parse(typeof(StaminaDecreaseReason), key.GetVariable(0).SValue), key.GetVariable(1).FValue); } else if (key.GetName() == "EnergyDecrease") { this.m_EnergyDecreaseMap.Add((int)Enum.Parse(typeof(EnergyDecreaseReason), key.GetVariable(0).SValue), key.GetVariable(1).FValue); } else if (key.GetName() == "OxygenConsumptionPerSecond") { this.m_OxygenConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyConsumptionPerSecond") { this.m_EnergyConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyConsumptionPerSecondNoNutrition") { this.m_EnergyConsumptionPerSecondNoNutrition = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyConsumptionPerSecondFever") { this.m_EnergyConsumptionPerSecondFever = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyConsumptionPerSecondFoodPoison") { this.m_EnergyConsumptionPerSecondFoodPoison = key.GetVariable(0).FValue; } else if (key.GetName() == "HealtLossPerSecondNoNutrition") { this.m_HealthLossPerSecondNoNutrition = key.GetVariable(0).FValue; } else if (key.GetName() == "HealthLossPerSecondNoHydration") { this.m_HealthLossPerSecondNoHydration = key.GetVariable(0).FValue; } else if (key.GetName() == "HealthRecoveryPerDay") { this.m_HealthRecoveryPerDay = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionPerSecond") { this.m_NutritionCarbohydratesConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionPerSecond") { this.m_NutritionFatConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionPerSecond") { this.m_NutritionProteinsConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionMulNoCarbs") { this.m_NutritionFatConsumptionMulNoCarbs = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionMulNoCarbs") { this.m_NutritionProteinsConsumptionMulNoCarbs = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionRunMul") { this.m_NutritionCarbohydratesConsumptionRunMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionRunMul") { this.m_NutritionFatConsumptionRunMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionRunMul") { this.m_NutritionProteinsConsumptionRunMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionActionMul") { this.m_NutritionCarbohydratesConsumptionActionMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionActionMul") { this.m_NutritionFatConsumptionActionMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionActionMul") { this.m_NutritionProteinsConsumptionActionMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionWeightNormalMul") { this.m_NutritionCarbohydratesConsumptionWeightNormalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionWeightNormalMul") { this.m_NutritionFatConsumptionWeightNormalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionWeightNormalMul") { this.m_NutritionFatConsumptionWeightNormalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionWeightNormalMul") { this.m_NutritionProteinsConsumptionWeightNormalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionWeightOverloadMul") { this.m_NutritionCarbohydratesConsumptionWeightOverloadMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionWeightOverloadMul") { this.m_NutritionFatConsumptionWeightOverloadMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionWeightOverloadMul") { this.m_NutritionProteinsConsumptionWeightOverloadMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionCarbohydratesConsumptionWeightCriticalMul") { this.m_NutritionCarbohydratesConsumptionWeightCriticalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionFatConsumptionWeightCriticalMul") { this.m_NutritionFatConsumptionWeightCriticalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "NutritionProteinsConsumptionWeightCriticalMul") { this.m_NutritionProteinsConsumptionWeightCriticalMul = key.GetVariable(0).FValue; } else if (key.GetName() == "HydrationConsumptionPerSecond") { this.m_HydrationConsumptionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "HydrationConsumptionDuringFeverPerSecond") { this.m_HydrationConsumptionDuringFeverPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "HydrationConsumptionRunMul") { this.m_HydrationConsumptionRunMul = key.GetVariable(0).FValue; } else if (key.GetName() == "HydrationDecreaseJump") { this.m_HydrationDecreaseJump = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyLossDueLackOfNutritionPerSecond") { this.m_EnergyLossDueLackOfNutritionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyRecoveryDueNutritionPerSecond") { this.m_EnergyRecoveryDueNutritionPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "EnergyRecoveryDueHydrationPerSecond") { this.m_EnergyRecoveryDueHydrationPerSecond = key.GetVariable(0).FValue; } else if (key.GetName() == "HealthLossPerSecondNoOxygen") { this.m_HealthLossPerSecondNoOxygen = key.GetVariable(0).FValue; } } }
internal static bool TryParseSources(ScriptParser Parser, out SourceDefinition Source) { if (!TryParseSource(Parser, out Source)) { return(false); } while (true) { string s = Parser.PeekNextToken().ToUpper(); switch (s) { case ",": Parser.NextToken(); if (!TryParseSource(Parser, out SourceDefinition Source2)) { return(false); } Source = new CrossJoin(Source, Source2, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; case "INNER": case "JOIN": Parser.NextToken(); if (s == "INNER") { if (Parser.NextToken().ToUpper() != "JOIN") { return(false); } } if (!TryParseSource(Parser, out Source2)) { return(false); } ScriptNode Conditions = ParseJoinConditions(Parser); Source = new InnerJoin(Source, Source2, Conditions, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; case "LEFT": Parser.NextToken(); switch (Parser.NextToken().ToUpper()) { case "JOIN": break; case "OUTER": if (Parser.NextToken().ToUpper() != "JOIN") { return(false); } break; default: return(false); } if (!TryParseSource(Parser, out Source2)) { return(false); } Conditions = ParseJoinConditions(Parser); Source = new LeftOuterJoin(Source, Source2, Conditions, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; case "RIGHT": Parser.NextToken(); switch (Parser.NextToken().ToUpper()) { case "JOIN": break; case "OUTER": if (Parser.NextToken().ToUpper() != "JOIN") { return(false); } break; default: return(false); } if (!TryParseSource(Parser, out Source2)) { return(false); } Conditions = ParseJoinConditions(Parser); Source = new RightOuterJoin(Source, Source2, Conditions, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; case "FULL": Parser.NextToken(); switch (Parser.NextToken().ToUpper()) { case "JOIN": break; case "OUTER": if (Parser.NextToken().ToUpper() != "JOIN") { return(false); } break; default: return(false); } if (!TryParseSource(Parser, out Source2)) { return(false); } Conditions = ParseJoinConditions(Parser); Source = new FullOuterJoin(Source, Source2, Conditions, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; case "OUTER": Parser.NextToken(); if (Parser.NextToken().ToUpper() != "JOIN") { return(false); } if (!TryParseSource(Parser, out Source2)) { return(false); } Conditions = ParseJoinConditions(Parser); Source = new FullOuterJoin(Source, Source2, Conditions, Source.Start, Parser.Position - Source.Start, Parser.Expression); break; default: return(true); } } }
static public void Main(string[] args) { if (args.Length == 0 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))) { Console.WriteLine(usage); } else if (args[0].Trim().ToLower() == "/i") { SharpDevelopIDE.InstallShellExtension(); } else if (args[0].Trim().ToLower() == "/u") { SharpDevelopIDE.UninstallShellExtension(); } else { try { FileInfo info = new FileInfo(args[0]); scriptFile = info.FullName; string srcProjDir = @"Lib\Debug\#D1.1"; //relative to CSSCRIPT_DIR string scHomeDir = SharpDevelopIDE.GetEnvironmentVariable("CSSCRIPT_DIR"); string tempDir = Path.Combine(Path.Combine(Path.GetTempPath(), "CSSCRIPT"), Environment.TickCount.ToString()); string projFile = Path.Combine(tempDir, "DebugScript.prjx"); string solutionFile = Path.Combine(tempDir, "DebugScript.cmbx"); //copy project template Directory.CreateDirectory(tempDir); foreach (string file in Directory.GetFiles(Path.Combine(scHomeDir, srcProjDir))) { File.Copy(file, Path.Combine(tempDir, Path.GetFileName(file)), true); } //update project template with script specific data SharpDevelopIDE ide = new SharpDevelopIDE(); ScriptParser parser = new ScriptParser(scriptFile, SearchDirs); AssemblyResolver asmResolver = new AssemblyResolver(); ide.InsertFile(scriptFile, projFile); string[] importerdScripts = parser.SaveImportedScripts(); foreach (string file in importerdScripts) { ide.InsertFile(file, projFile); } System.Diagnostics.Debug.Assert(false); foreach (string name in parser.ReferencedNamespaces) { bool ignore = false; foreach (string ignoreName in parser.IgnoreNamespaces) { if (ignore = (name == ignoreName)) { break; } } if (ignore) { continue; } string[] asmFiles = AssemblyResolver.FindAssembly(name, SearchDirs); foreach (string file in asmFiles) { ide.InsertReference(file, projFile); } } foreach (string asmName in parser.ReferencedAssemblies) //some assemblies were referenced from code { string[] asmFiles = AssemblyResolver.FindAssembly(asmName, SearchDirs); foreach (string file in asmFiles) { ide.InsertReference(file, projFile); } } //open project Environment.CurrentDirectory = Path.GetDirectoryName(scriptFile); Process myProcess = new Process(); myProcess.StartInfo.FileName = SharpDevelopIDE.GetIDEFile(); myProcess.StartInfo.Arguments = "\"" + solutionFile + "\" "; myProcess.Start(); myProcess.WaitForExit(); //do clean up Directory.Delete(tempDir, true); foreach (string file in importerdScripts) { if (Path.GetFileName(file).StartsWith("i_")) //imported modified files have name "i_file_XXXXXX.cs>" { File.SetAttributes(file, FileAttributes.Normal); File.Delete(file); } } } catch (Exception e) { MessageBox.Show("Specified file could not be linked to the temp project:\n" + e.Message); } } }
/// <summary> /// Tries to parse a script node. /// </summary> /// <param name="Parser">Custom parser.</param> /// <param name="Result">Parsed Script Node.</param> /// <returns>If successful in parsing a script node.</returns> public bool TryParse(ScriptParser Parser, out ScriptNode Result) { Result = null; try { if (!SelectParser.TryParseSources(Parser, out SourceDefinition Source)) { return(false); } string s = Parser.NextToken().ToUpper(); if (s != "SET") { return(false); } List <Assignment> SetOperations = new List <Assignment>(); ScriptNode Node = Parser.ParseList(); if (!(Node is ElementList List)) { List = new ElementList(new ScriptNode[] { Node }, Node.Start, Node.Length, Node.Expression); } foreach (ScriptNode Operation in List.Elements) { if (Operation is EqualTo EqualTo) { if (EqualTo.LeftOperand is VariableReference Ref) { SetOperations.Add(new Assignment(Ref.VariableName, EqualTo.RightOperand, EqualTo.Start, EqualTo.Length, EqualTo.Expression)); } else { return(false); } } else if (Operation is Assignment Assignment) { SetOperations.Add(Assignment); } else { return(false); } } ScriptNode Where = null; s = Parser.PeekNextToken().ToUpper(); if (s == "WHERE") { Parser.NextToken(); Where = Parser.ParseOrs(); } Result = new Update(Source, SetOperations.ToArray(), Where, Parser.Start, Parser.Length, Parser.Expression); return(true); } catch (Exception) { return(false); } }
void test() { ScriptParser.advanceScript(); }
public override ScriptVariableType Process(ScriptParser parser, int level) { base.Process(parser, level); // check script if it has a function we can execute if (parser.GetFunction(Name.Value, out ScriptFunction)) { if (ScriptFunction.Parameters.Count < Parameters.Count) { parser.Errors.Add(new ErrorInfo(ErrorLevel.Error, ErrorCode.TooManyParameters, this)); } else { ParamDefault = new bool[ScriptFunction.Parameters.Count]; for (int i = 0; i < ScriptFunction.Parameters.Count; i++) { if (Parameters.Count <= i || Parameters[i] == null) { if (ScriptFunction.Parameters[i].HasDefaultValue) { ParamDefault[i] = true; } else { parser.Errors.Add(new ErrorInfo(ErrorLevel.Error, ErrorCode.ParameterIsRequired, this, i, Name.Value)); } } else { ParamDefault[i] = false; Parameters[i] = TypeCastExecutionNode.ImplicitCast(parser, level, ScriptFunction.Parameters[i].ParamType, Parameters[i]); } } } ResultType = (ScriptFunction.ReturnType == ScriptVariableType.Void) ? ScriptVariableType.Undefined : ScriptFunction.ReturnType; return(ResultType); } // check environment if it has a function we can execute if (parser.Script.Environment.GetFunction(Name.Value, out EnvironmentFunction)) { ResultType = EnvironmentFunction.ReturnType; ParameterInfo[] envFuncParams = EnvironmentFunction.Function.GetParameters(); FuncParamCount = envFuncParams.Length; if (envFuncParams.Length < Parameters.Count) { parser.Errors.Add(new ErrorInfo(ErrorLevel.Error, ErrorCode.TooManyParameters, this)); } else { for (int i = 1, j = 0; i < envFuncParams.Length; i++, j++) { if (Parameters.Count <= j || Parameters[j] == null) { parser.Errors.Add(new ErrorInfo(ErrorLevel.Error, ErrorCode.ParameterIsRequired, this, j, Name.Value)); } else { if (!envFuncParams[i].ParameterType.Equals(typeof(object))) { Parameters[j] = TypeCastExecutionNode.ImplicitCast(parser, level, ScriptVariableTypeExtension.GetScriptVariableTypeFromType(envFuncParams[i].ParameterType), Parameters[j]); } else { Parameters[j].Process(parser, level); } } } } return(ResultType); } parser.Errors.Add(new ErrorInfo(ErrorLevel.CriticalError, ErrorCode.FunctionNotFound, this, Name.Value)); throw new ScriptCriticalErrorException(); }
public Statement Parse(ScriptParser parser, ScriptToken token, out bool trailingSemicolon) { trailingSemicolon = false; parser.Take(ScriptTokenType.LeftParen); var expression = parser.ParseExpression(); parser.Take(ScriptTokenType.RightParen); parser.Take(ScriptTokenType.LeftBrace); var hasDefault = false; var branches = new List <SwitchStatement.Branch>(); while (!parser.Match(ScriptTokenType.RightBrace)) { var conditions = new List <Expression>(); while (true) { if (parser.MatchAndTake(ScriptTokenType.Case)) { var condition = parser.ParseExpression(); conditions.Add(condition); parser.Take(ScriptTokenType.Colon); continue; } if (!parser.Match(ScriptTokenType.Default)) { break; } var defaultToken = parser.Take(ScriptTokenType.Default); if (hasDefault) { throw new CompilerException(defaultToken, "Multiple default labels"); } conditions.Add(null); // special default condition hasDefault = true; parser.Take(ScriptTokenType.Colon); } if (conditions.Count > 0) { var block = ParseBlock(parser); var branch = new SwitchStatement.Branch(conditions, block); branches.Add(branch); continue; } var errorToken = parser.Peek(); throw new CompilerException(errorToken, "Expected Case or Default but found {0}", errorToken); } parser.Take(ScriptTokenType.RightBrace); return(new SwitchStatement(token, parser.Previous, expression, branches)); }
public TokenFloat(ScriptParser parser) : base(parser) { }
private void BuildSource() { var script = new ScriptParser(); var source = script.Split(SourceCodeTextEditor.Text); if (ExecuteTypeComboBox.SelectedIndex == 0) { _compiler.Method = source[1]; } else if (ExecuteTypeComboBox.SelectedIndex == 1) { _compiler.Class = source[1]; } else { _compiler.Namespace = source[1]; } _compiler.Entry = source[0]; _compiler.AssemblySources = AssemblyFilesTextEditor.Text; _compiler.Using = UsingTextEditor.Text; _compiler.SourceCode = TemplateTextEditor.Text; }