Parser.cs 27 KB

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