behavior-contracts 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +20 -0
  2. package/dist/authoring.d.ts +4 -4
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +11 -23
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/behavior.d.ts +3 -3
  7. package/dist/behavior.d.ts.map +1 -1
  8. package/dist/behavior.js +7 -10
  9. package/dist/behavior.js.map +1 -1
  10. package/dist/generator/emit-native-dynamic.d.ts.map +1 -1
  11. package/dist/generator/emit-native-dynamic.js +7 -4
  12. package/dist/generator/emit-native-dynamic.js.map +1 -1
  13. package/dist/generator/emit-shared-typescript.d.ts.map +1 -1
  14. package/dist/generator/emit-shared-typescript.js +15 -20
  15. package/dist/generator/emit-shared-typescript.js.map +1 -1
  16. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  17. package/dist/generator/emit-typed-native-go.js +19 -11
  18. package/dist/generator/emit-typed-native-go.js.map +1 -1
  19. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  20. package/dist/generator/emit-typed-native-rust.js +10 -10
  21. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  22. package/go/api_test.go +675 -0
  23. package/go/behavior.go +1202 -0
  24. package/go/cmd/conformance/main.go +40 -0
  25. package/go/codec.go +170 -0
  26. package/go/coderuntime/behaviorcore.go +93 -0
  27. package/go/coderuntime/canonical.go +287 -0
  28. package/go/coderuntime/exprcore.go +334 -0
  29. package/go/coderuntime/plan.go +422 -0
  30. package/go/coderuntime/primitives.go +383 -0
  31. package/go/coderuntime/rawabi.go +281 -0
  32. package/go/coderuntime/spec.go +17 -0
  33. package/go/coderuntime/template.go +139 -0
  34. package/go/coderuntime/value.go +138 -0
  35. package/go/coderuntime/version.go +9 -0
  36. package/go/compat.go +289 -0
  37. package/go/conformance.go +1046 -0
  38. package/go/envelope.go +77 -0
  39. package/go/expr.go +347 -0
  40. package/go/fingerprint.go +147 -0
  41. package/go/fingerprint_test.go +94 -0
  42. package/go/go.mod +3 -0
  43. package/go/guard.go +538 -0
  44. package/go/jsonord.go +151 -0
  45. package/go/plan_parallel_test.go +279 -0
  46. package/go/primitives_test.go +227 -0
  47. package/package.json +5 -2
@@ -0,0 +1,40 @@
1
+ // Command conformance runs the dsl-contracts conformance kit (Go runner).
2
+ //
3
+ // go run ./cmd/conformance
4
+ //
5
+ // Loads ../../conformance/vectors/*.json (or $DSL_CONTRACTS_VECTORS), runs all 7
6
+ // suites, and exits 0 (all pass) / 1 (any fail) / 2 (spec-version mismatch,
7
+ // pre-flight fail-closed).
8
+ package main
9
+
10
+ import (
11
+ "os"
12
+ "path/filepath"
13
+ "runtime"
14
+
15
+ dslcontracts "github.com/foo-ogawa/behavior-contracts/go"
16
+ )
17
+
18
+ func vectorsDir() string {
19
+ if env := os.Getenv("DSL_CONTRACTS_VECTORS"); env != "" {
20
+ return env
21
+ }
22
+ // this file: <repo>/go/cmd/conformance/main.go ; vectors at <repo>/conformance/vectors
23
+ _, file, _, ok := runtime.Caller(0)
24
+ if ok {
25
+ repo := filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(file))))
26
+ return filepath.Join(repo, "conformance", "vectors")
27
+ }
28
+ return filepath.Join("..", "..", "..", "conformance", "vectors")
29
+ }
30
+
31
+ func main() {
32
+ failed, mismatch := dslcontracts.RunConformance(vectorsDir(), os.Stdout)
33
+ if mismatch {
34
+ os.Exit(2)
35
+ }
36
+ if failed > 0 {
37
+ os.Exit(1)
38
+ }
39
+ os.Exit(0)
40
+ }
package/go/codec.go ADDED
@@ -0,0 +1,170 @@
1
+ package dslcontracts
2
+
3
+ import (
4
+ "encoding/json"
5
+ "fmt"
6
+ "strconv"
7
+ "strings"
8
+ )
9
+
10
+ // DecodeFailure is a decode error that carries a stable conformance Failure code
11
+ // for normative fail-closed cases (e.g. FORBIDDEN_KEY for a "__proto__" own key).
12
+ // Plain malformed-wire errors use fmt.Errorf and have no code.
13
+ type DecodeFailure struct {
14
+ Code string
15
+ Msg string
16
+ }
17
+
18
+ func (e *DecodeFailure) Error() string { return e.Code + ": " + e.Msg }
19
+
20
+ // DecodeValue converts the golden-vector typed wire encoding (a JNode) into a
21
+ // runtime Value (expression-ir.md §2.3 inverse map):
22
+ //
23
+ // bare JSON number -> integral => int64, fractional => float64
24
+ // {"int":"…"} -> int64 (decimal string)
25
+ // {"float":n} -> float64 (explicit integral-valued float)
26
+ // {"nan"} -> NaN
27
+ // {"inf":±1} -> ±Inf
28
+ func DecodeValue(x JNode) (Value, error) {
29
+ switch v := x.(type) {
30
+ case nil:
31
+ return nil, nil
32
+ case bool:
33
+ return v, nil
34
+ case string:
35
+ return v, nil
36
+ case json.Number:
37
+ return decodeNumber(v)
38
+ case []JNode:
39
+ out := make([]Value, 0, len(v))
40
+ for _, e := range v {
41
+ dv, err := DecodeValue(e)
42
+ if err != nil {
43
+ return nil, err
44
+ }
45
+ out = append(out, dv)
46
+ }
47
+ return out, nil
48
+ case *JObj:
49
+ if v.Len() == 1 {
50
+ k := v.Keys[0]
51
+ raw := v.Vals[k]
52
+ switch k {
53
+ case "int":
54
+ s, ok := raw.(string)
55
+ if !ok {
56
+ return nil, fmt.Errorf("{int:…} expects a string")
57
+ }
58
+ i, err := strconv.ParseInt(s, 10, 64)
59
+ if err != nil {
60
+ return nil, fmt.Errorf("int literal %q not int64", s)
61
+ }
62
+ return i, nil
63
+ case "float":
64
+ n, ok := raw.(json.Number)
65
+ if !ok {
66
+ return nil, fmt.Errorf("{float:…} expects a number")
67
+ }
68
+ f, err := n.Float64()
69
+ if err != nil {
70
+ return nil, err
71
+ }
72
+ return f, nil
73
+ case "nan":
74
+ return nan(), nil
75
+ case "inf":
76
+ sign := 1.0
77
+ if n, ok := raw.(json.Number); ok {
78
+ if f, err := n.Float64(); err == nil {
79
+ sign = f
80
+ }
81
+ }
82
+ if sign < 0 {
83
+ return negInf(), nil
84
+ }
85
+ return posInf(), nil
86
+ }
87
+ }
88
+ out := NewObj()
89
+ for _, k := range v.Keys {
90
+ // fail-closed: own key "__proto__" diverges across languages
91
+ // (expression-ir.md §2.3/§8).
92
+ if k == ForbiddenObjectKey {
93
+ return nil, &DecodeFailure{Code: "FORBIDDEN_KEY", Msg: fmt.Sprintf("object key %q is forbidden (fail-closed)", ForbiddenObjectKey)}
94
+ }
95
+ dv, err := DecodeValue(v.Vals[k])
96
+ if err != nil {
97
+ return nil, err
98
+ }
99
+ out.Set(k, dv)
100
+ }
101
+ return out, nil
102
+ default:
103
+ return nil, fmt.Errorf("cannot decode value: %T", x)
104
+ }
105
+ }
106
+
107
+ // decodeNumber classifies a bare JSON number: integral (no '.'/'e') => int64,
108
+ // otherwise => float64 (PROTOCOL §2).
109
+ func decodeNumber(n json.Number) (Value, error) {
110
+ s := n.String()
111
+ if !strings.ContainsAny(s, ".eE") {
112
+ i, err := strconv.ParseInt(s, 10, 64)
113
+ if err != nil {
114
+ return nil, fmt.Errorf("integer %s exceeds int64", s)
115
+ }
116
+ return i, nil
117
+ }
118
+ f, err := n.Float64()
119
+ if err != nil {
120
+ return nil, err
121
+ }
122
+ return f, nil
123
+ }
124
+
125
+ // EncodeValue renders a runtime Value back into a compact wire-encoded JSON
126
+ // string (for diagnostics on a failing vector; mirrors TS encodeValue).
127
+ func EncodeValue(v Value) string {
128
+ switch t := v.(type) {
129
+ case nil:
130
+ return "null"
131
+ case bool:
132
+ if t {
133
+ return "true"
134
+ }
135
+ return "false"
136
+ case string:
137
+ b, _ := json.Marshal(t)
138
+ return string(b)
139
+ case int64:
140
+ const safe = int64(9007199254740991) // 2^53 - 1
141
+ if t >= -safe && t <= safe {
142
+ return strconv.FormatInt(t, 10)
143
+ }
144
+ return fmt.Sprintf("{\"int\":%q}", strconv.FormatInt(t, 10))
145
+ case float64:
146
+ r, err := pyFloatRepr(t)
147
+ if err != nil {
148
+ return "NaN/Inf"
149
+ }
150
+ if t == float64(int64(t)) && !isNaN(t) {
151
+ return fmt.Sprintf("{\"float\":%s}", r)
152
+ }
153
+ return r
154
+ case []Value:
155
+ parts := make([]string, len(t))
156
+ for i, e := range t {
157
+ parts[i] = EncodeValue(e)
158
+ }
159
+ return "[" + strings.Join(parts, ",") + "]"
160
+ case *Obj:
161
+ parts := make([]string, 0, t.Len())
162
+ for _, k := range t.Keys {
163
+ kb, _ := json.Marshal(k)
164
+ parts = append(parts, string(kb)+":"+EncodeValue(t.Vals[k]))
165
+ }
166
+ return "{" + strings.Join(parts, ",") + "}"
167
+ default:
168
+ return "?"
169
+ }
170
+ }
@@ -0,0 +1,93 @@
1
+ package coderuntime
2
+
3
+ // behaviorcore.go — the native (non-IR) part of the RunBehavior surface, split
4
+ // out of the parent package's behavior.go so the JSON-free codegen surface owns
5
+ // it: the coded BehaviorFailure, the boundary-injected handler seams
6
+ // (ComponentExec / ComponentCtxExec) and their dispatch discipline, and the
7
+ // exec-internal failure precedence restore (bc#23) that straight-line generated
8
+ // code shares with the RunBehavior interpreter. The component-graph IR walk
9
+ // itself (RunBehavior) stays in the parent package — it consumes IR (JNode) and
10
+ // must not enter a codegen consumer's compile unit.
11
+
12
+ import "sort"
13
+
14
+ // BehaviorFailure is a RunBehavior failure with a stable code (in addition to the
15
+ // plan/expression failure codes that RunBehavior may surface).
16
+ type BehaviorFailure struct {
17
+ Code string
18
+ Msg string
19
+ Detail *ErrorDetail
20
+ }
21
+
22
+ func (e *BehaviorFailure) Error() string { return e.Code + ": " + e.Msg }
23
+
24
+ func behaviorFail(code, msg string) *BehaviorFailure { return &BehaviorFailure{Code: code, Msg: msg} }
25
+
26
+ // ComponentExec is the boundary-injected handler registry seam (§7.1). Exec resolves
27
+ // a catalog name to a leaf implementation and runs it with the evaluated ports (+ the
28
+ // map element bound value, if any). It returns (outcome, true) on resolution, or
29
+ // (_, false) when the name is unknown so RunBehavior can fail closed with
30
+ // UNKNOWN_COMPONENT.
31
+ type ComponentExec interface {
32
+ Exec(component string, ports *Obj, bound Value) (ExecOutcome, bool)
33
+ }
34
+
35
+ // ComponentCtxExec is an optional extension of ComponentExec (behaviorVersion 2).
36
+ // When the injected handler registry also implements it, RunBehavior calls ExecCtx
37
+ // for every handler invocation, carrying the handler ctx (nodeID = body node id,
38
+ // component = catalog name) for error context / tracing. Additive: registries that
39
+ // only implement ComponentExec keep working unchanged.
40
+ type ComponentCtxExec interface {
41
+ ExecCtx(nodeID, component string, ports *Obj, bound Value) (ExecOutcome, bool)
42
+ }
43
+
44
+ // execHandler dispatches to ExecCtx when available, else falls back to Exec.
45
+ func execHandler(handlers ComponentExec, nodeID, component string, ports *Obj, bound Value) (ExecOutcome, bool) {
46
+ if hc, ok := handlers.(ComponentCtxExec); ok {
47
+ return hc.ExecCtx(nodeID, component, ports, bound)
48
+ }
49
+ return handlers.Exec(component, ports, bound)
50
+ }
51
+
52
+ // firstExecErrInVisitOrder restores the sequential precedence of exec-internal
53
+ // failures (bc#23). It scans ops in plan visit order (stages in plan order,
54
+ // ascending index within a stage; 1 op = 1 stage when plan is nil) up to and
55
+ // including the op that raised planErr (all ops when planErr is nil or not
56
+ // attributable), and returns the first recorded exec-internal error, if any.
57
+ func firstExecErrInVisitOrder(execErrs []error, plan *ExecutionPlanSpec, n int, planErr error) error {
58
+ var stages [][]int
59
+ if plan != nil {
60
+ stages = plan.Groups
61
+ } else {
62
+ stages = make([][]int, n)
63
+ for i := 0; i < n; i++ {
64
+ stages[i] = []int{i}
65
+ }
66
+ }
67
+
68
+ unwindOp := -1 // -1 = plan completed (or failure not attributable to an op)
69
+ if planErr != nil {
70
+ pf, ok := planErr.(*PlanFailure)
71
+ if !ok {
72
+ return nil
73
+ }
74
+ if pf.OpIndex < 0 {
75
+ return nil // INVALID_PLAN etc.: no exec ran
76
+ }
77
+ unwindOp = pf.OpIndex
78
+ }
79
+
80
+ for _, stage := range stages {
81
+ ordered := append([]int(nil), stage...)
82
+ sort.Ints(ordered)
83
+ for _, i := range ordered {
84
+ if i >= 0 && i < len(execErrs) && execErrs[i] != nil {
85
+ return execErrs[i]
86
+ }
87
+ if i == unwindOp {
88
+ return nil // reached the unwind point without an exec-internal error
89
+ }
90
+ }
91
+ }
92
+ return nil
93
+ }
@@ -0,0 +1,287 @@
1
+ package coderuntime
2
+
3
+ import (
4
+ "fmt"
5
+ "math"
6
+ "sort"
7
+ "strconv"
8
+ "strings"
9
+ )
10
+
11
+ // CanonicalFailure is a canonical-serialization Failure with a stable code.
12
+ type CanonicalFailure struct {
13
+ Code string
14
+ Msg string
15
+ }
16
+
17
+ func (e *CanonicalFailure) Error() string { return e.Code + ": " + e.Msg }
18
+
19
+ func canonFail(code, msg string) *CanonicalFailure { return &CanonicalFailure{Code: code, Msg: msg} }
20
+
21
+ // guardKeys rejects an object whose own keys contain "__proto__" (fail-closed),
22
+ // matching the expression obj node's forbidden-key rule (expression-ir.md §2.3/§8).
23
+ func guardKeys(keys []string) *CanonicalFailure {
24
+ for _, k := range keys {
25
+ if k == ForbiddenObjectKey {
26
+ return canonFail("FORBIDDEN_KEY", fmt.Sprintf("object key %q is forbidden (fail-closed)", ForbiddenObjectKey))
27
+ }
28
+ }
29
+ return nil
30
+ }
31
+
32
+ func nan() float64 { return math.NaN() }
33
+ func posInf() float64 { return math.Inf(1) }
34
+ func negInf() float64 { return math.Inf(-1) }
35
+
36
+ // PyFloatRepr renders f exactly as CPython repr(float) / json.dumps(float) would.
37
+ // Finite floats only; NaN/±Inf return a NAN_OR_INF Failure.
38
+ //
39
+ // Ported from graphddb pyfloat.go / pyfloat.rs.
40
+ func PyFloatRepr(f float64) (string, error) { return pyFloatRepr(f) }
41
+
42
+ func pyFloatRepr(f float64) (string, error) {
43
+ if math.IsNaN(f) || math.IsInf(f, 0) {
44
+ return "", canonFail("NAN_OR_INF", fmt.Sprintf("non-finite float cannot be serialized: %v", f))
45
+ }
46
+ // Zero handled before digit extraction; sign recovered via Signbit.
47
+ if f == 0.0 {
48
+ if math.Signbit(f) {
49
+ return "-0.0", nil
50
+ }
51
+ return "0.0", nil
52
+ }
53
+
54
+ neg, digits, decpt := shortestDigits(f)
55
+ n := len(digits)
56
+
57
+ var out string
58
+ // format_float_short 'r': scientific iff decpt <= -4 or decpt > 16.
59
+ if decpt <= -4 || decpt > 16 {
60
+ var mant strings.Builder
61
+ mant.WriteByte(digits[0])
62
+ if n > 1 {
63
+ mant.WriteByte('.')
64
+ mant.WriteString(digits[1:])
65
+ }
66
+ e := decpt - 1
67
+ esign := byte('+')
68
+ if e < 0 {
69
+ esign = '-'
70
+ }
71
+ ea := e
72
+ if ea < 0 {
73
+ ea = -ea
74
+ }
75
+ eabs := strconv.Itoa(ea)
76
+ if len(eabs) < 2 {
77
+ eabs = "0" + eabs
78
+ }
79
+ out = mant.String() + "e" + string(esign) + eabs
80
+ } else if decpt <= 0 {
81
+ out = "0." + strings.Repeat("0", -decpt) + digits
82
+ } else if decpt >= n {
83
+ out = digits + strings.Repeat("0", decpt-n) + ".0"
84
+ } else {
85
+ out = digits[:decpt] + "." + digits[decpt:]
86
+ }
87
+
88
+ if neg {
89
+ return "-" + out, nil
90
+ }
91
+ return out, nil
92
+ }
93
+
94
+ func shortestDigits(f float64) (bool, string, int) {
95
+ var chosen string
96
+ for p := 0; p <= 17; p++ {
97
+ s := strconv.FormatFloat(f, 'e', p, 64)
98
+ if v, err := strconv.ParseFloat(s, 64); err == nil && v == f {
99
+ chosen = s
100
+ break
101
+ }
102
+ }
103
+ if chosen == "" {
104
+ chosen = strconv.FormatFloat(f, 'e', 17, 64)
105
+ }
106
+ s := chosen
107
+ neg := false
108
+ if strings.HasPrefix(s, "-") {
109
+ neg = true
110
+ s = s[1:]
111
+ }
112
+ mantissa := s
113
+ expPart := "0"
114
+ if i := strings.IndexAny(s, "eE"); i >= 0 {
115
+ mantissa = s[:i]
116
+ expPart = s[i+1:]
117
+ }
118
+ exp, _ := strconv.Atoi(expPart)
119
+
120
+ intPart := mantissa
121
+ fracPart := ""
122
+ if i := strings.IndexByte(mantissa, '.'); i >= 0 {
123
+ intPart = mantissa[:i]
124
+ fracPart = mantissa[i+1:]
125
+ }
126
+ digits := intPart + fracPart
127
+ decpt := len(intPart) + exp
128
+
129
+ lead := len(digits) - len(strings.TrimLeft(digits, "0"))
130
+ if lead == len(digits) {
131
+ return neg, "0", 1
132
+ }
133
+ digits = digits[lead:]
134
+ decpt -= lead
135
+
136
+ trimmed := strings.TrimRight(digits, "0")
137
+ if trimmed == "" {
138
+ trimmed = "0"
139
+ }
140
+ return neg, trimmed, decpt
141
+ }
142
+
143
+ // CanonicalValue is key-identity canonical serialization: only the top-level
144
+ // object's keys are code-point sorted; nested values keep insertion order.
145
+ func CanonicalValue(v Value) (string, error) {
146
+ if o, ok := v.(*Obj); ok {
147
+ if cf := guardKeys(o.Keys); cf != nil {
148
+ return "", cf
149
+ }
150
+ keys := append([]string(nil), o.Keys...)
151
+ sortCodePoints(keys)
152
+ parts := make([]string, 0, len(keys))
153
+ for _, k := range keys {
154
+ s, err := encodeNested(o.Vals[k])
155
+ if err != nil {
156
+ return "", err
157
+ }
158
+ parts = append(parts, jsonString(k)+":"+s)
159
+ }
160
+ return "{" + strings.Join(parts, ",") + "}", nil
161
+ }
162
+ return encodeNested(v)
163
+ }
164
+
165
+ // CanonicalJSON is fingerprint canonical serialization: all object levels are
166
+ // code-point key-sorted; arrays keep order.
167
+ func CanonicalJSON(v Value) (string, error) {
168
+ switch t := v.(type) {
169
+ case *Obj:
170
+ if cf := guardKeys(t.Keys); cf != nil {
171
+ return "", cf
172
+ }
173
+ keys := append([]string(nil), t.Keys...)
174
+ sortCodePoints(keys)
175
+ parts := make([]string, 0, len(keys))
176
+ for _, k := range keys {
177
+ s, err := CanonicalJSON(t.Vals[k])
178
+ if err != nil {
179
+ return "", err
180
+ }
181
+ parts = append(parts, jsonString(k)+":"+s)
182
+ }
183
+ return "{" + strings.Join(parts, ",") + "}", nil
184
+ case []Value:
185
+ parts := make([]string, len(t))
186
+ for i, e := range t {
187
+ s, err := CanonicalJSON(e)
188
+ if err != nil {
189
+ return "", err
190
+ }
191
+ parts[i] = s
192
+ }
193
+ return "[" + strings.Join(parts, ",") + "]", nil
194
+ default:
195
+ return scalarJSON(v)
196
+ }
197
+ }
198
+
199
+ func encodeNested(v Value) (string, error) {
200
+ switch t := v.(type) {
201
+ case *Obj:
202
+ if cf := guardKeys(t.Keys); cf != nil {
203
+ return "", cf
204
+ }
205
+ parts := make([]string, 0, t.Len())
206
+ for _, k := range t.Keys {
207
+ s, err := encodeNested(t.Vals[k])
208
+ if err != nil {
209
+ return "", err
210
+ }
211
+ parts = append(parts, jsonString(k)+":"+s)
212
+ }
213
+ return "{" + strings.Join(parts, ",") + "}", nil
214
+ case []Value:
215
+ parts := make([]string, len(t))
216
+ for i, e := range t {
217
+ s, err := encodeNested(e)
218
+ if err != nil {
219
+ return "", err
220
+ }
221
+ parts[i] = s
222
+ }
223
+ return "[" + strings.Join(parts, ",") + "]", nil
224
+ default:
225
+ return scalarJSON(v)
226
+ }
227
+ }
228
+
229
+ func scalarJSON(v Value) (string, error) {
230
+ switch t := v.(type) {
231
+ case nil:
232
+ return "null", nil
233
+ case bool:
234
+ if t {
235
+ return "true", nil
236
+ }
237
+ return "false", nil
238
+ case string:
239
+ return jsonString(t), nil
240
+ case int64:
241
+ return strconv.FormatInt(t, 10), nil
242
+ case float64:
243
+ return pyFloatRepr(t)
244
+ default:
245
+ return "", canonFail("INVALID_VALUE", "cannot serialize value of unknown type")
246
+ }
247
+ }
248
+
249
+ // sortCodePoints sorts keys in Unicode code-point order. Go string comparison is
250
+ // byte-wise over UTF-8, which equals code-point order, so sort.Strings suffices;
251
+ // kept explicit to make the normative choice clear (verified by the astral vector).
252
+ func sortCodePoints(keys []string) {
253
+ sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
254
+ }
255
+
256
+ // jsonString JSON-encodes a string with ensure_ascii=False semantics (non-ASCII
257
+ // passed through as UTF-8, matching json.dumps(ensure_ascii=False) / JSON.stringify).
258
+ func jsonString(s string) string {
259
+ var b strings.Builder
260
+ b.WriteByte('"')
261
+ for _, r := range s {
262
+ switch r {
263
+ case '"':
264
+ b.WriteString("\\\"")
265
+ case '\\':
266
+ b.WriteString("\\\\")
267
+ case '\n':
268
+ b.WriteString("\\n")
269
+ case '\r':
270
+ b.WriteString("\\r")
271
+ case '\t':
272
+ b.WriteString("\\t")
273
+ case '\b':
274
+ b.WriteString("\\b")
275
+ case '\f':
276
+ b.WriteString("\\f")
277
+ default:
278
+ if r < 0x20 {
279
+ b.WriteString(fmt.Sprintf("\\u%04x", r))
280
+ } else {
281
+ b.WriteRune(r)
282
+ }
283
+ }
284
+ }
285
+ b.WriteByte('"')
286
+ return b.String()
287
+ }