| 1 |
// Copyright (c) 2017, Daniel Martà <[email protected]> |
| 2 |
// See LICENSE for licensing information |
| 3 |
|
| 4 |
// Package typedjson allows encoding and decoding shell syntax trees as JSON. |
| 5 |
// The decoding process needs to know what syntax node types to decode into, |
| 6 |
// so the "typed JSON" requires "Type" keys in some syntax tree node objects: |
| 7 |
// |
| 8 |
// - The root node |
| 9 |
// - Any node represented as an interface field in the parent Go type |
| 10 |
// |
| 11 |
// The types of all other nodes can be inferred from context alone. |
| 12 |
// |
| 13 |
// For the sake of efficiency and simplicity, the "Type" key |
| 14 |
// described above must be first in each JSON object. |
| 15 |
package typedjson |
| 16 |
|
| 17 |
import ( |
| 18 |
"encoding" |
| 19 |
"encoding/json" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"math" |
| 23 |
"reflect" |
| 24 |
|
| 25 |
"mvdan.cc/sh/v3/syntax" |
| 26 |
) |
| 27 |
|
| 28 |
// Encode is a shortcut for [EncodeOptions.Encode] with the default options. |
| 29 |
func Encode(w io.Writer, node syntax.Node) error { |
| 30 |
return EncodeOptions{}.Encode(w, node) |
| 31 |
} |
| 32 |
|
| 33 |
// EncodeOptions allows configuring how syntax nodes are encoded. |
| 34 |
type EncodeOptions struct { |
| 35 |
Indent string // e.g. "\t" |
| 36 |
|
| 37 |
// Allows us to add options later. |
| 38 |
} |
| 39 |
|
| 40 |
// Encode writes node to w in its typed JSON form, |
| 41 |
// as described in the package documentation. |
| 42 |
func (opts EncodeOptions) Encode(w io.Writer, node syntax.Node) error { |
| 43 |
val := reflect.ValueOf(node) |
| 44 |
encVal, tname := encodeValue(val) |
| 45 |
if tname == "" { |
| 46 |
panic("node did not contain a named type?") |
| 47 |
} |
| 48 |
encVal.Elem().Field(0).SetString(tname) |
| 49 |
enc := json.NewEncoder(w) |
| 50 |
enc.SetEscapeHTML(false) |
| 51 |
if opts.Indent != "" { |
| 52 |
enc.SetIndent("", opts.Indent) |
| 53 |
} |
| 54 |
return enc.Encode(encVal.Interface()) |
| 55 |
} |
| 56 |
|
| 57 |
func encodeValue(val reflect.Value) (reflect.Value, string) { |
| 58 |
switch val.Kind() { |
| 59 |
case reflect.Pointer: |
| 60 |
if val.IsNil() { |
| 61 |
break |
| 62 |
} |
| 63 |
return encodeValue(val.Elem()) |
| 64 |
case reflect.Interface: |
| 65 |
if val.IsNil() { |
| 66 |
break |
| 67 |
} |
| 68 |
enc, tname := encodeValue(val.Elem()) |
| 69 |
if tname == "" { |
| 70 |
panic("interface did not contain a named type?") |
| 71 |
} |
| 72 |
enc.Elem().Field(0).SetString(tname) |
| 73 |
return enc, "" |
| 74 |
case reflect.Struct: |
| 75 |
// Construct a new struct with an optional Type, Pos and End, |
| 76 |
// and then all the visible fields which aren't positions. |
| 77 |
typ := val.Type() |
| 78 |
fields := []reflect.StructField{typeField, posField, endField} |
| 79 |
for field := range typ.Fields() { |
| 80 |
typ := anyType |
| 81 |
if field.Type == posType { |
| 82 |
typ = exportedPosType |
| 83 |
} |
| 84 |
fields = append(fields, reflect.StructField{ |
| 85 |
Name: field.Name, |
| 86 |
Type: typ, |
| 87 |
Tag: `json:",omitempty"`, |
| 88 |
}) |
| 89 |
} |
| 90 |
encTyp := reflect.StructOf(fields) |
| 91 |
enc := reflect.New(encTyp).Elem() |
| 92 |
|
| 93 |
// Node methods are defined on struct pointer receivers. |
| 94 |
if node, _ := reflect.TypeAssert[syntax.Node](val.Addr()); node != nil { |
| 95 |
encodePos(enc.Field(1), node.Pos()) // posField |
| 96 |
encodePos(enc.Field(2), node.End()) // endField |
| 97 |
} |
| 98 |
// Do the rest of the fields. |
| 99 |
for i := 3; i < encTyp.NumField(); i++ { |
| 100 |
ftyp := encTyp.Field(i) |
| 101 |
fval := val.FieldByName(ftyp.Name) |
| 102 |
if ftyp.Type == exportedPosType { |
| 103 |
encodePos(enc.Field(i), fval.Interface().(syntax.Pos)) |
| 104 |
} else { |
| 105 |
encElem, _ := encodeValue(fval) |
| 106 |
if encElem.IsValid() { |
| 107 |
enc.Field(i).Set(encElem) |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
// Addr helps prevent an allocation as we use any fields. |
| 113 |
return enc.Addr(), typ.Name() |
| 114 |
case reflect.Slice: |
| 115 |
n := val.Len() |
| 116 |
if n == 0 { |
| 117 |
break |
| 118 |
} |
| 119 |
enc := reflect.MakeSlice(anySliceType, n, n) |
| 120 |
for i := range n { |
| 121 |
elem := val.Index(i) |
| 122 |
encElem, _ := encodeValue(elem) |
| 123 |
enc.Index(i).Set(encElem) |
| 124 |
} |
| 125 |
return enc, "" |
| 126 |
case reflect.Bool: |
| 127 |
if val.Bool() { |
| 128 |
return val, "" |
| 129 |
} |
| 130 |
case reflect.String: |
| 131 |
if val.String() != "" { |
| 132 |
return val, "" |
| 133 |
} |
| 134 |
case reflect.Uint8, reflect.Uint32: |
| 135 |
if val.Uint() == 0 { |
| 136 |
break |
| 137 |
} |
| 138 |
// Encode token-derived operator enums as their syntax string form |
| 139 |
// so the wire format stays stable as new tokens are added. |
| 140 |
if s, ok := reflect.TypeAssert[fmt.Stringer](val); ok { |
| 141 |
return reflect.ValueOf(s.String()), "" |
| 142 |
} |
| 143 |
return val, "" |
| 144 |
default: |
| 145 |
panic(val.Kind().String()) |
| 146 |
} |
| 147 |
return noValue, "" |
| 148 |
} |
| 149 |
|
| 150 |
var ( |
| 151 |
noValue reflect.Value |
| 152 |
|
| 153 |
anyType = reflect.TypeFor[any]() |
| 154 |
anySliceType = reflect.TypeFor[[]any]() |
| 155 |
posType = reflect.TypeFor[syntax.Pos]() |
| 156 |
exportedPosType = reflect.TypeFor[*exportedPos]() |
| 157 |
|
| 158 |
// TODO(v4): derived fields like Type, Pos, and End should have clearly |
| 159 |
// different names to prevent confusion. For example: _type, _pos, _end. |
| 160 |
typeField = reflect.StructField{ |
| 161 |
Name: "Type", |
| 162 |
Type: reflect.TypeFor[string](), |
| 163 |
Tag: `json:",omitempty"`, |
| 164 |
} |
| 165 |
posField = reflect.StructField{ |
| 166 |
Name: "Pos", |
| 167 |
Type: exportedPosType, |
| 168 |
Tag: `json:",omitempty"`, |
| 169 |
} |
| 170 |
endField = reflect.StructField{ |
| 171 |
Name: "End", |
| 172 |
Type: exportedPosType, |
| 173 |
Tag: `json:",omitempty"`, |
| 174 |
} |
| 175 |
) |
| 176 |
|
| 177 |
type exportedPos struct { |
| 178 |
Offset, Line, Col uint |
| 179 |
} |
| 180 |
|
| 181 |
func encodePos(encPtr reflect.Value, val syntax.Pos) { |
| 182 |
// TODO: perhaps we should encode recovered positions, as that is still useful information. |
| 183 |
// Note that decoding them back requires a way to build a recovered position, |
| 184 |
// as [syntax.NewPos] clamps offsets and so can never produce one. |
| 185 |
if !val.IsValid() { |
| 186 |
return |
| 187 |
} |
| 188 |
enc := reflect.New(exportedPosType.Elem()) |
| 189 |
encPtr.Set(enc) |
| 190 |
enc = enc.Elem() |
| 191 |
|
| 192 |
enc.Field(0).SetUint(uint64(val.Offset())) |
| 193 |
enc.Field(1).SetUint(uint64(val.Line())) |
| 194 |
enc.Field(2).SetUint(uint64(val.Col())) |
| 195 |
} |
| 196 |
|
| 197 |
// posFieldNames are the fields of [exportedPos], which must all be present. |
| 198 |
var posFieldNames = [...]string{"Offset", "Line", "Col"} |
| 199 |
|
| 200 |
func decodePos(val reflect.Value, enc any) error { |
| 201 |
obj, ok := enc.(map[string]any) |
| 202 |
if !ok { |
| 203 |
return fmt.Errorf("cannot decode JSON %s into a position", jsonTypeName(enc)) |
| 204 |
} |
| 205 |
if len(obj) != len(posFieldNames) { |
| 206 |
return fmt.Errorf("a position must contain exactly the fields %s", posFieldNames) |
| 207 |
} |
| 208 |
var nums [len(posFieldNames)]uint |
| 209 |
for i, name := range posFieldNames { |
| 210 |
fv, ok := obj[name] |
| 211 |
if !ok { |
| 212 |
return fmt.Errorf("a position must contain the field %q", name) |
| 213 |
} |
| 214 |
num, ok := fv.(float64) |
| 215 |
if !ok { |
| 216 |
return fmt.Errorf("cannot decode JSON %s into the position field %q", jsonTypeName(fv), name) |
| 217 |
} |
| 218 |
// Note that this is only a sanity bound; |
| 219 |
// [syntax.NewPos] clamps beyond its own tighter limits. |
| 220 |
u, ok := jsonUint(num) |
| 221 |
if !ok { |
| 222 |
return fmt.Errorf("the position field %q is out of range: %v", name, num) |
| 223 |
} |
| 224 |
nums[i] = uint(u) |
| 225 |
} |
| 226 |
val.Set(reflect.ValueOf(syntax.NewPos(nums[0], nums[1], nums[2]))) |
| 227 |
return nil |
| 228 |
} |
| 229 |
|
| 230 |
// jsonUint converts a JSON number to an integer, reporting whether it is a |
| 231 |
// non-negative integer which fits in a uint32, as no syntax node field is |
| 232 |
// wider than that. The upper bound also keeps the conversion well defined. |
| 233 |
func jsonUint(num float64) (uint64, bool) { |
| 234 |
if num < 0 || num > math.MaxUint32 || num != math.Trunc(num) { |
| 235 |
return 0, false |
| 236 |
} |
| 237 |
return uint64(num), true |
| 238 |
} |
| 239 |
|
| 240 |
// jsonTypeName describes a decoded JSON value in terms of JSON types, |
| 241 |
// as the Go types that [encoding/json] decodes into are an implementation detail. |
| 242 |
func jsonTypeName(enc any) string { |
| 243 |
switch enc.(type) { |
| 244 |
case nil: |
| 245 |
return "null" |
| 246 |
case bool: |
| 247 |
return "boolean" |
| 248 |
case float64: |
| 249 |
return "number" |
| 250 |
case string: |
| 251 |
return "string" |
| 252 |
case []any: |
| 253 |
return "array" |
| 254 |
case map[string]any: |
| 255 |
return "object" |
| 256 |
default: |
| 257 |
return fmt.Sprintf("%T", enc) |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Decode is a shortcut for [DecodeOptions.Decode] with the default options. |
| 262 |
func Decode(r io.Reader) (syntax.Node, error) { |
| 263 |
return DecodeOptions{}.Decode(r) |
| 264 |
} |
| 265 |
|
| 266 |
// DecodeOptions allows configuring how syntax nodes are encoded. |
| 267 |
type DecodeOptions struct { |
| 268 |
// Empty for now; allows us to add options later. |
| 269 |
} |
| 270 |
|
| 271 |
// Decode reads a node from r in its typed JSON form, |
| 272 |
// as described in the package documentation. |
| 273 |
// |
| 274 |
// Malformed input results in an error. Note that the resulting tree is only |
| 275 |
// validated as far as its types and shape; just like a tree built by hand, |
| 276 |
// it may be missing nodes which the printer and interpreter require. |
| 277 |
func (opts DecodeOptions) Decode(r io.Reader) (syntax.Node, error) { |
| 278 |
var enc any |
| 279 |
if err := json.NewDecoder(r).Decode(&enc); err != nil { |
| 280 |
return nil, err |
| 281 |
} |
| 282 |
node := new(syntax.Node) |
| 283 |
if err := decodeValue(reflect.ValueOf(node).Elem(), enc); err != nil { |
| 284 |
return nil, err |
| 285 |
} |
| 286 |
if *node == nil { |
| 287 |
// Only a JSON null decodes into a nil node without an error. |
| 288 |
return nil, fmt.Errorf("cannot decode JSON null into a syntax node") |
| 289 |
} |
| 290 |
return *node, nil |
| 291 |
} |
| 292 |
|
| 293 |
// nodeByName holds every [syntax.Node] type, as any of them may be the root |
| 294 |
// node, which always requires a "Type" key. |
| 295 |
var nodeByName = map[string]reflect.Type{ |
| 296 |
"File": reflect.TypeFor[syntax.File](), |
| 297 |
"Comment": reflect.TypeFor[syntax.Comment](), |
| 298 |
"Stmt": reflect.TypeFor[syntax.Stmt](), |
| 299 |
"Assign": reflect.TypeFor[syntax.Assign](), |
| 300 |
"Redirect": reflect.TypeFor[syntax.Redirect](), |
| 301 |
"Word": reflect.TypeFor[syntax.Word](), |
| 302 |
|
| 303 |
"Lit": reflect.TypeFor[syntax.Lit](), |
| 304 |
"SglQuoted": reflect.TypeFor[syntax.SglQuoted](), |
| 305 |
"DblQuoted": reflect.TypeFor[syntax.DblQuoted](), |
| 306 |
"ParamExp": reflect.TypeFor[syntax.ParamExp](), |
| 307 |
"CmdSubst": reflect.TypeFor[syntax.CmdSubst](), |
| 308 |
"CallExpr": reflect.TypeFor[syntax.CallExpr](), |
| 309 |
"ArithmExp": reflect.TypeFor[syntax.ArithmExp](), |
| 310 |
"ProcSubst": reflect.TypeFor[syntax.ProcSubst](), |
| 311 |
"ExtGlob": reflect.TypeFor[syntax.ExtGlob](), |
| 312 |
"BraceExp": reflect.TypeFor[syntax.BraceExp](), |
| 313 |
|
| 314 |
"ArithmCmd": reflect.TypeFor[syntax.ArithmCmd](), |
| 315 |
"BinaryCmd": reflect.TypeFor[syntax.BinaryCmd](), |
| 316 |
"IfClause": reflect.TypeFor[syntax.IfClause](), |
| 317 |
"ForClause": reflect.TypeFor[syntax.ForClause](), |
| 318 |
"WhileClause": reflect.TypeFor[syntax.WhileClause](), |
| 319 |
"CaseClause": reflect.TypeFor[syntax.CaseClause](), |
| 320 |
"Block": reflect.TypeFor[syntax.Block](), |
| 321 |
"Subshell": reflect.TypeFor[syntax.Subshell](), |
| 322 |
"FuncDecl": reflect.TypeFor[syntax.FuncDecl](), |
| 323 |
"TestClause": reflect.TypeFor[syntax.TestClause](), |
| 324 |
"DeclClause": reflect.TypeFor[syntax.DeclClause](), |
| 325 |
"LetClause": reflect.TypeFor[syntax.LetClause](), |
| 326 |
"TimeClause": reflect.TypeFor[syntax.TimeClause](), |
| 327 |
"CoprocClause": reflect.TypeFor[syntax.CoprocClause](), |
| 328 |
"TestDecl": reflect.TypeFor[syntax.TestDecl](), |
| 329 |
|
| 330 |
"UnaryArithm": reflect.TypeFor[syntax.UnaryArithm](), |
| 331 |
"BinaryArithm": reflect.TypeFor[syntax.BinaryArithm](), |
| 332 |
"ParenArithm": reflect.TypeFor[syntax.ParenArithm](), |
| 333 |
"FlagsArithm": reflect.TypeFor[syntax.FlagsArithm](), |
| 334 |
|
| 335 |
"UnaryTest": reflect.TypeFor[syntax.UnaryTest](), |
| 336 |
"BinaryTest": reflect.TypeFor[syntax.BinaryTest](), |
| 337 |
"ParenTest": reflect.TypeFor[syntax.ParenTest](), |
| 338 |
|
| 339 |
"WordIter": reflect.TypeFor[syntax.WordIter](), |
| 340 |
"CStyleLoop": reflect.TypeFor[syntax.CStyleLoop](), |
| 341 |
"CaseItem": reflect.TypeFor[syntax.CaseItem](), |
| 342 |
"ArrayExpr": reflect.TypeFor[syntax.ArrayExpr](), |
| 343 |
"ArrayElem": reflect.TypeFor[syntax.ArrayElem](), |
| 344 |
} |
| 345 |
|
| 346 |
// decodeValue decodes enc, which comes from untrusted input, into val. |
| 347 |
// Every reflect operation below must first check that val can hold the value, |
| 348 |
// so that a mismatch results in an error rather than a panic. |
| 349 |
func decodeValue(val reflect.Value, enc any) error { |
| 350 |
switch enc := enc.(type) { |
| 351 |
case map[string]any: |
| 352 |
typ := val.Type() |
| 353 |
if typeName, _ := enc["Type"].(string); typeName != "" { |
| 354 |
nodeType := nodeByName[typeName] |
| 355 |
if nodeType == nil { |
| 356 |
return fmt.Errorf("unknown type: %q", typeName) |
| 357 |
} |
| 358 |
if !reflect.PointerTo(nodeType).AssignableTo(typ) { |
| 359 |
return fmt.Errorf("cannot decode %s into %s", typeName, typ) |
| 360 |
} |
| 361 |
val.Set(reflect.New(nodeType)) |
| 362 |
} else if val.Kind() == reflect.Pointer && val.IsNil() { |
| 363 |
val.Set(reflect.New(typ.Elem())) |
| 364 |
} |
| 365 |
for val.Kind() == reflect.Pointer || val.Kind() == reflect.Interface { |
| 366 |
if val.IsNil() { |
| 367 |
return fmt.Errorf(`missing "Type" to decode a JSON object into %s`, typ) |
| 368 |
} |
| 369 |
val = val.Elem() |
| 370 |
} |
| 371 |
if val.Kind() != reflect.Struct { |
| 372 |
return fmt.Errorf("cannot decode JSON object into %s", typ) |
| 373 |
} |
| 374 |
for name, fv := range enc { |
| 375 |
switch name { |
| 376 |
case "Type", "Pos", "End": |
| 377 |
// Type is already used above. Pos and End came from method calls. |
| 378 |
continue |
| 379 |
} |
| 380 |
fval := val.FieldByName(name) |
| 381 |
if !fval.IsValid() || !fval.CanSet() { |
| 382 |
return fmt.Errorf("unknown field for %s: %q", val.Type(), name) |
| 383 |
} |
| 384 |
if fval.Type() == posType { |
| 385 |
if err := decodePos(fval, fv); err != nil { |
| 386 |
return err |
| 387 |
} |
| 388 |
continue |
| 389 |
} |
| 390 |
if err := decodeValue(fval, fv); err != nil { |
| 391 |
return err |
| 392 |
} |
| 393 |
} |
| 394 |
case []any: |
| 395 |
if val.Kind() != reflect.Slice { |
| 396 |
return fmt.Errorf("cannot decode JSON array into %s", val.Type()) |
| 397 |
} |
| 398 |
for _, encElem := range enc { |
| 399 |
elem := reflect.New(val.Type().Elem()).Elem() |
| 400 |
if err := decodeValue(elem, encElem); err != nil { |
| 401 |
return err |
| 402 |
} |
| 403 |
val.Set(reflect.Append(val, elem)) |
| 404 |
} |
| 405 |
case string: |
| 406 |
if val.Kind() == reflect.String { |
| 407 |
val.SetString(enc) |
| 408 |
break |
| 409 |
} |
| 410 |
// Operators are encoded as their syntax form, such as "&&". |
| 411 |
if u, ok := textUnmarshaler(val); ok { |
| 412 |
return u.UnmarshalText([]byte(enc)) |
| 413 |
} |
| 414 |
return fmt.Errorf("cannot decode JSON string into %s", val.Type()) |
| 415 |
case float64: |
| 416 |
// Note that encoding/json defaults to float64 for numbers, |
| 417 |
// and that the kinds mirror those encoded by [encodeValue]. |
| 418 |
switch val.Kind() { |
| 419 |
case reflect.Uint8, reflect.Uint32: |
| 420 |
if _, ok := textUnmarshaler(val); ok { |
| 421 |
// Operator integer values are not part of the wire format. |
| 422 |
return fmt.Errorf("cannot decode JSON number into %s; a string is required", val.Type()) |
| 423 |
} |
| 424 |
u, ok := jsonUint(enc) |
| 425 |
if !ok || val.OverflowUint(u) { |
| 426 |
return fmt.Errorf("cannot decode the JSON number %v into %s", enc, val.Type()) |
| 427 |
} |
| 428 |
val.SetUint(u) |
| 429 |
default: |
| 430 |
return fmt.Errorf("cannot decode JSON number into %s", val.Type()) |
| 431 |
} |
| 432 |
default: |
| 433 |
// Note that a JSON null leaves the destination as its zero value. |
| 434 |
if enc != nil { |
| 435 |
encVal := reflect.ValueOf(enc) |
| 436 |
if !encVal.Type().AssignableTo(val.Type()) { |
| 437 |
return fmt.Errorf("cannot decode JSON %s into %s", jsonTypeName(enc), val.Type()) |
| 438 |
} |
| 439 |
val.Set(encVal) |
| 440 |
} |
| 441 |
} |
| 442 |
return nil |
| 443 |
} |
| 444 |
|
| 445 |
// textUnmarshaler reports whether val is an operator enum, |
| 446 |
// as those are encoded as strings rather than as their integer values. |
| 447 |
// Note that val is always addressable, |
| 448 |
// as [decodeValue] only writes to new values and to their fields. |
| 449 |
func textUnmarshaler(val reflect.Value) (encoding.TextUnmarshaler, bool) { |
| 450 |
return reflect.TypeAssert[encoding.TextUnmarshaler](val.Addr()) |
| 451 |
} |