Parser.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // $Id$
  2. using System;
  3. using System.IO;
  4. namespace Lisp
  5. {
  6. public class Parser {
  7. public enum LispType {
  8. START_LIST,
  9. END_LIST,
  10. SYMBOL,
  11. INTEGER,
  12. STRING,
  13. REAL,
  14. BOOLEAN
  15. };
  16. private Lexer lexer;
  17. private Lexer.TokenType token;
  18. public Parser(StreamReader stream) {
  19. lexer = new Lexer(stream);
  20. }
  21. public bool Parse() {
  22. token = lexer.GetNextToken();
  23. if(delayinc) {
  24. depth++;
  25. delayinc = false;
  26. }
  27. if(token == Lexer.TokenType.EOF) {
  28. depth = 0;
  29. return false;
  30. }
  31. /*
  32. Console.WriteLine("Token: " + token.ToString() + " - " +
  33. lexer.TokenString);
  34. */
  35. switch(token) {
  36. case Lexer.TokenType.CLOSE_PAREN:
  37. if(depth == 0)
  38. throw new Exception("Parse Error: unexpected )");
  39. depth--;
  40. type = LispType.END_LIST;
  41. break;
  42. case Lexer.TokenType.OPEN_PAREN:
  43. type = LispType.START_LIST;
  44. delayinc = true;
  45. break;
  46. case Lexer.TokenType.SYMBOL:
  47. type = LispType.SYMBOL;
  48. break;
  49. case Lexer.TokenType.STRING:
  50. type = LispType.STRING;
  51. break;
  52. case Lexer.TokenType.TRUE:
  53. type = LispType.BOOLEAN;
  54. break;
  55. case Lexer.TokenType.INTEGER:
  56. type = LispType.INTEGER;
  57. break;
  58. }
  59. return true;
  60. }
  61. public static void ParseIntList(Parser parser, System.Collections.Generic.List<int> intList) {
  62. int d = parser.Depth;
  63. while(parser.Depth >= d) {
  64. intList.Add(parser.IntegerValue);
  65. parser.Parse();
  66. }
  67. }
  68. private LispType type;
  69. public LispType Type {
  70. get { return type; }
  71. }
  72. private bool delayinc;
  73. private int depth;
  74. public int Depth {
  75. get { return depth; }
  76. }
  77. //public int IntValue
  78. public string SymbolValue {
  79. get { return lexer.TokenString; }
  80. }
  81. public string StringValue {
  82. get { return lexer.TokenString; }
  83. }
  84. public int IntegerValue {
  85. get { return Int32.Parse(lexer.TokenString); }
  86. }
  87. public bool BoolValue {
  88. get { return StringValue == "t"; }
  89. }
  90. public float FloatValue {
  91. get { return Single.Parse(lexer.TokenString); }
  92. }
  93. }
  94. }