Lexer.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "Lexer.h"
  2. /// gettok - Return the next token from standard input.
  3. namespace lexer{
  4. int gettok() {
  5. static int LastChar = ' ';
  6. // Skip any whitespace.
  7. while (isspace(LastChar))
  8. LastChar = getchar();
  9. if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
  10. IdentifierStr = LastChar;
  11. while (isalnum((LastChar = getchar())))
  12. IdentifierStr += LastChar;
  13. if (IdentifierStr == "def")
  14. return tok_def;
  15. if (IdentifierStr == "extern")
  16. return tok_extern;
  17. return tok_identifier;
  18. }
  19. if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
  20. std::string NumStr;
  21. do {
  22. NumStr += LastChar;
  23. LastChar = getchar();
  24. } while (isdigit(LastChar) || LastChar == '.');
  25. NumVal = strtod(NumStr.c_str(), nullptr);
  26. return tok_number;
  27. }
  28. if (LastChar == '#') {
  29. // Comment until end of line.
  30. do
  31. LastChar = getchar();
  32. while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
  33. if (LastChar != EOF)
  34. return gettok();
  35. }
  36. // Check for end of file. Don't eat the EOF.
  37. if (LastChar == EOF)
  38. return tok_eof;
  39. // Otherwise, just return the character as its ascii value.
  40. int ThisChar = LastChar;
  41. LastChar = getchar();
  42. return ThisChar;
  43. }
  44. }