Lexer.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #ifndef PARSER_H
  2. #define PARSER_H
  3. #include <stdexcept>
  4. #include "Exception.h"
  5. #include <ctype.h>
  6. #include <string>
  7. class Lexer
  8. {
  9. public:
  10. static const int nothing = 0;
  11. static const int integer = 1;
  12. static const int floatingpoint = 2;
  13. static const int identifier = 4;
  14. static const int stringliteral = 8;
  15. static const int singlecharacter = 16;
  16. Lexer(const std::string& s, int start = 0):
  17. str(s), pos(start)
  18. {
  19. nextToken();
  20. }
  21. // all handled
  22. virtual bool empty() const
  23. {
  24. return token.empty() && pos >= str.size();
  25. }
  26. // get next token
  27. virtual void nextToken();
  28. virtual std::string getAll()
  29. {
  30. std::string res = str.substr(pos, str.size() - pos);
  31. pos = str.size();
  32. return res;
  33. }
  34. virtual long int getInt();
  35. virtual double getDouble();
  36. virtual std::string getString();
  37. virtual std::string getWord();
  38. // expect and remove specific token (string)
  39. virtual void expect(const std::string& tok)
  40. {
  41. if (token != tok)
  42. throw Exception("Parsing", "Expected " + tok);
  43. nextToken();
  44. }
  45. // expect and remove specific token (singlecharacter)
  46. virtual void expect(char tok)
  47. {
  48. if (type != singlecharacter || token[0] != tok)
  49. throw Exception("Parsing", std::string("Expected ") + tok);
  50. nextToken();
  51. }
  52. virtual std::string getString() const
  53. {
  54. return str;
  55. }
  56. std::string token;
  57. int type;
  58. private:
  59. virtual char nextChar() const;
  60. virtual char getChar();
  61. virtual void skipChar();
  62. virtual void skipWhiteSpace();
  63. // virtual void get_token();
  64. std::string str;
  65. unsigned int pos;
  66. };
  67. #endif