github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/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 // Error implements the error interface. 18 func (e OutOfRange) Error() string { 19 if e.ValidHigh < e.ValidLow { 20 return fmt.Sprintf( 21 "out of range: %v has no valid value, but is %v", e.What, e.Actual) 22 } 23 return fmt.Sprintf( 24 "out of range: %s must be from %s to %s, but is %s", 25 e.What, e.ValidLow, e.ValidHigh, e.Actual) 26 } 27 28 // BadValue encodes an error where the value does not meet a requirement. For 29 // out-of-range erros, use OutOfRange. 30 type BadValue struct { 31 What string 32 Valid string 33 Actual string 34 } 35 36 // Error implements the error interface. 37 func (e BadValue) Error() string { 38 return fmt.Sprintf( 39 "bad value: %v must be %v, but is %v", e.What, e.Valid, e.Actual) 40 } 41 42 // ArityMismatch encodes an error where the expected number of values is out of 43 // the valid range. 44 type ArityMismatch struct { 45 What string 46 ValidLow int 47 ValidHigh int 48 Actual int 49 } 50 51 func (e ArityMismatch) Error() string { 52 switch { 53 case e.ValidHigh == e.ValidLow: 54 return fmt.Sprintf("arity mismatch: %v must be %v, but is %v", 55 e.What, nValues(e.ValidLow), nValues(e.Actual)) 56 case e.ValidHigh == -1: 57 return fmt.Sprintf("arity mismatch: %v must be %v or more values, but is %v", 58 e.What, e.ValidLow, nValues(e.Actual)) 59 default: 60 return fmt.Sprintf("arity mismatch: %v must be %v to %v values, but is %v", 61 e.What, e.ValidLow, e.ValidHigh, nValues(e.Actual)) 62 } 63 } 64 65 func nValues(n int) string { 66 if n == 1 { 67 return "1 value" 68 } 69 return strconv.Itoa(n) + " values" 70 } 71 72 // SetReadOnlyVar is returned by the Set method of a read-only variable. 73 type SetReadOnlyVar struct { 74 // Name of the read-only variable. This fiels is initially empty, and 75 // populated later when context information is available. 76 VarName string 77 } 78 79 // Error implements the error interface. 80 func (e SetReadOnlyVar) Error() string { 81 return fmt.Sprintf("cannot set read-only variable %q", e.VarName) 82 }