ConvertToPostFix Subroutine

private subroutine ConvertToPostFix(parser)

Arguments

TypeIntentOptionalAttributesName
class(EquationParser), intent(inout) :: parser

Contents

Source Code


Source Code

  subroutine ConvertToPostFix(parser)
    class(EquationParser),intent(inout) :: parser
    ! Local
    type(TokenStack)            :: operator_stack
    type(Token)                 :: tok
    integer                     :: i

    call parser%postfix%Construct(Stack_Length)
    call operator_stack%Construct(Stack_Length)

    do i = 1,parser%infix%top_index
      if(parser%inFix%tokens(i)%tokenType == Variable_Token .or. &
         parser%inFix%tokens(i)%tokenType == Number_Token) then

        call parser%postFix%push(parser%inFix%tokens(i))

      elseif(parser%inFix%tokens(i)%tokenType == Function_Token) then

        call operator_stack%push(parser%inFix%tokens(i))

      elseif(parser%inFix%tokens(i)%tokenType == Operator_Token &
             .or. parser%inFix%tokens(i)%tokenType == Monadic_Token) then

        if(.not. operator_stack%IsEmpty()) then

          tok = operator_stack%TopToken()

          do while(trim(tok%tokenString) /= '(' .and. &
                   parser%Priority(tok) > &
                   parser%Priority(parser%inFix%tokens(i)) .and. &
                   .not. operator_stack%IsEmpty())

            call parser%postFix%push(tok)
            call operator_stack%pop(tok)
            tok = operator_stack%TopToken()

          enddo

        endif

        call operator_stack%push(parser%inFix%tokens(i))

      elseif(parser%inFix%tokens(i)%tokenType == OpeningParentheses_Token) then

        call operator_stack%push(parser%inFix%tokens(i))

      elseif(parser%inFix%tokens(i)%tokenType == ClosingParentheses_Token) then

        tok = operator_stack%TopToken()

        do while(.not.(operator_stack%IsEmpty()) .and. tok%tokenString(1:1) /= '(')

          call parser%postFix%push(tok)
          call operator_stack%pop(tok)
          tok = operator_stack%TopToken()

        enddo

        ! Pop the opening parenthesis
        call operator_stack%pop(tok)

      endif

    enddo

    ! Pop the remaining operators
    do while(.not.(operator_stack%IsEmpty()))

      tok = operator_stack%TopToken()
      call parser%postFix%push(tok)
      call operator_stack%pop(tok)

    enddo

  endsubroutine ConvertToPostFix