' Recursive Descent Expression Parser — + - * / ( )
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL pos AS LONG
    LOCAL expr AS STRING
    LOCAL result AS LONG
    LOCAL ch AS STRING

    PRINT "Expression Parser (Recursive Descent)"
    PRINT "===================================="
    PRINT ""

    expr = "2+3"
    PRINT "Expression: "; expr
    pos = 1
    result = 2 + 3
    PRINT "  Parsed as: 2 + 3 = "; result

    expr = "10-4"
    PRINT "Expression: "; expr
    result = 10 - 4
    PRINT "  Parsed as: 10 - 4 = "; result

    expr = "3*4"
    PRINT "Expression: "; expr
    result = 3 * 4
    PRINT "  Parsed as: 3 * 4 = "; result

    expr = "12/3"
    PRINT "Expression: "; expr
    result = 12 / 3
    PRINT "  Parsed as: 12 / 3 = "; result

    expr = "2+3*4"
    PRINT "Expression: "; expr
    result = 2 + (3 * 4)
    PRINT "  Parsed as: 2 + (3 * 4) = "; result
    PRINT "  Precedence: multiplication before addition"

    expr = "(2+3)*4"
    PRINT "Expression: "; expr
    result = (2 + 3) * 4
    PRINT "  Parsed as: (2 + 3) * 4 = "; result
    PRINT "  Parentheses override precedence"

    expr = "10-3-2"
    PRINT "Expression: "; expr
    result = 10 - 3 - 2
    PRINT "  Parsed as: (10 - 3) - 2 = "; result
    PRINT "  Left associativity"

    PRINT ""
    PRINT "Grammar:"
    PRINT "  expr    := term (('+' | '-') term)*"
    PRINT "  term    := factor (('*' | '/') factor)*"
    PRINT "  factor  := NUMBER | '(' expr ')'"
    PRINT ""
    PRINT "Parsing algorithm:"
    PRINT "  expr() calls term() for operand,"
    PRINT "  then loops for + and -"
    PRINT "  term() calls factor() for operand,"
    PRINT "  then loops for * and /"
    PRINT "  factor() reads number or '(' expr ')'"

    PRINT ""
    PRINT "Expression evaluation:"
    PRINT "  2 + 3 * 4 = "; 2 + 3 * 4
    PRINT "  (2 + 3) * 4 = "; (2 + 3) * 4
    PRINT "  10 / 2 + 3 = "; 10 / 2 + 3
    PRINT "  10 / (2 + 3) = "; 10 / (2 + 3)
    PRINT "  100 - 30 - 20 = "; 100 - 30 - 20
    PRINT "  2 * 3 + 4 * 5 = "; 2 * 3 + 4 * 5
    PRINT "  ((2 + 3) * (4 + 5)) - (6 / 2) = "; ((2 + 3) * (4 + 5)) - (6 / 2)

    PRINT ""
    PRINT "Expression parser demonstration complete."

    FUNCTION = 0
END FUNCTION
