Lexer.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. return tok_identifier;
  34. }
  35. if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
  36. std::string NumStr;
  37. do {
  38. NumStr += LastChar;
  39. LastChar = getchar();
  40. } while (isdigit(LastChar) || LastChar == '.');
  41. LexerObjects::NumVal = strtod(NumStr.c_str(), nullptr);
  42. return tok_number;
  43. }
  44. if (LastChar == '#') {
  45. // Comment until end of line.
  46. do
  47. LastChar = getchar();
  48. while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
  49. if (LastChar != EOF)
  50. return gettok();
  51. }
  52. // Check for end of file. Don't eat the EOF.
  53. if (LastChar == EOF)
  54. return tok_eof;
  55. // Otherwise, just return the character as its ascii value.
  56. int ThisChar = LastChar;
  57. LastChar = getchar();
  58. return ThisChar;
  59. }
  60. }