github.com/elves/elvish@v0.15.0/pkg/eval/errs/errs.go (about)

     1  // Package errs declares error types used as exception causes.
     2  package errs
     3  
     4  import (
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  // OutOfRange encodes an error where a value is out of its valid range.
    10  type OutOfRange struct {
    11  	What      string
    12  	ValidLow  string
    13  	ValidHigh string
    14  	Actual    string
    15  }
    16  
    17  func (e OutOfRange) Error() string {
    18  	if e.ValidHigh < e.ValidLow {
    19  		return fmt.Sprintf(
    20  			"out of range: %v has no valid value, but is %v", e.What, e.Actual)
    21  	}
    22  	return fmt.Sprintf(
    23  		"out of range: %s must be from %s to %s, but is %s",
    24  		e.What, e.ValidLow, e.ValidHigh, e.Actual)
    25  }
    26  
    27  // BadValue encodes an error where the value does not meet a requirement. For
    28  // out-of-range erros, use OutOfRange.
    29  type BadValue struct {
    30  	What   string
    31  	Valid  string
    32  	Actual string
    33  }
    34  
    35  func (e BadValue) Error() string {
    36  	return fmt.Sprintf(
    37  		"bad value: %v must be %v, but is %v", e.What, e.Valid, e.Actual)
    38  }
    39  
    40  // ArityMismatch encodes an error where the expected number of values is out of
    41  // the valid range.
    42  type ArityMismatch struct {
    43  	What      string
    44  	ValidLow  int
    45  	ValidHigh int
    46  	Actual    int
    47  }
    48  
    49  func (e ArityMismatch) Error() string {
    50  	switch {
    51  	case e.ValidHigh == e.ValidLow:
    52  		return fmt.Sprintf("arity mismatch: %v must be %v, but is %v",
    53  			e.What, nValues(e.ValidLow), nValues(e.Actual))
    54  	case e.ValidHigh == -1:
    55  		return fmt.Sprintf("arity mismatch: %v must be %v or more values, but is %v",
    56  			e.What, e.ValidLow, nValues(e.Actual))
    57  	default:
    58  		return fmt.Sprintf("arity mismatch: %v must be %v to %v values, but is %v",
    59  			e.What, e.ValidLow, e.ValidHigh, nValues(e.Actual))
    60  	}
    61  }
    62  
    63  func nValues(n int) string {
    64  	if n == 1 {
    65  		return "1 value"
    66  	}
    67  	return strconv.Itoa(n) + " values"
    68  }