error.go 1.8 KB

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