Parser.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace NTERA.Engine.Compiler
  6. {
  7. public class Parser
  8. {
  9. protected Lexer Lexer { get; }
  10. protected FunctionDefinition SelfDefinition { get; }
  11. protected ICollection<FunctionDefinition> FunctionDefinitions { get; }
  12. protected ICollection<FunctionDefinition> ProcedureDefinitions { get; }
  13. protected ICollection<FunctionVariable> ConstantDefinitions { get; }
  14. protected ICollection<FunctionVariable> GlobalVariables { get; }
  15. protected ICollection<FunctionVariable> LocalVariables { get; }
  16. protected ICollection<Keyword> ExplicitKeywords { get; }
  17. protected CSVDefinition CsvDefinition { get; }
  18. protected List<ParserError> Errors { get; } = new List<ParserError>();
  19. protected List<ParserError> Warnings { get; } = new List<ParserError>();
  20. protected IEnumerator<Token> Enumerator { get; }
  21. protected bool hasPeeked = false;
  22. protected Token peekedToken = Token.Unknown;
  23. protected Token GetNextToken(bool peek = false)
  24. {
  25. if (peek && hasPeeked)
  26. return peekedToken;
  27. if (!hasPeeked)
  28. Enumerator.MoveNext();
  29. peekedToken = Enumerator.Current;
  30. hasPeeked = peek;
  31. return Enumerator.Current;
  32. }
  33. protected Marker CurrentPosition => new Marker(Lexer.TokenMarker.Pointer + SelfDefinition.Position.Pointer,
  34. Lexer.TokenMarker.Line + SelfDefinition.Position.Line - 1,
  35. Lexer.TokenMarker.Column);
  36. public Parser(string input, FunctionDefinition selfDefinition, ICollection<FunctionDefinition> functionDefinitions, ICollection<FunctionDefinition> procedureDefinitions, ICollection<FunctionVariable> globalVariables, ICollection<FunctionVariable> localVariables, ICollection<Keyword> explicitKeywords, CSVDefinition csvDefinition, ICollection<FunctionVariable> constantDefinitions)
  37. {
  38. Lexer = new Lexer(input);
  39. Enumerator = Lexer.GetEnumerator();
  40. SelfDefinition = selfDefinition;
  41. FunctionDefinitions = functionDefinitions;
  42. ProcedureDefinitions = procedureDefinitions;
  43. ConstantDefinitions = constantDefinitions;
  44. GlobalVariables = globalVariables;
  45. LocalVariables = localVariables;
  46. ExplicitKeywords = explicitKeywords;
  47. CsvDefinition = csvDefinition;
  48. }
  49. public IEnumerable<ExecutionNode> Parse(out List<ParserError> errors, out List<ParserError> warnings)
  50. {
  51. List<ExecutionNode> nodes = new List<ExecutionNode>();
  52. using (Enumerator)
  53. {
  54. do
  55. {
  56. var node = ParseLine(out var error);
  57. if (error != null)
  58. {
  59. Errors.Add(error);
  60. nodes.Add(new ExecutionNode
  61. {
  62. Type = "error",
  63. Metadata =
  64. {
  65. ["message"] = error.ErrorMessage,
  66. ["symbol"] = error.SymbolMarker.ToString()
  67. },
  68. Symbol = error.SymbolMarker
  69. });
  70. //resynchronize to a new line
  71. while (Enumerator.MoveNext()
  72. && Enumerator.Current != Token.NewLine
  73. && Enumerator.Current != Token.EOF)
  74. {
  75. }
  76. }
  77. else if (node != null)
  78. {
  79. nodes.Add(node);
  80. }
  81. hasPeeked = false;
  82. } while (Enumerator.MoveNext());
  83. }
  84. errors = Errors;
  85. warnings = Warnings;
  86. if (errors.Count == 0)
  87. PostProcess(nodes);
  88. return nodes;
  89. }
  90. #region Processor
  91. protected ExecutionNode ParseLine(out ParserError error)
  92. {
  93. error = null;
  94. switch (Enumerator.Current)
  95. {
  96. case Token.Identifer:
  97. if (IsVariable(Lexer.Identifier))
  98. {
  99. string variableName = Lexer.Identifier;
  100. ValueType type = 0;
  101. if (GlobalVariables.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
  102. type = GlobalVariables.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
  103. else if (LocalVariables.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
  104. type = LocalVariables.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
  105. else if (ConstantDefinitions.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
  106. type = ConstantDefinitions.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
  107. var node = new ExecutionNode
  108. {
  109. Type = "assignment",
  110. Symbol = CurrentPosition
  111. };
  112. var variable = GetVariable(out error);
  113. if (error != null)
  114. return null;
  115. if (GetNextToken() != Token.Equal
  116. && Enumerator.Current != Token.Increment
  117. && Enumerator.Current != Token.Decrement
  118. && Enumerator.Current != Token.Append
  119. && !Enumerator.Current.IsArithmetic())
  120. {
  121. error = new ParserError($"Unexpected token, expecting assignment: {Enumerator.Current}", CurrentPosition);
  122. return null;
  123. }
  124. ExecutionNode value;
  125. if (Enumerator.Current == Token.Increment)
  126. {
  127. value = OperateNodes(variable, CreateConstant(1, CurrentPosition), Token.Plus);
  128. }
  129. else if (Enumerator.Current == Token.Decrement)
  130. {
  131. value = OperateNodes(variable, CreateConstant(1, CurrentPosition), Token.Minus);
  132. }
  133. else if (Enumerator.Current == Token.Append)
  134. {
  135. value = OperateNodes(variable, Expression(out error), Token.Plus);
  136. if (error != null)
  137. return null;
  138. }
  139. else if (Enumerator.Current != Token.Equal)
  140. {
  141. Token arithmeticToken = Enumerator.Current;
  142. if (GetNextToken() != Token.Equal)
  143. {
  144. error = new ParserError($"Unexpected token, expecting assignment: {Enumerator.Current}", CurrentPosition);
  145. return null;
  146. }
  147. ExecutionNode newValue = Expression(out error);
  148. value = OperateNodes(variable, newValue, arithmeticToken);
  149. }
  150. else
  151. {
  152. value = type == ValueType.String
  153. ? ParseString(out error, true, true)
  154. : Expression(out error);
  155. }
  156. if (error != null)
  157. return null;
  158. node.SubNodes = new[]
  159. {
  160. variable,
  161. new ExecutionNode
  162. {
  163. Type = "value",
  164. SubNodes = new[] { value }
  165. }
  166. };
  167. return node;
  168. }
  169. else if (Lexer.Identifier.Equals("CASE", StringComparison.OrdinalIgnoreCase))
  170. {
  171. var node = new ExecutionNode
  172. {
  173. Type = "case",
  174. Symbol = CurrentPosition
  175. };
  176. List<ExecutionNode> subNodes = new List<ExecutionNode>();
  177. do
  178. {
  179. if (GetNextToken(true) == Token.NewLine
  180. || GetNextToken(true) == Token.EOF)
  181. break;
  182. var value = Expression(out error);
  183. if (error != null)
  184. return null;
  185. if (Enumerator.Current == Token.To)
  186. {
  187. var value2 = Expression(out error);
  188. if (error != null)
  189. return null;
  190. subNodes.Add(new ExecutionNode
  191. {
  192. Type = "case-to",
  193. SubNodes = new[] { value, value2 }
  194. });
  195. continue;
  196. }
  197. subNodes.Add(new ExecutionNode
  198. {
  199. Type = "case-exact",
  200. SubNodes = new[] { value }
  201. });
  202. } while (Enumerator.Current == Token.Comma);
  203. if (Enumerator.Current != Token.NewLine
  204. && Enumerator.Current != Token.EOF)
  205. {
  206. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  207. return null;
  208. }
  209. node.SubNodes = subNodes.ToArray();
  210. return node;
  211. }
  212. else if (Lexer.Identifier.Equals("CALL", StringComparison.OrdinalIgnoreCase)
  213. || Lexer.Identifier.Equals("TRYCALL", StringComparison.OrdinalIgnoreCase))
  214. {
  215. Enumerator.MoveNext();
  216. if (Enumerator.Current != Token.Identifer)
  217. {
  218. error = new ParserError($"Expecting a call to a function, got token instead: {Enumerator.Current}", CurrentPosition);
  219. return null;
  220. }
  221. Marker symbolMarker = CurrentPosition;
  222. string target = Lexer.Identifier;
  223. List<ExecutionNode> parameters = new List<ExecutionNode>();
  224. if (ProcedureDefinitions.All(x => !x.Name.Equals(target, StringComparison.OrdinalIgnoreCase)))
  225. {
  226. error = new ParserError($"Could not find procedure: {Lexer.Identifier}", CurrentPosition);
  227. return null;
  228. }
  229. Enumerator.MoveNext();
  230. while (Enumerator.Current != Token.NewLine
  231. && Enumerator.Current != Token.EOF
  232. && Enumerator.Current != Token.RParen)
  233. {
  234. parameters.Add(Expression(out error));
  235. if (error != null)
  236. {
  237. error = new ParserError($"{error.ErrorMessage} (target [{target}])", error.SymbolMarker);
  238. return null;
  239. }
  240. if (Enumerator.Current != Token.Comma
  241. && Enumerator.Current != Token.RParen
  242. && Enumerator.Current != Token.NewLine
  243. && Enumerator.Current != Token.EOF)
  244. {
  245. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  246. return null;
  247. }
  248. }
  249. if (Enumerator.Current == Token.RParen)
  250. Enumerator.MoveNext();
  251. if (Enumerator.Current != Token.NewLine
  252. && Enumerator.Current != Token.EOF)
  253. {
  254. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  255. return null;
  256. }
  257. return CallMethod(target, symbolMarker, parameters.ToArray());
  258. }
  259. else if (Lexer.Identifier.Equals("CALLFORM", StringComparison.OrdinalIgnoreCase)
  260. || Lexer.Identifier.Equals("TRYCALLFORM", StringComparison.OrdinalIgnoreCase)
  261. || Lexer.Identifier.Equals("TRYCCALLFORM", StringComparison.OrdinalIgnoreCase)
  262. || Lexer.Identifier.Equals("TRYJUMPFORM", StringComparison.OrdinalIgnoreCase))
  263. {
  264. string statementName = Lexer.Identifier;
  265. var node = new ExecutionNode
  266. {
  267. Type = "callform",
  268. Metadata =
  269. {
  270. ["try"] = statementName.StartsWith("TRY").ToString()
  271. },
  272. Symbol = CurrentPosition
  273. };
  274. ExecutionNode nameValue = null;
  275. List<ExecutionNode> parameters = new List<ExecutionNode>();
  276. Enumerator.MoveNext();
  277. do
  278. {
  279. ExecutionNode newValue = null;
  280. if (Enumerator.Current == Token.Identifer)
  281. {
  282. newValue = CreateConstant(Lexer.Identifier, CurrentPosition);
  283. }
  284. else if (Enumerator.Current == Token.OpenBracket)
  285. {
  286. newValue = Expression(out error);
  287. if (error != null)
  288. return null;
  289. }
  290. else if (Enumerator.Current == Token.LParen)
  291. {
  292. break;
  293. }
  294. else
  295. {
  296. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  297. return null;
  298. }
  299. nameValue = nameValue == null
  300. ? newValue
  301. : OperateNodes(nameValue, newValue, Token.Plus);
  302. Enumerator.MoveNext();
  303. } while (Enumerator.Current != Token.Comma
  304. && Enumerator.Current != Token.NewLine
  305. && Enumerator.Current != Token.EOF);
  306. while (Enumerator.Current != Token.NewLine
  307. && Enumerator.Current != Token.EOF
  308. && Enumerator.Current != Token.RParen)
  309. {
  310. parameters.Add(Expression(out error));
  311. if (error != null)
  312. {
  313. error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
  314. return null;
  315. }
  316. if (Enumerator.Current != Token.Comma
  317. && Enumerator.Current != Token.NewLine
  318. && Enumerator.Current != Token.EOF
  319. && Enumerator.Current != Token.RParen)
  320. {
  321. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  322. return null;
  323. }
  324. }
  325. node.SubNodes = new[]
  326. {
  327. new ExecutionNode
  328. {
  329. Type = "name",
  330. SubNodes = new[] { nameValue }
  331. },
  332. new ExecutionNode
  333. {
  334. Type = "parameters",
  335. SubNodes = parameters.ToArray()
  336. },
  337. };
  338. return node;
  339. }
  340. else if (Lexer.Identifier.Equals("BEGIN", StringComparison.OrdinalIgnoreCase))
  341. {
  342. var node = new ExecutionNode
  343. {
  344. Type = "statement",
  345. Metadata =
  346. {
  347. ["name"] = "BEGIN"
  348. },
  349. Symbol = CurrentPosition
  350. };
  351. Enumerator.MoveNext();
  352. if (Enumerator.Current != Token.Identifer)
  353. {
  354. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  355. return null;
  356. }
  357. node.SubNodes = new[] { CreateConstant(Lexer.Identifier, CurrentPosition) };
  358. return node;
  359. }
  360. else //treat as statement
  361. {
  362. string statementName = Lexer.Identifier;
  363. var node = new ExecutionNode
  364. {
  365. Type = "statement",
  366. Metadata =
  367. {
  368. ["name"] = statementName
  369. },
  370. Symbol = CurrentPosition
  371. };
  372. List<ExecutionNode> parameters = new List<ExecutionNode>();
  373. Keyword keyword = ExplicitKeywords.FirstOrDefault(x => x.Name == statementName);
  374. if (keyword?.ImplicitString == true)
  375. {
  376. var value = ParseString(out error, true, keyword.ImplicitFormatted);
  377. if (error != null)
  378. return null;
  379. if (value != null)
  380. parameters.Add(value);
  381. node.SubNodes = parameters.ToArray();
  382. return node;
  383. }
  384. if (GetNextToken(true) == Token.NewLine
  385. || GetNextToken(true) == Token.EOF)
  386. {
  387. return node;
  388. }
  389. if (GetNextToken(true) == Token.Colon
  390. || GetNextToken(true) == Token.Equal)
  391. {
  392. error = new ParserError($"Undeclared variable: {statementName}", node.Symbol);
  393. return null;
  394. }
  395. while (Enumerator.Current != Token.NewLine
  396. && Enumerator.Current != Token.EOF)
  397. {
  398. parameters.Add(Expression(out error));
  399. if (error != null)
  400. {
  401. error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
  402. return null;
  403. }
  404. if (Enumerator.Current != Token.Comma
  405. && Enumerator.Current != Token.NewLine
  406. && Enumerator.Current != Token.EOF)
  407. {
  408. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  409. return null;
  410. }
  411. }
  412. node.SubNodes = parameters.ToArray();
  413. return node;
  414. }
  415. case Token.AtSymbol:
  416. case Token.Sharp:
  417. while (Enumerator.MoveNext()
  418. && Enumerator.Current != Token.NewLine
  419. && Enumerator.Current != Token.EOF)
  420. {
  421. }
  422. return null;
  423. case Token.NewLine:
  424. case Token.EOF:
  425. return null;
  426. default:
  427. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  428. return null;
  429. }
  430. }
  431. protected bool IsVariable(string identifier)
  432. {
  433. return GlobalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
  434. || LocalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
  435. || ConstantDefinitions.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase));
  436. }
  437. protected ExecutionNode GetVariable(out ParserError error)
  438. {
  439. string variableName = Lexer.Identifier;
  440. var node = new ExecutionNode
  441. {
  442. Type = "variable",
  443. Metadata =
  444. {
  445. ["name"] = variableName
  446. },
  447. Symbol = CurrentPosition
  448. };
  449. List<ExecutionNode> indices = new List<ExecutionNode>();
  450. error = null;
  451. while (GetNextToken(true) == Token.Colon)
  452. {
  453. GetNextToken();
  454. var token = GetNextToken();
  455. if (token == Token.LParen)
  456. {
  457. indices.Add(Expression(out error));
  458. if (error != null)
  459. return null;
  460. if (Enumerator.Current != Token.RParen)
  461. {
  462. error = new ParserError("Invalid expression - Expected right bracket", CurrentPosition);
  463. return null;
  464. }
  465. }
  466. else if (token == Token.Value)
  467. {
  468. indices.Add(CreateConstant(Lexer.Value, CurrentPosition));
  469. }
  470. else if (token == Token.Identifer)
  471. {
  472. if (CsvDefinition.VariableIndexDictionary.TryGetValue(variableName, out var varTable)
  473. && varTable.TryGetValue(Lexer.Identifier, out int index))
  474. {
  475. indices.Add(CreateConstant(index, CurrentPosition));
  476. continue;
  477. }
  478. if (IsVariable(Lexer.Identifier))
  479. {
  480. var subNode = new ExecutionNode
  481. {
  482. Type = "variable",
  483. Metadata =
  484. {
  485. ["name"] = Lexer.Identifier
  486. },
  487. Symbol = CurrentPosition
  488. };
  489. indices.Add(subNode);
  490. continue;
  491. }
  492. if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  493. {
  494. indices.Add(GetFunction(out error));
  495. if (error != null)
  496. return null;
  497. continue;
  498. }
  499. error = new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition);
  500. return null;
  501. }
  502. }
  503. if (indices.Count > 0)
  504. {
  505. ExecutionNode indexNode = new ExecutionNode
  506. {
  507. Type = "index",
  508. SubNodes = indices.ToArray()
  509. };
  510. node.SubNodes = new[] { indexNode };
  511. }
  512. return node;
  513. }
  514. protected ExecutionNode GetFunction(out ParserError error)
  515. {
  516. error = null;
  517. Marker symbolMarker = CurrentPosition;
  518. List<ExecutionNode> parameters = new List<ExecutionNode>();
  519. string functionName = Lexer.Identifier;
  520. if (GetNextToken() != Token.LParen)
  521. {
  522. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  523. return null;
  524. }
  525. while (Enumerator.Current == Token.Comma
  526. || Enumerator.Current == Token.LParen)
  527. {
  528. if (GetNextToken(true) == Token.RParen)
  529. break;
  530. if (GetNextToken(true) == Token.Comma)
  531. {
  532. var defaultValue = new ExecutionNode
  533. {
  534. Type = "defaultvalue",
  535. Symbol = CurrentPosition
  536. };
  537. parameters.Add(defaultValue);
  538. GetNextToken();
  539. continue;
  540. }
  541. parameters.Add(Expression(out error));
  542. if (error != null)
  543. return null;
  544. if (Enumerator.Current != Token.Comma
  545. && Enumerator.Current != Token.RParen)
  546. {
  547. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  548. return null;
  549. }
  550. }
  551. if (Enumerator.Current != Token.RParen)
  552. {
  553. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  554. return null;
  555. }
  556. if (hasPeeked)
  557. {
  558. GetNextToken();
  559. }
  560. var functionDefinition = FunctionDefinitions.FirstOrDefault(x => x.Name == functionName
  561. && (x.Parameters.Length >= parameters.Count
  562. || x.Parameters.Any(y => y.IsArrayParameter)));
  563. if (functionDefinition == null)
  564. {
  565. error = new ParserError($"No matching method with same amount of parameters: {functionName} ({parameters.Count})", CurrentPosition);
  566. return null;
  567. }
  568. return CallMethod(functionName, symbolMarker, parameters.ToArray());
  569. }
  570. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
  571. {
  572. { Token.Or, 0 }, { Token.And, 0 }, { Token.Not, 0 },
  573. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  574. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  575. { Token.Plus, 2 }, { Token.Minus, 2 },
  576. { Token.Asterisk, 3 }, { Token.Slash, 3 }, { Token.Modulo, 3 },
  577. { Token.Caret, 4 }
  578. };
  579. protected ExecutionNode Expression(out ParserError error, bool useModulo = true, bool ternaryString = false)
  580. {
  581. error = null;
  582. var operators = new Stack<Token>();
  583. var operands = new Stack<ExecutionNode>();
  584. Token token;
  585. void ProcessOperation(out ParserError localError)
  586. {
  587. localError = null;
  588. Token op = operators.Pop();
  589. if (op.IsUnary() && operands.Count == 1)
  590. {
  591. var operand = operands.Pop();
  592. operands.Push(new ExecutionNode
  593. {
  594. Type = "operation",
  595. Metadata =
  596. {
  597. ["type"] = GetOperationName(op),
  598. ["unary"] = "true"
  599. },
  600. SubNodes = new[]
  601. {
  602. operand
  603. }
  604. });
  605. }
  606. else if (operands.Count >= 2)
  607. {
  608. ExecutionNode right = operands.Pop();
  609. ExecutionNode left = operands.Pop();
  610. operands.Push(new ExecutionNode
  611. {
  612. Type = "operation",
  613. Metadata =
  614. {
  615. ["type"] = GetOperationName(op),
  616. ["unary"] = "false"
  617. },
  618. SubNodes = new[]
  619. {
  620. left,
  621. right
  622. }
  623. });
  624. }
  625. else
  626. localError = new ParserError("Invalid expression - not enough operands", CurrentPosition);
  627. }
  628. void AttemptUnaryConversion(out ParserError localError)
  629. {
  630. localError = null;
  631. while (operators.Count > 0
  632. && operators.Peek().IsUnary())
  633. {
  634. ProcessOperation(out localError);
  635. if (localError != null)
  636. return;
  637. }
  638. }
  639. while ((token = GetNextToken()) != Token.NewLine
  640. && token != Token.EOF
  641. && token != Token.Comma
  642. && token != Token.Colon
  643. && token != Token.To
  644. && token != Token.CloseBracket
  645. && token != Token.RParen
  646. && token != Token.QuestionMark
  647. && token != Token.Sharp
  648. && (!ternaryString || token != Token.TernaryEscape)
  649. && (useModulo || token != Token.Modulo))
  650. {
  651. if (token == Token.Value)
  652. {
  653. operands.Push(CreateConstant(Lexer.Value, CurrentPosition));
  654. AttemptUnaryConversion(out error);
  655. if (error != null)
  656. return null;
  657. }
  658. else if (token == Token.QuotationMark || token == Token.AtSymbol)
  659. {
  660. operands.Push(ParseString(out error, false, false));
  661. if (error != null)
  662. return null;
  663. }
  664. else if (token == Token.Identifer)
  665. {
  666. if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  667. {
  668. operands.Push(GetFunction(out error));
  669. if (error != null)
  670. return null;
  671. }
  672. else if (IsVariable(Lexer.Identifier))
  673. {
  674. operands.Push(GetVariable(out error));
  675. if (error != null)
  676. return null;
  677. }
  678. else
  679. {
  680. Warnings.Add(new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition));
  681. break;
  682. }
  683. }
  684. else if (token == Token.TernaryEscape)
  685. {
  686. operands.Push(Expression(out error, useModulo, true));
  687. if (error != null)
  688. return null;
  689. }
  690. else if (token.IsArithmetic())
  691. {
  692. if (!operands.Any() && token.IsUnary())
  693. {
  694. operators.Push(token);
  695. continue;
  696. }
  697. if (!operands.Any() && !token.IsUnary())
  698. {
  699. error = new ParserError($"Invalid unary operator: {token}", CurrentPosition);
  700. return null;
  701. }
  702. while (operators.Any() && OrderOfOps[token] <= OrderOfOps[operators.Peek()])
  703. {
  704. ProcessOperation(out error);
  705. if (error != null)
  706. return null;
  707. }
  708. operators.Push(token);
  709. }
  710. else if (token == Token.LParen)
  711. {
  712. operands.Push(Expression(out var localError));
  713. if (localError != null)
  714. {
  715. error = localError;
  716. return null;
  717. }
  718. }
  719. else if (token == Token.RParen)
  720. {
  721. break;
  722. }
  723. else
  724. {
  725. error = new ParserError($"Unexpected token: {token}", CurrentPosition);
  726. return null;
  727. }
  728. }
  729. while (operators.Any())
  730. {
  731. ProcessOperation(out error);
  732. if (error != null)
  733. return null;
  734. }
  735. if (!operands.Any())
  736. {
  737. error = new ParserError("Invalid expression - Empty operand stack", CurrentPosition);
  738. return null;
  739. }
  740. var result = operands.Pop();
  741. if (token != Token.QuestionMark)
  742. return result;
  743. var resultTrue = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
  744. if (error != null)
  745. return null;
  746. var resultFalse = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
  747. if (error != null)
  748. return null;
  749. return CallMethod("__INLINEIF", CurrentPosition, result, resultTrue, resultFalse);
  750. }
  751. protected ExecutionNode ParseString(out ParserError error, bool implicitString, bool canFormat = false, bool nestedTernary = false)
  752. {
  753. error = null;
  754. ExecutionNode value = null;
  755. if (Lexer.IsPeeking)
  756. Lexer.GetNextChar();
  757. if (nestedTernary && (Lexer.CurrentChar == '?' || Lexer.CurrentChar == '#'))
  758. Lexer.GetNextChar();
  759. if (!implicitString)
  760. {
  761. if (Lexer.CurrentChar == '@')
  762. {
  763. canFormat = true;
  764. Lexer.GetNextChar();
  765. }
  766. if (Lexer.CurrentChar == '"')
  767. {
  768. Lexer.GetNextChar();
  769. }
  770. }
  771. else
  772. {
  773. if (char.IsWhiteSpace(Lexer.CurrentChar))
  774. Lexer.GetNextChar();
  775. }
  776. StringBuilder currentBlock = new StringBuilder();
  777. void commitBlock()
  778. {
  779. if (currentBlock.Length == 0)
  780. return;
  781. ExecutionNode stringBlock = CreateConstant(currentBlock.ToString(), CurrentPosition);
  782. value = value == null
  783. ? stringBlock
  784. : OperateNodes(value, stringBlock, Token.Plus);
  785. currentBlock.Clear();
  786. }
  787. while ((Lexer.CurrentChar != '"' || implicitString)
  788. && Lexer.CurrentChar != '\n'
  789. && Lexer.CurrentChar != '\0')
  790. {
  791. if (Lexer.CurrentChar == '\r')
  792. {
  793. Lexer.GetNextChar();
  794. continue;
  795. }
  796. if (nestedTernary && Lexer.CurrentChar == '#')
  797. break;
  798. if (canFormat && Lexer.CurrentChar == '\\')
  799. {
  800. Lexer.GetNextChar();
  801. if (Lexer.CurrentChar == '@')
  802. {
  803. if (nestedTernary)
  804. break;
  805. var expressionValue = Expression(out error, true, true);
  806. if (error != null)
  807. return null;
  808. commitBlock();
  809. value = value == null
  810. ? expressionValue
  811. : OperateNodes(value, expressionValue, Token.Plus);
  812. }
  813. else if (Lexer.CurrentChar == 'n')
  814. {
  815. currentBlock.Append('\n');
  816. Lexer.GetNextChar();
  817. continue;
  818. }
  819. currentBlock.Append(Lexer.CurrentChar);
  820. Lexer.GetNextChar();
  821. continue;
  822. }
  823. if (canFormat && (Lexer.CurrentChar == '{' || Lexer.CurrentChar == '%'))
  824. {
  825. bool useModulo = Lexer.CurrentChar != '%';
  826. List<ExecutionNode> formatParams = new List<ExecutionNode>();
  827. Marker symbolMarker = CurrentPosition;
  828. do
  829. {
  830. var expressionValue = Expression(out error, useModulo, nestedTernary);
  831. if (error != null)
  832. return null;
  833. formatParams.Add(expressionValue);
  834. } while (Enumerator.Current == Token.Comma);
  835. var formattedValue = CallMethod("__FORMAT", symbolMarker, formatParams.ToArray());
  836. commitBlock();
  837. value = value == null
  838. ? formattedValue
  839. : OperateNodes(value, formattedValue, Token.Plus);
  840. Lexer.GetNextChar();
  841. continue;
  842. }
  843. currentBlock.Append(Lexer.CurrentChar);
  844. Lexer.GetNextChar();
  845. }
  846. if (!nestedTernary && !implicitString && (Lexer.CurrentChar == '\0' || Lexer.CurrentChar == '\n'))
  847. {
  848. error = new ParserError("Was expecting string to be closed", CurrentPosition);
  849. return null;
  850. }
  851. commitBlock();
  852. value = value ?? CreateConstant("", CurrentPosition);
  853. return value;
  854. }
  855. private static readonly Dictionary<Token, string> OperationNames = new Dictionary<Token, string>
  856. {
  857. [Token.Plus] = "add",
  858. [Token.Asterisk] = "multiply",
  859. [Token.Minus] = "subtract",
  860. [Token.Slash] = "divide",
  861. };
  862. public static string GetOperationName(Token token)
  863. {
  864. return OperationNames.TryGetValue(token, out string result)
  865. ? result
  866. : token.ToString();
  867. }
  868. public static ExecutionNode CreateConstant(Value value, Marker symbolMarker)
  869. {
  870. return new ExecutionNode
  871. {
  872. Type = "constant",
  873. Metadata =
  874. {
  875. ["type"] = value.Type.ToString(),
  876. ["value"] = value.ToString()
  877. },
  878. Symbol = symbolMarker
  879. };
  880. }
  881. public static ExecutionNode OperateNodes(ExecutionNode left, ExecutionNode right, Token token)
  882. {
  883. return new ExecutionNode
  884. {
  885. Type = "operation",
  886. Metadata =
  887. {
  888. ["type"] = GetOperationName(token)
  889. },
  890. SubNodes = new[]
  891. {
  892. left,
  893. right
  894. }
  895. };
  896. }
  897. public static ExecutionNode CallMethod(string methodName, Marker symbolMarker, params ExecutionNode[] parameters)
  898. {
  899. return new ExecutionNode
  900. {
  901. Type = "call",
  902. Metadata =
  903. {
  904. ["target"] = methodName
  905. },
  906. Symbol = symbolMarker,
  907. SubNodes = new[]
  908. {
  909. new ExecutionNode
  910. {
  911. Type = "parameters",
  912. SubNodes = parameters.ToArray()
  913. }
  914. }
  915. };
  916. }
  917. #endregion
  918. #region Post-processor
  919. protected void PostProcess(List<ExecutionNode> nodes)
  920. {
  921. Branchify(nodes);
  922. }
  923. protected void Branchify(List<ExecutionNode> nodes)
  924. {
  925. Stack<ExecutionNode> workingStack = new Stack<ExecutionNode>();
  926. foreach (var node in nodes)
  927. {
  928. if (node.Type == "statement" && node["name"].Equals("FOR", StringComparison.OrdinalIgnoreCase))
  929. {
  930. workingStack.Push(node);
  931. }
  932. }
  933. foreach (var forNode in workingStack)
  934. {
  935. int index = nodes.IndexOf(forNode);
  936. int endIndex = 0;
  937. for (int i = index; i < nodes.Count; i++)
  938. {
  939. var node = nodes[i];
  940. if (node.Type == "statement" && node["name"].Equals("NEXT", StringComparison.OrdinalIgnoreCase))
  941. {
  942. endIndex = i;
  943. break;
  944. }
  945. }
  946. if (endIndex == 0)
  947. throw new ParserException("Could not find matching NEXT for FOR statement");
  948. List<ExecutionNode> subNodes = new List<ExecutionNode>();
  949. forNode.Type = "for-context";
  950. subNodes.Add(forNode);
  951. subNodes.AddRange(nodes.Skip(index + 1).Take(endIndex - index - 1));
  952. nodes.RemoveRange(index, (endIndex - index) + 1);
  953. ExecutionNode newNode = new ExecutionNode
  954. {
  955. Type = "for",
  956. SubNodes = subNodes.ToArray()
  957. };
  958. nodes.Insert(index, newNode);
  959. }
  960. }
  961. #endregion
  962. }
  963. }