Preprocessor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace NTERA.Engine.Compiler
  6. {
  7. public static class Preprocessor
  8. {
  9. public static IEnumerable<FunctionVariable> PreprocessHeaderFile(string contents)
  10. {
  11. Lexer lexer = new Lexer(contents);
  12. List<FunctionVariable> constantDefinitions = new List<FunctionVariable>();
  13. using (var enumerator = lexer.GetEnumerator())
  14. {
  15. do
  16. {
  17. if (lexer.TokenMarker.Column != 1)
  18. continue;
  19. if (enumerator.Current == Token.Sharp)
  20. {
  21. enumerator.MoveNext();
  22. switch (enumerator.Current)
  23. {
  24. case Token.Dims:
  25. case Token.Dim:
  26. {
  27. bool isString = enumerator.Current != Token.Dim;
  28. enumerator.MoveNext();
  29. VariableType variableType = VariableType.None;
  30. while (enumerator.Current == Token.Const
  31. || enumerator.Current == Token.Ref
  32. || enumerator.Current == Token.Dynamic
  33. || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("GLOBAL", StringComparison.OrdinalIgnoreCase))
  34. || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("CHARADATA", StringComparison.OrdinalIgnoreCase))
  35. || (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("SAVEDATA", StringComparison.OrdinalIgnoreCase)))
  36. {
  37. if (enumerator.Current == Token.Const)
  38. variableType |= VariableType.Constant;
  39. else if (enumerator.Current == Token.Ref)
  40. variableType |= VariableType.Reference;
  41. else if (enumerator.Current == Token.Dynamic)
  42. variableType |= VariableType.Dynamic;
  43. else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("GLOBAL", StringComparison.OrdinalIgnoreCase))
  44. variableType |= VariableType.SaveData;
  45. else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("CHARADATA", StringComparison.OrdinalIgnoreCase))
  46. variableType |= VariableType.CharaData;
  47. else if (enumerator.Current == Token.Identifer && lexer.Identifier.Equals("SAVEDATA", StringComparison.OrdinalIgnoreCase))
  48. variableType |= VariableType.Global;
  49. enumerator.MoveNext();
  50. }
  51. string variable = lexer.Identifier;
  52. enumerator.MoveNext();
  53. Value? defaultValue = null;
  54. if (enumerator.Current == Token.Comma)
  55. {
  56. while (enumerator.MoveNext()
  57. && enumerator.Current != Token.Equal
  58. && enumerator.Current != Token.NewLine
  59. && enumerator.Current != Token.EOF)
  60. {
  61. //arraySize = (int)lexer.Expression().Real;
  62. //the array size goes here, but we ignore it since it's useless to us
  63. }
  64. }
  65. if (enumerator.Current == Token.Equal)
  66. {
  67. enumerator.MoveNext();
  68. defaultValue = ConstantExpression(lexer, constantDefinitions);
  69. }
  70. else if (enumerator.Current != Token.NewLine
  71. && enumerator.Current != Token.EOF)
  72. {
  73. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  74. }
  75. var functionDefinition = new FunctionVariable(variable,
  76. isString ? ValueType.String : ValueType.Real,
  77. variableType,
  78. defaultValue);
  79. constantDefinitions.Add(functionDefinition);
  80. yield return functionDefinition;
  81. break;
  82. }
  83. }
  84. }
  85. else
  86. {
  87. //resynchronize to next line
  88. while (enumerator.Current != Token.NewLine
  89. && enumerator.Current != Token.EOF
  90. && enumerator.MoveNext())
  91. {
  92. }
  93. }
  94. } while (enumerator.MoveNext());
  95. }
  96. }
  97. public static IDictionary<FunctionDefinition, string> PreprocessCodeFile(string contents, string filename, ICollection<FunctionVariable> constantDefinitions)
  98. {
  99. Dictionary<FunctionDefinition, string> procedures = new Dictionary<FunctionDefinition, string>();
  100. Lexer lexer = new Lexer(contents);
  101. Marker startMarker = lexer.TokenMarker;
  102. string currentDefinitionName = null;
  103. List<FunctionParameter> currentDefinitionParameters = new List<FunctionParameter>();
  104. List<FunctionVariable> currentDefinitionVariables = new List<FunctionVariable>();
  105. bool isReturnFunction = false;
  106. void Commit()
  107. {
  108. if (currentDefinitionName != null)
  109. {
  110. string procBody = contents.Substring(startMarker.Pointer,
  111. lexer.TokenMarker.Pointer - startMarker.Pointer);
  112. var definition = new FunctionDefinition(currentDefinitionName,
  113. currentDefinitionParameters.ToArray(),
  114. currentDefinitionVariables.ToArray(),
  115. isReturnFunction,
  116. filename,
  117. startMarker);
  118. procedures.Add(definition, procBody);
  119. isReturnFunction = false;
  120. currentDefinitionName = null;
  121. currentDefinitionParameters.Clear();
  122. }
  123. }
  124. using (var enumerator = lexer.GetEnumerator())
  125. {
  126. do
  127. {
  128. if (lexer.TokenMarker.Column != 1)
  129. continue;
  130. if (enumerator.Current == Token.AtSymbol)
  131. {
  132. Commit();
  133. startMarker = lexer.TokenMarker;
  134. enumerator.MoveNext();
  135. if (enumerator.Current != Token.Identifer)
  136. throw new ParserException("Invalid function declaration - Expected an identifier", lexer.TokenMarker);
  137. currentDefinitionName = lexer.Identifier;
  138. enumerator.MoveNext();
  139. if (enumerator.Current == Token.NewLine
  140. || enumerator.Current == Token.EOF)
  141. continue;
  142. if (enumerator.Current != Token.LParen
  143. && enumerator.Current != Token.Comma)
  144. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  145. enumerator.MoveNext();
  146. if (enumerator.Current != Token.Identifer
  147. && enumerator.Current != Token.RParen)
  148. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  149. while (enumerator.Current == Token.Identifer)
  150. {
  151. string parameterName = lexer.Identifier;
  152. List<string> indices = new List<string>();
  153. Value? defaultValue = null;
  154. enumerator.MoveNext();
  155. while (enumerator.Current == Token.Colon
  156. && enumerator.MoveNext())
  157. {
  158. if (enumerator.Current == Token.Value)
  159. {
  160. indices.Add(lexer.Value.Type == ValueType.Real
  161. ? ((int)lexer.Value).ToString()
  162. : lexer.Value.String);
  163. }
  164. else if (enumerator.Current == Token.Identifer)
  165. {
  166. indices.Add(lexer.Identifier);
  167. }
  168. enumerator.MoveNext();
  169. }
  170. if (enumerator.Current == Token.Equal)
  171. {
  172. enumerator.MoveNext();
  173. defaultValue = ConstantExpression(lexer, constantDefinitions);
  174. }
  175. if (enumerator.Current == Token.Comma
  176. || enumerator.Current == Token.RParen)
  177. {
  178. enumerator.MoveNext();
  179. }
  180. else if (enumerator.Current != Token.NewLine
  181. && enumerator.Current != Token.EOF)
  182. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  183. currentDefinitionParameters.Add(new FunctionParameter(parameterName, indices.ToArray(), defaultValue));
  184. }
  185. if (enumerator.Current == Token.RParen)
  186. enumerator.MoveNext();
  187. if (enumerator.Current != Token.NewLine
  188. && enumerator.Current != Token.EOF)
  189. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  190. }
  191. else if (enumerator.Current == Token.Sharp)
  192. {
  193. enumerator.MoveNext();
  194. switch (enumerator.Current)
  195. {
  196. case Token.Dims:
  197. case Token.Dim:
  198. {
  199. bool isString = enumerator.Current != Token.Dim;
  200. enumerator.MoveNext();
  201. VariableType variableType = VariableType.None;
  202. while (enumerator.Current == Token.Const
  203. || enumerator.Current == Token.Ref
  204. || enumerator.Current == Token.Dynamic)
  205. {
  206. if (enumerator.Current == Token.Const)
  207. variableType |= VariableType.Constant;
  208. else if (enumerator.Current == Token.Ref)
  209. variableType |= VariableType.Reference;
  210. else if (enumerator.Current == Token.Dynamic)
  211. variableType |= VariableType.Dynamic;
  212. enumerator.MoveNext();
  213. }
  214. string variable = lexer.Identifier;
  215. enumerator.MoveNext();
  216. Value? defaultValue = null;
  217. if (enumerator.Current == Token.Comma)
  218. {
  219. while (enumerator.MoveNext()
  220. && enumerator.Current != Token.Equal
  221. && enumerator.Current != Token.NewLine
  222. && enumerator.Current != Token.EOF)
  223. {
  224. //arraySize = (int)lexer.Expression().Real;
  225. //the array size goes here, but we ignore it since it's useless to us
  226. }
  227. }
  228. if (enumerator.Current == Token.Equal)
  229. {
  230. enumerator.MoveNext();
  231. defaultValue = ConstantExpression(lexer, constantDefinitions);
  232. }
  233. else if (enumerator.Current != Token.NewLine
  234. && enumerator.Current != Token.EOF)
  235. {
  236. throw new ParserException("Invalid function declaration", lexer.TokenMarker);
  237. }
  238. currentDefinitionVariables.Add(new FunctionVariable(variable,
  239. isString ? ValueType.String : ValueType.Real,
  240. variableType,
  241. defaultValue));
  242. break;
  243. }
  244. case Token.ReturnFunction:
  245. {
  246. isReturnFunction = true;
  247. break;
  248. }
  249. }
  250. }
  251. else
  252. {
  253. //resynchronize to next line
  254. while (enumerator.Current != Token.NewLine
  255. && enumerator.Current != Token.EOF
  256. && enumerator.MoveNext())
  257. {
  258. }
  259. }
  260. } while (enumerator.MoveNext());
  261. }
  262. Commit();
  263. return procedures;
  264. }
  265. private static IList<IList<string>> SplitCSV(IEnumerable<string> lines)
  266. {
  267. List<IList<string>> csv = new List<IList<string>>();
  268. foreach (var line in lines)
  269. {
  270. if (string.IsNullOrWhiteSpace(line)
  271. || line[0] == ';')
  272. continue;
  273. string newLine = line;
  274. int commentIndex = line.IndexOf(';');
  275. if (commentIndex >= 0)
  276. newLine = line.Substring(0, commentIndex);
  277. string[] split = newLine.Split(new[] { ',' }, StringSplitOptions.None);
  278. if (split.Length == 1)
  279. continue;
  280. csv.Add(split.ToList());
  281. }
  282. return csv;
  283. }
  284. private static Dictionary<string, string[]> NameIndexDictionary = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
  285. {
  286. ["ITEM"] = new[] { "ITEM", "ITEMSALES", "ITEMPRICE" },
  287. ["BASE"] = new[] { "BASE", "LOSEBASE", "MAXBASE", "DOWNBASE" },
  288. ["ABL"] = new[] { "ABL" },
  289. ["TALENT"] = new[] { "TALENT" },
  290. ["EXP"] = new[] { "EXP" },
  291. ["MARK"] = new[] { "MARK" },
  292. ["PALAM"] = new[] { "PALAM", "UP", "DOWN", "JUEL", "GOTJUEL", "CUP", "CDOWN" },
  293. ["STAIN"] = new[] { "STAIN" },
  294. ["SOURCE"] = new[] { "SOURCE" },
  295. ["EX"] = new[] { "EX", "NOWEX" },
  296. ["TEQUIP"] = new[] { "TEQUIP" },
  297. ["EQUIP"] = new[] { "EQUIP" },
  298. ["FLAG"] = new[] { "FLAG" },
  299. ["TFLAG"] = new[] { "TFLAG" },
  300. ["CFLAG"] = new[] { "CFLAG" },
  301. ["STRNAME"] = new[] { "STR" },
  302. ["SAVESTR"] = new[] { "SAVESTR" },
  303. ["TCVAR"] = new[] { "TCVAR" },
  304. ["TSTR"] = new[] { "TSTR" },
  305. ["CSTR"] = new[] { "CSTR" },
  306. ["CDFLAG1"] = new[] { "CDFLAG" },
  307. ["CDFLAG2"] = new[] { "CDFLAG" },
  308. ["GLOBAL"] = new[] { "GLOBAL" },
  309. ["GLOBALS"] = new[] { "GLOBALS" },
  310. };
  311. public static void ProcessCSV(CSVDefinition targetDefinition, string filename, IEnumerable<string> lines)
  312. {
  313. if (filename.EndsWith("_TR", StringComparison.OrdinalIgnoreCase))
  314. return;
  315. if (filename.Equals("VariableSize", StringComparison.OrdinalIgnoreCase))
  316. return;
  317. if (filename.Equals("_Replace", StringComparison.OrdinalIgnoreCase))
  318. return;
  319. var csv = SplitCSV(lines);
  320. void AddVariableIndices(string variableName)
  321. {
  322. Dictionary<string, int> varIndices = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
  323. foreach (var line in csv)
  324. if (!string.IsNullOrWhiteSpace(line[1]))
  325. varIndices[line[1]] = int.Parse(line[0]);
  326. targetDefinition.VariableIndexDictionary[variableName] = varIndices;
  327. }
  328. if (filename.Equals("GameBase", StringComparison.OrdinalIgnoreCase))
  329. {
  330. foreach (var line in csv)
  331. targetDefinition.GameBaseInfo.Add(line[0], line[1]);
  332. return;
  333. }
  334. if (NameIndexDictionary.TryGetValue(filename, out var variables))
  335. {
  336. foreach (var variable in variables)
  337. AddVariableIndices(variable);
  338. return;
  339. }
  340. if (filename.Equals("STR", StringComparison.OrdinalIgnoreCase))
  341. {
  342. Dictionary<int, string> strDefaultValues = new Dictionary<int, string>();
  343. foreach (var line in csv)
  344. strDefaultValues.Add(int.Parse(line[0]), line[1]);
  345. targetDefinition.VariableDefaultValueDictionary["STR"] = strDefaultValues;
  346. return;
  347. }
  348. if (filename.StartsWith("CHARA", StringComparison.OrdinalIgnoreCase))
  349. {
  350. //Dictionary<int, string> strDefaultValues = new Dictionary<int, string>();
  351. //foreach (var line in csv)
  352. // strDefaultValues.Add(int.Parse(line[0]), line[1]);
  353. //targetDefinition.VariableDefaultValueDictionary["STR"] = strDefaultValues;
  354. return;
  355. }
  356. //AddVariableIndices(Path.GetFileNameWithoutExtension(filename));
  357. }
  358. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
  359. {
  360. { Token.Or, 0 }, { Token.And, 0 },
  361. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  362. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  363. { Token.Plus, 2 }, { Token.Minus, 2 },
  364. { Token.Asterisk, 3 }, { Token.Slash, 3 },
  365. { Token.Caret, 4 }
  366. };
  367. public static Value ConstantExpression(Lexer lexer, ICollection<FunctionVariable> constantDefinitions = null)
  368. {
  369. IEnumerator<Token> currentEnumerator = lexer.GetEnumerator();
  370. Stack<Value> stack = new Stack<Value>();
  371. Stack<Token> operators = new Stack<Token>();
  372. void Operation(Token token)
  373. {
  374. if (stack.Count < 2)
  375. throw new ParserException("Not enough operands to perform operation", lexer.TokenMarker);
  376. Value b = stack.Pop();
  377. Value a = stack.Pop();
  378. Value result = a.Operate(b, token);
  379. stack.Push(result);
  380. }
  381. int i = 0;
  382. while (true)
  383. {
  384. if (currentEnumerator.Current == Token.Value)
  385. {
  386. stack.Push(lexer.Value);
  387. }
  388. else if (currentEnumerator.Current == Token.QuotationMark)
  389. {
  390. StringBuilder builder = new StringBuilder();
  391. char stringChar;
  392. while ((stringChar = lexer.GetNextChar()) != '"')
  393. builder.Append(stringChar);
  394. stack.Push(builder.ToString());
  395. }
  396. else if (currentEnumerator.Current == Token.Identifer)
  397. {
  398. var variable = constantDefinitions?.FirstOrDefault(x => x.Name.Equals(lexer.Identifier, StringComparison.OrdinalIgnoreCase) && x.VariableType.HasFlag(VariableType.Constant));
  399. if (variable == null)
  400. throw new ParserException("Undeclared variable " + lexer.Identifier, lexer.TokenMarker);
  401. stack.Push(variable.CalculatedValue);
  402. }
  403. else if (currentEnumerator.Current == Token.LParen)
  404. {
  405. currentEnumerator.MoveNext();
  406. stack.Push(ConstantExpression(lexer));
  407. if (currentEnumerator.Current != Token.RParen)
  408. throw new ParserException($"Was expecting [LParen] got [{currentEnumerator.Current}]", lexer.TokenMarker);
  409. }
  410. else if (currentEnumerator.Current.IsArithmetic() && currentEnumerator.Current.IsUnary() && i == 0)
  411. {
  412. stack.Push(0);
  413. operators.Push(currentEnumerator.Current);
  414. }
  415. else if (currentEnumerator.Current.IsArithmetic())
  416. {
  417. while (operators.Count > 0 && OrderOfOps[currentEnumerator.Current] <= OrderOfOps[operators.Peek()])
  418. Operation(operators.Pop());
  419. operators.Push(currentEnumerator.Current);
  420. }
  421. else
  422. {
  423. if (i == 0)
  424. throw new ParserException("Empty expression", lexer.TokenMarker);
  425. break;
  426. }
  427. i++;
  428. currentEnumerator.MoveNext();
  429. }
  430. while (operators.Count > 0)
  431. Operation(operators.Pop());
  432. if (stack.Count == 0)
  433. throw new ParserException("Empty expression", lexer.TokenMarker);
  434. return stack.Pop();
  435. }
  436. }
  437. }