error.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <stdexcept>
  5. #include "str.h"
  6. class NeedMoreLines : public std::exception {
  7. public:
  8. NeedMoreLines(bool isClassDef) : isClassDef(isClassDef) {}
  9. bool isClassDef;
  10. };
  11. class _Error : public std::exception {
  12. private:
  13. _Str _what;
  14. public:
  15. _Error(_Str type, _Str msg, _Str desc){
  16. _what = desc + type + ": " + msg;
  17. }
  18. const char* what() const noexcept override {
  19. return _what;
  20. }
  21. };
  22. struct LineSnapshot {
  23. _Str filename;
  24. int lineno;
  25. _Str source;
  26. _Str str() const {
  27. _StrStream ss;
  28. ss << " " << "File \"" << filename << "\", line " << lineno << '\n';
  29. ss << " " << source << '\n';
  30. return ss.str();
  31. }
  32. };
  33. class CompileError : public _Error {
  34. public:
  35. CompileError(_Str type, _Str msg, const LineSnapshot& snapshot)
  36. : _Error(type, msg, snapshot.str()) {}
  37. };
  38. class RuntimeError : public _Error {
  39. private:
  40. static _Str __concat(std::stack<LineSnapshot> snapshots){
  41. _StrStream ss;
  42. ss << "Traceback (most recent call last):" << '\n';
  43. while(!snapshots.empty()){
  44. ss << snapshots.top().str();
  45. snapshots.pop();
  46. }
  47. return ss.str();
  48. }
  49. public:
  50. RuntimeError(_Str type, _Str msg, std::stack<LineSnapshot> snapshots)
  51. : _Error(type, msg, __concat(snapshots)) {}
  52. };
  53. class UnexpectedError : public _Error {
  54. public:
  55. UnexpectedError(_Str msg)
  56. : _Error("UnexpectedError", msg, "") {}
  57. };