Lexer.cpp 1.9 KB

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