Lexer.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Standard includes
  2. #include <cctype>
  3. #include <cstdio>
  4. // Local includes
  5. #include "Lexer.h"
  6. /// gettok - Return the next token from standard input.
  7. namespace lexer{
  8. std::string LexerObjects::IdentifierStr; // Filled in if tok_identifier
  9. double LexerObjects::NumVal;
  10. int gettok() {
  11. static int LastChar = ' ';
  12. // Skip any whitespace.
  13. while (isspace(LastChar))
  14. LastChar = getchar();
  15. if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
  16. LexerObjects::IdentifierStr = LastChar;
  17. while (isalnum((LastChar = getchar())))
  18. LexerObjects::IdentifierStr += LastChar;
  19. if (LexerObjects::IdentifierStr == "def")
  20. return tok_def;
  21. if (LexerObjects::IdentifierStr == "extern")
  22. return tok_extern;
  23. if (LexerObjects::IdentifierStr == "if")
  24. return tok_if;
  25. if (LexerObjects::IdentifierStr == "then")
  26. return tok_then;
  27. if (LexerObjects::IdentifierStr == "else")
  28. return tok_else;
  29. if (LexerObjects::IdentifierStr == "for")
  30. return tok_for;
  31. if (LexerObjects::IdentifierStr == "in")
  32. return tok_in;
  33. if (LexerObjects::IdentifierStr == "binary")
  34. return tok_binary;
  35. if (LexerObjects::IdentifierStr == "unary")
  36. return tok_unary;
  37. if (LexerObjects::IdentifierStr == "var")
  38. return tok_var;
  39. return tok_identifier;
  40. }
  41. if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
  42. std::string NumStr;
  43. do {
  44. NumStr += LastChar;
  45. LastChar = getchar();
  46. } while (isdigit(LastChar) || LastChar == '.');
  47. LexerObjects::NumVal = strtod(NumStr.c_str(), nullptr);
  48. return tok_number;
  49. }
  50. if (LastChar == '#') {
  51. // Comment until end of line.
  52. do
  53. LastChar = getchar();
  54. while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
  55. if (LastChar != EOF)
  56. return gettok();
  57. }
  58. // Check for end of file. Don't eat the EOF.
  59. if (LastChar == EOF)
  60. return tok_eof;
  61. // Otherwise, just return the character as its ascii value.
  62. int ThisChar = LastChar;
  63. LastChar = getchar();
  64. return ThisChar;
  65. }
  66. }