github.com/jhump/protocompile@v0.0.0-20221021153901-4f6f732835e8/reporter/errors.go (about)

     1  package reporter
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  
     7  	"github.com/jhump/protocompile/ast"
     8  )
     9  
    10  // ErrInvalidSource is a sentinel error that is returned by compilation and
    11  // stand-alone compilation steps (such as parsing, linking) when one or more
    12  // errors is reported but the configured ErrorReporter always returns nil.
    13  var ErrInvalidSource = errors.New("parse failed: invalid proto source")
    14  
    15  // ErrorWithPos is an error about a proto source file that adds information
    16  // about the location in the file that caused the error.
    17  type ErrorWithPos interface {
    18  	error
    19  	// GetPosition returns the source position that caused the underlying error.
    20  	GetPosition() ast.SourcePos
    21  	// Unwrap returns the underlying error.
    22  	Unwrap() error
    23  }
    24  
    25  // Error creates a new ErrorWithPos from the given error and source position.
    26  func Error(pos ast.SourcePos, err error) ErrorWithPos {
    27  	return errorWithSourcePos{pos: pos, underlying: err}
    28  }
    29  
    30  // Errorf creates a new ErrorWithPos whose underlying error is created using the
    31  // given message format and arguments (via fmt.Errorf).
    32  func Errorf(pos ast.SourcePos, format string, args ...interface{}) ErrorWithPos {
    33  	return errorWithSourcePos{pos: pos, underlying: fmt.Errorf(format, args...)}
    34  }
    35  
    36  type errorWithSourcePos struct {
    37  	underlying error
    38  	pos        ast.SourcePos
    39  }
    40  
    41  func (e errorWithSourcePos) Error() string {
    42  	sourcePos := e.GetPosition()
    43  	return fmt.Sprintf("%s: %v", sourcePos, e.underlying)
    44  }
    45  
    46  func (e errorWithSourcePos) GetPosition() ast.SourcePos {
    47  	return e.pos
    48  }
    49  
    50  func (e errorWithSourcePos) Unwrap() error {
    51  	return e.underlying
    52  }
    53  
    54  var _ ErrorWithPos = errorWithSourcePos{}