Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json parsing improvements & fixes #58

Merged
merged 3 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 55 additions & 22 deletions json/jsonDecoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,36 @@ import (
. "github.com/polydawn/refmt/tok"
)

type stackFrame struct {
step decoderStep
some bool // Set to true after first value in any context; use to decide if a comma must precede the next value.
}

type Decoder struct {
r shared.SlickReader

stack []decoderStep // When empty, and step returns done, all done.
step decoderStep // Shortcut to end of stack.
some bool // Set to true after first value in any context; use to decide if a comma must precede the next value.
stack []stackFrame // When empty, and step returns done, all done.
frame stackFrame // Shortcut to end of stack.
}

func NewDecoder(r io.Reader) (d *Decoder) {
d = &Decoder{
r: shared.NewReader(r),
stack: make([]decoderStep, 0, 10),
stack: make([]stackFrame, 0, 10),
}
d.step = d.step_acceptValue
d.frame = stackFrame{d.step_acceptValue, false}
return
}

func (d *Decoder) Reset() {
d.stack = d.stack[0:0]
d.step = d.step_acceptValue
d.some = false
d.frame = stackFrame{d.step_acceptValue, false}
}

type decoderStep func(tokenSlot *Token) (done bool, err error)

func (d *Decoder) Step(tokenSlot *Token) (done bool, err error) {
done, err = d.step(tokenSlot)
done, err = d.frame.step(tokenSlot)
// If the step errored: out, entirely.
if err != nil {
return true, err
Expand All @@ -49,16 +52,14 @@ func (d *Decoder) Step(tokenSlot *Token) (done bool, err error) {
return true, nil // that's all folks
}
// Pop the stack. Reset "some" to true.
d.step = d.stack[nSteps]
d.frame = d.stack[nSteps]
d.stack = d.stack[0:nSteps]
d.some = true
return false, nil
}

func (d *Decoder) pushPhase(newPhase decoderStep) {
d.stack = append(d.stack, d.step)
d.step = newPhase
d.some = false
d.stack = append(d.stack, d.frame)
d.frame = stackFrame{newPhase, false}
}

func readn1skippingWhitespace(r shared.SlickReader) (majorByte byte, err error) {
Expand Down Expand Up @@ -88,7 +89,7 @@ func (d *Decoder) step_acceptArrValueOrBreak(tokenSlot *Token) (done bool, err e
if err != nil {
return true, err
}
if d.some {
if d.frame.some {
switch majorByte {
case ']':
tokenSlot.Type = TArrClose
Expand All @@ -99,15 +100,17 @@ func (d *Decoder) step_acceptArrValueOrBreak(tokenSlot *Token) (done bool, err e
return true, err
}
// and now fall through to the next switch
default:
return true, fmt.Errorf("expected comma or array close after array value; got %s", byteToString(majorByte))
}
}
switch majorByte {
case ']':
tokenSlot.Type = TArrClose
return true, nil
default:
d.frame = stackFrame{d.frame.step, true}
_, err := d.stepHelper_acceptValue(majorByte, tokenSlot)
d.some = true
return false, err
}
}
Expand All @@ -118,7 +121,7 @@ func (d *Decoder) step_acceptMapKeyOrBreak(tokenSlot *Token) (done bool, err err
if err != nil {
return true, err
}
if d.some {
if d.frame.some {
switch majorByte {
case '}':
tokenSlot.Type = TMapClose
Expand All @@ -129,26 +132,31 @@ func (d *Decoder) step_acceptMapKeyOrBreak(tokenSlot *Token) (done bool, err err
return true, err
}
// and now fall through to the next switch
default:
return true, fmt.Errorf("expected comma or map close after map value; got %s", byteToString(majorByte))
}
}
switch majorByte {
case '}':
tokenSlot.Type = TMapClose
return true, nil
default:
d.frame.some = true
// Consume a string for key.
_, err := d.stepHelper_acceptValue(majorByte, tokenSlot) // FIXME surely not *any* value? not composites, at least?
_, err := d.stepHelper_acceptKey(majorByte, tokenSlot) // FIXME surely not *any* value? not composites, at least?
if err != nil {
return true, err
}
// Now scan up to consume the colon as well, which is required next.
majorByte, err = readn1skippingWhitespace(d.r)
if err != nil {
return true, err
}
if majorByte != ':' {
return true, fmt.Errorf("expected colon after map key; got 0x%x", majorByte)
return true, fmt.Errorf("expected colon after map key; got %s", byteToString(majorByte))
}
// Next up: expect a value.
d.step = d.step_acceptMapValue
d.some = true
d.frame = stackFrame{d.step_acceptMapValue, false}
return false, err
}
}
Expand All @@ -159,12 +167,20 @@ func (d *Decoder) step_acceptMapValue(tokenSlot *Token) (done bool, err error) {
if err != nil {
return true, err
}
d.step = d.step_acceptMapKeyOrBreak
d.frame = stackFrame{d.step_acceptMapKeyOrBreak, true}
_, err = d.stepHelper_acceptValue(majorByte, tokenSlot)
return false, err
}

func (d *Decoder) stepHelper_acceptValue(majorByte byte, tokenSlot *Token) (done bool, err error) {
return d.stepHelper_acceptKV("value", majorByte, tokenSlot)
}

func (d *Decoder) stepHelper_acceptKey(majorByte byte, tokenSlot *Token) (done bool, err error) {
return d.stepHelper_acceptKV("key", majorByte, tokenSlot)
}

func (d *Decoder) stepHelper_acceptKV(t string, majorByte byte, tokenSlot *Token) (done bool, err error) {
switch majorByte {
case '{':
tokenSlot.Type = TMapOpen
Expand Down Expand Up @@ -202,6 +218,23 @@ func (d *Decoder) stepHelper_acceptValue(majorByte byte, tokenSlot *Token) (done
tokenSlot.Type, tokenSlot.Int, tokenSlot.Float64, err = d.decodeNumber(majorByte)
return true, err
default:
return true, fmt.Errorf("Invalid byte while expecting start of value: 0x%x", majorByte)
return true, fmt.Errorf("invalid char while expecting start of %s: %s", t, byteToString(majorByte))
}
}

var byteToStringMap = map[byte]string{
',': "comma",
':': "colon",
'{': "map open",
'}': "map close",
'[': "array open",
']': "array close",
'"': "quote",
}

func byteToString(b byte) string {
if s, ok := byteToStringMap[b]; ok {
return s
}
return fmt.Sprintf("0x%x", b)
}
51 changes: 51 additions & 0 deletions unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,63 @@ func TestUnmarshal(t *testing.T) {
bs := []byte(`"str"`)
err := Unmarshal(json.DecodeOptions{}, bs, &slot)
So(err, ShouldBeNil)
So(slot, ShouldEqual, "str")
})
Convey("map", func() {
var slot map[string]string
bs := []byte(`{"x":"1"}`)
err := Unmarshal(json.DecodeOptions{}, bs, &slot)
So(err, ShouldBeNil)
So(slot, ShouldResemble, map[string]string{"x": "1"})
})
Convey("map comma handling", func() {
var slot map[string]string
bs := []byte(`{"x":"1","y":"2"}`)
err := Unmarshal(json.DecodeOptions{}, bs, &slot)
So(err, ShouldBeNil)
So(slot, ShouldResemble, map[string]string{"x": "1", "y": "2"})
})
Convey("map comma handling errors", func() {
for _, tc := range []struct {
name string
j string
err string
}{
{"trailing commas", `{"x":"1","y":"2",,,}`, "invalid char while expecting start of key: comma"},
{"just commas", `{,,,}`, "invalid char while expecting start of key: comma"},
{"leading commas", `{,,,"x":"1","y":"2",,,}`, "invalid char while expecting start of key: comma"},
{"no commas", `{"x":"1""y":"2"}`, "expected comma or map close after map value; got quote"},
{"no commas, just spaces", `{ "x":"1" "y":"2" }`, "expected comma or map close after map value; got quote"},
{"no commas, just tabs", `{ "x":"1" "y":"2" }`, "expected comma or map close after map value; got quote"},
} {
Convey(tc.name, func() {
var slot map[string]string
err := Unmarshal(json.DecodeOptions{}, []byte(tc.j), &slot)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, tc.err)
})
}
})
Convey("array comma handling errors", func() {
for _, tc := range []struct {
name string
j string
err string
}{
{"trailing commas", `["1","2",,,]`, "invalid char while expecting start of value: comma"},
{"just commas", `[,,,]`, "invalid char while expecting start of value: comma"},
{"leading commas", `[,,,"1","2",,,]`, "invalid char while expecting start of value: comma"},
{"no commas", `["1""2"]`, "expected comma or array close after array value; got quote"},
{"no commas, just spaces", `[ "1" "2" ]`, "expected comma or array close after array value; got quote"},
{"no commas, just tabs", `[ "1" "2" ]`, "expected comma or array close after array value; got quote"},
} {
Convey(tc.name, func() {
var slot []string
err := Unmarshal(json.DecodeOptions{}, []byte(tc.j), &slot)
So(err, ShouldNotBeNil)
So(err.Error(), ShouldEqual, tc.err)
})
}
})
})
}
Expand Down