code_junkie

Parsers and Compilers for Dummies. Where to start?

Nov 13th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. addOp = '+' | '-';
  2. mulOp = '*' | '/';
  3. parLeft = '(';
  4. parRight = ')';
  5. number = digit, {digit};
  6. digit = '0'..'9';
  7.  
  8. Each token can have different representations: + and = are both addOp and
  9. 23 6643 and 223322 are all numbers.
  10.  
  11. exp = term | exp, addOp, term;
  12. // an expression is a series of terms separated by addOps.
  13. term = factor | term, mulOp, factor;
  14. // a term is a series of factors separated by mulOps
  15. factor = addOp, factor | parLeft, exp, parRight | number;
  16. // a factor can be an addOp followed by another factor,
  17. // an expression enclosed in parentheses or a number.
  18.  
  19. s00
  20. '+', '-' -> s01 // if a + or - is found, read it and go to state s01.
  21. '*', '/' -> s02
  22. '(' -> s03
  23. ')' -> s04
  24. '0'..'9' -> s05
  25. whitespace -> ignore and retry // if a whitespace is found ignore it
  26. else ERROR // sorry but we don't recognize this character in this state.
  27. s01
  28. found TOKEN addOp // ok we have found an addOp, stop reading and return token
  29. s02
  30. found TOKEN mulOp
  31. s03
  32. found TOKEN parLeft
  33. s04
  34. found TOKEN parRight
  35. s05
  36. '0'..'9' -> s05 // as long as we find digits, keep collecting them
  37. else found number // last digit read, we have a number
  38.  
  39. ParseExp
  40. temp = ParseTerm // start by reading a term
  41. while token = addOp do
  42. // as long as we read an addop keep reading terms
  43. if token('+') then temp = temp + ParseTerm // + so we add the term
  44. if token('-') then temp = temp - ParseTerm // - so we subtract the term
  45. od
  46. return temp // we are done with the expression
  47.  
  48. ParseTerm
  49. temp = ParseFactor
  50. while token = mulOp do
  51. if token('*') then temp = temp * ParseFactor
  52. if token('/') then temp = temp / ParseFactor
  53. od
  54. return temp
  55.  
  56. ParseFactor
  57. if token = addOp then
  58. if token('-') then return - ParseFactor // yes we can have a lot of these
  59. if token('+') then return ParseFactor
  60. else if token = parLeft then
  61. return ParseExpression
  62. if not token = parRight then ERROR
  63. else if token = number then
  64. return EvaluateNumber // use magic to translate a string into a number
Add Comment
Please, Sign In to add comment