public object Execute(Reduction node) { string returnValue = node[1].Data.ToString(); returnValue = Regex.Replace(returnValue, "\"", ""); Console.WriteLine(returnValue); return returnValue; }
public object Execute(Reduction node) { string DEBUG = "DEBUG"; if (node.Count() == 3) { // van operátor és két operandus, először a két nem terminálist bontom, majd a terminálisként adott operátorral // elvégzem a megfelelő műveletet és értéket adok/másolom if (node[1].Data.ToString().Contains("\"")) { string returnValue = Regex.Replace(node[1].Data.ToString(), "\"", ""); return returnValue; } else { int tmp; if (int.TryParse(node[1].Data.ToString(), out tmp)) { return tmp; } return node[1].Data.ToString(); } } return DEBUG; }
public object Execute(Reduction node) { string DEBUG = "DEBUG - Container"; List<string> _operand = null; // lehet List, Set vagy ID switch (node[0].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = (List<string>) Context.NonTerminalContext.Execute(ntt, (Reduction)node[0].Data); return _operand; case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt egy ID List<string> retVal = new List<string>(); retVal.Add(node[0].Data as string); return retVal; } return DEBUG; }
public object Execute(GOLD.Reduction node) { string DEBUG = "DEBUG - Container"; List <string> _operand = null; // lehet List vagy ID switch (node[0].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = (List <string>)Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[0].Data); return(_operand); case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt egy ID List <string> retVal = new List <string>(); retVal.Add(node[0].Data as string); return(retVal); } return(DEBUG); }
private void TraverseNodes(Reduction root) { while (true) { var globalStatement = (Reduction)root[0].Data; var declaration = (Reduction)globalStatement[0].Data; switch (declaration.Parent.Head().Name()) { case "StructureDeclaration": this.TraverseStructureDeclaration(declaration); break; case "FunctionDeclaration": this.TraverseFunctionDeclaration(declaration); break; } if (root.Count() == 1) { return; } root = (Reduction)root[1].Data; } }
public object Execute(Reduction node) { List<string> container = null; string whereClosure = null; string orderByClosure = null; for (int i = 2; i < node.Count(); i++) { string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (container == null) { // egyelőre használaton kívül van, valamint ezt lehet, hogy projekt specifikusan át kell írni nyelvtan szinten is container = (List<string>) Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); } else if (whereClosure == null) { whereClosure = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data).ToString(); } else if (orderByClosure == null) { orderByClosure = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data).ToString(); } } var retVal = Operation(whereClosure, orderByClosure, null); string DEBUG = "DEBUG"; return DEBUG; }
public object Execute(GOLD.Reduction node) { if (node.Count() == 2) { // ID [szóköz] Indexer string _operator = null; object _operand = null; for (int i = 0; i < node.Count(); i++) { switch (node[i].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); break; case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt maga az ID _operator = node[i].Data as string; break; } } string _path = _operator + ":" + _operand.ToString(); if (_operator != null) { _operand = Operation(_operand, _operator, null); } Console.WriteLine("Element value: " + _operand + "\ttype: " + _operand.GetType()); return(_path); } else { // egy nem terminális van, azt kell lebontani, majd // értékadás/másolás try { return(node[0].Data.ToString()); } catch (InvalidCastException ice) { Console.WriteLine(ice.Message); } catch (Exception exc) { Console.WriteLine(exc.Message); } } return(null); }
public object Execute(Reduction node) { if (node.Count() == 2) { // ID [szóköz] Indexer string _operator = null; object _operand = null; for (int i = 0; i < node.Count(); i++) { switch (node[i].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); break; case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt maga az ID _operator = node[i].Data as string; break; } } string _path = _operator + ":" + _operand.ToString(); if (_operator != null) _operand = Operation(_operand, _operator, null); Console.WriteLine("Element value: " + _operand + "\ttype: " + _operand.GetType()); return _path; } else { // egy nem terminális van, azt kell lebontani, majd // értékadás/másolás try { return node[0].Data.ToString(); } catch (InvalidCastException ice) { Console.WriteLine(ice.Message); } catch (Exception exc) { Console.WriteLine(exc.Message); } } return null; }
public object Execute(Reduction node) { string DEBUG = "DEBUG - Items"; object _item = null, _operator = null; object _items = null; if (node.Count() == 3) {// <Item> ',' <Items> for (int i=0; i<node.Count(); i++) { switch (node[i].Type()) { case GOLD.SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (_item == null) { _item = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); } else if (_items == null) { _items = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); } break; case GOLD.SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt egy vessző _operator = node[i].Data as string; break; } } object returnValue = _item.ToString() + "," + _items.ToString(); return returnValue; } else if (node.Count() == 1) {// <Item> string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); object returnValue = Context.NonTerminalContext.Execute(ntt, (Reduction)node[0].Data); return returnValue; } Console.WriteLine(DEBUG); return DEBUG; }
public object Execute(GOLD.Reduction node) { string DEBUG = "DEBUG - Items"; object _item = null, _operator = null; object _items = null; /// TODO: Meg kell oldani a lista kezelését, egyelőre még a lista is egy item jellegű objektum (akár listaelemek konkatenációjából álló string) if (node.Count() == 3) {// <Item> ',' <Items> for (int i = 0; i < node.Count(); i++) { switch (node[i].Type()) { case GOLD.SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (_item == null) { _item = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } else if (_items == null) { _items = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } break; case GOLD.SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt egy vessző _operator = node[i].Data as string; break; } } object returnValue = _item.ToString() + "," + _items.ToString(); return(returnValue); } else if (node.Count() == 1) {// <Item> string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); object returnValue = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[0].Data); return(returnValue); } Console.WriteLine(DEBUG); return(DEBUG); }
private LogicExpression ParseAddExpression(Reduction expression) { if (expression.Count() == 3) { return new AdditionLogicExpression( this.ParseAddExpression((Reduction)expression[0].Data), (string)expression[1].Data, this.ParseMultiplyExpression((Reduction)expression[2].Data)); } return this.ParseMultiplyExpression((Reduction)expression[0].Data); }
public object Execute(Reduction node) { object _operand = null; string type = Regex.Replace(node[1].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = Context.NonTerminalContext.Execute(ntt, (Reduction)node[1].Data); List<string> returnValue = (List<string>) Operation(null, _operand.ToString(), null); return returnValue; }
public object Execute(GOLD.Reduction node) { object _operand = null; string type = Regex.Replace(node[1].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[1].Data); List <string> returnValue = (List <string>)Operation(null, _operand.ToString(), null); return(returnValue); }
public object Execute(Reduction node) { try { string returnValue = node[2].Data.ToString(); returnValue = Regex.Replace(returnValue, "\"", ""); Console.WriteLine(returnValue); return returnValue; } catch(Exception) { return ""; } }
public object Execute(GOLD.Reduction node) { List <string> container = null; List <string> whereClosure = null; List <string> orderByClosure = null; List <string> retVal; for (int i = 2; i < node.Count(); i++) { string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (container == null) { // egyelőre használaton kívül van, valamint ezt lehet, hogy projekt specifikusan át kell írni nyelvtan szinten is container = (List <string>)Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } else if (whereClosure == null) { whereClosure = (List <string>)Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } else if (orderByClosure == null) { orderByClosure = (List <string>)Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } } ///Amennyiben a szervertől valamiért csak egy obj jönne vissza, azt is listába kell rakni, mert a GetExpression mindenképp listval tér vissza object SO = SpecialOperation(container, whereClosure, orderByClosure); if (SO is List <string> ) { retVal = (List <string>)SO; return(retVal); } else { retVal = new List <string>(); retVal.Add(SO as string); return(retVal); } }
public object Execute(GOLD.Reduction node) { List <string> _operand = null; try { // lehet List vagy ID switch (node[2].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[2].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); _operand = (List <string>)Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[2].Data); return(_operand); case SymbolType.Error: break; default: // Terminálisok vizsgálata - itt egy StringLiteral vagy null try { List <string> retVal = new List <string>(); string returnValue = node[2].Data.ToString(); returnValue = Regex.Replace(returnValue, "\"", ""); retVal.Add(returnValue); return(retVal); } catch (Exception) { return(null); } } } catch (Exception) //nics order by feltétel megadva { return(null); } return(null); }
public object Execute(GOLD.Reduction node) { string time = node[0].Data.ToString(); return(time); }
private string ParseOptionalSemantic(Reduction optionalSemantic) { if (optionalSemantic.Count() == 0) { return null; } else { return (string)((Reduction)optionalSemantic[0].Data)[1].Data; } }
public object Execute(GOLD.Reduction node) { return(node[0].Data as string); }
private object CreateNewObject(GOLD.Reduction r) { object result = null; switch ((ProductionIndex)r.Parent.TableIndex) { case ProductionIndex.Nl_Newline: // <nl> ::= NewLine <nl> break; case ProductionIndex.Nl_Newline2: // <nl> ::= NewLine break; case ProductionIndex.Multiplier_Plus: // <Multiplier> ::= '+' break; case ProductionIndex.Multiplier_Times: // <Multiplier> ::= '*' break; case ProductionIndex.Multiplier: // <Multiplier> ::= break; case ProductionIndex.Regform_Pipepipe: // <regForm> ::= <regForm> '||' <regFormSeq> break; case ProductionIndex.Regform: // <regForm> ::= <regFormSeq> break; case ProductionIndex.Regformseq_Dot: // <regFormSeq> ::= <regFormSeq> '.' <regForm> break; case ProductionIndex.Regformseq: // <regFormSeq> ::= <regFormValue> break; case ProductionIndex.Regformvalue_Identifier: // <regFormValue> ::= Identifier <Multiplier> break; case ProductionIndex.Regformvalue_Not: // <regFormValue> ::= not <regForm> break; case ProductionIndex.Regformvalue_Lparen_Rparen: // <regFormValue> ::= '(' <regForm> ')' <Multiplier> break; case ProductionIndex.Muform_Identifier: // <muForm> ::= Identifier break; case ProductionIndex.Muform_Variable: // <muForm> ::= Variable break; case ProductionIndex.Muform_Lparen_Pipepipe_Rparen: // <muForm> ::= '(' <muForm> '||' <muForm> ')' break; case ProductionIndex.Muform_Lparen_Ampamp_Rparen: // <muForm> ::= '(' <muForm> '&&' <muForm> ')' break; case ProductionIndex.Muform_Lt_Gt: // <muForm> ::= '<' <regForm> '>' <muForm> break; case ProductionIndex.Muform_Lbracket_Rbracket: // <muForm> ::= '[' <regForm> ']' <muForm> break; case ProductionIndex.Muform_Mu_Variable_Dot: // <muForm> ::= mu Variable '.' <muForm> break; case ProductionIndex.Muform_Nu_Variable_Dot: // <muForm> ::= nu Variable '.' <muForm> break; case ProductionIndex.Muform_Not: // <muForm> ::= not <muForm> break; case ProductionIndex.Muform_Lparen_Rparen: // <muForm> ::= '(' <muForm> ')' break; case ProductionIndex.Line_Commentl: // <Line> ::= CommentL <nl> break; case ProductionIndex.Line: // <Line> ::= <muForm> <nl> break; case ProductionIndex.Line2: // <Line> ::= <nl> break; case ProductionIndex.Lines: // <Lines> ::= <Line> <Lines> break; case ProductionIndex.Lines2: // <Lines> ::= break; } //switch return(result); }
//public bool Parse(TextReader reader) public bool Parse(string path) { parser.Restart(); //This procedure starts the GOLD Parser Engine and handles each of the //messages it returns. Each time a reduction is made, you can create new //custom object and reassign the .CurrentReduction property. Otherwise, //the system will use the Reduction object that was returned. // //The resulting tree will be a pure representation of the language //and will be ready to implement. GOLD.ParseMessage response; bool done; //Controls when we leave the loop bool accepted = false; //Was the parse successful? FailMessage = null; using (TextReader reader = File.OpenText(path)) { parser.Open(reader); parser.TrimReductions = true; //Please read about this feature before enabling done = false; while (!done) { response = parser.Parse(); switch (response) { case GOLD.ParseMessage.LexicalError: //Cannot recognize token FailMessage = "Lexical Error in " + path + ":\n" + "Position: Ln " + parser.CurrentPosition().Line + ", Col " + parser.CurrentPosition().Column + "\n" + "Read: " + parser.CurrentToken().Data; done = true; break; case GOLD.ParseMessage.SyntaxError: //Expecting a different token FailMessage = "Syntax Error in " + path + ":\n" + "Position: Ln " + parser.CurrentPosition().Line + ", Col " + parser.CurrentPosition().Column + "\n" + "Read: " + parser.CurrentToken().Data + "\n" + "Expecting: " + parser.ExpectedSymbols().Text(); done = true; break; case GOLD.ParseMessage.Reduction: //For this project, we will let the parser build a tree of Reduction objects //parser.CurrentReduction = CreateNewObject(parser.CurrentReduction); break; case GOLD.ParseMessage.Accept: //Accepted! Root = (GOLD.Reduction)parser.CurrentReduction; //The root node! done = true; accepted = true; break; case GOLD.ParseMessage.TokenRead: //You don't have to do anything here. break; case GOLD.ParseMessage.InternalError: //INTERNAL ERROR! Something is horribly wrong. done = true; break; case GOLD.ParseMessage.NotLoadedError: //This error occurs if the CGT was not loaded. FailMessage = "Tables not loaded"; done = true; break; case GOLD.ParseMessage.GroupError: //GROUP ERROR! Unexpected end of file FailMessage = "Runaway group"; done = true; break; } } //while } return(accepted); }
private ParseResult ParseLALR(ref Token nextToken) { // This function analyzes a token and either: // 1. Makes a SINGLE reduction and pushes a complete Reduction object on the m_Stack // 2. Accepts the token and shifts // 3. Errors and places the expected symbol indexes in the Tokens list // The Token is assumed to be valid and WILL be checked // If an action is performed that requires controlt to be returned to the user, the function returns true. // The Message parameter is then set to the type of action. var result = default(ParseResult); var parseAction = this.m_LRStates[this.m_CurrentLALR][nextToken.Parent]; // Work - shift or reduce if (parseAction != null) { this.m_HaveReduction = false; // Will be set true if a reduction is made // 'Debug.WriteLine("Action: " & ParseAction.Text) switch (parseAction.Type) { case LRActionType.Accept: this.m_HaveReduction = true; result = ParseResult.Accept; break; case LRActionType.Shift: this.m_CurrentLALR = parseAction.Value; nextToken.State = (short)this.m_CurrentLALR; this.m_Stack.Push(ref nextToken); result = ParseResult.Shift; break; case LRActionType.Reduce: // Produce a reduction - remove as many tokens as members in the rule & push a nonterminal token var prod = this.m_ProductionTable[parseAction.Value]; // ======== Create Reduction Token head; short n; if (this.m_TrimReductions && prod.ContainsOneNonTerminal()) { // The current rule only consists of a single nonterminal and can be trimmed from the // parse tree. Usually we create a new Reduction, assign it to the Data property // of Head and push it on the m_Stack. However, in this case, the Data property of the // Head will be assigned the Data property of the reduced token (i.e. the only one // on the m_Stack). // In this case, to save code, the value popped of the m_Stack is changed into the head. head = this.m_Stack.Pop(); head.Parent = prod.Head(); result = ParseResult.ReduceEliminated; // Build a Reduction } else { this.m_HaveReduction = true; var newReduction = new Reduction(prod.Handle().Count()); var with2 = newReduction; with2.Parent = prod; for (n = (short)(prod.Handle().Count() - 1); n >= 0; n += -1) { with2[n] = this.m_Stack.Pop(); } head = new Token(prod.Head(), newReduction); result = ParseResult.ReduceNormal; } // ========== Goto var index = this.m_Stack.Top().State; // ========= If n is -1 here, then we have an Internal Table Error!!!! n = this.m_LRStates[index].IndexOf(prod.Head()); if (n != -1) { this.m_CurrentLALR = this.m_LRStates[index][n].Value; head.State = (short)this.m_CurrentLALR; this.m_Stack.Push(ref head); } else { result = ParseResult.InternalError; } break; } } else { // === Syntax Error! Fill Expected Tokens this.m_ExpectedSymbols.Clear(); // .Count - 1 foreach (LRAction action in this.m_LRStates[this.m_CurrentLALR]) { switch (action.Symbol.Type) { case SymbolType.Content: case SymbolType.End: case SymbolType.GroupStart: case SymbolType.GroupEnd: this.m_ExpectedSymbols.Add(action.Symbol); break; } } result = ParseResult.SyntaxError; } return(result); // Very important }
private LogicStatement ParseAssignStatement(Reduction statement) { return new AssignLogicStatement( this.ParseAssignTarget((Reduction)statement[0].Data), (string)statement[1].Data, this.ParseExpression((Reduction)statement[2].Data)); }
private LogicStatement ParseIfStatement(Reduction statement) { if (statement.Count() == 7) { return new IfElseLogicStatement( this.ParseExpression((Reduction)statement[2].Data), this.ParseStatement((Reduction)statement[4].Data), this.ParseStatement((Reduction)statement[6].Data)); } return new IfLogicStatement( this.ParseExpression((Reduction)statement[2].Data), this.ParseStatement((Reduction)statement[4].Data)); }
private void OnReduction(Reduction r, object newObj) { int count = r.Count(); string dataOutput = String.Empty; for (int i = 0; i < count; i++) { dataOutput += r.get_Data(i).ToString(); } Console.WriteLine(String.Format("R: {0}, C: {1}, D: {2}", r.Parent.Text(), count, dataOutput)); if (newObj is IASTNode) { ((IASTNode)newObj).SourcePosition = parser.ParserPosition; } }
private List<LogicStatement> ParseStatements(Reduction inputStatements) { var statements = new List<LogicStatement>(); while (true) { var statement = (Reduction)inputStatements[0].Data; statements.Add(this.ParseStatement(statement)); if (inputStatements.Count() == 1) { return statements; } inputStatements = (Reduction)inputStatements[1].Data; } }
private LogicStatement ParseStatement(Reduction statement) { if (statement.Parent.Head().Name() == "TerminatedStatement") { statement = (Reduction)statement[0].Data; } if (statement.Parent.Head().Name() == "Statement") { statement = (Reduction)statement[0].Data; } switch (statement.Parent.Head().Name()) { case "WhileStatement": return this.ParseWhileStatement(statement); case "IfStatement": return this.ParseIfStatement(statement); case "AssignStatement": return this.ParseAssignStatement(statement); case "ReturnStatement": return this.ParseReturnStatement(statement); case "BlockStatement": return this.ParseBlockStatement(statement); } throw new InvalidOperationException(); }
private LogicStatement ParseReturnStatement(Reduction statement) { return new ReturnLogicStatement(this.ParseExpression((Reduction)statement[1].Data)); }
private List<LogicParameter> ParseParameters(Reduction parameterDeclarations) { var parameters = new List<LogicParameter>(); if (parameterDeclarations.Count() == 0) { return parameters; } while (true) { var parameter = (Reduction)parameterDeclarations[0].Data; var type = (string)((Reduction)parameter[0].Data)[0].Data; var name = (string)parameter[1].Data; var optionalSemantic = this.ParseOptionalSemantic((Reduction)parameter[2].Data); parameters.Add(new LogicParameter { Index = parameters.Count, Type = type, Name = name, Semantic = optionalSemantic }); if (parameterDeclarations.Count() == 1) { return parameters; } parameterDeclarations = (Reduction)parameterDeclarations[2].Data; } }
public object Execute(GOLD.Reduction node) { if (node.Count() == 2) { // Date Time object _operand1 = null, _operand2 = null; for (int i = 0; i < node.Count(); i++) { string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (_operand1 == null) { _operand1 = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } else { _operand2 = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } } // a visszatérési értéknek szabvány dátum formának kell lennie a megfelelő módon string[] _op1 = _operand1.ToString().Split('.'); string[] _op2 = _operand2.ToString().Split(':'); if (_op2.Length == 3) { try { return(new DateTime(Int32.Parse(_op1[0]), Int32.Parse(_op1[1]), Int32.Parse(_op1[2]), Int32.Parse(_op2[0]), Int32.Parse(_op2[1]), Int32.Parse(_op2[2]))); } catch (Exception exc) { Console.WriteLine(exc.Message); string ERROR = "ERROR"; return(ERROR); } } else { try { return(new DateTime(Int32.Parse(_op1[0]), Int32.Parse(_op1[1]), Int32.Parse(_op1[2]), Int32.Parse(_op2[0]), Int32.Parse(_op2[1]), 0)); } catch (Exception exc) { Console.WriteLine(exc.Message); string ERROR = "ERROR"; return(ERROR); } } } else { // vagy Date, vagy Time string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); object _operand1 = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[0].Data); // szabvány Date, vagy Time objektum visszaadása if (ntt == Enums.eNonTerminals.Date) { //Date string[] _op1 = _operand1.ToString().Split('.'); try { return(new DateTime(Int32.Parse(_op1[0]), Int32.Parse(_op1[1]), Int32.Parse(_op1[2]))); } catch (Exception exc) { Console.WriteLine(exc.Message); string ERROR = "ERROR"; return(ERROR); } } else { //Time string[] _op2 = _operand1.ToString().Split(':'); if (_op2.Length == 3) { try { return(new TimeSpan(Int32.Parse(_op2[0]), Int32.Parse(_op2[1]), Int32.Parse(_op2[2]))); } catch (Exception exc) { Console.WriteLine(exc.Message); string ERROR = "ERROR"; return(ERROR); } } else { try { return(new TimeSpan(Int32.Parse(_op2[0]), Int32.Parse(_op2[1]), 0)); } catch (Exception exc) { Console.WriteLine(exc.Message); string ERROR = "ERROR"; return(ERROR); } } } } }
private LogicAssignmentTarget ParseAssignTarget(Reduction assignTarget) { if (assignTarget.Count() == 1) { return new IdentifierLogicAssignmentTarget((string)assignTarget[0].Data); } return new FieldLogicAssignmentTarget( this.ParseLookupExpression((Reduction)assignTarget[0].Data), (string)assignTarget[2].Data); }
private LogicStatement ParseWhileStatement(Reduction statement) { return new WhileLogicStatement( this.ParseExpression((Reduction)statement[2].Data), this.ParseStatement((Reduction)statement[4].Data)); }
public object Execute(Reduction node) { if (node.Count() == 3) { // van operátor és két operandus, először a két nem terminálist bontom, majd a terminálisként adott operátorral // elvégzem a megfelelő műveletet és értéket adok/másolom string _operator = null; object _operand1 = null , _operand2 = null ; for (int i = 0; i < node.Count(); i++) { switch (node[i].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (_operand1 == null) { /* * Elsőként meg kell nézni, hogy a keresett objektum Document, vagy Resource * A második lépés, hogy az ennek megfelelő objektumot az arra létrehozott service-től lekérjük * Az objektum lekérése után a lebontás kicsit másképp néz ki majd az eddigiekhez képes, ugyanis * objektumon belüli elérési vizsgálatokkal folytatódik */ // Element lekérés, majd ID -> megkapom a hivatkozandó neveket, ezeket pedig feldolgozom _operand1 = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); } else { /* * Amennyiben az objektum lekérése sikeresen megtörtént, a lebontás itt folytatódik az objektumon belüli * hivatkozás kiértékelésével (létezik-e, ha igen, akkor mi az, stb...) */ // belső hivatkozott név, csupán a továbbbontáshoz kell _operand2 = Context.NonTerminalContext.Execute(ntt, (Reduction)node[i].Data); } break; case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt operátor jel _operator = node[i].Data as string; break; } } if (_operator != null) _operand1 = Operation(_operand1, _operator, _operand2); Console.WriteLine("Chain value: " + _operand1 + " type: " + _operand1.GetType()); return _operand1; } else { // egy nem terminális van, azt kell lebontani, majd // értékadás/másolás string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); object returnValue = Context.NonTerminalContext.Execute(ntt, (Reduction)node[0].Data); Console.WriteLine("Expression value: " + returnValue + " type: " + returnValue.GetType()); return returnValue; } }
private void TraverseFunctionDeclaration(Reduction functionDeclaration) { var returnType = (string)((Reduction)functionDeclaration[0].Data)[0].Data; var name = (string)functionDeclaration[1].Data; var parameterDeclarations = (Reduction)functionDeclaration[3].Data; var optionalSemantic = (Reduction)functionDeclaration[5].Data; var statements = functionDeclaration.Count() >= 9 ? (Reduction)functionDeclaration[7].Data : null; this.Functions.Add( new LogicFunction { Name = name, ReturnSemantic = this.ParseOptionalSemantic(optionalSemantic), ReturnType = returnType, Parameters = this.ParseParameters(parameterDeclarations), Statements = statements == null ? new List<LogicStatement>() : this.ParseStatements(statements) }); }
private ParseResult ParseLALR(ref Token nextToken) { // This function analyzes a token and either: // 1. Makes a SINGLE reduction and pushes a complete Reduction object on the m_Stack // 2. Accepts the token and shifts // 3. Errors and places the expected symbol indexes in the Tokens list // The Token is assumed to be valid and WILL be checked // If an action is performed that requires controlt to be returned to the user, the function returns true. // The Message parameter is then set to the type of action. var result = default(ParseResult); var parseAction = this.m_LRStates[this.m_CurrentLALR][nextToken.Parent]; // Work - shift or reduce if (parseAction != null) { this.m_HaveReduction = false; // Will be set true if a reduction is made // 'Debug.WriteLine("Action: " & ParseAction.Text) switch (parseAction.Type) { case LRActionType.Accept: this.m_HaveReduction = true; result = ParseResult.Accept; break; case LRActionType.Shift: this.m_CurrentLALR = parseAction.Value; nextToken.State = (short)this.m_CurrentLALR; this.m_Stack.Push(ref nextToken); result = ParseResult.Shift; break; case LRActionType.Reduce: // Produce a reduction - remove as many tokens as members in the rule & push a nonterminal token var prod = this.m_ProductionTable[parseAction.Value]; // ======== Create Reduction Token head; short n; if (this.m_TrimReductions && prod.ContainsOneNonTerminal()) { // The current rule only consists of a single nonterminal and can be trimmed from the // parse tree. Usually we create a new Reduction, assign it to the Data property // of Head and push it on the m_Stack. However, in this case, the Data property of the // Head will be assigned the Data property of the reduced token (i.e. the only one // on the m_Stack). // In this case, to save code, the value popped of the m_Stack is changed into the head. head = this.m_Stack.Pop(); head.Parent = prod.Head(); result = ParseResult.ReduceEliminated; // Build a Reduction } else { this.m_HaveReduction = true; var newReduction = new Reduction(prod.Handle().Count()); var with2 = newReduction; with2.Parent = prod; for (n = (short)(prod.Handle().Count() - 1); n >= 0; n += -1) { with2[n] = this.m_Stack.Pop(); } head = new Token(prod.Head(), newReduction); result = ParseResult.ReduceNormal; } // ========== Goto var index = this.m_Stack.Top().State; // ========= If n is -1 here, then we have an Internal Table Error!!!! n = this.m_LRStates[index].IndexOf(prod.Head()); if (n != -1) { this.m_CurrentLALR = this.m_LRStates[index][n].Value; head.State = (short)this.m_CurrentLALR; this.m_Stack.Push(ref head); } else { result = ParseResult.InternalError; } break; } } else { // === Syntax Error! Fill Expected Tokens this.m_ExpectedSymbols.Clear(); // .Count - 1 foreach (LRAction action in this.m_LRStates[this.m_CurrentLALR]) { switch (action.Symbol.Type) { case SymbolType.Content: case SymbolType.End: case SymbolType.GroupStart: case SymbolType.GroupEnd: this.m_ExpectedSymbols.Add(action.Symbol); break; } } result = ParseResult.SyntaxError; } return result; // Very important }
private void TraverseStructureDeclaration(Reduction structureDeclaration) { var root = structureDeclaration; var name = (string)root[1].Data; var fields = (Reduction)root[3].Data; var logicFields = new List<LogicField>(); Reduction field; while (fields.Count() == 2) { field = (Reduction)fields[0].Data; logicFields.Add(new LogicField { Name = (string)field[1].Data, Type = (string)((Reduction)field[0].Data)[0].Data, Semantic = (string)((Reduction)field[2].Data)[1].Data }); fields = (Reduction)fields[1].Data; } field = (Reduction)fields[0].Data; logicFields.Add(new LogicField { Name = (string)field[1].Data, Type = (string)((Reduction)field[0].Data)[0].Data, Semantic = (string)((Reduction)field[2].Data)[1].Data }); this.Structures.Add(new LogicStructure { Name = name, Fields = logicFields }); }
private LogicStatement ParseBlockStatement(Reduction statement) { if (statement.Count() != 3) { return new BlockLogicStatement(new List<LogicStatement>()); } return new BlockLogicStatement(this.ParseStatements((Reduction)statement[1].Data)); }
private List<LogicExpression> ParseArguments(Reduction inputExpressions) { var expressions = new List<LogicExpression>(); if (inputExpressions.Count() == 0) { return expressions; } while (true) { var statement = (Reduction)inputExpressions[0].Data; expressions.Add(this.ParseExpression(statement)); if (inputExpressions.Count() == 1) { return expressions; } inputExpressions = (Reduction)inputExpressions[2].Data; } }
public object Execute(GOLD.Reduction node) { if (node.Count() == 3) { // van operátor és két operandus, először a két nem terminálist kell bontnai, majd a terminálisként adott operátorral // elvégzem a megfelelő műveletet és értéket adok/másolom string _operator = null; object _operand1 = null , _operand2 = null ; for (int i = 0; i < node.Count(); i++) { switch (node[i].Type()) { case SymbolType.Nonterminal: // Nemterminálisok vizsgálata string type = Regex.Replace(node[i].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); if (_operand1 == null) { /* * Elsőként meg kell nézni, hogy a keresett objektum Document, vagy Resource * A második lépés, hogy az ennek megfelelő objektumot az arra létrehozott service-től lekérjük * Az objektum lekérése után a lebontás kicsit másképp néz ki majd az eddigiekhez képes, ugyanis * objektumon belüli elérési vizsgálatokkal folytatódik */ // Element lekérés, majd ID -> megkapom a hivatkozandó neveket, ezeket pedig feldolgozom _operand1 = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } else { /* * Amennyiben az objektum lekérése sikeresen megtörtént, a lebontás itt folytatódik az objektumon belüli * hivatkozás kiértékelésével (létezik-e, ha igen, akkor mi az, stb...) */ // belső hivatkozott név, csupán a továbbbontáshoz kell _operand2 = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[i].Data); } break; case SymbolType.Error: Console.WriteLine("ERROR in Logical_Engine.Classes.Processor.ProcessTree"); break; default: // Terminálisok vizsgálata - itt operátor jel _operator = node[i].Data as string; break; } } if (_operator != null) { _operand1 = Operation(_operand1, _operator, _operand2); } Console.WriteLine("Chain value: " + _operand1 + " type: " + _operand1.GetType()); return(_operand1); } else { // egy nem terminális van, azt kell lebontani, majd // értékadás/másolás string type = Regex.Replace(node[0].Parent.ToString(), "[^0-9a-zA-Z]+", ""); Enums.eNonTerminals ntt = (Enums.eNonTerminals)Enum.Parse(typeof(Enums.eNonTerminals), type); object returnValue = Context.NonTerminalContext.Execute(ntt, (GOLD.Reduction)node[0].Data); Console.WriteLine("Expression value: " + returnValue + " type: " + returnValue.GetType()); return(returnValue); } }
private object CreateNewObject(GOLD.Reduction r) { object result = null; switch ((ProductionIndex)r.Parent.TableIndex()) { case ProductionIndex.Nl_Newline: // <nl> ::= NewLine <nl> break; case ProductionIndex.Nl_Newline2: // <nl> ::= NewLine break; case ProductionIndex.Regform_Pipepipe: // <regForm> ::= <regForm> '||' <regFormSeq> result = new UnionFormula((RegularFormula)r[0].Data, (RegularFormula)r[2].Data); break; case ProductionIndex.Regform: // <regForm> ::= <regFormSeq> result = r[0].Data; break; case ProductionIndex.Regformseq_Dot: // <regFormSeq> ::= <regFormSeq> '.' <regFormValue> result = new SequenceFormula((RegularFormula)r[0].Data, (RegularFormula)r[2].Data); break; case ProductionIndex.Regformseq: // <regFormSeq> ::= <regFormValue> result = r[0].Data; break; case ProductionIndex.Regformvalue_Identifier: // <regFormValue> ::= Identifier <Multiplier> result = new SingleAction((string)r[0].Data, (string)r[1].Data); break; case ProductionIndex.Regformvalue_Not: // <regFormValue> ::= not <regForm> result = new NegateAction((RegularFormula)r[1].Data); break; case ProductionIndex.Regformvalue_Lparen_Rparen: // <regFormValue> ::= '(' <regForm> ')' <Multiplier> if ((string)r[3].Data != "") { return(new NestedFormula((RegularFormula)r[1].Data, (string)r[3].Data)); } else // small optimization { result = r[1].Data; } break; case ProductionIndex.Multiplier_Plus: // <Multiplier> ::= '+' result = "+"; break; case ProductionIndex.Multiplier_Times: // <Multiplier> ::= '*' result = "*"; break; case ProductionIndex.Multiplier: // <Multiplier> ::= result = ""; break; case ProductionIndex.Muform_Identifier: // <muForm> ::= Identifier result = new Proposition((string)r[0].Data); break; case ProductionIndex.Muform_Variable: // <muForm> ::= Variable result = new Variable((string)r[0].Data); break; case ProductionIndex.Muform_Lparen_Pipepipe_Rparen: // <muForm> ::= '(' <muForm> '||' <muForm> ')' result = new Disjunction((MuFormula)r[1].Data, (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Lparen_Ampamp_Rparen: // <muForm> ::= '(' <muForm> '&&' <muForm> ')' result = new Conjunction((MuFormula)r[1].Data, (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Lt_Gt: // <muForm> ::= '<' <regForm> '>' <muForm> result = new Diamond((RegularFormula)r[1].Data, (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Lbracket_Rbracket: // <muForm> ::= '[' <regForm> ']' <muForm> result = new Box((RegularFormula)r[1].Data, (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Mu_Variable_Dot: // <muForm> ::= mu Variable '.' <muForm> result = new Mu(new Variable((string)r[1].Data), (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Nu_Variable_Dot: // <muForm> ::= nu Variable '.' <muForm> result = new Nu(new Variable((string)r[1].Data), (MuFormula)r[3].Data); break; case ProductionIndex.Muform_Not: // <muForm> ::= not <muForm> result = new Negation((MuFormula)r[1].Data); break; case ProductionIndex.Muform_Lparen_Rparen: result = r[1].Data as MuFormula; break; case ProductionIndex.Line_Commentl: // <Line> ::= CommentL <nl> break; case ProductionIndex.Line: // <Line> ::= <muForm> <nl> var form = (MuFormula)r[0].Data; FormulaRewriter.ResetFreeVars(); form = FormulaRewriter.Rewrite(form); form.SetParents(null /* root has no parent */); formulas.Add(form); break; case ProductionIndex.Line2: // <Line> ::= <nl> break; case ProductionIndex.Lines: // <Lines> ::= <Line> <Lines> break; case ProductionIndex.Lines2: // <Lines> ::= break; } //switch return(result); }
private LogicExpression ParseUnaryExpression(Reduction expression) { if (expression.Count() == 2) { return new UnaryLogicExpression( (string)expression[0].Data, this.ParseLookupExpression((Reduction)expression[1].Data)); } return this.ParseLookupExpression((Reduction)expression[0].Data); }
private LogicExpression ParseLookupExpression(Reduction expression) { if (expression.Count() == 3) { return new LookupLogicExpression( this.ParseLookupExpression((Reduction)expression[0].Data), (string)expression[2].Data); } return this.ParseValueExpression((Reduction)expression[0].Data); }
public bool Parse(TextReader reader) { //This procedure starts the GOLD Parser Engine and handles each of the //messages it returns. Each time a reduction is made, you can create new //custom object and reassign the .CurrentReduction property. Otherwise, //the system will use the Reduction object that was returned. // //The resulting tree will be a pure representation of the language //and will be ready to implement. GOLD.ParseMessage response; bool done; //Controls when we leave the loop bool accepted = false; //Was the parse successful? parser.Open(reader); parser.TrimReductions = false; //Please read about this feature before enabling done = false; while (!done) { response = parser.Parse(); switch (response) { case GOLD.ParseMessage.LexicalError: //Cannot recognize token FailMessage = "Lexical Error:\n" + "Position: " + parser.CurrentPosition().Line + ", " + parser.CurrentPosition().Column + "\n" + "Read: " + parser.CurrentToken().Data; done = true; break; case GOLD.ParseMessage.SyntaxError: //Expecting a different token FailMessage = "Syntax Error:\n" + "Position: " + parser.CurrentPosition().Line + ", " + parser.CurrentPosition().Column + "\n" + "Read: " + parser.CurrentToken().Data + "\n" + "Expecting: " + parser.ExpectedSymbols().Text(); done = true; break; case GOLD.ParseMessage.Reduction: //Create a customized object to store the reduction //parser.CurrentReduction = CreateNewObject(parser.CurrentReduction as GOLD.Reduction); break; case GOLD.ParseMessage.Accept: //Accepted! //program = parser.CurrentReduction //The root node! Root = (GOLD.Reduction)parser.CurrentReduction; //The root node! done = true; accepted = true; break; case GOLD.ParseMessage.TokenRead: //You don't have to do anything here. break; case GOLD.ParseMessage.InternalError: //INTERNAL ERROR! Something is horribly wrong. done = true; break; case GOLD.ParseMessage.NotLoadedError: //This error occurs if the CGT was not loaded. FailMessage = "Tables not loaded"; done = true; break; case GOLD.ParseMessage.GroupError: //GROUP ERROR! Unexpected end of file FailMessage = "Runaway group"; done = true; break; } } //while return accepted; }
private LogicExpression ParseValueExpression(Reduction expression) { if (expression.Count() == 1) { switch (expression[0].Parent.Name()) { case "Id": return new IdentifierLogicExpression( (string)expression[0].Data); case "StringLiteral": return new ConstantLogicExpression( this.ParseString((string)expression[0].Data)); case "NumberLiteral": return new ConstantLogicExpression( float.Parse((string)expression[0].Data, CultureInfo.InvariantCulture.NumberFormat)); case "BooleanLiteral": return new ConstantLogicExpression( (string)((Reduction)expression[0].Data)[0].Data == "true"); } } if (expression.Count() == 3) { return this.ParseExpression((Reduction)expression[1].Data); } if (expression.Count() == 4) { return new FunctionCallLogicExpression( (string)((Reduction)expression[0].Data)[0].Data, this.ParseArguments((Reduction)expression[2].Data)); } throw new InvalidOperationException(); }