Parser.cs 24 KB

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