Ben Clayton | 27f480b | 2022-04-29 11:06:34 +0000 | [diff] [blame] | 1 | // Copyright 2022 The Dawn Authors |
| 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 expectations |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
Ben Clayton | aad2e9c | 2022-09-17 19:30:29 +0000 | [diff] [blame] | 19 | "io" |
Ben Clayton | 27f480b | 2022-04-29 11:06:34 +0000 | [diff] [blame] | 20 | "strings" |
| 21 | ) |
| 22 | |
| 23 | // Severity is an enumerator of diagnostic severity |
| 24 | type Severity string |
| 25 | |
| 26 | const ( |
| 27 | Error Severity = "error" |
| 28 | Warning Severity = "warning" |
| 29 | Note Severity = "note" |
| 30 | ) |
| 31 | |
| 32 | // Diagnostic holds a line, column, message and severity. |
| 33 | // Diagnostic also implements the 'error' interface. |
| 34 | type Diagnostic struct { |
| 35 | Severity Severity |
| 36 | Line int // 1-based |
| 37 | Column int // 1-based |
| 38 | Message string |
| 39 | } |
| 40 | |
| 41 | func (e Diagnostic) String() string { |
| 42 | sb := &strings.Builder{} |
| 43 | if e.Line > 0 { |
| 44 | fmt.Fprintf(sb, "%v", e.Line) |
| 45 | if e.Column > 0 { |
| 46 | fmt.Fprintf(sb, ":%v", e.Column) |
| 47 | } |
| 48 | sb.WriteString(" ") |
| 49 | } |
| 50 | sb.WriteString(string(e.Severity)) |
| 51 | sb.WriteString(": ") |
| 52 | sb.WriteString(e.Message) |
| 53 | return sb.String() |
| 54 | } |
| 55 | |
| 56 | // Error implements the 'error' interface. |
| 57 | func (e Diagnostic) Error() string { return e.String() } |
Ben Clayton | aad2e9c | 2022-09-17 19:30:29 +0000 | [diff] [blame] | 58 | |
| 59 | // Diagnostics is a list of diagnostic |
| 60 | type Diagnostics []Diagnostic |
| 61 | |
| 62 | // NumErrors returns number of errors in the diagnostics |
| 63 | func (l Diagnostics) NumErrors() int { |
| 64 | count := 0 |
| 65 | for _, d := range l { |
| 66 | if d.Severity == Error { |
| 67 | count++ |
| 68 | } |
| 69 | } |
| 70 | return count |
| 71 | } |
| 72 | |
| 73 | // Print prints the list of diagnostics to 'w' |
| 74 | func (l Diagnostics) Print(w io.Writer, path string) { |
| 75 | for _, d := range l { |
| 76 | fmt.Fprintf(w, "%v:%v %v\n", path, d.Line, d.Message) |
| 77 | } |
| 78 | } |