Skip to content

Commit d55b62d

Browse files
committed
json: Add ParseExpression function
1 parent 50eda8b commit d55b62d

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

json/parser.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,21 @@ func parseFileContent(buf []byte, filename string) (node, hcl.Diagnostics) {
3030
return node, diags
3131
}
3232

33+
func parseExpression(buf []byte, filename string, start hcl.Pos) (node, hcl.Diagnostics) {
34+
tokens := scan(buf, pos{Filename: filename, Pos: start})
35+
p := newPeeker(tokens)
36+
node, diags := parseValue(p)
37+
if len(diags) == 0 && p.Peek().Type != tokenEOF {
38+
diags = diags.Append(&hcl.Diagnostic{
39+
Severity: hcl.DiagError,
40+
Summary: "Extraneous data after value",
41+
Detail: "Extra characters appear after the JSON value.",
42+
Subject: p.Peek().Range.Ptr(),
43+
})
44+
}
45+
return node, diags
46+
}
47+
3348
func parseValue(p *peeker) (node, hcl.Diagnostics) {
3449
tok := p.Peek()
3550

json/public.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ func Parse(src []byte, filename string) (*hcl.File, hcl.Diagnostics) {
6262
return file, diags
6363
}
6464

65+
// ParseExpression parses the given buffer as a standalone JSON expression,
66+
// returning it as an instance of Expression.
67+
func ParseExpression(src []byte, filename string, start hcl.Pos) (hcl.Expression, hcl.Diagnostics) {
68+
node, diags := parseExpression(src, filename, start)
69+
return &expression{src: node}, diags
70+
}
71+
6572
// ParseFile is a convenience wrapper around Parse that first attempts to load
6673
// data from the given filename, passing the result to Parse if successful.
6774
//

0 commit comments

Comments
 (0)