internal static DynamicExprExpression LoadDynamicExpr(Script script, SourceCode source) { AntlrErrorListener listener = new AntlrErrorListener(source); try { LuaParser parser = CreateParser(script, new AntlrInputStream(source.Code), source.SourceID, p => p.dynamicexp(), listener); ScriptLoadingContext lcontext = CreateLoadingContext(script, source); lcontext.IsDynamicExpression = true; lcontext.Anonymous = true; DynamicExprExpression stat; using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation)) stat = new DynamicExprExpression(parser.dynamicexp(), lcontext); return(stat); } catch (ParseCanceledException ex) { HandleParserError(ex, listener); throw; } }
public static void DbAttachLuaLoader <T>(DbDebugItem <T> debug, string tableName, string path) { try { var db = debug.AbsractDb; var data = debug.AbsractDb.ProjectDatabase.MetaGrf.GetData(path); if (data == null) { db.Attached[tableName] = null; db.Attached[tableName + "_T"] = null; return; } LuaParser parser = new LuaParser(data, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(data), EncodingService.DisplayEncoding); try { var luaTable = parser.Tables[tableName]; Dictionary <string, string> dico = new Dictionary <string, string>(); foreach (var pair in luaTable) { dico[pair.Key.Trim('[', ']', '\"')] = pair.Value; } parser.Tables[tableName] = dico; db.Attached[tableName] = parser; db.Attached[tableName + "_T"] = dico; } catch { db.Attached[tableName] = null; } } catch (Exception err) { debug.ReportException(err); } }
public static void Main() { var codeReader = new StringReader(_code); var rawTokens = new LuaRawTokenizer(); var luaTokens = new LuaTokenizer(); rawTokens.Reset(codeReader); luaTokens.Reset(rawTokens); var parser = new LuaParser(); var builder = new SyntaxTreeBuilder(); builder.Start(); luaTokens.EnsureMoveNext(); parser.Reset(luaTokens, builder); parser.Parse(); var ast = builder.Finish(); var env = new Table(); env.SetRaw(TypedValue.MakeString("print"), TypedValue.MakeNClosure(Print)); var codeGen = new CodeGenerator(); var closure = codeGen.Compile(ast, env); var thread = new Thread(); var stack = thread.AllocateRootCSharpStack(1); var arg = TypedValue.MakeString("C#"); stack.Write(0, in arg); LuaInterpreter.Execute(stack, closure, 0, 1); stack.Read(0, out var ret); }
private List <NewFolding> CreateNewFoldings(String text, ref List <MarkerPosition> markers) { List <NewFolding> newFoldings = null; try { using (var reader = new StringReader(text)) { var antlrInputStream = new AntlrInputStream(reader); var lexer = new LuaLexer(antlrInputStream); var tokens = new CommonTokenStream(lexer); var parser = new LuaParser(tokens) { BuildParseTree = true }; parser.RemoveErrorListeners(); parser.AddErrorListener(new MyErrorListener(_textMarkerService, ref markers)); var tree = parser.block(); var visitor = new LuaVisitor(); newFoldings = visitor.Visit(tree); Interlocked.Exchange(ref _syntaxErrors, parser.NumberOfSyntaxErrors); } } catch (Exception e) { // MessageBox.Show(e.ToString(), "NodeMCU Studio 2015", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.Yes); //On error resume next } return(newFoldings ?? new List <NewFolding>()); }
public static void Format(ICharStream stream, IFormatWriter writer, FormatOptions options) { var lexer = new LuaLexer(stream); var tokens = new CommonTokenStream(lexer); var parser = new LuaParser(tokens); tokens.Fill(); var comments = tokens.GetTokens().Where(t => t.Channel == LuaLexer.Hidden); var spaces = tokens.GetTokens().Where(t => t.Channel == 2); parser.BuildParseTree = true; parser.TrimParseTree = false; IRuleNode root = parser.chunk(); var ctx = new FormatContext(root, comments, spaces, writer, options); RuleFormatter.Format(root, ctx); ctx.WriteComments(int.MaxValue); var allTokens = tokens.GetTokens(); if (allTokens.Count > 0) { var lastToken = allTokens[allTokens.Count - 1]; while (ctx.line <= lastToken.Line) { ctx.WriteLineBreak(); } } tokens.Release(0); }
public static void DbLuaLoader <T>(DbDebugItem <T> debug, DbAttribute attribute, string tableName, int tableId, Func <string> getPath, Func <string, T> getId, Func <string, string> getValue) { try { var table = debug.AbsractDb.Table; var data = debug.AbsractDb.ProjectDatabase.MetaGrf.GetData(getPath()); if (data == null) { return; } LuaParser parser = new LuaParser(data, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(data), EncodingService.DisplayEncoding); var luaTable = parser.Tables[tableName]; foreach (var pair in luaTable) { T id = getId(pair.Key); if (id.Equals(default(T))) { continue; } table.SetRaw(id, attribute, getValue(pair.Value)); } } catch (Exception err) { debug.ReportException(err); } }
private static LuaParser CreateParser(Script script, ICharStream charStream, int sourceIdx, Func <LuaParser, IParseTree> dumper, AntlrErrorListener errorListener) { LuaLexer lexer; LuaParser parser; using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Parsing)) { lexer = new LuaLexer(charStream); lexer.RemoveErrorListeners(); lexer.AddErrorListener(errorListener); parser = new LuaParser(new CommonTokenStream(lexer)) { ErrorHandler = new BailErrorStrategy(), }; parser.Interpreter.PredictionMode = PredictionMode.Ll; parser.RemoveErrorListeners(); parser.AddErrorListener(errorListener); //Debug_DumpAst(parser, sourceIdx, dumper); } return(parser); }
private Dictionary <int, int> _getWeaponClasses() { Dictionary <int, int> table = new Dictionary <int, int>(); var accIdPath = ProjectConfiguration.SyncAccId; for (int i = 0; i <= 30; i++) { table[i] = i; } if (_database.MetaGrf.GetData(ProjectConfiguration.SyncAccId) == null || _database.MetaGrf.GetData(ProjectConfiguration.SyncAccName) == null) { return(table); } var weaponPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "weapontable" + Path.GetExtension(accIdPath)); var weaponData = _database.MetaGrf.GetData(weaponPath); if (weaponData == null) { return(table); } var weaponTable = new LuaParser(weaponData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(weaponData), EncodingService.DisplayEncoding); var weaponIds = LuaHelper.GetLuaTable(weaponTable, "Weapon_IDs"); var weaponExpansionNameTable = LuaHelper.GetLuaTable(weaponTable, "Expansion_Weapon_IDs"); var ids = LuaHelper.SetIds(weaponIds, "Weapon_IDs"); foreach (var id in ids) { if (id.Value == 24) { continue; } if (id.Value <= 30) { table[id.Value] = id.Value; } else { string sval; if (weaponExpansionNameTable.TryGetValue("[" + id.Key + "]", out sval)) { int ival; if (ids.TryGetValue(sval, out ival)) { table[id.Value] = ival; } } } } return(table); }
internal static Dictionary <string, string> GetLuaTable(LuaParser parser, string tId) { if (parser.Tables.Keys.Any(p => String.Compare(tId, p, StringComparison.OrdinalIgnoreCase) == 0)) { return(parser.Tables.FirstOrDefault(p => String.Compare(tId, p.Key, StringComparison.OrdinalIgnoreCase) == 0).Value); } _debugStatus += "#" + tId + " missing"; throw new Exception("Invalid table file (lua/lub), missing '" + tId + "'. Tables found: " + Methods.Aggregate(parser.Tables.Keys.ToList(), ", ")); }
//[Conditional("DEBUG_COMPILER")] private static void Debug_DumpAst(LuaParser parser, int sourceIdx, Func <LuaParser, IParseTree> dumper) { try { AstDump astDump = new AstDump(); // astDump.DumpTree(dumper(parser), string.Format(@"c:\temp\treedump_{0:000}.txt", sourceIdx)); astDump.WalkTreeForWaste(dumper(parser)); } catch { } parser.Reset(); }
public void HelloWorldTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "helloworld.lua"); parser.Parse(); }
public void DoFileTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "dofile.lua"); parser.Parse(); }
private static void _writeLuaFiles(LuaParser accId, LuaParser accName, AbstractDb <int> db) { string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accId.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncAccId, File.ReadAllBytes(file)); file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accName.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncAccName, File.ReadAllBytes(file)); }
public void FunctionScopesTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "functionscopes.lua"); parser.Parse(); }
public void FunctionScopesTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "functionscopes.lua"); parser.Parse(); }
public void DoFileTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "dofile.lua"); parser.Parse(); }
public void HelloWorldTest() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); parser = new LuaParser(context, "helloworld.lua"); parser.Parse(); }
public LuaParser CreateParser(string code) { ICharStream stream = CharStreams.fromstring(code); var lexer = new LuaLexer(stream); lexer.AddErrorListener(new ThrowExceptionErrorListener()); ITokenStream tokens = new CommonTokenStream(lexer); var parser = new LuaParser(tokens); parser.BuildParseTree = true; parser.RemoveErrorListeners(); parser.AddErrorListener(new ThrowExceptionErrorListener()); return(parser); }
public bool ProcessEsoGuildStoreSales(Action <EsoSale> onSaleFound, params EsoSaleFilter[] filters) { if (FilePath == null) { return(false); } // Set a default filter to not filter anything if (filters == null || filters.Length == 0) { filters = new EsoSaleFilter[1]; filters[0] = new EsoSaleFilter(); } // Set up our custom Lua listener for extracting sale data var listener = new MMLuaListener(); // Open the saved variables file for reading using (var stream = File.OpenRead(FilePath)) { // Lua parser stuff var charStream = new AntlrInputStream(stream); var lexer = new LuaLexer(charStream); var tokenStream = new CommonTokenStream(lexer); var parser = new LuaParser(tokenStream); listener.SaleFound += (sender, saleFoundArgs) => { // Make sure the sale matches at least one of the filters, then add it to the list var sale = saleFoundArgs.Sale; if (filters.Where(filter => string.IsNullOrEmpty(filter.GuildName) || filter.GuildName.Equals(sale.GuildName, StringComparison.CurrentCultureIgnoreCase)) .Any(filter => (filter.TimestampMinimum == null || sale.SaleTimestamp >= filter.TimestampMinimum) && (filter.TimestampMaximum == null || sale.SaleTimestamp <= filter.TimestampMaximum))) { onSaleFound(sale); } }; parser.AddParseListener(listener); // Run the Lua parser on the saved variables file parser.exp(); } return(true); }
// Compiling. public static LuaPrototype Compile(TextWriter errorWriter, TextReader sourceReader, string sourceName) { // Parse the function. LuaAST LuaAST = LuaParser.Parse(errorWriter, sourceReader, sourceName); if (LuaAST == null) { return(null); } // Compile. BytecodeCompiler compiler = new BytecodeCompiler(sourceName); LuaPrototype prototype = compiler.BuildPrototype(LuaAST); return(prototype); }
private void _save(string path = null) { _async.SetAndRunOperation(new GrfThread(delegate { try { Progress = -1; LuaParser accId = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding); Dictionary <string, string> accIdT = new Dictionary <string, string>(); accId.Tables["ACCESSORY_IDs"] = accIdT; LuaParser accName = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding); Dictionary <string, string> accNameT = new Dictionary <string, string>(); accName.Tables["AccNameTable"] = accNameT; foreach (var item in _obItems.Where(item => item.Id > 0).Where(item => !String.IsNullOrEmpty(item.AccId))) { accIdT[item.AccId] = item.Id.ToString(CultureInfo.InvariantCulture); } if (path == null) { _multiGrf.Clear(); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); _writeAccName(file, EncodingService.DisplayEncoding); _multiGrf.SetData(ProjectConfiguration.SyncAccName, File.ReadAllBytes(file)); file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accId.Write(file, EncodingService.DisplayEncoding); _multiGrf.SetData(ProjectConfiguration.SyncAccId, File.ReadAllBytes(file)); _multiGrf.SaveAndReload(); } else { Directory.CreateDirectory(path); _writeAccName(GrfPath.Combine(path, "accname.lub"), EncodingService.DisplayEncoding); accId.Write(GrfPath.Combine(path, "accessoryid.lub"), EncodingService.DisplayEncoding); } } catch (Exception err) { ErrorHandler.HandleException(err); } finally { Progress = 100f; } }, this, 200)); }
public override void Parse(string lua) { double numValue = 0.0; string stringValue = ""; if (LuaParser.ReadNumericValue(lua, @"\[""mobvalue_required""\]\s=\s(?<value>.*)", out numValue)) { MobRequired = System.Convert.ToInt32(numValue); } if (LuaParser.ReadNumericValue(lua, @"\[""proximity_required""\]\s=\s(?<value>.*)", out numValue)) { ProximityRequired = System.Convert.ToInt32(numValue); } if (LuaParser.ReadStringValue(lua, @"\[""squad_activated""\]\s=\s(true)", out stringValue)) { SquadActivated = true; } }
public void MethodBinding() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); double res = 0; var func = (Func<double, double>)((a) => { res = a; return a + 1; }); context.SetGlobal("test", LuaObject.FromDelegate(func)); parser = new LuaParser(context, new StringReader("test(123)")); parser.Parse(); Assert.AreEqual(123.0,res); }
public AccessoryTable(AbstractDb <int> db, byte[] dataAccId, byte[] dataAccName) { // Load current tables as fallback values ItemIdToSprite = LuaHelper.GetRedirectionTable(); _itemDb = db.GetMeta <int>(ServerDbs.Items); _cItemDb = db.Get <int>(ServerDbs.CItems); LuaAccIdParser = new LuaParser(dataAccId, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccId), EncodingService.DisplayEncoding); LuaAccNameParser = new LuaParser(dataAccName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccName), EncodingService.DisplayEncoding); LuaAccId = LuaHelper.GetLuaTable(LuaAccIdParser, "ACCESSORY_IDs"); LuaAccName = LuaHelper.GetLuaTable(LuaAccNameParser, "AccNameTable"); _viewIdToSpriteFallback = GetViewIdTableFallback(LuaAccId, LuaAccName); _headgears = _itemDb.FastItems.Where(p => ItemParser.IsArmorType(p) && (p.GetIntNoThrow(ServerItemAttributes.Location) & 7937) != 0).OrderBy(p => p.GetIntNoThrow(ServerItemAttributes.ClassNumber)).ToList(); LuaAccId.Clear(); LuaAccName.Clear(); }
public void MethodBinding() { LuaParser parser; var context = new LuaContext(); context.AddBasicLibrary(); context.AddIoLibrary(); double res = 0; var func = (Func <double, double>)((a) => { res = a; return(a + 1); }); context.SetGlobal("test", LuaObject.FromDelegate(func)); parser = new LuaParser(context, new StringReader("test(123)")); parser.Parse(); Assert.AreEqual(123.0, res); }
private static LClosure Compile(string code) { var codeReader = new StringReader(code); var rawTokens = new LuaRawTokenizer(); var luaTokens = new LuaTokenizer(); rawTokens.Reset(codeReader); luaTokens.Reset(rawTokens); var parser = new LuaParser(); var builder = new SyntaxTreeBuilder(); builder.Start(); luaTokens.EnsureMoveNext(); parser.Reset(luaTokens, builder); parser.Parse(); var ast = builder.Finish(); return(_fastLuaCodeGen.Compile(ast, _fastLuaEnv)); }
public SavedVariable(string path) { var fields = path.Split("."); foreach (var field in fields) { _path.Add(field); } Name = _path[fields.Length - 1]; var parser = LuaParser.Parse(File.ReadAllText(_filePath)); foreach (var s in _path) { parser = parser.Field(s); } Fields = parser.GetList(); }
public void ParseLua() { var inputStream = new AntlrInputStream(@" do local t = {} t[f(1)] = g t[1] = 5 -- 1st exp t[2] = 2 -- 2nd exp t.x = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end "); var lexer = new LuaLexer(inputStream); var commonTokenStream = new CommonTokenStream(lexer); var parser = new LuaParser(commonTokenStream); var visitor = new CstBuilderForAntlr4(parser); visitor.Visit(parser.chunk()); Console.WriteLine(visitor.FinishParsing()); }
internal static int LoadChunk(Script script, SourceCode source, ByteCode bytecode, Table globalContext) { AntlrErrorListener listener = new AntlrErrorListener(source); try { LuaParser parser = CreateParser(script, new AntlrInputStream(source.Code), source.SourceID, p => p.chunk(), listener); ScriptLoadingContext lcontext = CreateLoadingContext(script, source); ChunkStatement stat; using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation)) stat = new ChunkStatement(parser.chunk(), lcontext, globalContext); int beginIp = -1; //var srcref = new SourceRef(source.SourceID); using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation)) using (bytecode.EnterSource(null)) { bytecode.Emit_Nop(string.Format("Begin chunk {0}", source.Name)); beginIp = bytecode.GetJumpPointForLastInstruction(); stat.Compile(bytecode); bytecode.Emit_Nop(string.Format("End chunk {0}", source.Name)); } Debug_DumpByteCode(bytecode, source.SourceID); return(beginIp); } catch (ParseCanceledException ex) { HandleParserError(ex, listener); throw; } }
internal static int LoadFunction(Script script, SourceCode source, ByteCode bytecode, Table globalContext) { AntlrErrorListener listener = new AntlrErrorListener(source); try { LuaParser parser = CreateParser(script, new AntlrInputStream(source.Code), source.SourceID, p => p.singlefunc(), listener); ScriptLoadingContext lcontext = CreateLoadingContext(script, source); FunctionDefinitionExpression fndef; using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.AstCreation)) fndef = new FunctionDefinitionExpression(parser.anonfunctiondef(), lcontext, false, globalContext); int beginIp = -1; // var srcref = new SourceRef(source.SourceID); using (script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Compilation)) using (bytecode.EnterSource(null)) { bytecode.Emit_Nop(string.Format("Begin function {0}", source.Name)); beginIp = fndef.CompileBody(bytecode, source.Name); bytecode.Emit_Nop(string.Format("End function {0}", source.Name)); Debug_DumpByteCode(bytecode, source.SourceID); } return(beginIp); } catch (ParseCanceledException ex) { HandleParserError(ex, listener); throw; } }
public static void Dump() { // Clear Resources Addons.Clear(); Skills.Clear(); Squads.Clear(); Buildings.Clear(); Units.Clear(); Researches.Clear(); MainForm.Log("Lua processing started..."); DateTime start = DateTime.Now; Hashtable temp = (Hashtable)FilesTable.Clone(); foreach (string lua in temp.Keys) { LuaInfo lInfo = temp[lua] as LuaInfo; if (lInfo.Type == InfoTypes.Building) { StreamReader file = new StreamReader(File.OpenRead(lInfo.Path), System.Text.Encoding.ASCII); file.BaseStream.Seek(0, SeekOrigin.Begin); string s = file.ReadToEnd(); file.Close(); MatchCollection mccR = Regex.Matches(s, @"GameData\[""research_ext""\]\[""research_table""\]\[""research_([0-9]?[0-9]?)""\]\s=\s""(.*\\\\)?((?<research>.*)\.lua|(?<research>.*))"""); if (mccR.Count > 0) { foreach (Match mt in mccR) { Group research = mt.Groups["research"]; if (research.Success && research.Value != "") { string res = research.Value; if (!res.EndsWith(".lua")) { res += ".lua"; } res = Path.Combine("research", res); string path = DataPath.GetPath(res); string race = GetRace(lInfo.Path); LuaInfo resLua = new LuaInfo(path, InfoTypes.Research, race); if (!FilesTable.Contains(res)) { FilesTable.Add(res, resLua); } } } } } } int count = FilesTable.Count; MainForm.BarSetMax(Bars.Data, count); // Collecting resources from lua files. foreach (string lua in FilesTable.Keys) { LuaInfo lInfo = FilesTable[lua] as LuaInfo; switch (lInfo.Type) { case InfoTypes.Research: ResearchInfo rInfo = new ResearchInfo(); rInfo.Race = lInfo.Race; rInfo.FileName = Regex.Replace(lua, @"\.lua|\.nil|(.*)\\", ""); try { LuaParser.ParseResearch(lInfo.Path, rInfo); } catch (Exception e) { } MainForm.BarInc(Bars.Data); Researches.Add(rInfo); break; case InfoTypes.Unit: SquadInfo sInfo = new SquadInfo(); sInfo.Race = lInfo.Race; sInfo.FileName = Regex.Replace(lua, @"\.lua|\.nil", ""); LuaParser.ParseSquad(lInfo.Path, sInfo); MainForm.BarInc(Bars.Data); if (sInfo.Unit != null) { Squads.Add(sInfo); } break; case InfoTypes.Building: BuildingInfo bInfo = new BuildingInfo(); bInfo.Race = lInfo.Race; bInfo.FileName = Regex.Replace(lua, @"\.lua|\.nil", ""); LuaParser.ParseBuilding(lInfo.Path, bInfo); MainForm.BarInc(Bars.Data); Buildings.Add(bInfo); break; } } Researches.Sort(); Squads.Sort(); Buildings.Sort(); TimeSpan elapsed = DateTime.Now - start; MainForm.Log("Lua processing done in " + Math.Round(elapsed.TotalSeconds, 2) + " seconds."); }
public static void WriteMobLuaFiles(AbstractDb <int> db) { // Ensures this is only written once if (ProjectConfiguration.SynchronizeWithClientDatabases && db.DbSource == ServerDbs.Mobs && ProjectConfiguration.SyncMobTables) { var metaTable = db.ProjectDatabase.GetMetaTable <int>(ServerDbs.Mobs); //var table = Attached["jobtbl_T"] as Dictionary<string, string>; // Load the tables DbDebugItem <int> debug = new DbDebugItem <int>(db); DbAttachLuaLoaderUpper(debug, "jobtbl", ProjectConfiguration.SyncMobId); var table = db.Attached["jobtbl_T"] as Dictionary <string, string>; if (table != null) { Dictionary <int, Npc> npcs = new Dictionary <int, Npc>(); var dataJobName = debug.AbsractDb.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncMobName); if (dataJobName == null) { return; } LuaParser parser = new LuaParser(dataJobName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataJobName), EncodingService.DisplayEncoding); var jobNames = parser.Tables["JobNameTable"]; // Load the npcs from the lua files first foreach (var keyPair in table) { npcs[Int32.Parse(keyPair.Value)] = new Npc { NpcName = keyPair.Key }; } foreach (var keyPair in jobNames) { var key = keyPair.Key.Trim('[', ']'); var ingameSprite = keyPair.Value.Trim('\"'); int ival; if (!Int32.TryParse(key, out ival)) { key = key.Substring(7); var npcKeyPair = npcs.FirstOrDefault(p => p.Value.NpcName == key); if (npcKeyPair.Equals(default(KeyValuePair <int, Npc>))) { // Key not found // We ignore it } else { npcs[npcKeyPair.Key] = new Npc(npcKeyPair.Value) { IngameSprite = ingameSprite }; //npcKeyPair.Value = new ingameSprite; } continue; } npcs[ival] = new Npc { IngameSprite = ingameSprite }; } foreach (var tuple in metaTable.FastItems.OrderBy(p => p.Key)) { var ssprite = "JT_" + (tuple.GetValue <string>(ServerMobAttributes.SpriteName) ?? ""); var csprite = tuple.GetValue <string>(ServerMobAttributes.ClientSprite); if (ssprite != "JT_") { // not empty if (npcs.ContainsKey(tuple.Key)) { npcs[tuple.Key] = new Npc(npcs[tuple.Key]) { IngameSprite = csprite, NpcName = ssprite }; } else { Npc npc = new Npc { IngameSprite = csprite, NpcName = ssprite }; npcs[tuple.Key] = npc; } } } // Validation HashSet <string> duplicates = new HashSet <string>(); foreach (var npc in npcs) { if (!duplicates.Add(npc.Value.NpcName)) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Duplicate mob name (" + npc.Value.NpcName + ") for mobid " + npc.Key + " while saving npcidentity and jobname. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } if (LatinOnly(npc.Value.NpcName) != npc.Value.NpcName) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "The mob name (" + npc.Value.NpcName + ") is invalid, only ASCII characters are allowed. Consider using '" + LatinOnly(npc.Value.NpcName) + "' as the name instead. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } } // Converts back to a lua format { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobId, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["jobtbl"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { dico[npc.Value.NpcName] = npc.Key.ToString(CultureInfo.InvariantCulture); } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobId, File.ReadAllBytes(file)); } { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobName, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["JobNameTable"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { var ingameSprite = LatinUpper((npc.Value.IngameSprite ?? "")); if (!String.IsNullOrEmpty(ingameSprite.GetExtension())) { ingameSprite = ingameSprite.ReplaceExtension(ingameSprite.GetExtension().ToLower()); } if (string.IsNullOrEmpty(ingameSprite)) { continue; } dico["[jobtbl." + npc.Value.NpcName + "]"] = "\"" + ingameSprite + "\""; } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobName, File.ReadAllBytes(file)); } } } }
public static bool GetIdToSpriteTable(AbstractDb <int> db, ViewIdTypes type, out Dictionary <int, string> outputIdsToSprites, out string error) { outputIdsToSprites = new Dictionary <int, string>(); error = null; if (db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId) == null || db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName) == null) { error = "The accessory ID table or accessory name table has not been set, the paths are based on those."; return(false); } int temp_i; string temp_s; var accIdPath = ProjectConfiguration.SyncAccId; Dictionary <string, int> ids; switch (type) { case ViewIdTypes.Weapon: if (_weaponBuffer.IsBuffered()) { outputIdsToSprites = _weaponBuffer.Ids; error = _weaponBuffer.Error; return(_weaponBuffer.Result); } var weaponPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "weapontable" + Path.GetExtension(accIdPath)); var weaponData = db.ProjectDatabase.MetaGrf.GetData(weaponPath); if (weaponData == null) { error = "Couldn't find " + weaponPath; _weaponBuffer.Buffer(outputIdsToSprites, false, error); return(false); } var weaponTable = new LuaParser(weaponData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(weaponData), EncodingService.DisplayEncoding); var weaponIds = GetLuaTable(weaponTable, "Weapon_IDs"); var weaponNameTable = GetLuaTable(weaponTable, "WeaponNameTable"); ids = SetIds(weaponIds, "Weapon_IDs"); foreach (var pair in weaponNameTable) { temp_s = pair.Key.Trim('[', ']'); if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i)) { outputIdsToSprites[temp_i] = pair.Value.Trim('\"'); } } _weaponBuffer.Buffer(outputIdsToSprites, true, null); return(true); case ViewIdTypes.Npc: if (_npcBuffer.IsBuffered()) { outputIdsToSprites = _npcBuffer.Ids; error = _npcBuffer.Error; return(_npcBuffer.Result); } var npcPathSprites = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "jobname" + Path.GetExtension(accIdPath)); var npcPathIds = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "npcIdentity" + Path.GetExtension(accIdPath)); var npcDataSprites = db.ProjectDatabase.MetaGrf.GetData(npcPathSprites); var npcDataIds = db.ProjectDatabase.MetaGrf.GetData(npcPathIds); if (npcDataSprites == null) { error = "Couldn't find " + npcPathSprites; _npcBuffer.Buffer(outputIdsToSprites, false, error); return(false); } if (npcDataIds == null) { error = "Couldn't find " + npcPathIds; _npcBuffer.Buffer(outputIdsToSprites, false, error); return(false); } //var itemDb = db.GetMeta<int>(ServerDbs.Items); var jobname = new LuaParser(npcDataSprites, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(npcDataSprites), EncodingService.DisplayEncoding); var jobtbl = new LuaParser(npcDataIds, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(npcDataIds), EncodingService.DisplayEncoding); var jobtblT = GetLuaTable(jobtbl, "jobtbl"); var jobnameT = GetLuaTable(jobname, "JobNameTable"); ids = SetIds(jobtblT, "jobtbl"); foreach (var pair in jobnameT) { temp_s = pair.Key.Trim('[', ']'); if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i)) { outputIdsToSprites[temp_i] = pair.Value.Trim('\"'); } } _npcBuffer.Buffer(outputIdsToSprites, true, null); return(true); case ViewIdTypes.Headgear: if (_headgearBuffer.IsBuffered()) { outputIdsToSprites = _headgearBuffer.Ids; error = _headgearBuffer.Error; return(_headgearBuffer.Result); } var redirectionTable = GetRedirectionTable(); var dataAccId = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId); var dataAccName = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName); var itemDb = db.GetMeta <int>(ServerDbs.Items); var accId = new LuaParser(dataAccId, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccId), EncodingService.DisplayEncoding); var accName = new LuaParser(dataAccName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataAccName), EncodingService.DisplayEncoding); var accIdT = GetLuaTable(accId, "ACCESSORY_IDs"); var accNameT = GetLuaTable(accName, "AccNameTable"); outputIdsToSprites = _getViewIdTable(accIdT, accNameT); accIdT.Clear(); accNameT.Clear(); var resourceToIds = new Dictionary <string, int>(); if (ProjectConfiguration.HandleViewIds) { try { List <ReadableTuple <int> > headgears = itemDb.FastItems.Where(p => ItemParser.IsArmorType(p) && (p.GetIntNoThrow(ServerItemAttributes.Location) & 7937) != 0).OrderBy(p => p.GetIntNoThrow(ServerItemAttributes.ClassNumber)).ToList(); _loadFallbackValues(outputIdsToSprites, headgears, accIdT, accNameT, resourceToIds, redirectionTable); } catch (Exception err) { error = err.ToString(); _headgearBuffer.Buffer(outputIdsToSprites, false, error); return(false); } } _headgearBuffer.Buffer(outputIdsToSprites, true, null); return(true); case ViewIdTypes.Shield: if (_shieldBuffer.IsBuffered()) { outputIdsToSprites = _shieldBuffer.Ids; error = _shieldBuffer.Error; return(_shieldBuffer.Result); } var shieldPath = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "ShieldTable" + Path.GetExtension(accIdPath)); var shieldData = db.ProjectDatabase.MetaGrf.GetData(shieldPath); if (shieldData == null) { outputIdsToSprites[1] = "_°¡µå"; outputIdsToSprites[2] = "_¹öŬ·¯"; outputIdsToSprites[3] = "_½¯µå"; outputIdsToSprites[4] = "_¹Ì·¯½¯µå"; outputIdsToSprites[5] = ""; outputIdsToSprites[6] = ""; } else { _debugStatus = "OK"; var shieldTable = new LuaParser(shieldData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(shieldData), EncodingService.DisplayEncoding); _debugStatus = "LoadTables"; var shieldIds = GetLuaTable(shieldTable, "Shield_IDs"); var shieldNameTable = GetLuaTable(shieldTable, "ShieldNameTable"); var shieldMapTable = GetLuaTable(shieldTable, "ShieldMapTable"); ids = SetIds(shieldIds, "Shield_IDs"); Dictionary <int, string> idsToSprite = new Dictionary <int, string>(); foreach (var pair in shieldNameTable) { temp_s = pair.Key.Trim('[', ']'); if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i)) { temp_s = pair.Value.Trim('\"'); idsToSprite[temp_i] = temp_s; outputIdsToSprites[temp_i] = temp_s; } } foreach (var pair in shieldMapTable) { var key = pair.Key.Trim('[', ']', '\t'); int id1; if (ids.TryGetValue(key, out id1)) { int id2; temp_s = pair.Value.Trim('\"', '\t'); if (ids.TryGetValue(temp_s, out id2) || Int32.TryParse(temp_s, out id2)) { if (idsToSprite.TryGetValue(id2, out temp_s)) { outputIdsToSprites[id1] = temp_s; } } } } error = PreviewHelper.ViewIdIncrease; } _shieldBuffer.Buffer(outputIdsToSprites, true, error); return(true); case ViewIdTypes.Garment: if (_garmentBuffer.IsBuffered()) { outputIdsToSprites = _garmentBuffer.Ids; error = _garmentBuffer.Error; return(_garmentBuffer.Result); } var robeSpriteName = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "spriterobename" + Path.GetExtension(accIdPath)); var robeSpriteId = GrfPath.Combine(GrfPath.GetDirectoryName(accIdPath), "spriterobeid" + Path.GetExtension(accIdPath)); var robeNameData = db.ProjectDatabase.MetaGrf.GetData(robeSpriteName); var robeIdData = db.ProjectDatabase.MetaGrf.GetData(robeSpriteId); if (robeNameData == null) { error = "Couldn't find " + robeSpriteName; _garmentBuffer.Buffer(outputIdsToSprites, false, error); return(false); } if (robeIdData == null) { error = "Couldn't find " + robeSpriteId; _garmentBuffer.Buffer(outputIdsToSprites, false, error); return(false); } var robeNameTable = new LuaParser(robeNameData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(robeNameData), EncodingService.DisplayEncoding); var robeIdTable = new LuaParser(robeIdData, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(robeIdData), EncodingService.DisplayEncoding); var robeNames = GetLuaTable(robeNameTable, "RobeNameTable"); var robeIds = GetLuaTable(robeIdTable, "SPRITE_ROBE_IDs"); ids = SetIds(robeIds, "SPRITE_ROBE_IDs"); foreach (var pair in robeNames) { temp_s = pair.Key.Trim('[', ']'); if (ids.TryGetValue(temp_s, out temp_i) || Int32.TryParse(temp_s, out temp_i)) { outputIdsToSprites[temp_i] = pair.Value.Trim('\"'); } } _garmentBuffer.Buffer(outputIdsToSprites, true, null); return(true); } return(false); }
private void _loadData() { try { var data1 = _multiGrf.GetData(ProjectConfiguration.SyncAccId); var data2 = _multiGrf.GetData(ProjectConfiguration.SyncAccName); var accId = new LuaParser(data1, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(data1), EncodingService.DisplayEncoding); var accName = new LuaParser(data2, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(data2), EncodingService.DisplayEncoding); var accIdT = LuaHelper.GetLuaTable(accId, "ACCESSORY_IDs"); var accNameT = LuaHelper.GetLuaTable(accName, "AccNameTable"); Dictionary <int, AccessoryItem> viewIds = new Dictionary <int, AccessoryItem>(); foreach (var pair in accIdT) { int ival; if (Int32.TryParse(pair.Value, out ival)) { viewIds[ival] = new AccessoryItem { Id = ival, AccId = pair.Key }; } } int notFound = -1; foreach (var pair in accNameT) { int ival; string key = pair.Key.Replace("ACCESSORY_IDs.", "").Trim('[', ']'); var bind = viewIds.Values.FirstOrDefault(p => p.AccId == key); string texture = pair.Value.Replace("\"_", "").Trim('\"'); if (bind.Id == 0 && bind.Texture == null && bind.AccId == null) { string id = pair.Key.Trim('[', ']'); if (Int32.TryParse(id, out ival)) { bind.Texture = texture; bind.Id = ival; viewIds[bind.Id] = bind; } else { viewIds[notFound] = new AccessoryItem { Id = notFound, AccId = key, Texture = texture }; notFound--; } } else { bind.Texture = texture; viewIds[bind.Id] = bind; } } _obItems = new ObservableCollection <AccessoryItemView>(viewIds.OrderBy(p => p.Key).ToList().Select(p => new AccessoryItemView(p.Value)).ToList()); _dataGrid.ItemsSource = _obItems; _dataGrid.CanUserAddRows = true; _dataGrid.CanUserDeleteRows = true; _dataGrid.IsReadOnly = false; _dataGrid.CanUserReorderColumns = false; _dataGrid.CanUserResizeColumns = false; _dataGrid.CanUserSortColumns = true; _dataGrid.SelectionMode = Microsoft.Windows.Controls.DataGridSelectionMode.Extended; _dataGrid.SelectionUnit = Microsoft.Windows.Controls.DataGridSelectionUnit.CellOrRowHeader; _dataGrid.CanUserResizeRows = false; _dataGrid.KeyDown += new KeyEventHandler(_dataGrid_KeyDown); if (_obItems.Count > 0) { _dataGrid.ScrollIntoView(_obItems.Last()); } } catch (Exception err) { ErrorHandler.HandleException("Couldn't load the table files.", err); } }
public void ParseLua() { var inputStream = new AntlrInputStream(@" do local t = {} t[f(1)] = g t[1] = 5 -- 1st exp t[2] = 2 -- 2nd exp t.x = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end "); var lexer = new LuaLexer(inputStream); var commonTokenStream = new CommonTokenStream(lexer); var parser = new LuaParser(commonTokenStream); var visitor = new CstBuilderForAntlr4(parser); visitor.Visit(parser.chunk()); Console.WriteLine(visitor.FinishParsing()); }