error.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #pragma once
  2. #include "safestl.h"
  3. struct NeedMoreLines {
  4. NeedMoreLines(bool is_compiling_class) : is_compiling_class(is_compiling_class) {}
  5. bool is_compiling_class;
  6. };
  7. struct HandledException {};
  8. struct UnhandledException {};
  9. struct ToBeRaisedException {};
  10. enum CompileMode {
  11. EXEC_MODE,
  12. EVAL_MODE,
  13. REPL_MODE,
  14. JSON_MODE,
  15. };
  16. struct SourceData {
  17. const char* source;
  18. _Str filename;
  19. std::vector<const char*> line_starts;
  20. CompileMode mode;
  21. std::pair<const char*,const char*> get_line(int lineno) const {
  22. if(lineno == -1) return {nullptr, nullptr};
  23. lineno -= 1;
  24. if(lineno < 0) lineno = 0;
  25. const char* _start = line_starts.at(lineno);
  26. const char* i = _start;
  27. while(*i != '\n' && *i != '\0') i++;
  28. return {_start, i};
  29. }
  30. SourceData(const char* source, _Str filename, CompileMode mode) {
  31. source = strdup(source);
  32. // Skip utf8 BOM if there is any.
  33. if (strncmp(source, "\xEF\xBB\xBF", 3) == 0) source += 3;
  34. this->filename = filename;
  35. this->source = source;
  36. line_starts.push_back(source);
  37. this->mode = mode;
  38. }
  39. _Str snapshot(int lineno, const char* cursor=nullptr){
  40. _StrStream ss;
  41. ss << " " << "File \"" << filename << "\", line " << lineno << '\n';
  42. std::pair<const char*,const char*> pair = get_line(lineno);
  43. _Str line = "<?>";
  44. int removed_spaces = 0;
  45. if(pair.first && pair.second){
  46. line = _Str(pair.first, pair.second-pair.first).lstrip();
  47. removed_spaces = pair.second - pair.first - line.size();
  48. if(line.empty()) line = "<?>";
  49. }
  50. ss << " " << line;
  51. if(cursor && line != "<?>" && cursor >= pair.first && cursor <= pair.second){
  52. auto column = cursor - pair.first - removed_spaces;
  53. if(column >= 0) ss << "\n " << std::string(column, ' ') << "^";
  54. }
  55. return ss.str();
  56. }
  57. ~SourceData() { free((void*)source); }
  58. };
  59. class _Exception {
  60. _Str type;
  61. _Str msg;
  62. std::stack<_Str> stacktrace;
  63. public:
  64. _Exception(_Str type, _Str msg): type(type), msg(msg) {}
  65. bool match_type(const _Str& type) const { return this->type == type;}
  66. bool is_re = true;
  67. void st_push(_Str snapshot){
  68. if(stacktrace.size() >= 8) return;
  69. stacktrace.push(snapshot);
  70. }
  71. _Str summary() const {
  72. std::stack<_Str> st(stacktrace);
  73. _StrStream ss;
  74. if(is_re) ss << "Traceback (most recent call last):\n";
  75. while(!st.empty()) { ss << st.top() << '\n'; st.pop(); }
  76. ss << type << ": " << msg;
  77. return ss.str();
  78. }
  79. };