123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NTERA.Interpreter.Compiler
- {
- public static class Preprocessor
- {
- public static IEnumerable<FunctionVariable> PreprocessHeaderFile(string contents)
- {
- Lexer lexer = new Lexer(contents);
- List<FunctionVariable> constantDefinitions = new List<FunctionVariable>();
- using (var enumerator = lexer.GetEnumerator())
- {
- do
- {
- if (lexer.TokenMarker.Column != 1)
- continue;
- if (enumerator.Current == Token.Sharp)
- {
- enumerator.MoveNext();
- switch (enumerator.Current)
- {
- case Token.Dims:
- case Token.Dim:
- {
- bool isString = enumerator.Current != Token.Dim;
- enumerator.MoveNext();
- VariableType variableType = VariableType.None;
- while (enumerator.Current == Token.Const
- || enumerator.Current == Token.Ref
- || enumerator.Current == Token.Dynamic
- || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("GLOBAL", StringComparison.OrdinalIgnoreCase))
- || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("CHARADATA", StringComparison.OrdinalIgnoreCase))
- || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("SAVEDATA", StringComparison.OrdinalIgnoreCase)))
- {
- if (enumerator.Current == Token.Const)
- variableType |= VariableType.Constant;
- else if (enumerator.Current == Token.Ref)
- variableType |= VariableType.Reference;
- else if (enumerator.Current == Token.Dynamic)
- variableType |= VariableType.Dynamic;
- else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("GLOBAL", StringComparison.OrdinalIgnoreCase))
- variableType |= VariableType.SaveData;
- else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("CHARADATA", StringComparison.OrdinalIgnoreCase))
- variableType |= VariableType.CharaData;
- else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("SAVEDATA", StringComparison.OrdinalIgnoreCase))
- variableType |= VariableType.Global;
- enumerator.MoveNext();
- }
- string variable = lexer.Identifier;
- enumerator.MoveNext();
- Value? defaultValue = null;
- if (enumerator.Current == Token.Comma)
- {
- while (enumerator.MoveNext()
- && enumerator.Current != Token.Equal
- && enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- {
- //arraySize = (int)lexer.Expression().Real;
- //the array size goes here, but we ignore it since it's useless to us
- }
- }
- if (enumerator.Current == Token.Equal)
- {
- enumerator.MoveNext();
- defaultValue = ConstantExpression(lexer, constantDefinitions);
- }
- else if (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- {
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- }
- var functionDefinition = new FunctionVariable(variable,
- isString ? ValueType.String : ValueType.Real,
- variableType,
- defaultValue);
- constantDefinitions.Add(functionDefinition);
- yield return functionDefinition;
- break;
- }
- }
- }
- else
- {
- //resynchronize to next line
- while (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF
- && enumerator.MoveNext())
- {
- }
- }
- } while (enumerator.MoveNext());
- }
- }
- public static IDictionary<FunctionDefinition, string> PreprocessCodeFile(string contents, string filename, ICollection<FunctionVariable> constantDefinitions)
- {
- Dictionary<FunctionDefinition, string> procedures = new Dictionary<FunctionDefinition, string>();
- Lexer lexer = new Lexer(contents);
- Marker startMarker = lexer.TokenMarker;
- string currentDefinitionName = null;
- List<FunctionParameter> currentDefinitionParameters = new List<FunctionParameter>();
- List<FunctionVariable> currentDefinitionVariables = new List<FunctionVariable>();
- bool isReturnFunction = false;
- void Commit()
- {
- if (currentDefinitionName != null)
- {
- string procBody = contents.Substring(startMarker.Pointer,
- lexer.TokenMarker.Pointer - startMarker.Pointer);
- var definition = new FunctionDefinition(currentDefinitionName,
- currentDefinitionParameters.ToArray(),
- currentDefinitionVariables.ToArray(),
- isReturnFunction,
- filename,
- startMarker);
- procedures.Add(definition, procBody);
- isReturnFunction = false;
- currentDefinitionName = null;
- currentDefinitionParameters.Clear();
- }
- }
- using (var enumerator = lexer.GetEnumerator())
- {
- do
- {
- if (lexer.TokenMarker.Column != 1)
- continue;
- if (enumerator.Current == Token.AtSymbol)
- {
- Commit();
- startMarker = lexer.TokenMarker;
- enumerator.MoveNext();
- if (enumerator.Current != Token.Identifer)
- throw new ParserException("Invalid function declaration - Expected an identifier", lexer.TokenMarker);
- currentDefinitionName = lexer.Identifier;
- enumerator.MoveNext();
- if (enumerator.Current == Token.NewLine
- || enumerator.Current == Token.EOF)
- continue;
- if (enumerator.Current != Token.LParen
- && enumerator.Current != Token.Comma)
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- enumerator.MoveNext();
- if (enumerator.Current != Token.Identifer
- && enumerator.Current != Token.RParen)
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- while (enumerator.Current == Token.Identifer)
- {
- string parameterName = lexer.Identifier;
- List<string> indices = new List<string>();
- Value? defaultValue = null;
- enumerator.MoveNext();
- while (enumerator.Current == Token.Colon
- && enumerator.MoveNext())
- {
- if (enumerator.Current == Token.Value)
- {
- indices.Add(lexer.Value.Type == ValueType.Real
- ? ((int)lexer.Value).ToString()
- : lexer.Value.String);
- }
- else if (enumerator.Current == Token.Identifer)
- {
- indices.Add(lexer.Identifier);
- }
- enumerator.MoveNext();
- }
- if (enumerator.Current == Token.Equal)
- {
- enumerator.MoveNext();
- defaultValue = ConstantExpression(lexer, constantDefinitions);
- }
- if (enumerator.Current == Token.Comma
- || enumerator.Current == Token.RParen)
- {
- enumerator.MoveNext();
- }
- else if (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- currentDefinitionParameters.Add(new FunctionParameter(parameterName, indices.ToArray(), defaultValue));
- }
- if (enumerator.Current == Token.RParen)
- enumerator.MoveNext();
- if (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- }
- else if (enumerator.Current == Token.Sharp)
- {
- enumerator.MoveNext();
- switch (enumerator.Current)
- {
- case Token.Dims:
- case Token.Dim:
- {
- bool isString = enumerator.Current != Token.Dim;
- enumerator.MoveNext();
- VariableType variableType = VariableType.None;
- while (enumerator.Current == Token.Const
- || enumerator.Current == Token.Ref
- || enumerator.Current == Token.Dynamic)
- {
- if (enumerator.Current == Token.Const)
- variableType |= VariableType.Constant;
- else if (enumerator.Current == Token.Ref)
- variableType |= VariableType.Reference;
- else if (enumerator.Current == Token.Dynamic)
- variableType |= VariableType.Dynamic;
- enumerator.MoveNext();
- }
- string variable = lexer.Identifier;
- enumerator.MoveNext();
- Value? defaultValue = null;
- if (enumerator.Current == Token.Comma)
- {
- while (enumerator.MoveNext()
- && enumerator.Current != Token.Equal
- && enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- {
- //arraySize = (int)lexer.Expression().Real;
- //the array size goes here, but we ignore it since it's useless to us
- }
- }
- if (enumerator.Current == Token.Equal)
- {
- enumerator.MoveNext();
- defaultValue = ConstantExpression(lexer, constantDefinitions);
- }
- else if (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF)
- {
- throw new ParserException("Invalid function declaration", lexer.TokenMarker);
- }
- currentDefinitionVariables.Add(new FunctionVariable(variable,
- isString ? ValueType.String : ValueType.Real,
- variableType,
- defaultValue));
- break;
- }
- case Token.ReturnFunction:
- {
- isReturnFunction = true;
- break;
- }
- }
- }
- else
- {
- //resynchronize to next line
- while (enumerator.Current != Token.NewLine
- && enumerator.Current != Token.EOF
- && enumerator.MoveNext())
- {
- }
- }
- } while (enumerator.MoveNext());
- }
- Commit();
- return procedures;
- }
- private static IList<IList<string>> SplitCSV(IEnumerable<string> lines)
- {
- List<IList<string>> csv = new List<IList<string>>();
- foreach (var line in lines)
- {
- if (string.IsNullOrWhiteSpace(line)
- || line[0] == ';')
- continue;
- string newLine = line;
- int commentIndex = line.IndexOf(';');
- if (commentIndex >= 0)
- newLine = line.Substring(0, commentIndex);
- string[] split = newLine.Split(new[] { ',' }, StringSplitOptions.None);
- if (split.Length == 1)
- continue;
- csv.Add(split.ToList());
- }
- return csv;
- }
- private static Dictionary<string, string[]> NameIndexDictionary = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
- {
- ["ITEM"] = new[] { "ITEM", "ITEMSALES", "ITEMPRICE" },
- ["BASE"] = new[] { "BASE", "LOSEBASE", "MAXBASE", "DOWNBASE" },
- ["ABL"] = new[] { "ABL" },
- ["TALENT"] = new[] { "TALENT" },
- ["EXP"] = new[] { "EXP" },
- ["MARK"] = new[] { "MARK" },
- ["PALAM"] = new[] { "PALAM", "UP", "DOWN", "JUEL", "GOTJUEL", "CUP", "CDOWN" },
- ["STAIN"] = new[] { "STAIN" },
- ["SOURCE"] = new[] { "SOURCE" },
- ["EX"] = new[] { "EX", "NOWEX" },
- ["TEQUIP"] = new[] { "TEQUIP" },
- ["EQUIP"] = new[] { "EQUIP" },
- ["FLAG"] = new[] { "FLAG" },
- ["TFLAG"] = new[] { "TFLAG" },
- ["CFLAG"] = new[] { "CFLAG" },
- ["STRNAME"] = new[] { "STR" },
- ["SAVESTR"] = new[] { "SAVESTR" },
- ["TCVAR"] = new[] { "TCVAR" },
- ["TSTR"] = new[] { "TSTR" },
- ["CSTR"] = new[] { "CSTR" },
- ["CDFLAG1"] = new[] { "CDFLAG" },
- ["CDFLAG2"] = new[] { "CDFLAG" },
- ["GLOBAL"] = new[] { "GLOBAL" },
- ["GLOBALS"] = new[] { "GLOBALS" },
- };
- public static void ProcessCSV(CSVDefinition targetDefinition, string filename, IEnumerable<string> lines)
- {
- if (filename.EndsWith("_TR", StringComparison.OrdinalIgnoreCase))
- return;
- if (filename.Equals("VariableSize", StringComparison.OrdinalIgnoreCase))
- return;
- if (filename.Equals("_Replace", StringComparison.OrdinalIgnoreCase))
- return;
- var csv = SplitCSV(lines);
- void AddVariableIndices(string variableName)
- {
- Dictionary<string, int> varIndices = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
- foreach (var line in csv)
- if (!string.IsNullOrWhiteSpace(line[1]))
- varIndices[line[1]] = int.Parse(line[0]);
- targetDefinition.VariableIndexDictionary[variableName] = varIndices;
- }
- if (filename.Equals("GameBase", StringComparison.OrdinalIgnoreCase))
- {
- foreach (var line in csv)
- targetDefinition.GameBaseInfo.Add(line[0], line[1]);
- return;
- }
- if (NameIndexDictionary.TryGetValue(filename, out var variables))
- {
- foreach (var variable in variables)
- AddVariableIndices(variable);
- return;
- }
- if (filename.Equals("STR", StringComparison.OrdinalIgnoreCase))
- {
- Dictionary<int, string> strDefaultValues = new Dictionary<int, string>();
- foreach (var line in csv)
- strDefaultValues.Add(int.Parse(line[0]), line[1]);
- targetDefinition.VariableDefaultValueDictionary["STR"] = strDefaultValues;
- return;
- }
- if (filename.StartsWith("CHARA", StringComparison.OrdinalIgnoreCase))
- {
- //Dictionary<int, string> strDefaultValues = new Dictionary<int, string>();
- //foreach (var line in csv)
- // strDefaultValues.Add(int.Parse(line[0]), line[1]);
- //targetDefinition.VariableDefaultValueDictionary["STR"] = strDefaultValues;
- return;
- }
- //AddVariableIndices(Path.GetFileNameWithoutExtension(filename));
- }
- private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
- {
- { Token.Or, 0 }, { Token.And, 0 },
- { Token.Equal, 1 }, { Token.NotEqual, 1 },
- { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
- { Token.Plus, 2 }, { Token.Minus, 2 },
- { Token.Asterisk, 3 }, { Token.Slash, 3 },
- { Token.Caret, 4 }
- };
- public static Value ConstantExpression(Lexer lexer, ICollection<FunctionVariable> constantDefinitions = null)
- {
- IEnumerator<Token> currentEnumerator = lexer.GetEnumerator();
- Stack<Value> stack = new Stack<Value>();
- Stack<Token> operators = new Stack<Token>();
- void Operation(Token token)
- {
- if (stack.Count < 2)
- throw new ParserException("Not enough operands to perform operation", lexer.TokenMarker);
- Value b = stack.Pop();
- Value a = stack.Pop();
- Value result = a.Operate(b, token);
- stack.Push(result);
- }
- int i = 0;
- while (true)
- {
- if (currentEnumerator.Current == Token.Value)
- {
- stack.Push(lexer.Value);
- }
- else if (currentEnumerator.Current == Token.QuotationMark)
- {
- StringBuilder builder = new StringBuilder();
- char stringChar;
- while ((stringChar = lexer.GetNextChar()) != '"')
- builder.Append(stringChar);
- stack.Push(builder.ToString());
- }
- else if (currentEnumerator.Current == Token.Identifer)
- {
- var variable = constantDefinitions?.FirstOrDefault(x => x.Name.Equals(lexer.Identifier, StringComparison.OrdinalIgnoreCase) && x.VariableType.HasFlag(VariableType.Constant));
- if (variable == null)
- throw new ParserException("Undeclared variable " + lexer.Identifier, lexer.TokenMarker);
- stack.Push(variable.CalculatedValue);
- }
- else if (currentEnumerator.Current == Token.LParen)
- {
- currentEnumerator.MoveNext();
- stack.Push(ConstantExpression(lexer));
- if (currentEnumerator.Current != Token.RParen)
- throw new ParserException($"Was expecting [LParen] got [{currentEnumerator.Current}]", lexer.TokenMarker);
- }
- else if (currentEnumerator.Current.IsArithmetic() && currentEnumerator.Current.IsUnary() && i == 0)
- {
- stack.Push(0);
- operators.Push(currentEnumerator.Current);
- }
- else if (currentEnumerator.Current.IsArithmetic())
- {
- while (operators.Count > 0 && OrderOfOps[currentEnumerator.Current] <= OrderOfOps[operators.Peek()])
- Operation(operators.Pop());
- operators.Push(currentEnumerator.Current);
- }
- else
- {
- if (i == 0)
- throw new ParserException("Empty expression", lexer.TokenMarker);
- break;
- }
- i++;
- currentEnumerator.MoveNext();
- }
- while (operators.Count > 0)
- Operation(operators.Pop());
- if (stack.Count == 0)
- throw new ParserException("Empty expression", lexer.TokenMarker);
- return stack.Pop();
- }
- }
- }
|