TokenStream.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include <cstring>
  2. #include "TokenStream.h"
  3. TokenStream::TokenStream() : nextToken(0) {
  4. }
  5. bool TokenStream::hasToken() const {
  6. return nextToken < bytes.size();
  7. }
  8. std::string TokenStream::nextTokenString() {
  9. std::string t = "(";
  10. // line
  11. unsigned int line = nextLine();
  12. t += std::to_string(line);
  13. t += ", ";
  14. // tokentype
  15. TokenType type = nextTokenType();
  16. t += TokenTypeUtils::getEnumName(type);
  17. if(type == TokenType::STRING || type == TokenType::LITERAL || type == TokenType::LABEL) {
  18. t += ", \"";
  19. t += nextString();
  20. t += "\"";
  21. }
  22. if(type == TokenType::NUMBER) {
  23. t += ", ";
  24. double d = nextDouble();
  25. char buffer[32];
  26. snprintf(buffer, 32, (d == (long) d) ? "%lg.0" : "%lg", d);
  27. t += buffer;
  28. }
  29. t += ")";
  30. return t;
  31. }
  32. TokenType TokenStream::nextTokenType() {
  33. TokenType type = TokenType::EOF_TOKEN;
  34. read(&type, sizeof (TokenType));
  35. return type;
  36. }
  37. unsigned int TokenStream::nextLine() {
  38. unsigned int line = 0;
  39. read(&line, sizeof (unsigned int));
  40. return line;
  41. }
  42. std::string TokenStream::nextString() {
  43. std::string text;
  44. char c;
  45. while(true) {
  46. read(&c, 1);
  47. if(c == '\0') {
  48. break;
  49. }
  50. text += c;
  51. }
  52. return text;
  53. }
  54. double TokenStream::nextDouble() {
  55. double d;
  56. read(&d, sizeof (double));
  57. return d;
  58. }
  59. void TokenStream::write(const void* data, size_t length) {
  60. const char* chars = reinterpret_cast<const char*> (data);
  61. for(size_t i = 0; i < length; i++) {
  62. bytes.push_back(chars[i]);
  63. }
  64. }
  65. void TokenStream::read(void* data, size_t length) {
  66. memcpy(data, bytes.data() + nextToken, length);
  67. nextToken += length;
  68. }
  69. void TokenStream::add(TokenType type, unsigned int line) {
  70. write(&line, sizeof (unsigned int));
  71. write(&type, sizeof (TokenType));
  72. }
  73. void TokenStream::add(TokenType type, unsigned int line, double d) {
  74. add(type, line);
  75. write(&d, sizeof (double));
  76. }
  77. void TokenStream::add(TokenType type, unsigned int line, const std::string& text) {
  78. add(type, line);
  79. write(text.data(), text.length());
  80. write("\0", 1);
  81. }