error.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #pragma once
  2. #include "safestl.h"
  3. class NeedMoreLines {
  4. public:
  5. NeedMoreLines(bool isClassDef) : isClassDef(isClassDef) {}
  6. bool isClassDef;
  7. };
  8. enum CompileMode {
  9. EXEC_MODE,
  10. EVAL_MODE,
  11. SINGLE_MODE // for REPL
  12. };
  13. struct SourceMetadata {
  14. const char* source;
  15. _Str filename;
  16. std::vector<const char*> lineStarts;
  17. CompileMode mode;
  18. _Str getLine(int lineno) const {
  19. if(lineno == -1) return "<?>";
  20. const char* _start = lineStarts.at(lineno-1);
  21. const char* i = _start;
  22. while(*i != '\n' && *i != '\0') i++;
  23. return _Str(_start, i-_start);
  24. }
  25. SourceMetadata(const char* source, _Str filename, CompileMode mode) {
  26. source = strdup(source);
  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. ~SourceMetadata(){
  43. free((void*)source);
  44. }
  45. };
  46. typedef std::shared_ptr<SourceMetadata> _Source;
  47. class _Error : public std::exception {
  48. private:
  49. _Str _what;
  50. public:
  51. _Error(_Str type, _Str msg, _Str desc){
  52. _what = desc + type + ": " + msg;
  53. }
  54. const char* what() const noexcept override {
  55. return _what.c_str();
  56. }
  57. };
  58. class CompileError : public _Error {
  59. public:
  60. CompileError(_Str type, _Str msg, _Str snapshot)
  61. : _Error(type, msg, snapshot) {}
  62. };
  63. class RuntimeError : public _Error {
  64. private:
  65. static _Str __concat(std::stack<_Str> snapshots){
  66. _StrStream ss;
  67. ss << "Traceback (most recent call last):" << '\n';
  68. while(!snapshots.empty()){
  69. ss << snapshots.top();
  70. snapshots.pop();
  71. }
  72. return ss.str();
  73. }
  74. public:
  75. RuntimeError(_Str type, _Str msg, const std::stack<_Str>& snapshots)
  76. : _Error(type, msg, __concat(snapshots)) {}
  77. };