| 1 | // Copyright 2018 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package common |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "strings" |
| 20 | "unicode/utf8" |
| 21 | ) |
| 22 | |
| 23 | // NewError creates an error associated with an expression id with the given message at the given location. |
| 24 | func NewError(id int64, message string, location Location) *Error { |
| 25 | return &Error{Message: message, Location: location, ExprID: id} |
| 26 | } |
| 27 | |
| 28 | // Error type which references an expression id, a location within source, and a message. |
| 29 | type Error struct { |
| 30 | Location Location |
| 31 | Message string |
| 32 | ExprID int64 |
| 33 | } |
| 34 | |
| 35 | const ( |
| 36 | dot = "." |
| 37 | ind = "^" |
| 38 | wideDot = "\uff0e" |
| 39 | wideInd = "\uff3e" |
| 40 | |
| 41 | // maxSnippetLength is the largest number of characters which can be rendered in an error message snippet. |
| 42 | maxSnippetLength = 16384 |
| 43 | ) |
| 44 | |
| 45 | // ToDisplayString decorates the error message with the source location. |
| 46 | func (e *Error) ToDisplayString(source Source) string { |
| 47 | var result = fmt.Sprintf("ERROR: %s:%d:%d: %s", |
| 48 | source.Description(), |
| 49 | e.Location.Line(), |
| 50 | e.Location.Column()+1, // add one to the 0-based column for display |
| 51 | e.Message) |
| 52 | if snippet, found := source.Snippet(e.Location.Line()); found && len(snippet) <= maxSnippetLength { |
| 53 | snippet := strings.Replace(snippet, "\t", " ", -1) |
| 54 | srcLine := "\n | " + snippet |
| 55 | var bytes = []byte(snippet) |
| 56 | var indLine = "\n | " |
| 57 | for i := 0; i < e.Location.Column() && len(bytes) > 0; i++ { |
| 58 | _, sz := utf8.DecodeRune(bytes) |
| 59 | bytes = bytes[sz:] |
| 60 | if sz > 1 { |
| 61 | indLine += wideDot |
| 62 | } else { |
| 63 | indLine += dot |
| 64 | } |
| 65 | } |
| 66 | if _, sz := utf8.DecodeRune(bytes); sz > 1 { |
| 67 | indLine += wideInd |
| 68 | } else { |
| 69 | indLine += ind |
| 70 | } |
| 71 | result += srcLine + indLine |
| 72 | } |
| 73 | return result |
| 74 | } |