12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NTERA.Engine.Compiler
- {
- public class Parser
- {
- protected Lexer Lexer { get; }
- protected FunctionDefinition SelfDefinition { get; }
- protected ICollection<FunctionDefinition> FunctionDefinitions { get; }
- protected ICollection<FunctionDefinition> ProcedureDefinitions { get; }
- protected ICollection<FunctionVariable> ConstantDefinitions { get; }
- protected ICollection<FunctionVariable> GlobalVariables { get; }
- protected ICollection<FunctionVariable> LocalVariables { get; }
- protected ICollection<Keyword> ExplicitKeywords { get; }
- protected CSVDefinition CsvDefinition { get; }
- protected List<ParserError> Errors { get; } = new List<ParserError>();
- protected List<ParserError> Warnings { get; } = new List<ParserError>();
- protected IEnumerator<Token> Enumerator { get; }
- protected bool hasPeeked = false;
- protected Token peekedToken = Token.Unknown;
-
- protected Token GetNextToken(bool peek = false)
- {
- if (peek && hasPeeked)
- return peekedToken;
- if (!hasPeeked)
- Enumerator.MoveNext();
- peekedToken = Enumerator.Current;
- hasPeeked = peek;
- return Enumerator.Current;
- }
- protected Marker CurrentPosition => new Marker(Lexer.TokenMarker.Pointer + SelfDefinition.Position.Pointer,
- Lexer.TokenMarker.Line + SelfDefinition.Position.Line - 1,
- Lexer.TokenMarker.Column);
- 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)
- {
- Lexer = new Lexer(input);
- Enumerator = Lexer.GetEnumerator();
- SelfDefinition = selfDefinition;
- FunctionDefinitions = functionDefinitions;
- ProcedureDefinitions = procedureDefinitions;
- ConstantDefinitions = constantDefinitions;
- GlobalVariables = globalVariables;
- LocalVariables = localVariables;
- ExplicitKeywords = explicitKeywords;
- CsvDefinition = csvDefinition;
- }
- public IEnumerable<ExecutionNode> Parse(out List<ParserError> errors, out List<ParserError> warnings)
- {
- List<ExecutionNode> nodes = new List<ExecutionNode>();
- using (Enumerator)
- {
- do
- {
- var node = ParseLine(out var error);
- if (error != null)
- {
- Errors.Add(error);
- nodes.Add(new ExecutionNode
- {
- Type = "error",
- Metadata =
- {
- ["message"] = error.ErrorMessage,
- ["symbol"] = error.SymbolMarker.ToString()
- },
- Symbol = error.SymbolMarker
- });
- //resynchronize to a new line
- while (Enumerator.MoveNext()
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- }
- }
- else if (node != null)
- {
- nodes.Add(node);
- }
- hasPeeked = false;
- } while (Enumerator.MoveNext());
- }
- errors = Errors;
- warnings = Warnings;
- return nodes;
- }
- protected ExecutionNode ParseLine(out ParserError error)
- {
- error = null;
- switch (Enumerator.Current)
- {
- case Token.Identifer:
- if (IsVariable(Lexer.Identifier))
- {
- string variableName = Lexer.Identifier;
- ValueType type = 0;
-
- if (GlobalVariables.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
- type = GlobalVariables.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
- else if (LocalVariables.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
- type = LocalVariables.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
- else if (ConstantDefinitions.Any(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)))
- type = ConstantDefinitions.First(x => x.Name.Equals(variableName, StringComparison.OrdinalIgnoreCase)).ValueType;
- var node = new ExecutionNode
- {
- Type = "assignment",
- Symbol = CurrentPosition
- };
- var variable = GetVariable(out error);
- if (error != null)
- return null;
- if (GetNextToken() != Token.Equal
- && Enumerator.Current != Token.Increment
- && Enumerator.Current != Token.Decrement
- && !Enumerator.Current.IsArithmetic())
- {
- error = new ParserError($"Unexpected token, expecting assignment: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- ExecutionNode value;
- if (Enumerator.Current == Token.Increment)
- {
- value = OperateNodes(variable, CreateConstant(1, CurrentPosition), Token.Plus);
- }
- else if (Enumerator.Current == Token.Decrement)
- {
- value = OperateNodes(variable, CreateConstant(1, CurrentPosition), Token.Minus);
- }
- else if (Enumerator.Current != Token.Equal)
- {
- Token arithmeticToken = Enumerator.Current;
- if (GetNextToken() != Token.Equal)
- {
- error = new ParserError($"Unexpected token, expecting assignment: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- ExecutionNode newValue = Expression(out error);
- value = OperateNodes(variable, newValue, arithmeticToken);
- }
- else
- {
- value = type == ValueType.String
- ? ParseString(out error, true, true)
- : Expression(out error);
- }
- if (error != null)
- return null;
- node.SubNodes = new[]
- {
- variable,
- new ExecutionNode
- {
- Type = "value",
- SubNodes = new[] { value }
- }
- };
- return node;
- }
- else if (Lexer.Identifier.Equals("CASE", StringComparison.OrdinalIgnoreCase))
- {
- var node = new ExecutionNode
- {
- Type = "case",
- Symbol = CurrentPosition
- };
- List<ExecutionNode> subNodes = new List<ExecutionNode>();
- do
- {
- if (GetNextToken(true) == Token.NewLine
- || GetNextToken(true) == Token.EOF)
- break;
- var value = Expression(out error);
- if (error != null)
- return null;
- if (Enumerator.Current == Token.To)
- {
- var value2 = Expression(out error);
- if (error != null)
- return null;
- subNodes.Add(new ExecutionNode
- {
- Type = "case-to",
- SubNodes = new[] { value, value2 }
- });
- continue;
- }
- subNodes.Add(new ExecutionNode
- {
- Type = "case-exact",
- SubNodes = new[] { value }
- });
- } while (Enumerator.Current == Token.Comma);
- if (Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- node.SubNodes = subNodes.ToArray();
- return node;
- }
- else if (Lexer.Identifier.Equals("CALL", StringComparison.OrdinalIgnoreCase)
- || Lexer.Identifier.Equals("TRYCALL", StringComparison.OrdinalIgnoreCase))
- {
- Enumerator.MoveNext();
- if (Enumerator.Current != Token.Identifer)
- {
- error = new ParserError($"Expecting a call to a function, got token instead: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- Marker symbolMarker = CurrentPosition;
- string target = Lexer.Identifier;
- List<ExecutionNode> parameters = new List<ExecutionNode>();
- if (ProcedureDefinitions.All(x => !x.Name.Equals(target, StringComparison.OrdinalIgnoreCase)))
- {
- error = new ParserError($"Could not find procedure: {Lexer.Identifier}", CurrentPosition);
- return null;
- }
- Enumerator.MoveNext();
- while (Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF
- && Enumerator.Current != Token.RParen)
- {
- parameters.Add(Expression(out error));
- if (error != null)
- {
- error = new ParserError($"{error.ErrorMessage} (target [{target}])", error.SymbolMarker);
- return null;
- }
- if (Enumerator.Current != Token.Comma
- && Enumerator.Current != Token.RParen
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- }
- if (Enumerator.Current == Token.RParen)
- Enumerator.MoveNext();
- if (Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- return CallMethod(target, symbolMarker, parameters.ToArray());
- }
- else if (Lexer.Identifier.Equals("CALLFORM", StringComparison.OrdinalIgnoreCase)
- || Lexer.Identifier.Equals("TRYCALLFORM", StringComparison.OrdinalIgnoreCase)
- || Lexer.Identifier.Equals("TRYCCALLFORM", StringComparison.OrdinalIgnoreCase)
- || Lexer.Identifier.Equals("TRYJUMPFORM", StringComparison.OrdinalIgnoreCase))
- {
- string statementName = Lexer.Identifier;
- var node = new ExecutionNode
- {
- Type = "callform",
- Metadata =
- {
- ["try"] = statementName.StartsWith("TRY").ToString()
- },
- Symbol = CurrentPosition
- };
- ExecutionNode nameValue = null;
- List<ExecutionNode> parameters = new List<ExecutionNode>();
- Enumerator.MoveNext();
- do
- {
- ExecutionNode newValue = null;
- if (Enumerator.Current == Token.Identifer)
- {
- newValue = CreateConstant(Lexer.Identifier, CurrentPosition);
- }
- else if (Enumerator.Current == Token.OpenBracket)
- {
- newValue = Expression(out error);
- if (error != null)
- return null;
- }
- else if (Enumerator.Current == Token.LParen)
- {
- break;
- }
- else
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- nameValue = nameValue == null
- ? newValue
- : OperateNodes(nameValue, newValue, Token.Plus);
- Enumerator.MoveNext();
- } while (Enumerator.Current != Token.Comma
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF);
- while (Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF
- && Enumerator.Current != Token.RParen)
- {
- parameters.Add(Expression(out error));
- if (error != null)
- {
- error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
- return null;
- }
- if (Enumerator.Current != Token.Comma
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF
- && Enumerator.Current != Token.RParen)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- }
- node.SubNodes = new[]
- {
- new ExecutionNode
- {
- Type = "name",
- SubNodes = new[] { nameValue }
- },
- new ExecutionNode
- {
- Type = "parameters",
- SubNodes = parameters.ToArray()
- },
- };
- return node;
- }
- else if (Lexer.Identifier.Equals("BEGIN", StringComparison.OrdinalIgnoreCase))
- {
- var node = new ExecutionNode
- {
- Type = "statement",
- Metadata =
- {
- ["name"] = "BEGIN"
- },
- Symbol = CurrentPosition
- };
- Enumerator.MoveNext();
- if (Enumerator.Current != Token.Identifer)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- node.SubNodes = new[] { CreateConstant(Lexer.Identifier, CurrentPosition) };
- return node;
- }
- else //treat as statement
- {
- string statementName = Lexer.Identifier;
- var node = new ExecutionNode
- {
- Type = "statement",
- Metadata =
- {
- ["name"] = statementName
- },
- Symbol = CurrentPosition
- };
- List<ExecutionNode> parameters = new List<ExecutionNode>();
- Keyword keyword = ExplicitKeywords.FirstOrDefault(x => x.Name == statementName);
- if (keyword?.ImplicitString == true)
- {
- var value = ParseString(out error, true, keyword.ImplicitFormatted);
- if (error != null)
- return null;
- if (value != null)
- parameters.Add(value);
- node.SubNodes = parameters.ToArray();
- return node;
- }
- if (GetNextToken(true) == Token.NewLine
- || GetNextToken(true) == Token.EOF)
- {
- return node;
- }
- if (GetNextToken(true) == Token.Colon
- || GetNextToken(true) == Token.Equal)
- {
- error = new ParserError($"Undeclared variable: {statementName}", node.Symbol);
- return null;
- }
- while (Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- parameters.Add(Expression(out error));
- if (error != null)
- {
- error = new ParserError($"{error.ErrorMessage} (statement [{statementName}])", error.SymbolMarker);
- return null;
- }
- if (Enumerator.Current != Token.Comma
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- }
- node.SubNodes = parameters.ToArray();
- return node;
- }
- case Token.AtSymbol:
- case Token.Sharp:
- while (Enumerator.MoveNext()
- && Enumerator.Current != Token.NewLine
- && Enumerator.Current != Token.EOF)
- {
- }
- return null;
- case Token.NewLine:
- case Token.EOF:
- return null;
- default:
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- }
- protected bool IsVariable(string identifier)
- {
- return GlobalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
- || LocalVariables.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase))
- || ConstantDefinitions.Any(x => x.Name.Equals(identifier, StringComparison.OrdinalIgnoreCase));
- }
- protected ExecutionNode GetVariable(out ParserError error)
- {
- string variableName = Lexer.Identifier;
- var node = new ExecutionNode
- {
- Type = "variable",
- Metadata =
- {
- ["name"] = variableName
- },
- Symbol = CurrentPosition
- };
- List<ExecutionNode> indices = new List<ExecutionNode>();
- error = null;
- while (GetNextToken(true) == Token.Colon)
- {
- GetNextToken();
- var token = GetNextToken();
- if (token == Token.LParen)
- {
- indices.Add(Expression(out error));
- if (error != null)
- return null;
- if (Enumerator.Current != Token.RParen)
- {
- error = new ParserError("Invalid expression - Expected right bracket", CurrentPosition);
- return null;
- }
- }
- else if (token == Token.Value)
- {
- indices.Add(CreateConstant(Lexer.Value, CurrentPosition));
- }
- else if (token == Token.Identifer)
- {
- if (CsvDefinition.VariableIndexDictionary.TryGetValue(variableName, out var varTable)
- && varTable.TryGetValue(Lexer.Identifier, out int index))
- {
- indices.Add(CreateConstant(index, CurrentPosition));
- continue;
- }
- if (IsVariable(Lexer.Identifier))
- {
- var subNode = new ExecutionNode
- {
- Type = "variable",
- Metadata =
- {
- ["name"] = Lexer.Identifier
- },
- Symbol = CurrentPosition
- };
- indices.Add(subNode);
- continue;
- }
- if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
- {
- indices.Add(GetFunction(out error));
- if (error != null)
- return null;
- continue;
- }
- error = new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition);
- return null;
- }
- }
- if (indices.Count > 0)
- {
- ExecutionNode indexNode = new ExecutionNode
- {
- Type = "index",
- SubNodes = indices.ToArray()
- };
- node.SubNodes = new[] { indexNode };
- }
- return node;
- }
- protected ExecutionNode GetFunction(out ParserError error)
- {
- error = null;
- Marker symbolMarker = CurrentPosition;
- List<ExecutionNode> parameters = new List<ExecutionNode>();
- string functionName = Lexer.Identifier;
- if (GetNextToken() != Token.LParen)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- while (Enumerator.Current == Token.Comma
- || Enumerator.Current == Token.LParen)
- {
- if (GetNextToken(true) == Token.RParen)
- break;
- if (GetNextToken(true) == Token.Comma)
- {
- var defaultValue = new ExecutionNode
- {
- Type = "defaultvalue",
- Symbol = CurrentPosition
- };
- parameters.Add(defaultValue);
- GetNextToken();
- continue;
- }
- parameters.Add(Expression(out error));
- if (error != null)
- return null;
- if (Enumerator.Current != Token.Comma
- && Enumerator.Current != Token.RParen)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- }
- if (Enumerator.Current != Token.RParen)
- {
- error = new ParserError($"Unexpected token: {Enumerator.Current}", CurrentPosition);
- return null;
- }
- if (hasPeeked)
- {
- GetNextToken();
- }
- var functionDefinition = FunctionDefinitions.FirstOrDefault(x => x.Name == functionName
- && (x.Parameters.Length >= parameters.Count
- || x.Parameters.Any(y => y.IsArrayParameter)));
- if (functionDefinition == null)
- {
- error = new ParserError($"No matching method with same amount of parameters: {functionName} ({parameters.Count})", CurrentPosition);
- return null;
- }
- return CallMethod(functionName, symbolMarker, parameters.ToArray());
- }
- private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
- {
- { Token.Or, 0 }, { Token.And, 0 }, { Token.Not, 0 },
- { Token.Equal, 1 }, { Token.NotEqual, 1 },
- { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
- { Token.Plus, 2 }, { Token.Minus, 2 },
- { Token.Asterisk, 3 }, { Token.Slash, 3 }, { Token.Modulo, 3 },
- { Token.Caret, 4 }
- };
- protected ExecutionNode Expression(out ParserError error, bool useModulo = true, bool ternaryString = false)
- {
- error = null;
- var operators = new Stack<Token>();
- var operands = new Stack<ExecutionNode>();
- Token token;
- void ProcessOperation(out ParserError localError)
- {
- localError = null;
- Token op = operators.Pop();
- if (op.IsUnary() && operands.Count >= 1)
- {
- var operand = operands.Pop();
- operands.Push(new ExecutionNode
- {
- Type = "operation",
- Metadata =
- {
- ["type"] = GetOperationName(op),
- ["unary"] = "true"
- },
- SubNodes = new[]
- {
- operand
- }
- });
- }
- else if (operands.Count >= 2)
- {
- ExecutionNode right = operands.Pop();
- ExecutionNode left = operands.Pop();
- operands.Push(new ExecutionNode
- {
- Type = "operation",
- Metadata =
- {
- ["type"] = GetOperationName(op),
- ["unary"] = "false"
- },
- SubNodes = new[]
- {
- left,
- right
- }
- });
- }
- else
- localError = new ParserError("Invalid expression - not enough operands", CurrentPosition);
- }
- void AttemptUnaryConversion(out ParserError localError)
- {
- localError = null;
- while (operators.Count > 0
- && operators.Peek().IsUnary())
- {
- ProcessOperation(out localError);
- if (localError != null)
- return;
- }
- }
- while ((token = GetNextToken()) != Token.NewLine
- && token != Token.EOF
- && token != Token.Comma
- && token != Token.Colon
- && token != Token.To
- && token != Token.CloseBracket
- && token != Token.RParen
- && token != Token.QuestionMark
- && token != Token.Sharp
- && (!ternaryString || token != Token.TernaryEscape)
- && (useModulo || token != Token.Modulo))
- {
- if (token == Token.Value)
- {
- operands.Push(CreateConstant(Lexer.Value, CurrentPosition));
- AttemptUnaryConversion(out error);
- if (error != null)
- return null;
- }
- else if (token == Token.QuotationMark || token == Token.AtSymbol)
- {
- operands.Push(ParseString(out error, false, false));
- if (error != null)
- return null;
- }
- else if (token == Token.Identifer)
- {
- if (FunctionDefinitions.Any(x => x.Name == Lexer.Identifier))
- {
- operands.Push(GetFunction(out error));
- if (error != null)
- return null;
- }
- else if (IsVariable(Lexer.Identifier))
- {
- operands.Push(GetVariable(out error));
- if (error != null)
- return null;
- }
- else
- {
- Warnings.Add(new ParserError($"Unknown identifier: {Lexer.Identifier}", CurrentPosition));
- break;
- }
- }
- else if (token == Token.TernaryEscape)
- {
- operands.Push(Expression(out error, useModulo, true));
- if (error != null)
- return null;
- }
- else if (token.IsArithmetic())
- {
- if (token.IsUnary())
- {
- operators.Push(token);
- continue;
- }
- if (!operands.Any() && !token.IsUnary())
- {
- error = new ParserError($"Invalid unary operator: {token}", CurrentPosition);
- return null;
- }
- while (operators.Any() && OrderOfOps[token] <= OrderOfOps[operators.Peek()])
- {
- ProcessOperation(out error);
- if (error != null)
- return null;
- }
- operators.Push(token);
- }
- else if (token == Token.LParen)
- {
- operands.Push(Expression(out var localError));
- if (localError != null)
- {
- error = localError;
- return null;
- }
- }
- else if (token == Token.RParen)
- {
- break;
- }
- else
- {
- error = new ParserError($"Unexpected token: {token}", CurrentPosition);
- return null;
- }
- }
- while (operators.Any())
- {
- ProcessOperation(out error);
- if (error != null)
- return null;
- }
- if (!operands.Any())
- {
- error = new ParserError("Invalid expression - Empty operand stack", CurrentPosition);
- return null;
- }
- var result = operands.Pop();
- if (token != Token.QuestionMark)
- return result;
- var resultTrue = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
- if (error != null)
- return null;
- var resultFalse = ternaryString ? ParseString(out error, useModulo, true, true) : Expression(out error, useModulo, false);
- if (error != null)
- return null;
- return CallMethod("__INLINEIF", CurrentPosition, result, resultTrue, resultFalse);
- }
- protected ExecutionNode ParseString(out ParserError error, bool implicitString, bool canFormat = false, bool nestedTernary = false)
- {
- error = null;
- ExecutionNode value = null;
- if (Lexer.IsPeeking)
- Lexer.GetNextChar();
- if (nestedTernary && (Lexer.CurrentChar == '?' || Lexer.CurrentChar == '#'))
- Lexer.GetNextChar();
- if (!implicitString)
- {
- if (Lexer.CurrentChar == '@')
- {
- canFormat = true;
- Lexer.GetNextChar();
- }
- if (Lexer.CurrentChar == '"')
- {
- Lexer.GetNextChar();
- }
- }
- else
- {
- if (char.IsWhiteSpace(Lexer.CurrentChar))
- Lexer.GetNextChar();
- }
- StringBuilder currentBlock = new StringBuilder();
- void commitBlock()
- {
- if (currentBlock.Length == 0)
- return;
- ExecutionNode stringBlock = CreateConstant(currentBlock.ToString(), CurrentPosition);
- value = value == null
- ? stringBlock
- : OperateNodes(value, stringBlock, Token.Plus);
- currentBlock.Clear();
- }
- while ((Lexer.CurrentChar != '"' || implicitString)
- && Lexer.CurrentChar != '\n'
- && Lexer.CurrentChar != '\0')
- {
- if (Lexer.CurrentChar == '\r')
- {
- Lexer.GetNextChar();
- continue;
- }
- if (nestedTernary && Lexer.CurrentChar == '#')
- break;
- if (canFormat && Lexer.CurrentChar == '\\')
- {
- Lexer.GetNextChar();
- if (Lexer.CurrentChar == '@')
- {
- if (nestedTernary)
- break;
- var expressionValue = Expression(out error, true, true);
- if (error != null)
- return null;
- commitBlock();
- value = value == null
- ? expressionValue
- : OperateNodes(value, expressionValue, Token.Plus);
- }
- else if (Lexer.CurrentChar == 'n')
- {
- currentBlock.Append('\n');
- Lexer.GetNextChar();
- continue;
- }
- currentBlock.Append(Lexer.CurrentChar);
- Lexer.GetNextChar();
- continue;
- }
- if (canFormat && (Lexer.CurrentChar == '{' || Lexer.CurrentChar == '%'))
- {
- bool useModulo = Lexer.CurrentChar != '%';
- List<ExecutionNode> formatParams = new List<ExecutionNode>();
- Marker symbolMarker = CurrentPosition;
- do
- {
- var expressionValue = Expression(out error, useModulo, nestedTernary);
- if (error != null)
- return null;
- formatParams.Add(expressionValue);
- } while (Enumerator.Current == Token.Comma);
- var formattedValue = CallMethod("__FORMAT", symbolMarker, formatParams.ToArray());
- commitBlock();
- value = value == null
- ? formattedValue
- : OperateNodes(value, formattedValue, Token.Plus);
- Lexer.GetNextChar();
- continue;
- }
- currentBlock.Append(Lexer.CurrentChar);
- Lexer.GetNextChar();
- }
- if (!nestedTernary && !implicitString && (Lexer.CurrentChar == '\0' || Lexer.CurrentChar == '\n'))
- {
- error = new ParserError("Was expecting string to be closed", CurrentPosition);
- return null;
- }
- commitBlock();
- value = value ?? CreateConstant("", CurrentPosition);
- return value;
- }
- private static readonly Dictionary<Token, string> OperationNames = new Dictionary<Token, string>
- {
- [Token.Plus] = "add",
- [Token.Asterisk] = "multiply",
- [Token.Minus] = "subtract",
- [Token.Slash] = "divide",
- };
- public static string GetOperationName(Token token)
- {
- return OperationNames.TryGetValue(token, out string result)
- ? result
- : token.ToString();
- }
- public static ExecutionNode CreateConstant(Value value, Marker symbolMarker)
- {
- return new ExecutionNode
- {
- Type = "constant",
- Metadata =
- {
- ["type"] = value.Type.ToString(),
- ["value"] = value.ToString()
- },
- Symbol = symbolMarker
- };
- }
- public static ExecutionNode OperateNodes(ExecutionNode left, ExecutionNode right, Token token)
- {
- return new ExecutionNode
- {
- Type = "operation",
- Metadata =
- {
- ["type"] = GetOperationName(token)
- },
- SubNodes = new[]
- {
- left,
- right
- }
- };
- }
- public static ExecutionNode CallMethod(string methodName, Marker symbolMarker, params ExecutionNode[] parameters)
- {
- return new ExecutionNode
- {
- Type = "call",
- Metadata =
- {
- ["target"] = methodName
- },
- Symbol = symbolMarker,
- SubNodes = new[]
- {
- new ExecutionNode
- {
- Type = "parameters",
- SubNodes = parameters.ToArray()
- }
- }
- };
- }
- }
- }
|