| 1 |
// Copyright 2017 Google LLC. All Rights Reserved. |
| 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 compiler |
| 16 |
|
| 17 |
import "fmt" |
| 18 |
|
| 19 |
// Error represents compiler errors and their location in the document. |
| 20 |
type Error struct { |
| 21 |
Context *Context |
| 22 |
Message string |
| 23 |
} |
| 24 |
|
| 25 |
// NewError creates an Error. |
| 26 |
func NewError(context *Context, message string) *Error { |
| 27 |
return &Error{Context: context, Message: message} |
| 28 |
} |
| 29 |
|
| 30 |
func (err *Error) locationDescription() string { |
| 31 |
if err.Context.Node != nil { |
| 32 |
return fmt.Sprintf("[%d,%d] %s", err.Context.Node.Line, err.Context.Node.Column, err.Context.Description()) |
| 33 |
} |
| 34 |
return err.Context.Description() |
| 35 |
} |
| 36 |
|
| 37 |
// Error returns the string value of an Error. |
| 38 |
func (err *Error) Error() string { |
| 39 |
if err.Context == nil { |
| 40 |
return err.Message |
| 41 |
} |
| 42 |
return err.locationDescription() + " " + err.Message |
| 43 |
} |
| 44 |
|
| 45 |
// ErrorGroup is a container for groups of Error values. |
| 46 |
type ErrorGroup struct { |
| 47 |
Errors []error |
| 48 |
} |
| 49 |
|
| 50 |
// NewErrorGroupOrNil returns a new ErrorGroup for a slice of errors or nil if the slice is empty. |
| 51 |
func NewErrorGroupOrNil(errors []error) error { |
| 52 |
if len(errors) == 0 { |
| 53 |
return nil |
| 54 |
} else if len(errors) == 1 { |
| 55 |
return errors[0] |
| 56 |
} else { |
| 57 |
return &ErrorGroup{Errors: errors} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
func (group *ErrorGroup) Error() string { |
| 62 |
result := "" |
| 63 |
for i, err := range group.Errors { |
| 64 |
if i > 0 { |
| 65 |
result += "\n" |
| 66 |
} |
| 67 |
result += err.Error() |
| 68 |
} |
| 69 |
return result |
| 70 |
} |