-
Notifications
You must be signed in to change notification settings - Fork 0
/
try.go
98 lines (72 loc) · 1.77 KB
/
try.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
package jq
import (
"errors"
"fmt"
"nikand.dev/go/cbor"
)
type (
Try struct {
Expr Filter
Catch Filter
err bool
}
ErrorText string
ErrorExpr struct {
Expr Filter
}
)
func NewTry(expr, catch Filter) *Try { return &Try{Expr: expr, Catch: catch} }
func (f *Try) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
if !next {
f.err = false
}
if f.err {
return None, false, nil
}
e := csel[Filter](f.Expr != nil, f.Expr, Dot{})
res, more, err = e.ApplyTo(b, off, next)
if err == nil {
return res, more, nil
}
f.err = true
if f.Catch == nil {
return None, false, nil
}
res = b.AppendValue(err.Error())
return f.Catch.ApplyTo(b, res, false)
}
func NewErrorExpr(e Filter) ErrorExpr { return ErrorExpr{Expr: e} }
func (f ErrorExpr) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
if next {
return None, false, nil
}
if f.Expr == nil {
return None, false, fmt.Errorf("error of nil expression")
}
res, _, err = f.Expr.ApplyTo(b, off, false)
if err != nil {
return res, false, err
}
if res == None {
return None, false, nil
}
br := b.Reader()
tag := br.Tag(res)
switch tag {
case cbor.Bytes, cbor.String:
s := br.Bytes(res)
return None, false, errors.New(string(s))
}
return None, false, fmt.Errorf("not a string error: %+v", res)
}
func (f ErrorText) ApplyTo(b *Buffer, off Off, next bool) (res Off, more bool, err error) {
return None, false, errors.New(string(f))
}
func (f Try) String() string {
if f.Catch == nil {
return fmt.Sprintf("try %+v", f.Expr)
}
return fmt.Sprintf("try %+v catch %+v", f.Expr, f.Catch)
}
func (f ErrorText) String() string { return fmt.Sprintf(`error(%q)`, string(f)) }
func (f ErrorExpr) String() string { return fmt.Sprintf(`error(%+v)`, f.Expr) }