From 8bb321f8b032dfaeffbe3d1b8dfeb215c12d3642 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Mon, 18 Jul 2022 07:45:58 +0100 Subject: First public release --- errors/errors.go | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 errors/errors.go (limited to 'errors') diff --git a/errors/errors.go b/errors/errors.go new file mode 100644 index 0000000..a8d1eb0 --- /dev/null +++ b/errors/errors.go @@ -0,0 +1,106 @@ +package errors + +import ( + "fmt" + "strings" + + "usebox.net/lang/tokens" +) + +type ErrCode int + +const ( + Unimplemented ErrCode = iota + SyntaxError + IncompleteEscape + InvalidChar + ExpectedIdent + ExpectedType + AlreadyDeclared + Undefined + ExpectedSemicolon + ExpectedComma + ExpectedExpr + ExpectedLParen + ExpectedRParen + ExpectedLBrace + ExpectedRBrace + ExpectedIn + ExpectedRBracket + ExpectedAssign + ExpectedDefinition + AssignConst + FailedNumeric + InvalidOperation + InvalidValue + InvalidLength + InvalidIndex + InvalidType + TypeMismatch + InvalidTarget + UndefinedIdent + NotCallable + NotIndexable + NotStruct + InvalidNumberArgs + CallError + NoReturn + TailCallError + RecursiveStruct + Unexpected +) + +type Error struct { + Code ErrCode + Message string + Err error +} + +func (e Error) Error() string { + return e.Message +} + +func (e Error) Unwrap() error { + return e.Err +} + +func formatError(loc tokens.Location, msg ...string) string { + return fmt.Sprintf("%s:%d col %d error: %s", loc.File, loc.Line, loc.Column, strings.Join(msg, " ")) +} + +func NewError(code ErrCode, loc tokens.Location, msg ...string) error { + return Error{ + Code: code, + Message: formatError(loc, msg...), + } +} + +func NewErrorWrap(code ErrCode, loc tokens.Location, err error, msg ...string) error { + return Error{ + Code: code, + Message: formatError(loc, msg...), + Err: err, + } +} + +type ErrorList struct { + Errors []error +} + +func (el ErrorList) Error() string { + var b strings.Builder + var nerrors = len(el.Errors) + + for i := 0; i < nerrors; i++ { + fmt.Fprint(&b, el.Errors[i]) + if i == 10 { + fmt.Fprintf(&b, "\n...") + break + } + if i < nerrors-1 { + fmt.Fprintln(&b) + } + } + + return b.String() +} -- cgit v1.2.3