Parser.cs 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. while ((Lexer.CurrentChar != '"' || implicitString)
  765. && Lexer.CurrentChar != '\n'
  766. && Lexer.CurrentChar != '\0')
  767. {
  768. if (Lexer.CurrentChar == '\r')
  769. {
  770. Lexer.GetNextChar();
  771. continue;
  772. }
  773. if (nestedTernary && Lexer.CurrentChar == '#')
  774. break;
  775. if (canFormat && Lexer.CurrentChar == '\\')
  776. {
  777. Lexer.GetNextChar();
  778. if (Lexer.CurrentChar == '@')
  779. {
  780. if (nestedTernary)
  781. break;
  782. var expressionValue = Expression(out error, true, true);
  783. if (error != null)
  784. return null;
  785. value = value == null
  786. ? expressionValue
  787. : OperateNodes(value, expressionValue, Token.Plus);
  788. }
  789. currentBlock.Append(Lexer.CurrentChar);
  790. Lexer.GetNextChar();
  791. continue;
  792. }
  793. if (canFormat && (Lexer.CurrentChar == '{' || Lexer.CurrentChar == '%'))
  794. {
  795. bool useModulo = Lexer.CurrentChar != '%';
  796. List<ExecutionNode> formatParams = new List<ExecutionNode>();
  797. Marker symbolMarker = CurrentPosition;
  798. do
  799. {
  800. var expressionValue = Expression(out error, useModulo, nestedTernary);
  801. if (error != null)
  802. return null;
  803. formatParams.Add(expressionValue);
  804. } while (Enumerator.Current == Token.Comma);
  805. var formattedValue = CallMethod("__FORMAT", symbolMarker, formatParams.ToArray());
  806. value = value == null
  807. ? formattedValue
  808. : OperateNodes(value, formattedValue, Token.Plus);
  809. Lexer.GetNextChar();
  810. continue;
  811. }
  812. currentBlock.Append(Lexer.CurrentChar);
  813. Lexer.GetNextChar();
  814. }
  815. if (!nestedTernary && !implicitString && (Lexer.CurrentChar == '\0' || Lexer.CurrentChar == '\n'))
  816. {
  817. error = new ParserError("Was expecting string to be closed", CurrentPosition);
  818. return null;
  819. }
  820. ExecutionNode appendedValue = CreateConstant(currentBlock.ToString(), CurrentPosition);
  821. value = value == null
  822. ? appendedValue
  823. : OperateNodes(value, appendedValue, Token.Plus);
  824. return value;
  825. }
  826. private static readonly Dictionary<Token, string> OperationNames = new Dictionary<Token, string>
  827. {
  828. [Token.Plus] = "add",
  829. [Token.Asterisk] = "multiply",
  830. [Token.Minus] = "subtract",
  831. [Token.Slash] = "divide",
  832. };
  833. public static string GetOperationName(Token token)
  834. {
  835. return OperationNames.TryGetValue(token, out string result)
  836. ? result
  837. : token.ToString();
  838. }
  839. public static ExecutionNode CreateConstant(Value value, Marker symbolMarker)
  840. {
  841. return new ExecutionNode
  842. {
  843. Type = "constant",
  844. Metadata =
  845. {
  846. ["type"] = value.Type.ToString(),
  847. ["value"] = value.ToString()
  848. },
  849. Symbol = symbolMarker
  850. };
  851. }
  852. public static ExecutionNode OperateNodes(ExecutionNode left, ExecutionNode right, Token token)
  853. {
  854. return new ExecutionNode
  855. {
  856. Type = "operation",
  857. Metadata =
  858. {
  859. ["type"] = GetOperationName(token)
  860. },
  861. SubNodes = new[]
  862. {
  863. left,
  864. right
  865. }
  866. };
  867. }
  868. public static ExecutionNode CallMethod(string methodName, Marker symbolMarker, params ExecutionNode[] parameters)
  869. {
  870. return new ExecutionNode
  871. {
  872. Type = "call",
  873. Metadata =
  874. {
  875. ["target"] = methodName
  876. },
  877. Symbol = symbolMarker,
  878. SubNodes = new[]
  879. {
  880. new ExecutionNode
  881. {
  882. Type = "parameters",
  883. SubNodes = parameters.ToArray()
  884. }
  885. }
  886. };
  887. }
  888. }
  889. }