forked from elves/elvish
/
exception.go
233 lines (205 loc) · 5.34 KB
/
exception.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package eval
import (
"bytes"
"fmt"
"strconv"
"strings"
"syscall"
"unsafe"
"github.com/elves/elvish/eval/types"
"github.com/elves/elvish/parse"
"github.com/elves/elvish/util"
"github.com/xiaq/persistent/hash"
)
// Exception represents an elvish exception. It is both a Value accessible to
// elvishscript, and the type of error returned by public facing evaluation
// methods like (*Evaler)PEval.
type Exception struct {
Cause error
Traceback *util.SourceRange
}
// OK is a pointer to the zero value of Exception, representing the absence of
// exception.
var OK = &Exception{}
func (exc *Exception) Error() string {
return exc.Cause.Error()
}
func (exc *Exception) Pprint(indent string) string {
buf := new(bytes.Buffer)
var causeDescription string
if pprinter, ok := exc.Cause.(util.Pprinter); ok {
causeDescription = pprinter.Pprint(indent)
} else {
causeDescription = "\033[31;1m" + exc.Cause.Error() + "\033[m"
}
fmt.Fprintf(buf, "Exception: %s\n", causeDescription)
if exc.Traceback.Next == nil {
buf.WriteString(exc.Traceback.PprintCompact(indent))
} else {
buf.WriteString(indent + "Traceback:")
for tb := exc.Traceback; tb != nil; tb = tb.Next {
buf.WriteString("\n" + indent + " ")
buf.WriteString(tb.Pprint(indent + " "))
}
}
if pipeExcs, ok := exc.Cause.(PipelineError); ok {
buf.WriteString("\n" + indent + "Caused by:")
for _, e := range pipeExcs.Errors {
if e == OK {
continue
}
buf.WriteString("\n" + indent + " " + e.Pprint(indent+" "))
}
}
return buf.String()
}
func (exc *Exception) Kind() string {
return "exception"
}
func (exc *Exception) Repr(indent int) string {
if exc.Cause == nil {
return "$ok"
}
if r, ok := exc.Cause.(types.Reprer); ok {
return r.Repr(indent)
}
return "?(fail " + parse.Quote(exc.Cause.Error()) + ")"
}
// Equal compares by identity.
func (exc *Exception) Equal(rhs interface{}) bool {
return exc == rhs
}
func (exc *Exception) Hash() uint32 {
return hash.Pointer(unsafe.Pointer(exc))
}
func (exc *Exception) Bool() bool {
return exc.Cause == nil
}
// PipelineError represents the errors of pipelines, in which multiple commands
// may error.
type PipelineError struct {
Errors []*Exception
}
func (pe PipelineError) Repr(indent int) string {
// TODO Make a more generalized ListReprBuilder and use it here.
b := new(bytes.Buffer)
b.WriteString("?(multi-error")
elemIndent := indent + len("?(multi-error ")
for _, e := range pe.Errors {
if indent > 0 {
b.WriteString("\n" + strings.Repeat(" ", elemIndent))
} else {
b.WriteString(" ")
}
b.WriteString(e.Repr(elemIndent))
}
b.WriteString(")")
return b.String()
}
func (pe PipelineError) Error() string {
b := new(bytes.Buffer)
b.WriteString("(")
for i, e := range pe.Errors {
if i > 0 {
b.WriteString(" | ")
}
if e == nil || e.Cause == nil {
b.WriteString("<nil>")
} else {
b.WriteString(e.Error())
}
}
b.WriteString(")")
return b.String()
}
// ComposeExceptionsFromPipeline takes a slice of Exception pointers and
// composes a suitable error. If all elements of the slice are either nil or OK,
// a nil is returned. If there is exactly non-nil non-OK Exception, it is
// returned. Otherwise, a PipelineError built from the slice is returned, with
// nil items turned into OK's for easier access from elvishscript.
func ComposeExceptionsFromPipeline(excs []*Exception) error {
newexcs := make([]*Exception, len(excs))
notOK, lastNotOK := 0, 0
for i, e := range excs {
if e == nil {
newexcs[i] = OK
} else {
newexcs[i] = e
if e.Cause != nil {
notOK++
lastNotOK = i
}
}
}
switch notOK {
case 0:
return nil
case 1:
return newexcs[lastNotOK]
default:
return PipelineError{newexcs}
}
}
// Flow is a special type of error used for control flows.
type Flow uint
// Control flows.
const (
Return Flow = iota
Break
Continue
)
var flowNames = [...]string{
"return", "break", "continue",
}
func (f Flow) Repr(int) string {
return "?(" + f.Error() + ")"
}
func (f Flow) Error() string {
if f >= Flow(len(flowNames)) {
return fmt.Sprintf("!(BAD FLOW: %v)", f)
}
return flowNames[f]
}
func (f Flow) Pprint(string) string {
return "\033[33;1m" + f.Error() + "\033[m"
}
// ExternalCmdExit contains the exit status of external commands. If the
// command was stopped rather than terminated, the Pid field contains the pid
// of the process.
type ExternalCmdExit struct {
syscall.WaitStatus
CmdName string
Pid int
}
func NewExternalCmdExit(name string, ws syscall.WaitStatus, pid int) error {
if ws.Exited() && ws.ExitStatus() == 0 {
return nil
}
if !ws.Stopped() {
pid = 0
}
return ExternalCmdExit{ws, name, pid}
}
func (exit ExternalCmdExit) Error() string {
ws := exit.WaitStatus
quotedName := parse.Quote(exit.CmdName)
switch {
case ws.Exited():
return quotedName + " exited with " + strconv.Itoa(ws.ExitStatus())
case ws.Signaled():
causeDescription := quotedName + " killed by signal " + ws.Signal().String()
if ws.CoreDump() {
causeDescription += " (core dumped)"
}
return causeDescription
case ws.Stopped():
causeDescription := quotedName + " stopped by signal " + fmt.Sprintf("%s (pid=%d)", ws.StopSignal(), exit.Pid)
trap := ws.TrapCause()
if trap != -1 {
causeDescription += fmt.Sprintf(" (trapped %v)", trap)
}
return causeDescription
default:
return fmt.Sprint(quotedName, " has unknown WaitStatus ", ws)
}
}