Lexer.cpp 1.5 KB

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