MCPcopy
hub / github.com/hashicorp/hcl / ParseWithStartPos

Function ParseWithStartPos

json/public.go:32–75  ·  view source on GitHub ↗

ParseWithStartPos attempts to parse like json.Parse, but unlike json.Parse you can pass a start position of the given JSON as a hcl.Pos. In most cases json.Parse should be sufficient, but it can be useful for parsing a part of JSON with correct positions.

(src []byte, filename string, start hcl.Pos)

Source from the content-addressed store, hash-verified

30// In most cases json.Parse should be sufficient, but it can be useful for parsing
31// a part of JSON with correct positions.
32func ParseWithStartPos(src []byte, filename string, start hcl.Pos) (*hcl.File, hcl.Diagnostics) {
33 rootNode, diags := parseFileContent(src, filename, start)
34
35 switch rootNode.(type) {
36 case *objectVal, *arrayVal:
37 // okay
38 default:
39 diags = diags.Append(&hcl.Diagnostic{
40 Severity: hcl.DiagError,
41 Summary: "Root value must be object",
42 Detail: "The root value in a JSON-based configuration must be either a JSON object or a JSON array of objects.",
43 Subject: rootNode.StartRange().Ptr(),
44 })
45
46 // Since we've already produced an error message for this being
47 // invalid, we'll return an empty placeholder here so that trying to
48 // extract content from our root body won't produce a redundant
49 // error saying the same thing again in more general terms.
50 fakePos := hcl.Pos{
51 Byte: 0,
52 Line: 1,
53 Column: 1,
54 }
55 fakeRange := hcl.Range{
56 Filename: filename,
57 Start: fakePos,
58 End: fakePos,
59 }
60 rootNode = &objectVal{
61 Attrs: []*objectAttr{},
62 SrcRange: fakeRange,
63 OpenRange: fakeRange,
64 }
65 }
66
67 file := &hcl.File{
68 Body: &body{
69 val: rootNode,
70 },
71 Bytes: src,
72 Nav: navigation{rootNode},
73 }
74 return file, diags
75}
76
77// ParseExpression parses the given buffer as a standalone JSON expression,
78// returning it as an instance of Expression.

Callers 2

ParseFunction · 0.85
TestParseWithStartPosFunction · 0.85

Calls 4

parseFileContentFunction · 0.85
PtrMethod · 0.80
StartRangeMethod · 0.65
AppendMethod · 0.45

Tested by 1

TestParseWithStartPosFunction · 0.68