Parser.cs 25 KB

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