error.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "__stl__.h"
  3. #include "str.h"
  4. class NeedMoreLines {
  5. public:
  6. NeedMoreLines(bool isClassDef) : isClassDef(isClassDef) {}
  7. bool isClassDef;
  8. };
  9. enum CompileMode {
  10. EXEC_MODE,
  11. EVAL_MODE,
  12. SINGLE_MODE
  13. };
  14. struct SourceMetadata {
  15. const char* source;
  16. _Str filename;
  17. std::vector<const char*> lineStarts;
  18. CompileMode mode;
  19. _Str getLine(int lineno) const {
  20. if(lineno == -1) return "<?>";
  21. const char* _start = lineStarts.at(lineno-1);
  22. const char* i = _start;
  23. while(*i != '\n' && *i != '\0') i++;
  24. return _Str(_start, i-_start);
  25. }
  26. SourceMetadata(const char* source, _Str filename, CompileMode mode) {
  27. // Skip utf8 BOM if there is any.
  28. if (strncmp(source, "\xEF\xBB\xBF", 3) == 0) source += 3;
  29. this->filename = filename;
  30. this->source = source;
  31. lineStarts.push_back(source);
  32. this->mode = mode;
  33. }
  34. _Str snapshot(int lineno){
  35. _StrStream ss;
  36. ss << " " << "File \"" << filename << "\", line " << lineno << '\n';
  37. _Str line = getLine(lineno).__lstrip();
  38. if(line.empty()) line = "<?>";
  39. ss << " " << line << '\n';
  40. return ss.str();
  41. }
  42. };
  43. typedef std::shared_ptr<SourceMetadata> _Source;
  44. class _Error : public std::exception {
  45. private:
  46. _Str _what;
  47. public:
  48. _Error(_Str type, _Str msg, _Str desc){
  49. _what = desc + type + ": " + msg;
  50. }
  51. const char* what() const noexcept override {
  52. return _what.c_str();
  53. }
  54. };
  55. class CompileError : public _Error {
  56. public:
  57. CompileError(_Str type, _Str msg, _Str snapshot)
  58. : _Error(type, msg, snapshot) {}
  59. };
  60. class RuntimeError : public _Error {
  61. private:
  62. static _Str __concat(std::stack<_Str> snapshots){
  63. _StrStream ss;
  64. ss << "Traceback (most recent call last):" << '\n';
  65. while(!snapshots.empty()){
  66. ss << snapshots.top();
  67. snapshots.pop();
  68. }
  69. return ss.str();
  70. }
  71. public:
  72. RuntimeError(_Str type, _Str msg, std::stack<_Str> snapshots)
  73. : _Error(type, msg, __concat(snapshots)) {}
  74. };