Parser.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. List<ExecutionNode> subNodes = new List<ExecutionNode>();
  163. do
  164. {
  165. var value = Expression(out error);
  166. if (error != null)
  167. return null;
  168. if (Enumerator.Current == Token.Identifer)
  169. {
  170. if (Lexer.Identifier == "TO")
  171. {
  172. var value2 = Expression(out error);
  173. if (error != null)
  174. return null;
  175. subNodes.Add(new ExecutionNode
  176. {
  177. Type = "case-to",
  178. SubNodes = new[] { value, value2 }
  179. });
  180. continue;
  181. }
  182. }
  183. subNodes.Add(new ExecutionNode
  184. {
  185. Type = "case-exact",
  186. SubNodes = new[] { value }
  187. });
  188. } while (Enumerator.Current == Token.Comma);
  189. if (Enumerator.Current != Token.NewLine
  190. && Enumerator.Current != Token.EOF)
  191. {
  192. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  193. return null;
  194. }
  195. node.SubNodes = subNodes.ToArray();
  196. return node;
  197. }
  198. else if (Lexer.Identifier == "CALL"
  199. || Lexer.Identifier == "BEGIN")
  200. {
  201. Enumerator.MoveNext();
  202. if (Enumerator.Current != Token.Identifer)
  203. {
  204. error = new ParserError($"Expecting a call to a function, got token instead: {Enumerator.Current}", CurrentPosition);
  205. return null;
  206. }
  207. Marker symbolMarker = CurrentPosition;
  208. string target = Lexer.Identifier;
  209. List<ExecutionNode> parameters = new List<ExecutionNode>();
  210. if (ProcedureDefinitions.All(x => !x.Name.Equals(target, StringComparison.OrdinalIgnoreCase)))
  211. {
  212. error = new ParserError($"Could not find procedure: {Lexer.Identifier}", CurrentPosition);
  213. return null;
  214. }
  215. Enumerator.MoveNext();
  216. while (Enumerator.Current != Token.NewLine
  217. && Enumerator.Current != Token.EOF
  218. && Enumerator.Current != Token.RParen)
  219. {
  220. parameters.Add(Expression(out error));
  221. if (error != null)
  222. {
  223. error = new ParserError($"{error.ErrorMessage} (target [{target}])", error.SymbolMarker);
  224. return null;
  225. }
  226. if (Enumerator.Current != Token.Comma
  227. && Enumerator.Current != Token.RParen
  228. && Enumerator.Current != Token.NewLine
  229. && Enumerator.Current != Token.EOF)
  230. {
  231. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  232. return null;
  233. }
  234. }
  235. if (Enumerator.Current == Token.RParen)
  236. Enumerator.MoveNext();
  237. if (Enumerator.Current != Token.NewLine
  238. && Enumerator.Current != Token.EOF)
  239. {
  240. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  241. return null;
  242. }
  243. return CallMethod(target, symbolMarker, parameters.ToArray());
  244. }
  245. else if (Lexer.Identifier == "CALLFORM"
  246. || Lexer.Identifier == "TRYCALLFORM")
  247. {
  248. string statementName = Lexer.Identifier;
  249. var node = new ExecutionNode
  250. {
  251. Type = "callform",
  252. Metadata =
  253. {
  254. ["try"] = statementName.StartsWith("TRY").ToString()
  255. },
  256. Symbol = CurrentPosition
  257. };
  258. ExecutionNode nameValue = null;
  259. List<ExecutionNode> parameters = new List<ExecutionNode>();
  260. Enumerator.MoveNext();
  261. do
  262. {
  263. ExecutionNode newValue = null;
  264. if (Enumerator.Current == Token.Identifer)
  265. {
  266. newValue = CreateConstant(Lexer.Identifier);
  267. }
  268. else if (Enumerator.Current == Token.OpenBracket)
  269. {
  270. newValue = Expression(out error);
  271. if (error != null)
  272. return null;
  273. }
  274. else
  275. {
  276. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  277. return null;
  278. }
  279. nameValue = nameValue == null
  280. ? newValue
  281. : OperateNodes(nameValue, newValue, Token.Plus);
  282. Enumerator.MoveNext();
  283. } while (Enumerator.Current != Token.Comma
  284. && Enumerator.Current != Token.NewLine
  285. && Enumerator.Current != Token.EOF);
  286. while (Enumerator.Current != Token.NewLine
  287. && Enumerator.Current != Token.EOF)
  288. {
  289. parameters.Add(Expression(out error));
  290. if (error != null)
  291. {
  292. error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
  293. return null;
  294. }
  295. if (Enumerator.Current != Token.Comma
  296. && Enumerator.Current != Token.NewLine
  297. && Enumerator.Current != Token.EOF)
  298. {
  299. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  300. return null;
  301. }
  302. }
  303. node.SubNodes = new[]
  304. {
  305. new ExecutionNode
  306. {
  307. Type = "name",
  308. SubNodes = new[] { nameValue }
  309. },
  310. new ExecutionNode
  311. {
  312. Type = "parameters",
  313. SubNodes = parameters.ToArray()
  314. },
  315. };
  316. return node;
  317. }
  318. else //treat as statement
  319. {
  320. string statementName = Lexer.Identifier;
  321. var node = new ExecutionNode
  322. {
  323. Type = "statement",
  324. Metadata =
  325. {
  326. ["name"] = statementName
  327. },
  328. Symbol = CurrentPosition
  329. };
  330. List<ExecutionNode> parameters = new List<ExecutionNode>();
  331. if (StringStatements.Contains(statementName))
  332. {
  333. var value = ParseString(out error, true, true);
  334. if (error != null)
  335. return null;
  336. if (value != null)
  337. parameters.Add(value);
  338. node.SubNodes = parameters.ToArray();
  339. return node;
  340. }
  341. if (GetNextToken(true) == Token.NewLine
  342. || GetNextToken(true) == Token.EOF)
  343. {
  344. return node;
  345. }
  346. if (GetNextToken(true) == Token.Colon
  347. || GetNextToken(true) == Token.Equal)
  348. {
  349. error = new ParserError($"Undeclared variable: {statementName}", node.Symbol);
  350. return null;
  351. }
  352. while (Enumerator.Current != Token.NewLine
  353. && Enumerator.Current != Token.EOF)
  354. {
  355. parameters.Add(Expression(out error));
  356. if (error != null)
  357. {
  358. error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
  359. return null;
  360. }
  361. if (Enumerator.Current != Token.Comma
  362. && Enumerator.Current != Token.NewLine
  363. && Enumerator.Current != Token.EOF)
  364. {
  365. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  366. return null;
  367. }
  368. }
  369. node.SubNodes = parameters.ToArray();
  370. return node;
  371. }
  372. case Token.AtSymbol:
  373. case Token.Sharp:
  374. while (Enumerator.MoveNext()
  375. && Enumerator.Current != Token.NewLine
  376. && Enumerator.Current != Token.EOF)
  377. {
  378. }
  379. return null;
  380. case Token.NewLine:
  381. case Token.EOF:
  382. return null;
  383. default:
  384. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  385. return null;
  386. }
  387. }
  388. protected ExecutionNode GetVariable(out ParserError error)
  389. {
  390. string variableName = Lexer.Identifier;
  391. var node = new ExecutionNode
  392. {
  393. Type = "variable",
  394. Metadata =
  395. {
  396. ["name"] = variableName
  397. },
  398. Symbol = CurrentPosition
  399. };
  400. List<ExecutionNode> indices = new List<ExecutionNode>();
  401. error = null;
  402. while (GetNextToken(true) == Token.Colon)
  403. {
  404. GetNextToken();
  405. var token = GetNextToken();
  406. if (token == Token.LParen)
  407. {
  408. indices.Add(Expression(out error));
  409. if (error != null)
  410. return null;
  411. if (Enumerator.Current != Token.RParen)
  412. {
  413. error = new ParserError("Invalid expression - Expected right bracket", CurrentPosition);
  414. return null;
  415. }
  416. }
  417. else if (token == Token.Value)
  418. {
  419. indices.Add(CreateConstant(Lexer.Value));
  420. }
  421. else if (token == Token.Identifer)
  422. {
  423. if (CsvDefinition.VariableIndexDictionary.TryGetValue(variableName, out var varTable)
  424. && varTable.TryGetValue(Lexer.Identifier, out int index))
  425. {
  426. indices.Add(CreateConstant(index));
  427. continue;
  428. }
  429. if (GlobalVariables.ContainsKey(Lexer.Identifier)
  430. || LocalVariables.ContainsKey(Lexer.Identifier))
  431. {
  432. var subNode = new ExecutionNode
  433. {
  434. Type = "variable",
  435. Metadata =
  436. {
  437. ["name"] = Lexer.Identifier
  438. },
  439. Symbol = CurrentPosition
  440. };
  441. indices.Add(subNode);
  442. continue;
  443. }
  444. if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  445. {
  446. indices.Add(GetFunction(out error));
  447. if (error != null)
  448. return null;
  449. continue;
  450. }
  451. error = new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition);
  452. return null;
  453. }
  454. }
  455. if (indices.Count > 0)
  456. {
  457. ExecutionNode indexNode = new ExecutionNode
  458. {
  459. Type = "index",
  460. SubNodes = indices.ToArray()
  461. };
  462. node.SubNodes = new[] { indexNode };
  463. }
  464. return node;
  465. }
  466. protected ExecutionNode GetFunction(out ParserError error)
  467. {
  468. error = null;
  469. Marker symbolMarker = CurrentPosition;
  470. List<ExecutionNode> parameters = new List<ExecutionNode>();
  471. string functionName = Lexer.Identifier;
  472. if (GetNextToken() != Token.LParen)
  473. {
  474. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  475. return null;
  476. }
  477. while (Enumerator.Current == Token.Comma
  478. || Enumerator.Current == Token.LParen)
  479. {
  480. if (GetNextToken(true) == Token.RParen)
  481. break;
  482. parameters.Add(Expression(out error));
  483. if (error != null)
  484. return null;
  485. if (Enumerator.Current != Token.Comma
  486. && Enumerator.Current != Token.RParen)
  487. {
  488. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  489. return null;
  490. }
  491. }
  492. if (Enumerator.Current != Token.RParen)
  493. {
  494. error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
  495. return null;
  496. }
  497. if (hasPeeked)
  498. {
  499. GetNextToken();
  500. }
  501. var functionDefinition = FunctionDefinitions.FirstOrDefault(x => x.Name == functionName
  502. && (x.Parameters.Length >= parameters.Count
  503. || x.Parameters.Any(y => y.IsArrayParameter)));
  504. if (functionDefinition == null)
  505. {
  506. error = new ParserError($"No matching method with same amount of parameters: {functionName} ({parameters.Count})", CurrentPosition);
  507. return null;
  508. }
  509. return CallMethod(functionName, symbolMarker, parameters.ToArray());
  510. }
  511. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
  512. {
  513. { Token.Or, 0 }, { Token.And, 0 }, { Token.Not, 0 },
  514. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  515. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  516. { Token.Plus, 2 }, { Token.Minus, 2 },
  517. { Token.Asterisk, 3 }, { Token.Slash, 3 }, { Token.Modulo, 3 },
  518. { Token.Caret, 4 }
  519. };
  520. protected ExecutionNode Expression(out ParserError error, bool useModulo = true, bool ternaryString = false)
  521. {
  522. error = null;
  523. var operators = new Stack<Token>();
  524. var operands = new Stack<ExecutionNode>();
  525. Token token;
  526. void ProcessOperation(out ParserError localError)
  527. {
  528. localError = null;
  529. Token op = operators.Pop();
  530. if (op.IsUnary() && operands.Count >= 1)
  531. {
  532. var operand = operands.Pop();
  533. operands.Push(new ExecutionNode
  534. {
  535. Type = "operation",
  536. Metadata =
  537. {
  538. ["type"] = GetOperationName(op),
  539. ["unary"] = "true"
  540. },
  541. SubNodes = new[]
  542. {
  543. operand
  544. }
  545. });
  546. }
  547. else if (operands.Count >= 2)
  548. {
  549. ExecutionNode right = operands.Pop();
  550. ExecutionNode left = operands.Pop();
  551. operands.Push(new ExecutionNode
  552. {
  553. Type = "operation",
  554. Metadata =
  555. {
  556. ["type"] = GetOperationName(op),
  557. ["unary"] = "false"
  558. },
  559. SubNodes = new[]
  560. {
  561. left,
  562. right
  563. }
  564. });
  565. }
  566. else
  567. localError = new ParserError("Invalid expression - not enough operands", CurrentPosition);
  568. }
  569. void AttemptUnaryConversion(out ParserError localError)
  570. {
  571. localError = null;
  572. while (operators.Count > 0
  573. && operators.Peek().IsUnary())
  574. {
  575. ProcessOperation(out localError);
  576. if (localError != null)
  577. return;
  578. }
  579. }
  580. while ((token = GetNextToken()) != Token.NewLine
  581. && token != Token.EOF
  582. && token != Token.Comma
  583. && token != Token.Colon
  584. && token != Token.CloseBracket
  585. && token != Token.RParen
  586. && token != Token.QuestionMark
  587. && token != Token.Sharp
  588. && token != Token.TernaryEscape
  589. && (useModulo || token != Token.Modulo))
  590. {
  591. if (token == Token.Value)
  592. {
  593. operands.Push(CreateConstant(Lexer.Value));
  594. AttemptUnaryConversion(out error);
  595. if (error != null)
  596. return null;
  597. }
  598. else if (token == Token.QuotationMark || token == Token.AtSymbol)
  599. {
  600. operands.Push(ParseString(out error, false, false));
  601. if (error != null)
  602. return null;
  603. }
  604. else if (token == Token.Identifer)
  605. {
  606. if (GlobalVariables.ContainsKey(Lexer.Identifier)
  607. || LocalVariables.ContainsKey(Lexer.Identifier))
  608. {
  609. operands.Push(GetVariable(out error));
  610. if (error != null)
  611. return null;
  612. }
  613. else if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
  614. {
  615. operands.Push(GetFunction(out error));
  616. if (error != null)
  617. return null;
  618. }
  619. else
  620. {
  621. Warnings.Add(new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition));
  622. break;
  623. }
  624. }
  625. else if (token.IsArithmetic())
  626. {
  627. if (token.IsUnary())
  628. {
  629. operators.Push(token);
  630. continue;
  631. }
  632. if (!operands.Any() && !token.IsUnary())
  633. {
  634. error = new ParserError($"Invalid unary operator: {token}", CurrentPosition);
  635. return null;
  636. }
  637. while (operators.Any() && OrderOfOps[token] <= OrderOfOps[operators.Peek()])
  638. {
  639. ProcessOperation(out error);
  640. if (error != null)
  641. return null;
  642. }
  643. operators.Push(token);
  644. }
  645. else if (token == Token.LParen)
  646. {
  647. operands.Push(Expression(out var localError));
  648. if (localError != null)
  649. {
  650. error = localError;
  651. return null;
  652. }
  653. }
  654. else if (token == Token.RParen)
  655. {
  656. break;
  657. }
  658. else
  659. {
  660. error = new ParserError($"Unexpected token: {token}", CurrentPosition);
  661. return null;
  662. }
  663. }
  664. while (operators.Any())
  665. {
  666. ProcessOperation(out error);
  667. if (error != null)
  668. return null;
  669. }
  670. if (!operands.Any())
  671. {
  672. error = new ParserError("Invalid expression - Empty operand stack", CurrentPosition);
  673. return null;
  674. }
  675. var result = operands.Pop();
  676. if (token != Token.QuestionMark)
  677. return result;
  678. var resultTrue = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error);
  679. if (error != null)
  680. return null;
  681. var resultFalse = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error);
  682. if (error != null)
  683. return null;
  684. return CallMethod("__IMPLICITIF", CurrentPosition, result, resultTrue, resultFalse);
  685. }
  686. protected ExecutionNode ParseString(out ParserError error, bool implicitString, bool canFormat = false, bool nestedTernary = false)
  687. {
  688. error = null;
  689. ExecutionNode value = null;
  690. if (Lexer.IsPeeking)
  691. Lexer.GetNextChar();
  692. if (nestedTernary && (Lexer.CurrentChar == '?' || Lexer.CurrentChar == '#'))
  693. Lexer.GetNextChar();
  694. if (char.IsWhiteSpace(Lexer.CurrentChar))
  695. Lexer.GetNextChar();
  696. if (Lexer.CurrentChar == '@')
  697. {
  698. canFormat = true;
  699. Lexer.GetNextChar();
  700. }
  701. if (Lexer.CurrentChar == '"')
  702. {
  703. implicitString = false;
  704. Lexer.GetNextChar();
  705. }
  706. StringBuilder currentBlock = new StringBuilder();
  707. while ((Lexer.CurrentChar != '"' || implicitString)
  708. && Lexer.CurrentChar != '\n'
  709. && Lexer.CurrentChar != '\0')
  710. {
  711. if (Lexer.CurrentChar == '\r')
  712. {
  713. Lexer.GetNextChar();
  714. continue;
  715. }
  716. if (nestedTernary && Lexer.CurrentChar == '#')
  717. break;
  718. if (Lexer.CurrentChar == '\\')
  719. {
  720. Lexer.GetNextChar();
  721. if (Lexer.CurrentChar == '@')
  722. {
  723. if (nestedTernary)
  724. break;
  725. var expressionValue = Expression(out error, true, true);
  726. if (error != null)
  727. return null;
  728. value = value == null
  729. ? expressionValue
  730. : OperateNodes(value, expressionValue, Token.Plus);
  731. }
  732. currentBlock.Append(Lexer.CurrentChar);
  733. Lexer.GetNextChar();
  734. continue;
  735. }
  736. if (canFormat && Lexer.CurrentChar == '%')
  737. {
  738. var expressionValue = Expression(out error, false);
  739. if (error != null)
  740. return null;
  741. value = value == null
  742. ? expressionValue
  743. : OperateNodes(value, expressionValue, Token.Plus);
  744. Lexer.GetNextChar();
  745. continue;
  746. }
  747. if (canFormat && Lexer.CurrentChar == '{')
  748. {
  749. var expressionValue = Expression(out error, true);
  750. if (error != null)
  751. return null;
  752. value = value == null
  753. ? expressionValue
  754. : OperateNodes(value, expressionValue, Token.Plus);
  755. Lexer.GetNextChar();
  756. continue;
  757. }
  758. currentBlock.Append(Lexer.CurrentChar);
  759. Lexer.GetNextChar();
  760. }
  761. if (!nestedTernary && !implicitString && (Lexer.CurrentChar == '\0' || Lexer.CurrentChar == '\n'))
  762. {
  763. error = new ParserError("Was expecting string to be closed", CurrentPosition);
  764. return null;
  765. }
  766. ExecutionNode appendedValue = CreateConstant(currentBlock.ToString());
  767. value = value == null
  768. ? appendedValue
  769. : OperateNodes(value, appendedValue, Token.Plus);
  770. return value;
  771. }
  772. private static readonly Dictionary<Token, string> OperationNames = new Dictionary<Token, string>
  773. {
  774. [Token.Plus] = "add",
  775. [Token.Asterisk] = "multiply",
  776. [Token.Minus] = "subtract",
  777. [Token.Slash] = "divide",
  778. };
  779. private static string GetOperationName(Token token)
  780. {
  781. return OperationNames.TryGetValue(token, out string result)
  782. ? result
  783. : token.ToString();
  784. }
  785. private ExecutionNode CreateConstant(Value value)
  786. {
  787. return new ExecutionNode
  788. {
  789. Type = "constant",
  790. Metadata =
  791. {
  792. ["type"] = value.Type.ToString(),
  793. ["value"] = value.ToString()
  794. },
  795. Symbol = CurrentPosition
  796. };
  797. }
  798. private static ExecutionNode OperateNodes(ExecutionNode left, ExecutionNode right, Token token)
  799. {
  800. return new ExecutionNode
  801. {
  802. Type = "operation",
  803. Metadata =
  804. {
  805. ["type"] = GetOperationName(token)
  806. },
  807. SubNodes = new[]
  808. {
  809. left,
  810. right
  811. }
  812. };
  813. }
  814. private static ExecutionNode CallMethod(string methodName, Marker symbolMarker, params ExecutionNode[] parameters)
  815. {
  816. return new ExecutionNode
  817. {
  818. Type = "call",
  819. Metadata =
  820. {
  821. ["target"] = methodName
  822. },
  823. Symbol = symbolMarker,
  824. SubNodes = new[]
  825. {
  826. new ExecutionNode
  827. {
  828. Type = "parameters",
  829. SubNodes = parameters.ToArray()
  830. }
  831. }
  832. };
  833. }
  834. }
  835. }