/// <summary> /// modified method that implements part of Shunting Yard /// Algorithm. /// /// //Pseudo Code /// If token is an operator, o1 , then use pushSpew. /// /// ===Spew part===== /// while there is an operator token, o2, at the top of stack and : /// either o1 is left-associative (-,+,*,/) and its priority is less /// than or equal to o2, /// or o1 is right-associative ( ^ ), and priority is less than o2 /// /// pop o2 off stack onto output Queue /// end while /// /// ====Push part==== /// push o1 onto stack /// /// </summary> /// <param name="output">The Queue that holds the tokens in /// post fix notation</param> /// <param name="tokenToPush">Incoming token to be compared with /// stack</param> public void pushSpew(Queue<Token> output, Token tokenToPush_o1) { //deals with right-associative Token stackToken_o2 ; if (tokenToPush_o1.Type == tokenType.POST) { while (stack.Count != 0 && ((stackToken_o2 = stack.Peek()).Precedence > tokenToPush_o1.Precedence)) { output.Enqueue(stack.Pop()); } } //deals with left-associative else { while (stack.Count != 0 && ((stackToken_o2 = stack.Peek()).Precedence >= tokenToPush_o1.Precedence)) { output.Enqueue(stack.Pop()); } } stack.Push(tokenToPush_o1); }
Token getNextToken(string input) { input = input.Trim(); Token nextTok = new Token(); //Create Regexes for each string value Regex ARG_NUM_Regex = new Regex(@"^[0-9]*\.?[0-9]+"); //For now , variables can be any combination of letters and numbers Regex ARG_VAR_Regex = new Regex(@"^[a-zA-Z0-9]+"); Regex DI_OP_Regex = new Regex(@"^[+|\-|\/|*]"); Regex OPEN_Regex = new Regex(@"^\("); Regex CLOSE_Regex = new Regex(@"^\)"); Regex POST_Regex = new Regex(@"^[\^]"); //Case out matches if (ARG_NUM_Regex.IsMatch(input)) { nextTok.Type = tokenType.ARG_NUM; nextTok.TokenValue = ARG_NUM_Regex.Match(input).Value; nextTok.Precedence = 1; }else if(ARG_VAR_Regex.IsMatch(input)){ nextTok.Type = tokenType.ARG_VAR; nextTok.TokenValue = ARG_VAR_Regex.Match(input).Value; nextTok.Precedence = 1; } else if (DI_OP_Regex.IsMatch(input)) { nextTok.Type = tokenType.DI_OP; nextTok.TokenValue = DI_OP_Regex.Match(input).Value; switch (nextTok.TokenValue) { case "+": case "-": nextTok.Precedence = 2; break; case "*": case "/": nextTok.Precedence = 3; break; } } else if (OPEN_Regex.IsMatch(input)) { nextTok.Type = tokenType.OPEN; nextTok.Precedence = -2; nextTok.TokenValue = "("; } else if (CLOSE_Regex.IsMatch(input)) { nextTok.Type = tokenType.CLOSE; nextTok.Precedence = -1; nextTok.TokenValue = ")"; }else if (POST_Regex.IsMatch(input)) { nextTok.Type = tokenType.POST; nextTok.TokenValue = POST_Regex.Match(input).Value; nextTok.Precedence = 4; } else{ Console.WriteLine("Could not regex match next token,"); nextTok.Type = tokenType.UNRECOGNIZED; } //set values and return token return nextTok; }
public void push(Token tokenToPush) { this.stack.Push(tokenToPush); }
private string consume(string input, Token t) { return input.Substring(t.TokenValue.Length); }