Created
March 2, 2021 00:00
-
-
Save kfsone/ba8ce89ef2227c4230f1a9b40e3fe329 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (e *Error) Error() string { | |
w := new(strings.Builder) | |
fmt.Fprintf(w, "%d:%d: error: ", e.ErrorToken.Pos.Line, e.ErrorToken.Pos.Column) | |
if e.Err != nil { | |
fmt.Fprint(w, e.Err) | |
} else { | |
if len(e.ExpectedTokens) == 1 { | |
// if there's only one expectation, don't describe it in list terms. | |
fmt.Fprint(w, "expected ", e.ExpectedTokens[0]) | |
} else if len(e.ExpectedTokens) == 2 { | |
// for two, use a simple "either" expression | |
fmt.Fprint(w, "expected either ", e.ExpectedTokens[0], " or ", e.ExpectedTokens[1]) | |
} else { | |
// for a plurality > 2, use the expression "expected one of" and use an oxford comma to | |
// conclude the list. | |
fmt.Fprintf(w, "expected one of: ") | |
expected := make([]string, len(e.ExpectedTokens)) | |
for idx, tok := range e.ExpectedTokens { | |
switch idx { | |
case 0: | |
// noop | |
default: | |
if idx == len(expected) - 1 { | |
fmt.Fprint(w, ", or ") | |
} else { | |
fmt.Fprint(w, ", ") | |
} | |
} | |
fmt.Fprint(w, tok) | |
} | |
} | |
fmt.Fprint(w, "; got: ", string(e.ErrorToken.Lit)) | |
} | |
return w.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment