Parser.cs 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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.GotoLabel:
  416. if (GetNextToken() != Token.Identifer)
  417. {
  418. error = new ParserError($"Expected an identifer, got {Enumerator.Current}", CurrentPosition);
  419. return null;
  420. }
  421. return new ExecutionNode
  422. {
  423. Type = "anchor",
  424. Anchor = Lexer.Identifier
  425. };
  426. case Token.AtSymbol:
  427. case Token.Sharp:
  428. while (Enumerator.MoveNext()
  429. && Enumerator.Current != Token.NewLine
  430. && Enumerator.Current != Token.EOF)
  431. {
  432. }
  433. return null;
  434. case Token.NewLine:
  435. case Token.EOF:
  436. return null;
  437. default:
  438. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  439. return null;
  440. }
  441. }
  442. protected bool IsVariable(string identifier)
  443. {
  444. return GlobalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
  445. || LocalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
  446. || ConstantDefinitions.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase));
  447. }
  448. protected ExecutionNode GetVariable(out ParserError error)
  449. {
  450. string variableName = Lexer.Identifier;
  451. Marker symbol = CurrentPosition;
  452. List<ExecutionNode> indices = new List<ExecutionNode>();
  453. error = null;
  454. while (GetNextToken(true) == Token.Colon)
  455. {
  456. GetNextToken();
  457. var token = GetNextToken();
  458. if (token == Token.LParen)
  459. {
  460. indices.Add(Expression(out error));
  461. if (error != null)
  462. return null;
  463. if (Enumerator.Current != Token.RParen)
  464. {
  465. error = new ParserError("Invalid expression - Expected right bracket", CurrentPosition);
  466. return null;
  467. }
  468. }
  469. else if (token == Token.Value)
  470. {
  471. indices.Add(CreateConstant(Lexer.Value, CurrentPosition));
  472. }
  473. else if (token == Token.Identifer)
  474. {
  475. if (CsvDefinition.VariableIndexDictionary.TryGetValue(variableName, out var varTable)
  476. && varTable.TryGetValue(Lexer.Identifier, out int index))
  477. {
  478. indices.Add(CreateConstant(index, CurrentPosition));
  479. continue;
  480. }
  481. if (IsVariable(Lexer.Identifier))
  482. {
  483. var subNode = new ExecutionNode
  484. {
  485. Type = "variable",
  486. Metadata =
  487. {
  488. ["name"] = Lexer.Identifier
  489. },
  490. Symbol = CurrentPosition
  491. };
  492. indices.Add(subNode);
  493. continue;
  494. }
  495. if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  496. {
  497. indices.Add(GetFunction(out error));
  498. if (error != null)
  499. return null;
  500. continue;
  501. }
  502. error = new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition);
  503. return null;
  504. }
  505. }
  506. return GetVariable(variableName, symbol, indices.ToArray());
  507. }
  508. protected ExecutionNode GetFunction(out ParserError error)
  509. {
  510. error = null;
  511. Marker symbolMarker = CurrentPosition;
  512. List<ExecutionNode> parameters = new List<ExecutionNode>();
  513. string functionName = Lexer.Identifier;
  514. if (GetNextToken() != Token.LParen)
  515. {
  516. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  517. return null;
  518. }
  519. while (Enumerator.Current == Token.Comma
  520. || Enumerator.Current == Token.LParen)
  521. {
  522. if (GetNextToken(true) == Token.RParen)
  523. break;
  524. if (GetNextToken(true) == Token.Comma)
  525. {
  526. var defaultValue = new ExecutionNode
  527. {
  528. Type = "defaultvalue",
  529. Symbol = CurrentPosition
  530. };
  531. parameters.Add(defaultValue);
  532. GetNextToken();
  533. continue;
  534. }
  535. parameters.Add(Expression(out error));
  536. if (error != null)
  537. return null;
  538. if (Enumerator.Current != Token.Comma
  539. && Enumerator.Current != Token.RParen)
  540. {
  541. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  542. return null;
  543. }
  544. }
  545. if (Enumerator.Current != Token.RParen)
  546. {
  547. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  548. return null;
  549. }
  550. if (hasPeeked)
  551. {
  552. GetNextToken();
  553. }
  554. var functionDefinition = FunctionDefinitions.FirstOrDefault(x => x.Name == functionName
  555. && (x.Parameters.Length >= parameters.Count
  556. || x.Parameters.Any(y => y.IsArrayParameter)));
  557. if (functionDefinition == null)
  558. {
  559. error = new ParserError($"No matching method with same amount of parameters: {functionName} ({parameters.Count})", CurrentPosition);
  560. return null;
  561. }
  562. return CallMethod(functionName, symbolMarker, parameters.ToArray());
  563. }
  564. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
  565. {
  566. { Token.Or, 0 }, { Token.And, 0 }, { Token.Not, 0 },
  567. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  568. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  569. { Token.Plus, 2 }, { Token.Minus, 2 },
  570. { Token.Asterisk, 3 }, { Token.Slash, 3 }, { Token.Modulo, 3 },
  571. { Token.Caret, 4 }, { Token.ShiftLeft, 4 }, { Token.ShiftRight, 4 }
  572. };
  573. protected ExecutionNode Expression(out ParserError error, bool useModulo = true, bool ternaryString = false)
  574. {
  575. error = null;
  576. var operators = new Stack<Token>();
  577. var operands = new Stack<ExecutionNode>();
  578. Token token;
  579. void ProcessOperation(out ParserError localError)
  580. {
  581. localError = null;
  582. Token op = operators.Pop();
  583. if (op.IsUnary() && operands.Count == 1)
  584. {
  585. var operand = operands.Pop();
  586. operands.Push(new ExecutionNode
  587. {
  588. Type = "operation",
  589. Metadata =
  590. {
  591. ["type"] = GetOperationName(op),
  592. ["unary"] = "true"
  593. },
  594. SubNodes = new[]
  595. {
  596. operand
  597. }
  598. });
  599. }
  600. else if (operands.Count >= 2)
  601. {
  602. ExecutionNode right = operands.Pop();
  603. ExecutionNode left = operands.Pop();
  604. operands.Push(new ExecutionNode
  605. {
  606. Type = "operation",
  607. Metadata =
  608. {
  609. ["type"] = GetOperationName(op),
  610. ["unary"] = "false"
  611. },
  612. SubNodes = new[]
  613. {
  614. left,
  615. right
  616. }
  617. });
  618. }
  619. else
  620. localError = new ParserError("Invalid expression - not enough operands", CurrentPosition);
  621. }
  622. void AttemptUnaryConversion(out ParserError localError)
  623. {
  624. localError = null;
  625. while (operators.Count > 0
  626. && operators.Peek().IsUnary())
  627. {
  628. ProcessOperation(out localError);
  629. if (localError != null)
  630. return;
  631. }
  632. }
  633. while ((token = GetNextToken()) != Token.NewLine
  634. && token != Token.EOF
  635. && token != Token.Comma
  636. && token != Token.Colon
  637. && token != Token.To
  638. && token != Token.CloseBracket
  639. && token != Token.RParen
  640. && token != Token.QuestionMark
  641. && token != Token.Sharp
  642. && (!ternaryString || token != Token.TernaryEscape)
  643. && (useModulo || token != Token.Modulo))
  644. {
  645. if (token == Token.Value)
  646. {
  647. operands.Push(CreateConstant(Lexer.Value, CurrentPosition));
  648. AttemptUnaryConversion(out error);
  649. if (error != null)
  650. return null;
  651. }
  652. else if (token == Token.QuotationMark || token == Token.AtSymbol)
  653. {
  654. operands.Push(ParseString(out error, false, false));
  655. if (error != null)
  656. return null;
  657. }
  658. else if (token == Token.Identifer)
  659. {
  660. if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  661. {
  662. operands.Push(GetFunction(out error));
  663. if (error != null)
  664. return null;
  665. }
  666. else if (IsVariable(Lexer.Identifier))
  667. {
  668. operands.Push(GetVariable(out error));
  669. if (error != null)
  670. return null;
  671. }
  672. else
  673. {
  674. Warnings.Add(new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition));
  675. break;
  676. }
  677. }
  678. else if (token == Token.TernaryEscape)
  679. {
  680. operands.Push(Expression(out error, useModulo, true));
  681. if (error != null)
  682. return null;
  683. }
  684. else if (token.IsArithmetic())
  685. {
  686. if (!operands.Any() && token.IsUnary())
  687. {
  688. operators.Push(token);
  689. continue;
  690. }
  691. if (!operands.Any() && !token.IsUnary())
  692. {
  693. error = new ParserError($"Invalid unary operator: {token}", CurrentPosition);
  694. return null;
  695. }
  696. while (operators.Any() && OrderOfOps[token] <= OrderOfOps[operators.Peek()])
  697. {
  698. ProcessOperation(out error);
  699. if (error != null)
  700. return null;
  701. }
  702. operators.Push(token);
  703. }
  704. else if (token == Token.LParen)
  705. {
  706. operands.Push(Expression(out var localError));
  707. if (localError != null)
  708. {
  709. error = localError;
  710. return null;
  711. }
  712. }
  713. else if (token == Token.RParen)
  714. {
  715. break;
  716. }
  717. else
  718. {
  719. error = new ParserError($"Unexpected token: {token}", CurrentPosition);
  720. return null;
  721. }
  722. }
  723. while (operators.Any())
  724. {
  725. ProcessOperation(out error);
  726. if (error != null)
  727. return null;
  728. }
  729. if (!operands.Any())
  730. {
  731. error = new ParserError("Invalid expression - Empty operand stack", CurrentPosition);
  732. return null;
  733. }
  734. var result = operands.Pop();
  735. if (token != Token.QuestionMark)
  736. return result;
  737. var resultTrue = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
  738. if (error != null)
  739. return null;
  740. var resultFalse = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
  741. if (error != null)
  742. return null;
  743. return CallMethod("__INLINEIF", CurrentPosition, result, resultTrue, resultFalse);
  744. }
  745. protected ExecutionNode ParseString(out ParserError error, bool implicitString, bool canFormat = false, bool nestedTernary = false)
  746. {
  747. error = null;
  748. ExecutionNode value = null;
  749. if (Lexer.IsPeeking)
  750. Lexer.GetNextChar();
  751. if (nestedTernary && (Lexer.CurrentChar == '?' || Lexer.CurrentChar == '#'))
  752. Lexer.GetNextChar();
  753. if (!implicitString)
  754. {
  755. if (Lexer.CurrentChar == '@')
  756. {
  757. canFormat = true;
  758. Lexer.GetNextChar();
  759. }
  760. if (Lexer.CurrentChar == '"')
  761. {
  762. Lexer.GetNextChar();
  763. }
  764. }
  765. else
  766. {
  767. if (char.IsWhiteSpace(Lexer.CurrentChar) && Lexer.CurrentChar != '\n')
  768. Lexer.GetNextChar();
  769. }
  770. StringBuilder currentBlock = new StringBuilder();
  771. void commitBlock()
  772. {
  773. if (currentBlock.Length == 0)
  774. return;
  775. ExecutionNode stringBlock = CreateConstant(currentBlock.ToString(), CurrentPosition);
  776. value = value == null
  777. ? stringBlock
  778. : OperateNodes(value, stringBlock, Token.Plus);
  779. currentBlock.Clear();
  780. }
  781. while ((Lexer.CurrentChar != '"' || implicitString)
  782. && Lexer.CurrentChar != '\n'
  783. && Lexer.CurrentChar != '\0')
  784. {
  785. if (Lexer.CurrentChar == '\r')
  786. {
  787. Lexer.GetNextChar();
  788. continue;
  789. }
  790. if (nestedTernary && Lexer.CurrentChar == '#')
  791. break;
  792. if (canFormat && Lexer.CurrentChar == '\\')
  793. {
  794. Lexer.GetNextChar();
  795. if (Lexer.CurrentChar == '@')
  796. {
  797. if (nestedTernary)
  798. {
  799. Lexer.GetNextChar();
  800. break;
  801. }
  802. var expressionValue = Expression(out error, true, true);
  803. if (error != null)
  804. return null;
  805. commitBlock();
  806. value = value == null
  807. ? expressionValue
  808. : OperateNodes(value, expressionValue, Token.Plus);
  809. continue;
  810. }
  811. if (Lexer.CurrentChar == 'n')
  812. {
  813. currentBlock.Append('\n');
  814. Lexer.GetNextChar();
  815. continue;
  816. }
  817. currentBlock.Append(Lexer.CurrentChar);
  818. Lexer.GetNextChar();
  819. continue;
  820. }
  821. if (canFormat && (Lexer.CurrentChar == '{' || Lexer.CurrentChar == '%'))
  822. {
  823. bool useModulo = Lexer.CurrentChar != '%';
  824. List<ExecutionNode> formatParams = new List<ExecutionNode>();
  825. Marker symbolMarker = CurrentPosition;
  826. do
  827. {
  828. var expressionValue = Expression(out error, useModulo, nestedTernary);
  829. if (error != null)
  830. return null;
  831. formatParams.Add(expressionValue);
  832. } while (Enumerator.Current == Token.Comma);
  833. var formattedValue = CallMethod("__FORMAT", symbolMarker, formatParams.ToArray());
  834. commitBlock();
  835. value = value == null
  836. ? formattedValue
  837. : OperateNodes(value, formattedValue, Token.Plus);
  838. Lexer.GetNextChar();
  839. continue;
  840. }
  841. currentBlock.Append(Lexer.CurrentChar);
  842. Lexer.GetNextChar();
  843. }
  844. if (!nestedTernary && !implicitString && (Lexer.CurrentChar == '\0' || Lexer.CurrentChar == '\n'))
  845. {
  846. error = new ParserError("Was expecting string to be closed", CurrentPosition);
  847. return null;
  848. }
  849. commitBlock();
  850. value = value ?? CreateConstant("", CurrentPosition);
  851. return value;
  852. }
  853. private static readonly Dictionary<Token, string> OperationNames = new Dictionary<Token, string>
  854. {
  855. [Token.Plus] = "add",
  856. [Token.Asterisk] = "multiply",
  857. [Token.Minus] = "subtract",
  858. [Token.Slash] = "divide",
  859. };
  860. public static string GetOperationName(Token token)
  861. {
  862. return OperationNames.TryGetValue(token, out string result)
  863. ? result
  864. : token.ToString();
  865. }
  866. public static ExecutionNode CreateConstant(Value value, Marker symbolMarker)
  867. {
  868. return new ExecutionNode
  869. {
  870. Type = "constant",
  871. Metadata =
  872. {
  873. ["type"] = value.Type.ToString(),
  874. ["value"] = value.ToString()
  875. },
  876. Symbol = symbolMarker
  877. };
  878. }
  879. public static ExecutionNode OperateNodes(ExecutionNode left, ExecutionNode right, Token token)
  880. {
  881. return new ExecutionNode
  882. {
  883. Type = "operation",
  884. Metadata =
  885. {
  886. ["type"] = GetOperationName(token)
  887. },
  888. SubNodes = new[]
  889. {
  890. left,
  891. right
  892. }
  893. };
  894. }
  895. public static ExecutionNode CallMethod(string methodName, Marker symbolMarker, params ExecutionNode[] parameters)
  896. {
  897. return new ExecutionNode
  898. {
  899. Type = "call",
  900. Metadata =
  901. {
  902. ["target"] = methodName
  903. },
  904. Symbol = symbolMarker,
  905. SubNodes = new[]
  906. {
  907. new ExecutionNode
  908. {
  909. Type = "parameters",
  910. SubNodes = parameters.ToArray()
  911. }
  912. }
  913. };
  914. }
  915. public static ExecutionNode GetVariable(string variableName, Marker marker, params ExecutionNode[] indexNodes)
  916. {
  917. var node = new ExecutionNode
  918. {
  919. Type = "variable",
  920. Metadata =
  921. {
  922. ["name"] = variableName
  923. },
  924. SubNodes = indexNodes,
  925. Symbol = marker
  926. };
  927. if (indexNodes.Length > 0)
  928. node.SubNodes = new[]
  929. {
  930. new ExecutionNode
  931. {
  932. Type = "index",
  933. SubNodes = indexNodes
  934. }
  935. };
  936. return node;
  937. }
  938. #endregion
  939. #region Post-processor
  940. protected void PostProcess(List<ExecutionNode> nodes)
  941. {
  942. Branchify(nodes);
  943. }
  944. protected void Branchify(List<ExecutionNode> nodes)
  945. {
  946. Stack<ExecutionNode> forNodeStack = new Stack<ExecutionNode>();
  947. Stack<ExecutionNode> doNodeStack = new Stack<ExecutionNode>();
  948. foreach (var node in nodes)
  949. {
  950. if (node.Type == "statement")
  951. {
  952. if (node["name"].Equals("FOR", StringComparison.OrdinalIgnoreCase))
  953. forNodeStack.Push(node);
  954. else if (node["name"].Equals("DO", StringComparison.OrdinalIgnoreCase))
  955. doNodeStack.Push(node);
  956. }
  957. }
  958. foreach (var forNode in forNodeStack)
  959. {
  960. int index = nodes.IndexOf(forNode);
  961. int endIndex = 0;
  962. for (int i = index; i < nodes.Count; i++)
  963. {
  964. var node = nodes[i];
  965. if (node.Type == "statement" && node["name"].Equals("NEXT", StringComparison.OrdinalIgnoreCase))
  966. {
  967. endIndex = i;
  968. break;
  969. }
  970. }
  971. if (endIndex == 0)
  972. throw new ParserException("Could not find matching NEXT for FOR statement");
  973. List<ExecutionNode> subNodes = new List<ExecutionNode>();
  974. forNode.Type = "for-context";
  975. subNodes.Add(forNode);
  976. subNodes.AddRange(nodes.Skip(index + 1).Take(endIndex - index - 1));
  977. nodes.RemoveRange(index, (endIndex - index) + 1);
  978. ExecutionNode newNode = new ExecutionNode
  979. {
  980. Type = "for",
  981. SubNodes = subNodes.ToArray()
  982. };
  983. nodes.Insert(index, newNode);
  984. }
  985. foreach (var doNode in doNodeStack)
  986. {
  987. int index = nodes.IndexOf(doNode);
  988. int endIndex = 0;
  989. for (int i = index; i < nodes.Count; i++)
  990. {
  991. var node = nodes[i];
  992. if (node.Type == "statement" && node["name"].Equals("LOOP", StringComparison.OrdinalIgnoreCase))
  993. {
  994. endIndex = i;
  995. break;
  996. }
  997. }
  998. if (endIndex == 0)
  999. throw new ParserException("Could not find matching LOOP for DO statement");
  1000. List<ExecutionNode> subNodes = new List<ExecutionNode>();
  1001. var loopNode = nodes[endIndex];
  1002. loopNode.Type = "loop-context";
  1003. subNodes.Add(loopNode);
  1004. subNodes.AddRange(nodes.Skip(index + 1).Take(endIndex - index - 1));
  1005. nodes.RemoveRange(index, (endIndex - index) + 1);
  1006. ExecutionNode newNode = new ExecutionNode
  1007. {
  1008. Type = "do",
  1009. SubNodes = subNodes.ToArray()
  1010. };
  1011. nodes.Insert(index, newNode);
  1012. }
  1013. }
  1014. #endregion
  1015. }
  1016. }