Lexer.cpp 1.4 KB

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