Compare commits

..

2 Commits

Author SHA1 Message Date
Thomas Pelletier b371733c67 Make all nodes contain Raw 2022-08-22 21:05:41 -04:00
Thomas Pelletier 64dcce07ea WIP 2022-08-22 23:04:44 +00:00
34 changed files with 621 additions and 758 deletions
-26
View File
@@ -1,26 +0,0 @@
name: CIFuzz
on: [pull_request]
jobs:
Fuzzing:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'go-toml'
dry-run: false
language: go
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'go-toml'
fuzz-seconds: 300
dry-run: false
language: go
- name: Upload Crash
uses: actions/upload-artifact@v3
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts
+2 -2
View File
@@ -13,8 +13,8 @@ jobs:
with:
fetch-depth: 0
- name: Setup go
uses: actions/setup-go@v3
uses: actions/setup-go@master
with:
go-version: "1.20"
go-version: 1.19
- name: Run tests with coverage
run: ./ci.sh coverage -d "${GITHUB_BASE_REF-HEAD}"
+2 -2
View File
@@ -20,9 +20,9 @@ jobs:
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
uses: actions/setup-go@v2
with:
go-version: "1.20"
go-version: 1.19
- name: Login to GitHub Container Registry
uses: docker/login-action@v2
with:
+2 -2
View File
@@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
os: [ 'ubuntu-latest', 'windows-latest', 'macos-latest']
go: [ '1.19', '1.20' ]
go: [ '1.18', '1.19' ]
runs-on: ${{ matrix.os }}
name: ${{ matrix.go }}/${{ matrix.os }}
steps:
@@ -20,7 +20,7 @@ jobs:
with:
fetch-depth: 0
- name: Setup go ${{ matrix.go }}
uses: actions/setup-go@v3
uses: actions/setup-go@master
with:
go-version: ${{ matrix.go }}
- name: Run unit tests
+1 -12
View File
@@ -140,17 +140,6 @@ fmt.Println(string(b))
[marshal]: https://pkg.go.dev/github.com/pelletier/go-toml/v2#Marshal
## Unstable API
This API does not yet follow the backward compatibility guarantees of this
library. They provide early access to features that may have rough edges or an
API subject to change.
### Parser
Parser is the unstable API that allows iterative parsing of a TOML document at
the AST level. See https://pkg.go.dev/github.com/pelletier/go-toml/v2/unstable.
## Benchmarks
Execution time speedup compared to other Go TOML libraries:
@@ -553,7 +542,7 @@ complete solutions exist out there.
## Versioning
Go-toml follows [Semantic Versioning](https://semver.org). The supported version
Go-toml follows [Semantic Versioning](http://semver.org/). The supported version
of [TOML](https://github.com/toml-lang/toml) is indicated at the beginning of
this document. The last two major versions of Go are supported
(see [Go Release Policy](https://golang.org/doc/devel/release.html#policy)).
@@ -1,4 +1,4 @@
package unstable
package toml
import (
"bytes"
@@ -55,7 +55,7 @@ func BenchmarkParseLiteralStringValid(b *testing.B) {
for name, input := range inputs {
b.Run(name, func(b *testing.B) {
p := Parser{}
p := parser{}
b.SetBytes(int64(len(input)))
b.ReportAllocs()
b.ResetTimer()
+41 -47
View File
@@ -5,8 +5,6 @@ import (
"math"
"strconv"
"time"
"github.com/pelletier/go-toml/v2/unstable"
)
func parseInteger(b []byte) (int64, error) {
@@ -34,7 +32,7 @@ func parseLocalDate(b []byte) (LocalDate, error) {
var date LocalDate
if len(b) != 10 || b[4] != '-' || b[7] != '-' {
return date, unstable.NewParserError(b, "dates are expected to have the format YYYY-MM-DD")
return date, newDecodeError(b, "dates are expected to have the format YYYY-MM-DD")
}
var err error
@@ -55,7 +53,7 @@ func parseLocalDate(b []byte) (LocalDate, error) {
}
if !isValidDate(date.Year, date.Month, date.Day) {
return LocalDate{}, unstable.NewParserError(b, "impossible date")
return LocalDate{}, newDecodeError(b, "impossible date")
}
return date, nil
@@ -66,7 +64,7 @@ func parseDecimalDigits(b []byte) (int, error) {
for i, c := range b {
if c < '0' || c > '9' {
return 0, unstable.NewParserError(b[i:i+1], "expected digit (0-9)")
return 0, newDecodeError(b[i:i+1], "expected digit (0-9)")
}
v *= 10
v += int(c - '0')
@@ -99,7 +97,7 @@ func parseDateTime(b []byte) (time.Time, error) {
} else {
const dateTimeByteLen = 6
if len(b) != dateTimeByteLen {
return time.Time{}, unstable.NewParserError(b, "invalid date-time timezone")
return time.Time{}, newDecodeError(b, "invalid date-time timezone")
}
var direction int
switch b[0] {
@@ -108,11 +106,11 @@ func parseDateTime(b []byte) (time.Time, error) {
case '+':
direction = +1
default:
return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset character")
return time.Time{}, newDecodeError(b[:1], "invalid timezone offset character")
}
if b[3] != ':' {
return time.Time{}, unstable.NewParserError(b[3:4], "expected a : separator")
return time.Time{}, newDecodeError(b[3:4], "expected a : separator")
}
hours, err := parseDecimalDigits(b[1:3])
@@ -120,7 +118,7 @@ func parseDateTime(b []byte) (time.Time, error) {
return time.Time{}, err
}
if hours > 23 {
return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset hours")
return time.Time{}, newDecodeError(b[:1], "invalid timezone offset hours")
}
minutes, err := parseDecimalDigits(b[4:6])
@@ -128,7 +126,7 @@ func parseDateTime(b []byte) (time.Time, error) {
return time.Time{}, err
}
if minutes > 59 {
return time.Time{}, unstable.NewParserError(b[:1], "invalid timezone offset minutes")
return time.Time{}, newDecodeError(b[:1], "invalid timezone offset minutes")
}
seconds := direction * (hours*3600 + minutes*60)
@@ -141,7 +139,7 @@ func parseDateTime(b []byte) (time.Time, error) {
}
if len(b) > 0 {
return time.Time{}, unstable.NewParserError(b, "extra bytes at the end of the timezone")
return time.Time{}, newDecodeError(b, "extra bytes at the end of the timezone")
}
t := time.Date(
@@ -162,7 +160,7 @@ func parseLocalDateTime(b []byte) (LocalDateTime, []byte, error) {
const localDateTimeByteMinLen = 11
if len(b) < localDateTimeByteMinLen {
return dt, nil, unstable.NewParserError(b, "local datetimes are expected to have the format YYYY-MM-DDTHH:MM:SS[.NNNNNNNNN]")
return dt, nil, newDecodeError(b, "local datetimes are expected to have the format YYYY-MM-DDTHH:MM:SS[.NNNNNNNNN]")
}
date, err := parseLocalDate(b[:10])
@@ -173,7 +171,7 @@ func parseLocalDateTime(b []byte) (LocalDateTime, []byte, error) {
sep := b[10]
if sep != 'T' && sep != ' ' && sep != 't' {
return dt, nil, unstable.NewParserError(b[10:11], "datetime separator is expected to be T or a space")
return dt, nil, newDecodeError(b[10:11], "datetime separator is expected to be T or a space")
}
t, rest, err := parseLocalTime(b[11:])
@@ -197,7 +195,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
// check if b matches to have expected format HH:MM:SS[.NNNNNN]
const localTimeByteLen = 8
if len(b) < localTimeByteLen {
return t, nil, unstable.NewParserError(b, "times are expected to have the format HH:MM:SS[.NNNNNN]")
return t, nil, newDecodeError(b, "times are expected to have the format HH:MM:SS[.NNNNNN]")
}
var err error
@@ -208,10 +206,10 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
}
if t.Hour > 23 {
return t, nil, unstable.NewParserError(b[0:2], "hour cannot be greater 23")
return t, nil, newDecodeError(b[0:2], "hour cannot be greater 23")
}
if b[2] != ':' {
return t, nil, unstable.NewParserError(b[2:3], "expecting colon between hours and minutes")
return t, nil, newDecodeError(b[2:3], "expecting colon between hours and minutes")
}
t.Minute, err = parseDecimalDigits(b[3:5])
@@ -219,10 +217,10 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
return t, nil, err
}
if t.Minute > 59 {
return t, nil, unstable.NewParserError(b[3:5], "minutes cannot be greater 59")
return t, nil, newDecodeError(b[3:5], "minutes cannot be greater 59")
}
if b[5] != ':' {
return t, nil, unstable.NewParserError(b[5:6], "expecting colon between minutes and seconds")
return t, nil, newDecodeError(b[5:6], "expecting colon between minutes and seconds")
}
t.Second, err = parseDecimalDigits(b[6:8])
@@ -231,7 +229,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
}
if t.Second > 60 {
return t, nil, unstable.NewParserError(b[6:8], "seconds cannot be greater 60")
return t, nil, newDecodeError(b[6:8], "seconds cannot be greater 60")
}
b = b[8:]
@@ -244,7 +242,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
for i, c := range b[1:] {
if !isDigit(c) {
if i == 0 {
return t, nil, unstable.NewParserError(b[0:1], "need at least one digit after fraction point")
return t, nil, newDecodeError(b[0:1], "need at least one digit after fraction point")
}
break
}
@@ -268,7 +266,7 @@ func parseLocalTime(b []byte) (LocalTime, []byte, error) {
}
if precision == 0 {
return t, nil, unstable.NewParserError(b[:1], "nanoseconds need at least one digit")
return t, nil, newDecodeError(b[:1], "nanoseconds need at least one digit")
}
t.Nanosecond = frac * nspow[precision]
@@ -291,24 +289,24 @@ func parseFloat(b []byte) (float64, error) {
}
if cleaned[0] == '.' {
return 0, unstable.NewParserError(b, "float cannot start with a dot")
return 0, newDecodeError(b, "float cannot start with a dot")
}
if cleaned[len(cleaned)-1] == '.' {
return 0, unstable.NewParserError(b, "float cannot end with a dot")
return 0, newDecodeError(b, "float cannot end with a dot")
}
dotAlreadySeen := false
for i, c := range cleaned {
if c == '.' {
if dotAlreadySeen {
return 0, unstable.NewParserError(b[i:i+1], "float can have at most one decimal point")
return 0, newDecodeError(b[i:i+1], "float can have at most one decimal point")
}
if !isDigit(cleaned[i-1]) {
return 0, unstable.NewParserError(b[i-1:i+1], "float decimal point must be preceded by a digit")
return 0, newDecodeError(b[i-1:i+1], "float decimal point must be preceded by a digit")
}
if !isDigit(cleaned[i+1]) {
return 0, unstable.NewParserError(b[i:i+2], "float decimal point must be followed by a digit")
return 0, newDecodeError(b[i:i+2], "float decimal point must be followed by a digit")
}
dotAlreadySeen = true
}
@@ -319,12 +317,12 @@ func parseFloat(b []byte) (float64, error) {
start = 1
}
if cleaned[start] == '0' && isDigit(cleaned[start+1]) {
return 0, unstable.NewParserError(b, "float integer part cannot have leading zeroes")
return 0, newDecodeError(b, "float integer part cannot have leading zeroes")
}
f, err := strconv.ParseFloat(string(cleaned), 64)
if err != nil {
return 0, unstable.NewParserError(b, "unable to parse float: %w", err)
return 0, newDecodeError(b, "unable to parse float: %w", err)
}
return f, nil
@@ -338,7 +336,7 @@ func parseIntHex(b []byte) (int64, error) {
i, err := strconv.ParseInt(string(cleaned), 16, 64)
if err != nil {
return 0, unstable.NewParserError(b, "couldn't parse hexadecimal number: %w", err)
return 0, newDecodeError(b, "couldn't parse hexadecimal number: %w", err)
}
return i, nil
@@ -352,7 +350,7 @@ func parseIntOct(b []byte) (int64, error) {
i, err := strconv.ParseInt(string(cleaned), 8, 64)
if err != nil {
return 0, unstable.NewParserError(b, "couldn't parse octal number: %w", err)
return 0, newDecodeError(b, "couldn't parse octal number: %w", err)
}
return i, nil
@@ -366,7 +364,7 @@ func parseIntBin(b []byte) (int64, error) {
i, err := strconv.ParseInt(string(cleaned), 2, 64)
if err != nil {
return 0, unstable.NewParserError(b, "couldn't parse binary number: %w", err)
return 0, newDecodeError(b, "couldn't parse binary number: %w", err)
}
return i, nil
@@ -389,12 +387,12 @@ func parseIntDec(b []byte) (int64, error) {
}
if len(cleaned) > startIdx+1 && cleaned[startIdx] == '0' {
return 0, unstable.NewParserError(b, "leading zero not allowed on decimal number")
return 0, newDecodeError(b, "leading zero not allowed on decimal number")
}
i, err := strconv.ParseInt(string(cleaned), 10, 64)
if err != nil {
return 0, unstable.NewParserError(b, "couldn't parse decimal number: %w", err)
return 0, newDecodeError(b, "couldn't parse decimal number: %w", err)
}
return i, nil
@@ -411,11 +409,11 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) {
}
if b[start] == '_' {
return nil, unstable.NewParserError(b[start:start+1], "number cannot start with underscore")
return nil, newDecodeError(b[start:start+1], "number cannot start with underscore")
}
if b[len(b)-1] == '_' {
return nil, unstable.NewParserError(b[len(b)-1:], "number cannot end with underscore")
return nil, newDecodeError(b[len(b)-1:], "number cannot end with underscore")
}
// fast path
@@ -437,7 +435,7 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) {
c := b[i]
if c == '_' {
if !before {
return nil, unstable.NewParserError(b[i-1:i+1], "number must have at least one digit between underscores")
return nil, newDecodeError(b[i-1:i+1], "number must have at least one digit between underscores")
}
before = false
} else {
@@ -451,11 +449,11 @@ func checkAndRemoveUnderscoresIntegers(b []byte) ([]byte, error) {
func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) {
if b[0] == '_' {
return nil, unstable.NewParserError(b[0:1], "number cannot start with underscore")
return nil, newDecodeError(b[0:1], "number cannot start with underscore")
}
if b[len(b)-1] == '_' {
return nil, unstable.NewParserError(b[len(b)-1:], "number cannot end with underscore")
return nil, newDecodeError(b[len(b)-1:], "number cannot end with underscore")
}
// fast path
@@ -478,10 +476,10 @@ func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) {
switch c {
case '_':
if !before {
return nil, unstable.NewParserError(b[i-1:i+1], "number must have at least one digit between underscores")
return nil, newDecodeError(b[i-1:i+1], "number must have at least one digit between underscores")
}
if i < len(b)-1 && (b[i+1] == 'e' || b[i+1] == 'E') {
return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore before exponent")
return nil, newDecodeError(b[i+1:i+2], "cannot have underscore before exponent")
}
before = false
case '+', '-':
@@ -490,15 +488,15 @@ func checkAndRemoveUnderscoresFloats(b []byte) ([]byte, error) {
before = false
case 'e', 'E':
if i < len(b)-1 && b[i+1] == '_' {
return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore after exponent")
return nil, newDecodeError(b[i+1:i+2], "cannot have underscore after exponent")
}
cleaned = append(cleaned, c)
case '.':
if i < len(b)-1 && b[i+1] == '_' {
return nil, unstable.NewParserError(b[i+1:i+2], "cannot have underscore after decimal point")
return nil, newDecodeError(b[i+1:i+2], "cannot have underscore after decimal point")
}
if i > 0 && b[i-1] == '_' {
return nil, unstable.NewParserError(b[i-1:i], "cannot have underscore before decimal point")
return nil, newDecodeError(b[i-1:i], "cannot have underscore before decimal point")
}
cleaned = append(cleaned, c)
default:
@@ -544,7 +542,3 @@ func daysIn(m int, year int) int {
func isLeap(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
func isDigit(r byte) bool {
return r >= '0' && r <= '9'
}
+25 -7
View File
@@ -6,7 +6,6 @@ import (
"strings"
"github.com/pelletier/go-toml/v2/internal/danger"
"github.com/pelletier/go-toml/v2/unstable"
)
// DecodeError represents an error encountered during the parsing or decoding
@@ -56,6 +55,25 @@ func (s *StrictMissingError) String() string {
type Key []string
// internal version of DecodeError that is used as the base to create a
// DecodeError with full context.
type decodeError struct {
highlight []byte
message string
key Key // optional
}
func (de *decodeError) Error() string {
return de.message
}
func newDecodeError(highlight []byte, format string, args ...interface{}) error {
return &decodeError{
highlight: highlight,
message: fmt.Errorf(format, args...).Error(),
}
}
// Error returns the error message contained in the DecodeError.
func (e *DecodeError) Error() string {
return "toml: " + e.message
@@ -87,12 +105,12 @@ func (e *DecodeError) Key() Key {
// highlight can be freely deallocated.
//
//nolint:funlen
func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError {
offset := danger.SubsliceOffset(document, de.Highlight)
func wrapDecodeError(document []byte, de *decodeError) *DecodeError {
offset := danger.SubsliceOffset(document, de.highlight)
errMessage := de.Error()
errLine, errColumn := positionAtEnd(document[:offset])
before, after := linesOfContext(document, de.Highlight, offset, 3)
before, after := linesOfContext(document, de.highlight, offset, 3)
var buf strings.Builder
@@ -122,7 +140,7 @@ func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError {
buf.Write(before[0])
}
buf.Write(de.Highlight)
buf.Write(de.highlight)
if len(after) > 0 {
buf.Write(after[0])
@@ -140,7 +158,7 @@ func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError {
buf.WriteString(strings.Repeat(" ", len(before[0])))
}
buf.WriteString(strings.Repeat("~", len(de.Highlight)))
buf.WriteString(strings.Repeat("~", len(de.highlight)))
if len(errMessage) > 0 {
buf.WriteString(" ")
@@ -165,7 +183,7 @@ func wrapDecodeError(document []byte, de *unstable.ParserError) *DecodeError {
message: errMessage,
line: errLine,
column: errColumn,
key: de.Key,
key: de.key,
human: buf.String(),
}
}
+3 -4
View File
@@ -7,7 +7,6 @@ import (
"strings"
"testing"
"github.com/pelletier/go-toml/v2/unstable"
"github.com/stretchr/testify/assert"
)
@@ -171,9 +170,9 @@ line 5`,
doc := b.Bytes()
hl := doc[start:end]
err := wrapDecodeError(doc, &unstable.ParserError{
Highlight: hl,
Message: e.msg,
err := wrapDecodeError(doc, &decodeError{
highlight: hl,
message: e.msg,
})
var derr *DecodeError
+1 -8
View File
@@ -7,20 +7,13 @@ import (
"github.com/stretchr/testify/require"
)
func TestFastSimpleInt(t *testing.T) {
func TestFastSimple(t *testing.T) {
m := map[string]int64{}
err := toml.Unmarshal([]byte(`a = 42`), &m)
require.NoError(t, err)
require.Equal(t, map[string]int64{"a": 42}, m)
}
func TestFastSimpleFloat(t *testing.T) {
m := map[string]float64{}
err := toml.Unmarshal([]byte("a = 42\nb = 1.1\nc = 12341234123412341234123412341234"), &m)
require.NoError(t, err)
require.Equal(t, map[string]float64{"a": 42, "b": 1.1, "c": 1.2341234123412342e+31}, m)
}
func TestFastSimpleString(t *testing.T) {
m := map[string]string{}
err := toml.Unmarshal([]byte(`a = "hello"`), &m)
+2 -2
View File
@@ -1,5 +1,5 @@
//go:build go1.18 || go1.19 || go1.20
// +build go1.18 go1.19 go1.20
//go:build go1.18 || go1.19
// +build go1.18 go1.19
package toml_test
+1 -1
View File
@@ -2,4 +2,4 @@ module github.com/pelletier/go-toml/v2
go 1.16
require github.com/stretchr/testify v1.8.1
require github.com/stretchr/testify v1.8.0
+1 -3
View File
@@ -5,11 +5,9 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+38 -30
View File
@@ -1,4 +1,4 @@
package unstable
package ast
import (
"fmt"
@@ -7,16 +7,13 @@ import (
"github.com/pelletier/go-toml/v2/internal/danger"
)
// Iterator over a sequence of nodes.
//
// Starts uninitialized, you need to call Next() first.
// Iterator starts uninitialized, you need to call Next() first.
//
// For example:
//
// it := n.Children()
// for it.Next() {
// n := it.Node()
// // do something with n
// it.Node()
// }
type Iterator struct {
started bool
@@ -35,31 +32,42 @@ func (c *Iterator) Next() bool {
}
// IsLast returns true if the current node of the iterator is the last
// one. Subsequent calls to Next() will return false.
// one. Subsequent call to Next() will return false.
func (c *Iterator) IsLast() bool {
return c.node.next == 0
}
// Node returns a pointer to the node pointed at by the iterator.
// Node returns a copy of the node pointed at by the iterator.
func (c *Iterator) Node() *Node {
return c.node
}
// Node in a TOML expression AST.
// Root contains a full AST.
//
// Depending on Kind, its sequence of children should be interpreted
// differently.
//
// - Array have one child per element in the array.
// - InlineTable have one child per key-value in the table (each of kind
// InlineTable).
// - KeyValue have at least two children. The first one is the value. The rest
// make a potentially dotted key.
// - Table and ArrayTable's children represent a dotted key (same as
// KeyValue, but without the first node being the value).
//
// When relevant, Raw describes the range of bytes this node is referring to in
// the input document. Use Parser.Raw() to retrieve the actual bytes.
// It is immutable once constructed with Builder.
type Root struct {
nodes []Node
}
// Iterator over the top level nodes.
func (r *Root) Iterator() Iterator {
it := Iterator{}
if len(r.nodes) > 0 {
it.node = &r.nodes[0]
}
return it
}
func (r *Root) at(idx Reference) *Node {
return &r.nodes[idx]
}
// Arrays have one child per element in the array. InlineTables have
// one child per key-value pair in the table. KeyValues have at least
// two children. The first one is the value. The rest make a
// potentially dotted key. Table and Array table have one child per
// element of the key they represent (same as KeyValue, but without
// the last node being the value).
type Node struct {
Kind Kind
Raw Range // Raw bytes from the input.
@@ -72,13 +80,13 @@ type Node struct {
child int // 0 if no child
}
// Range of bytes in the document.
type Range struct {
Offset uint32
Length uint32
}
// Next returns a pointer to the next node, or nil if there is no next node.
// Next returns a copy of the next node, or an invalid Node if there
// is no next node.
func (n *Node) Next() *Node {
if n.next == 0 {
return nil
@@ -88,9 +96,9 @@ func (n *Node) Next() *Node {
return (*Node)(danger.Stride(ptr, size, n.next))
}
// Child returns a pointer to the first child node of this node. Other children
// can be accessed calling Next on the first child. Returns an nil if this Node
// has no child.
// Child returns a copy of the first child node of this node. Other
// children can be accessed calling Next on the first child. Returns
// an invalid Node if there is none.
func (n *Node) Child() *Node {
if n.child == 0 {
return nil
@@ -105,9 +113,9 @@ func (n *Node) Valid() bool {
return n != nil
}
// Key returns the children nodes making the Key on a supported node. Panics
// otherwise. They are guaranteed to be all be of the Kind Key. A simple key
// would return just one element.
// Key returns the child nodes making the Key on a supported
// node. Panics otherwise. They are guaranteed to be all be of the
// Kind Key. A simple key would return just one element.
func (n *Node) Key() Iterator {
switch n.Kind {
case KeyValue:
+51
View File
@@ -0,0 +1,51 @@
package ast
type Reference int
const InvalidReference Reference = -1
func (r Reference) Valid() bool {
return r != InvalidReference
}
type Builder struct {
tree Root
lastIdx int
}
func (b *Builder) Tree() *Root {
return &b.tree
}
func (b *Builder) NodeAt(ref Reference) *Node {
return b.tree.at(ref)
}
func (b *Builder) Reset() {
b.tree.nodes = b.tree.nodes[:0]
b.lastIdx = 0
}
func (b *Builder) Push(n Node) Reference {
b.lastIdx = len(b.tree.nodes)
b.tree.nodes = append(b.tree.nodes, n)
return Reference(b.lastIdx)
}
func (b *Builder) PushAndChain(n Node) Reference {
newIdx := len(b.tree.nodes)
b.tree.nodes = append(b.tree.nodes, n)
if b.lastIdx >= 0 {
b.tree.nodes[b.lastIdx].next = newIdx - b.lastIdx
}
b.lastIdx = newIdx
return Reference(b.lastIdx)
}
func (b *Builder) AttachChild(parent Reference, child Reference) {
b.tree.nodes[parent].child = int(child) - int(parent)
}
func (b *Builder) Chain(from Reference, to Reference) {
b.tree.nodes[from].next = int(to) - int(from)
}
+5 -7
View File
@@ -1,26 +1,25 @@
package unstable
package ast
import "fmt"
// Kind represents the type of TOML structure contained in a given Node.
type Kind int
const (
// Meta
// meta
Invalid Kind = iota
Comment
Key
// Top level structures
// top level structures
Table
ArrayTable
KeyValue
// Containers values
// containers values
Array
InlineTable
// Values
// values
String
Bool
Float
@@ -31,7 +30,6 @@ const (
DateTime
)
// String implementation of fmt.Stringer.
func (k Kind) String() string {
switch k {
case Invalid:
-42
View File
@@ -1,42 +0,0 @@
package characters
var invalidAsciiTable = [256]bool{
0x00: true,
0x01: true,
0x02: true,
0x03: true,
0x04: true,
0x05: true,
0x06: true,
0x07: true,
0x08: true,
// 0x09 TAB
// 0x0A LF
0x0B: true,
0x0C: true,
// 0x0D CR
0x0E: true,
0x0F: true,
0x10: true,
0x11: true,
0x12: true,
0x13: true,
0x14: true,
0x15: true,
0x16: true,
0x17: true,
0x18: true,
0x19: true,
0x1A: true,
0x1B: true,
0x1C: true,
0x1D: true,
0x1E: true,
0x1F: true,
// 0x20 - 0x7E Printable ASCII characters
0x7F: true,
}
func InvalidAscii(b byte) bool {
return invalidAsciiTable[b]
}
+1 -1
View File
@@ -18,7 +18,7 @@ type Program struct {
Usage string
Fn ConvertFn
// Inplace allows the command to take more than one file as argument and
// perform conversion in place on each provided file.
// perform convertion in place on each provided file.
Inplace bool
}
@@ -1085,6 +1085,10 @@ func TestUnmarshalCheckConversionFloatInt(t *testing.T) {
desc: "int",
input: `I = 1e300`,
},
{
desc: "float",
input: `F = 9223372036854775806`,
},
}
for _, test := range testCases {
+7 -5
View File
@@ -1,6 +1,8 @@
package tracker
import "github.com/pelletier/go-toml/v2/unstable"
import (
"github.com/pelletier/go-toml/v2/internal/ast"
)
// KeyTracker is a tracker that keeps track of the current Key as the AST is
// walked.
@@ -9,19 +11,19 @@ type KeyTracker struct {
}
// UpdateTable sets the state of the tracker with the AST table node.
func (t *KeyTracker) UpdateTable(node *unstable.Node) {
func (t *KeyTracker) UpdateTable(node *ast.Node) {
t.reset()
t.Push(node)
}
// UpdateArrayTable sets the state of the tracker with the AST array table node.
func (t *KeyTracker) UpdateArrayTable(node *unstable.Node) {
func (t *KeyTracker) UpdateArrayTable(node *ast.Node) {
t.reset()
t.Push(node)
}
// Push the given key on the stack.
func (t *KeyTracker) Push(node *unstable.Node) {
func (t *KeyTracker) Push(node *ast.Node) {
it := node.Key()
for it.Next() {
t.k = append(t.k, string(it.Node().Data))
@@ -29,7 +31,7 @@ func (t *KeyTracker) Push(node *unstable.Node) {
}
// Pop key from stack.
func (t *KeyTracker) Pop(node *unstable.Node) {
func (t *KeyTracker) Pop(node *ast.Node) {
it := node.Key()
for it.Next() {
t.k = t.k[:len(t.k)-1]
+14 -14
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"sync"
"github.com/pelletier/go-toml/v2/unstable"
"github.com/pelletier/go-toml/v2/internal/ast"
)
type keyKind uint8
@@ -150,23 +150,23 @@ func (s *SeenTracker) setExplicitFlag(parentIdx int) {
// CheckExpression takes a top-level node and checks that it does not contain
// keys that have been seen in previous calls, and validates that types are
// consistent.
func (s *SeenTracker) CheckExpression(node *unstable.Node) error {
func (s *SeenTracker) CheckExpression(node *ast.Node) error {
if s.entries == nil {
s.reset()
}
switch node.Kind {
case unstable.KeyValue:
case ast.KeyValue:
return s.checkKeyValue(node)
case unstable.Table:
case ast.Table:
return s.checkTable(node)
case unstable.ArrayTable:
case ast.ArrayTable:
return s.checkArrayTable(node)
default:
panic(fmt.Errorf("this should not be a top level node type: %s", node.Kind))
}
}
func (s *SeenTracker) checkTable(node *unstable.Node) error {
func (s *SeenTracker) checkTable(node *ast.Node) error {
if s.currentIdx >= 0 {
s.setExplicitFlag(s.currentIdx)
}
@@ -219,7 +219,7 @@ func (s *SeenTracker) checkTable(node *unstable.Node) error {
return nil
}
func (s *SeenTracker) checkArrayTable(node *unstable.Node) error {
func (s *SeenTracker) checkArrayTable(node *ast.Node) error {
if s.currentIdx >= 0 {
s.setExplicitFlag(s.currentIdx)
}
@@ -267,7 +267,7 @@ func (s *SeenTracker) checkArrayTable(node *unstable.Node) error {
return nil
}
func (s *SeenTracker) checkKeyValue(node *unstable.Node) error {
func (s *SeenTracker) checkKeyValue(node *ast.Node) error {
parentIdx := s.currentIdx
it := node.Key()
@@ -297,26 +297,26 @@ func (s *SeenTracker) checkKeyValue(node *unstable.Node) error {
value := node.Value()
switch value.Kind {
case unstable.InlineTable:
case ast.InlineTable:
return s.checkInlineTable(value)
case unstable.Array:
case ast.Array:
return s.checkArray(value)
}
return nil
}
func (s *SeenTracker) checkArray(node *unstable.Node) error {
func (s *SeenTracker) checkArray(node *ast.Node) error {
it := node.Children()
for it.Next() {
n := it.Node()
switch n.Kind {
case unstable.InlineTable:
case ast.InlineTable:
err := s.checkInlineTable(n)
if err != nil {
return err
}
case unstable.Array:
case ast.Array:
err := s.checkArray(n)
if err != nil {
return err
@@ -326,7 +326,7 @@ func (s *SeenTracker) checkArray(node *unstable.Node) error {
return nil
}
func (s *SeenTracker) checkInlineTable(node *unstable.Node) error {
func (s *SeenTracker) checkInlineTable(node *ast.Node) error {
if pool.New == nil {
pool.New = func() interface{} {
return &SeenTracker{}
+2 -4
View File
@@ -4,8 +4,6 @@ import (
"fmt"
"strings"
"time"
"github.com/pelletier/go-toml/v2/unstable"
)
// LocalDate represents a calendar day in no specific timezone.
@@ -77,7 +75,7 @@ func (d LocalTime) MarshalText() ([]byte, error) {
func (d *LocalTime) UnmarshalText(b []byte) error {
res, left, err := parseLocalTime(b)
if err == nil && len(left) != 0 {
err = unstable.NewParserError(left, "extra characters")
err = newDecodeError(left, "extra characters")
}
if err != nil {
return err
@@ -111,7 +109,7 @@ func (d LocalDateTime) MarshalText() ([]byte, error) {
func (d *LocalDateTime) UnmarshalText(data []byte) error {
res, left, err := parseLocalDateTime(data)
if err == nil && len(left) != 0 {
err = unstable.NewParserError(left, "extra characters")
err = newDecodeError(left, "extra characters")
}
if err != nil {
return err
+2 -4
View File
@@ -12,8 +12,6 @@ import (
"strings"
"time"
"unicode"
"github.com/pelletier/go-toml/v2/internal/characters"
)
// Marshal serializes a Go value as a TOML document.
@@ -357,9 +355,9 @@ func (enc *Encoder) encodeKv(b []byte, ctx encoderCtx, options valueOptions, v r
if !ctx.inline {
b = enc.encodeComment(ctx.indent, options.comment, b)
b = enc.indent(ctx.indent, b)
}
b = enc.indent(ctx.indent, b)
b = enc.encodeKey(b, ctx.key)
b = append(b, " = "...)
@@ -439,7 +437,7 @@ func (enc *Encoder) encodeString(b []byte, v string, options valueOptions) []byt
func needsQuoting(v string) bool {
// TODO: vectorize
for _, b := range []byte(v) {
if b == '\'' || b == '\r' || b == '\n' || characters.InvalidAscii(b) {
if b == '\'' || b == '\r' || b == '\n' || invalidAscii(b) {
return true
}
}
-21
View File
@@ -1190,27 +1190,6 @@ func TestMarshalUint64Overflow(t *testing.T) {
require.Error(t, err)
}
func TestIndentWithInlineTable(t *testing.T) {
x := map[string][]map[string]string{
"one": []map[string]string{
{"0": "0"},
{"1": "1"},
},
}
expected := `one = [
{0 = '0'},
{1 = '1'}
]
`
var buf bytes.Buffer
enc := toml.NewEncoder(&buf)
enc.SetIndentTables(true)
enc.SetTablesInline(true)
enc.SetArraysMultiline(true)
require.NoError(t, enc.Encode(x))
assert.Equal(t, expected, buf.String())
}
func ExampleMarshal() {
type MyConfig struct {
Version int
+175 -196
View File
@@ -1,108 +1,55 @@
package unstable
package toml
import (
"bytes"
"fmt"
"unicode"
"github.com/pelletier/go-toml/v2/internal/characters"
"github.com/pelletier/go-toml/v2/internal/ast"
"github.com/pelletier/go-toml/v2/internal/danger"
)
// ParserError describes an error relative to the content of the document.
//
// It cannot outlive the instance of Parser it refers to, and may cause panics
// if the parser is reset.
type ParserError struct {
Highlight []byte
Message string
Key []string // optional
}
// Error is the implementation of the error interface.
func (e *ParserError) Error() string {
return e.Message
}
// NewParserError is a convenience function to create a ParserError
//
// Warning: Highlight needs to be a subslice of Parser.data, so only slices
// returned by Parser.Raw are valid candidates.
func NewParserError(highlight []byte, format string, args ...interface{}) error {
return &ParserError{
Highlight: highlight,
Message: fmt.Errorf(format, args...).Error(),
}
}
// Parser scans over a TOML-encoded document and generates an iterative AST.
//
// To prime the Parser, first reset it with the contents of a TOML document.
// Then, process all top-level expressions sequentially. See Example.
//
// Don't forget to check Error() after you're done parsing.
//
// Each top-level expression needs to be fully processed before calling
// NextExpression() again. Otherwise, calls to various Node methods may panic if
// the parser has moved on the next expression.
//
// For performance reasons, go-toml doesn't make a copy of the input bytes to
// the parser. Make sure to copy all the bytes you need to outlive the slice
// given to the parser.
//
// The parser doesn't provide nodes for comments yet, nor for whitespace.
type Parser struct {
type parser struct {
builder ast.Builder
ref ast.Reference
data []byte
builder builder
ref reference
left []byte
err error
first bool
}
// Data returns the slice provided to the last call to Reset.
func (p *Parser) Data() []byte {
return p.data
}
// Range returns a range description that corresponds to a given slice of the
// input. If the argument is not a subslice of the parser input, this function
// panics.
func (p *Parser) Range(b []byte) Range {
return Range{
func (p *parser) Range(b []byte) ast.Range {
return ast.Range{
Offset: uint32(danger.SubsliceOffset(p.data, b)),
Length: uint32(len(b)),
}
}
// Raw returns the slice corresponding to the bytes in the given range.
func (p *Parser) Raw(raw Range) []byte {
func (p *parser) Raw(raw ast.Range) []byte {
return p.data[raw.Offset : raw.Offset+raw.Length]
}
// Reset brings the parser to its initial state for a given input. It wipes an
// reuses internal storage to reduce allocation.
func (p *Parser) Reset(b []byte) {
func (p *parser) SetRaw(ref ast.Reference, from []byte, to []byte) {
b := danger.BytesRange(from, to)
p.builder.NodeAt(ref).Raw = p.Range(b)
}
func (p *parser) Reset(b []byte) {
p.builder.Reset()
p.ref = invalidReference
p.ref = ast.InvalidReference
p.data = b
p.left = b
p.err = nil
p.first = true
}
// NextExpression parses the next top-level expression. If an expression was
// successfully parsed, it returns true. If the parser is at the end of the
// document or an error occurred, it returns false.
//
// Retrieve the parsed expression with Expression().
func (p *Parser) NextExpression() bool {
//nolint:cyclop
func (p *parser) NextExpression() bool {
if len(p.left) == 0 || p.err != nil {
return false
}
p.builder.Reset()
p.ref = invalidReference
p.ref = ast.InvalidReference
for {
if len(p.left) == 0 || p.err != nil {
@@ -131,18 +78,15 @@ func (p *Parser) NextExpression() bool {
}
}
// Expression returns a pointer to the node representing the last successfully
// parsed expression.
func (p *Parser) Expression() *Node {
func (p *parser) Expression() *ast.Node {
return p.builder.NodeAt(p.ref)
}
// Error returns any error that has occurred during parsing.
func (p *Parser) Error() error {
func (p *parser) Error() error {
return p.err
}
func (p *Parser) parseNewline(b []byte) ([]byte, error) {
func (p *parser) parseNewline(b []byte) ([]byte, error) {
if b[0] == '\n' {
return b[1:], nil
}
@@ -152,14 +96,14 @@ func (p *Parser) parseNewline(b []byte) ([]byte, error) {
return rest, err
}
return nil, NewParserError(b[0:1], "expected newline but got %#U", b[0])
return nil, newDecodeError(b[0:1], "expected newline but got %#U", b[0])
}
func (p *Parser) parseExpression(b []byte) (reference, []byte, error) {
func (p *parser) parseExpression(b []byte) (ast.Reference, []byte, error) {
// expression = ws [ comment ]
// expression =/ ws keyval ws [ comment ]
// expression =/ ws table ws [ comment ]
ref := invalidReference
ref := ast.InvalidReference
b = p.parseWhitespace(b)
@@ -197,7 +141,7 @@ func (p *Parser) parseExpression(b []byte) (reference, []byte, error) {
return ref, b, nil
}
func (p *Parser) parseTable(b []byte) (reference, []byte, error) {
func (p *parser) parseTable(b []byte) (ast.Reference, []byte, error) {
// table = std-table / array-table
if len(b) > 1 && b[1] == '[' {
return p.parseArrayTable(b)
@@ -206,19 +150,21 @@ func (p *Parser) parseTable(b []byte) (reference, []byte, error) {
return p.parseStdTable(b)
}
func (p *Parser) parseArrayTable(b []byte) (reference, []byte, error) {
func (p *parser) parseArrayTable(b []byte) (ast.Reference, []byte, error) {
// array-table = array-table-open key array-table-close
// array-table-open = %x5B.5B ws ; [[ Double left square bracket
// array-table-close = ws %x5D.5D ; ]] Double right square bracket
ref := p.builder.Push(Node{
Kind: ArrayTable,
ref := p.builder.Push(ast.Node{
Kind: ast.ArrayTable,
})
start := b
b = b[2:]
b = p.parseWhitespace(b)
k, b, err := p.parseKey(b)
if err != nil {
p.SetRaw(ref, start, b)
return ref, nil, err
}
@@ -227,27 +173,30 @@ func (p *Parser) parseArrayTable(b []byte) (reference, []byte, error) {
b, err = expect(']', b)
if err != nil {
p.SetRaw(ref, start, b)
return ref, nil, err
}
b, err = expect(']', b)
p.SetRaw(ref, start, b)
return ref, b, err
}
func (p *Parser) parseStdTable(b []byte) (reference, []byte, error) {
func (p *parser) parseStdTable(b []byte) (ast.Reference, []byte, error) {
// std-table = std-table-open key std-table-close
// std-table-open = %x5B ws ; [ Left square bracket
// std-table-close = ws %x5D ; ] Right square bracket
ref := p.builder.Push(Node{
Kind: Table,
ref := p.builder.Push(ast.Node{
Kind: ast.Table,
})
start := b
b = b[1:]
b = p.parseWhitespace(b)
key, b, err := p.parseKey(b)
if err != nil {
p.SetRaw(ref, start, b)
return ref, nil, err
}
@@ -257,18 +206,21 @@ func (p *Parser) parseStdTable(b []byte) (reference, []byte, error) {
b, err = expect(']', b)
p.SetRaw(ref, start, b)
return ref, b, err
}
func (p *Parser) parseKeyval(b []byte) (reference, []byte, error) {
func (p *parser) parseKeyval(b []byte) (ast.Reference, []byte, error) {
// keyval = key keyval-sep val
ref := p.builder.Push(Node{
Kind: KeyValue,
ref := p.builder.Push(ast.Node{
Kind: ast.KeyValue,
})
start := b
key, b, err := p.parseKey(b)
if err != nil {
return invalidReference, nil, err
p.SetRaw(ref, start, b)
return ast.InvalidReference, b, err
}
// keyval-sep = ws %x3D ws ; =
@@ -276,34 +228,38 @@ func (p *Parser) parseKeyval(b []byte) (reference, []byte, error) {
b = p.parseWhitespace(b)
if len(b) == 0 {
return invalidReference, nil, NewParserError(b, "expected = after a key, but the document ends there")
p.SetRaw(ref, start, b)
return ast.InvalidReference, b, newDecodeError(b, "expected = after a key, but the document ends there")
}
b, err = expect('=', b)
if err != nil {
return invalidReference, nil, err
p.SetRaw(ref, start, b)
return ast.InvalidReference, b, err
}
b = p.parseWhitespace(b)
valRef, b, err := p.parseVal(b)
if err != nil {
p.SetRaw(ref, start, b)
return ref, b, err
}
p.builder.Chain(valRef, key)
p.builder.AttachChild(ref, valRef)
p.SetRaw(ref, start, b)
return ref, b, err
}
//nolint:cyclop,funlen
func (p *Parser) parseVal(b []byte) (reference, []byte, error) {
func (p *parser) parseVal(b []byte) (ast.Reference, []byte, error) {
// val = string / boolean / array / inline-table / date-time / float / integer
ref := invalidReference
ref := ast.InvalidReference
if len(b) == 0 {
return ref, nil, NewParserError(b, "expected value, not eof")
return ref, b, newDecodeError(b, "expected value, not eof")
}
var err error
@@ -320,8 +276,8 @@ func (p *Parser) parseVal(b []byte) (reference, []byte, error) {
}
if err == nil {
ref = p.builder.Push(Node{
Kind: String,
ref = p.builder.Push(ast.Node{
Kind: ast.String,
Raw: p.Range(raw),
Data: v,
})
@@ -338,8 +294,8 @@ func (p *Parser) parseVal(b []byte) (reference, []byte, error) {
}
if err == nil {
ref = p.builder.Push(Node{
Kind: String,
ref = p.builder.Push(ast.Node{
Kind: ast.String,
Raw: p.Range(raw),
Data: v,
})
@@ -348,23 +304,25 @@ func (p *Parser) parseVal(b []byte) (reference, []byte, error) {
return ref, b, err
case 't':
if !scanFollowsTrue(b) {
return ref, nil, NewParserError(atmost(b, 4), "expected 'true'")
return ref, b, newDecodeError(atmost(b, 4), "expected 'true'")
}
ref = p.builder.Push(Node{
Kind: Bool,
ref = p.builder.Push(ast.Node{
Kind: ast.Bool,
Data: b[:4],
Raw: p.Range(b[:4]),
})
return ref, b[4:], nil
case 'f':
if !scanFollowsFalse(b) {
return ref, nil, NewParserError(atmost(b, 5), "expected 'false'")
return ref, b, newDecodeError(atmost(b, 5), "expected 'false'")
}
ref = p.builder.Push(Node{
Kind: Bool,
ref = p.builder.Push(ast.Node{
Kind: ast.Bool,
Data: b[:5],
Raw: p.Range(b[:5]),
})
return ref, b[5:], nil
@@ -385,29 +343,29 @@ func atmost(b []byte, n int) []byte {
return b[:n]
}
func (p *Parser) parseLiteralString(b []byte) ([]byte, []byte, []byte, error) {
func (p *parser) parseLiteralString(b []byte) ([]byte, []byte, []byte, error) {
v, rest, err := scanLiteralString(b)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
return v, v[1 : len(v)-1], rest, nil
}
func (p *Parser) parseInlineTable(b []byte) (reference, []byte, error) {
func (p *parser) parseInlineTable(b []byte) (ast.Reference, []byte, error) {
// inline-table = inline-table-open [ inline-table-keyvals ] inline-table-close
// inline-table-open = %x7B ws ; {
// inline-table-close = ws %x7D ; }
// inline-table-sep = ws %x2C ws ; , Comma
// inline-table-keyvals = keyval [ inline-table-sep inline-table-keyvals ]
parent := p.builder.Push(Node{
Kind: InlineTable,
Raw: p.Range(b[:1]),
parent := p.builder.Push(ast.Node{
Kind: ast.InlineTable,
})
start := b
first := true
var child reference
var child ast.Reference
b = b[1:]
@@ -418,7 +376,8 @@ func (p *Parser) parseInlineTable(b []byte) (reference, []byte, error) {
b = p.parseWhitespace(b)
if len(b) == 0 {
return parent, nil, NewParserError(previousB[:1], "inline table is incomplete")
p.SetRaw(parent, start, b)
return parent, b, newDecodeError(previousB[:1], "inline table is incomplete")
}
if b[0] == '}' {
@@ -428,16 +387,18 @@ func (p *Parser) parseInlineTable(b []byte) (reference, []byte, error) {
if !first {
b, err = expect(',', b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
b = p.parseWhitespace(b)
}
var kv reference
var kv ast.Reference
kv, b, err = p.parseKeyval(b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
if first {
@@ -452,11 +413,12 @@ func (p *Parser) parseInlineTable(b []byte) (reference, []byte, error) {
rest, err := expect('}', b)
p.SetRaw(parent, start, b)
return parent, rest, err
}
//nolint:funlen,cyclop
func (p *Parser) parseValArray(b []byte) (reference, []byte, error) {
func (p *parser) parseValArray(b []byte) (ast.Reference, []byte, error) {
// array = array-open [ array-values ] ws-comment-newline array-close
// array-open = %x5B ; [
// array-close = %x5D ; ]
@@ -465,25 +427,28 @@ func (p *Parser) parseValArray(b []byte) (reference, []byte, error) {
// array-sep = %x2C ; , Comma
// ws-comment-newline = *( wschar / [ comment ] newline )
arrayStart := b
start := b
b = b[1:]
parent := p.builder.Push(Node{
Kind: Array,
parent := p.builder.Push(ast.Node{
Kind: ast.Array,
})
first := true
var lastChild reference
var lastChild ast.Reference
var err error
for len(b) > 0 {
b, err = p.parseOptionalWhitespaceCommentNewline(b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
if len(b) == 0 {
return parent, nil, NewParserError(arrayStart[:1], "array is incomplete")
p.SetRaw(parent, start, b)
return parent, b, newDecodeError(arrayStart[:1], "array is incomplete")
}
if b[0] == ']' {
@@ -492,16 +457,19 @@ func (p *Parser) parseValArray(b []byte) (reference, []byte, error) {
if b[0] == ',' {
if first {
return parent, nil, NewParserError(b[0:1], "array cannot start with comma")
p.SetRaw(parent, start, b)
return parent, b, newDecodeError(b[0:1], "array cannot start with comma")
}
b = b[1:]
b, err = p.parseOptionalWhitespaceCommentNewline(b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
} else if !first {
return parent, nil, NewParserError(b[0:1], "array elements must be separated by commas")
p.SetRaw(parent, start, b)
return parent, b, newDecodeError(b[0:1], "array elements must be separated by commas")
}
// TOML allows trailing commas in arrays.
@@ -509,10 +477,11 @@ func (p *Parser) parseValArray(b []byte) (reference, []byte, error) {
break
}
var valueRef reference
var valueRef ast.Reference
valueRef, b, err = p.parseVal(b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
if first {
@@ -524,17 +493,20 @@ func (p *Parser) parseValArray(b []byte) (reference, []byte, error) {
b, err = p.parseOptionalWhitespaceCommentNewline(b)
if err != nil {
return parent, nil, err
p.SetRaw(parent, start, b)
return parent, b, err
}
first = false
}
rest, err := expect(']', b)
p.SetRaw(parent, start, rest)
return parent, rest, err
}
func (p *Parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error) {
func (p *parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error) {
for len(b) > 0 {
var err error
b = p.parseWhitespace(b)
@@ -542,7 +514,7 @@ func (p *Parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error)
if len(b) > 0 && b[0] == '#' {
_, b, err = scanComment(b)
if err != nil {
return nil, err
return b, err
}
}
@@ -553,7 +525,7 @@ func (p *Parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error)
if b[0] == '\n' || b[0] == '\r' {
b, err = p.parseNewline(b)
if err != nil {
return nil, err
return b, err
}
} else {
break
@@ -563,10 +535,10 @@ func (p *Parser) parseOptionalWhitespaceCommentNewline(b []byte) ([]byte, error)
return b, nil
}
func (p *Parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte, error) {
func (p *parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte, error) {
token, rest, err := scanMultilineLiteralString(b)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
i := 3
@@ -582,7 +554,7 @@ func (p *Parser) parseMultilineLiteralString(b []byte) ([]byte, []byte, []byte,
}
//nolint:funlen,gocognit,cyclop
func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, error) {
func (p *parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, error) {
// ml-basic-string = ml-basic-string-delim [ newline ] ml-basic-body
// ml-basic-string-delim
// ml-basic-string-delim = 3quotation-mark
@@ -595,7 +567,7 @@ func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er
// mlb-escaped-nl = escape ws newline *( wschar / newline )
token, escaped, rest, err := scanMultilineBasicString(b)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
i := 3
@@ -613,11 +585,11 @@ func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er
if !escaped {
str := token[startIdx:endIdx]
verr := characters.Utf8TomlValidAlreadyEscaped(str)
verr := utf8TomlValidAlreadyEscaped(str)
if verr.Zero() {
return token, str, rest, nil
}
return nil, nil, nil, NewParserError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8")
return nil, nil, rest, newDecodeError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8")
}
var builder bytes.Buffer
@@ -684,26 +656,26 @@ func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er
case 'u':
x, err := hexToRune(atmost(token[i+1:], 4), 4)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
builder.WriteRune(x)
i += 4
case 'U':
x, err := hexToRune(atmost(token[i+1:], 8), 8)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
builder.WriteRune(x)
i += 8
default:
return nil, nil, nil, NewParserError(token[i:i+1], "invalid escaped character %#U", c)
return nil, nil, rest, newDecodeError(token[i:i+1], "invalid escaped character %#U", c)
}
i++
} else {
size := characters.Utf8ValidNext(token[i:])
size := utf8ValidNext(token[i:])
if size == 0 {
return nil, nil, nil, NewParserError(token[i:i+1], "invalid character %#U", c)
return nil, nil, rest, newDecodeError(token[i:i+1], "invalid character %#U", c)
}
builder.Write(token[i : i+size])
i += size
@@ -713,7 +685,7 @@ func (p *Parser) parseMultilineBasicString(b []byte) ([]byte, []byte, []byte, er
return token, builder.Bytes(), rest, nil
}
func (p *Parser) parseKey(b []byte) (reference, []byte, error) {
func (p *parser) parseKey(b []byte) (ast.Reference, []byte, error) {
// key = simple-key / dotted-key
// simple-key = quoted-key / unquoted-key
//
@@ -724,11 +696,11 @@ func (p *Parser) parseKey(b []byte) (reference, []byte, error) {
// dot-sep = ws %x2E ws ; . Period
raw, key, b, err := p.parseSimpleKey(b)
if err != nil {
return invalidReference, nil, err
return ast.InvalidReference, b, err
}
ref := p.builder.Push(Node{
Kind: Key,
ref := p.builder.Push(ast.Node{
Kind: ast.Key,
Raw: p.Range(raw),
Data: key,
})
@@ -740,11 +712,11 @@ func (p *Parser) parseKey(b []byte) (reference, []byte, error) {
raw, key, b, err = p.parseSimpleKey(b)
if err != nil {
return ref, nil, err
return ref, b, err
}
p.builder.PushAndChain(Node{
Kind: Key,
p.builder.PushAndChain(ast.Node{
Kind: ast.Key,
Raw: p.Range(raw),
Data: key,
})
@@ -756,9 +728,9 @@ func (p *Parser) parseKey(b []byte) (reference, []byte, error) {
return ref, b, nil
}
func (p *Parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) {
func (p *parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) {
if len(b) == 0 {
return nil, nil, nil, NewParserError(b, "expected key but found none")
return nil, nil, b, newDecodeError(b, "expected key but found none")
}
// simple-key = quoted-key / unquoted-key
@@ -773,12 +745,12 @@ func (p *Parser) parseSimpleKey(b []byte) (raw, key, rest []byte, err error) {
key, rest = scanUnquotedKey(b)
return key, key, rest, nil
default:
return nil, nil, nil, NewParserError(b[0:1], "invalid character at start of key: %c", b[0])
return nil, nil, b[1:], newDecodeError(b[0:1], "invalid character at start of key: %c", b[0])
}
}
//nolint:funlen,cyclop
func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
func (p *parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
// basic-string = quotation-mark *basic-char quotation-mark
// quotation-mark = %x22 ; "
// basic-char = basic-unescaped / escaped
@@ -795,7 +767,7 @@ func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
// escape-seq-char =/ %x55 8HEXDIG ; UXXXXXXXX U+XXXXXXXX
token, escaped, rest, err := scanBasicString(b)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
startIdx := len(`"`)
@@ -806,11 +778,11 @@ func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
// validate the string and return a direct reference to the buffer.
if !escaped {
str := token[startIdx:endIdx]
verr := characters.Utf8TomlValidAlreadyEscaped(str)
verr := utf8TomlValidAlreadyEscaped(str)
if verr.Zero() {
return token, str, rest, nil
}
return nil, nil, nil, NewParserError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8")
return nil, nil, rest, newDecodeError(str[verr.Index:verr.Index+verr.Size], "invalid UTF-8")
}
i := startIdx
@@ -843,7 +815,7 @@ func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
case 'u':
x, err := hexToRune(token[i+1:len(token)-1], 4)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
builder.WriteRune(x)
@@ -851,19 +823,19 @@ func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
case 'U':
x, err := hexToRune(token[i+1:len(token)-1], 8)
if err != nil {
return nil, nil, nil, err
return nil, nil, rest, err
}
builder.WriteRune(x)
i += 8
default:
return nil, nil, nil, NewParserError(token[i:i+1], "invalid escaped character %#U", c)
return nil, nil, rest, newDecodeError(token[i:i+1], "invalid escaped character %#U", c)
}
i++
} else {
size := characters.Utf8ValidNext(token[i:])
size := utf8ValidNext(token[i:])
if size == 0 {
return nil, nil, nil, NewParserError(token[i:i+1], "invalid character %#U", c)
return nil, nil, rest, newDecodeError(token[i:i+1], "invalid character %#U", c)
}
builder.Write(token[i : i+size])
i += size
@@ -875,7 +847,7 @@ func (p *Parser) parseBasicString(b []byte) ([]byte, []byte, []byte, error) {
func hexToRune(b []byte, length int) (rune, error) {
if len(b) < length {
return -1, NewParserError(b, "unicode point needs %d character, not %d", length, len(b))
return -1, newDecodeError(b, "unicode point needs %d character, not %d", length, len(b))
}
b = b[:length]
@@ -890,19 +862,19 @@ func hexToRune(b []byte, length int) (rune, error) {
case 'A' <= c && c <= 'F':
d = uint32(c - 'A' + 10)
default:
return -1, NewParserError(b[i:i+1], "non-hex character")
return -1, newDecodeError(b[i:i+1], "non-hex character")
}
r = r*16 + d
}
if r > unicode.MaxRune || 0xD800 <= r && r < 0xE000 {
return -1, NewParserError(b, "escape sequence is invalid Unicode code point")
return -1, newDecodeError(b, "escape sequence is invalid Unicode code point")
}
return rune(r), nil
}
func (p *Parser) parseWhitespace(b []byte) []byte {
func (p *parser) parseWhitespace(b []byte) []byte {
// ws = *wschar
// wschar = %x20 ; Space
// wschar =/ %x09 ; Horizontal tab
@@ -912,25 +884,27 @@ func (p *Parser) parseWhitespace(b []byte) []byte {
}
//nolint:cyclop
func (p *Parser) parseIntOrFloatOrDateTime(b []byte) (reference, []byte, error) {
func (p *parser) parseIntOrFloatOrDateTime(b []byte) (ast.Reference, []byte, error) {
switch b[0] {
case 'i':
if !scanFollowsInf(b) {
return invalidReference, nil, NewParserError(atmost(b, 3), "expected 'inf'")
return ast.InvalidReference, b, newDecodeError(atmost(b, 3), "expected 'inf'")
}
return p.builder.Push(Node{
Kind: Float,
return p.builder.Push(ast.Node{
Kind: ast.Float,
Data: b[:3],
Raw: p.Range(b[:3]),
}), b[3:], nil
case 'n':
if !scanFollowsNan(b) {
return invalidReference, nil, NewParserError(atmost(b, 3), "expected 'nan'")
return ast.InvalidReference, b, newDecodeError(atmost(b, 3), "expected 'nan'")
}
return p.builder.Push(Node{
Kind: Float,
return p.builder.Push(ast.Node{
Kind: ast.Float,
Data: b[:3],
Raw: p.Range(b[:3]),
}), b[3:], nil
case '+', '-':
return p.scanIntOrFloat(b)
@@ -960,7 +934,7 @@ func (p *Parser) parseIntOrFloatOrDateTime(b []byte) (reference, []byte, error)
return p.scanIntOrFloat(b)
}
func (p *Parser) scanDateTime(b []byte) (reference, []byte, error) {
func (p *parser) scanDateTime(b []byte) (ast.Reference, []byte, error) {
// scans for contiguous characters in [0-9T:Z.+-], and up to one space if
// followed by a digit.
hasDate := false
@@ -1003,30 +977,31 @@ byteLoop:
}
}
var kind Kind
var kind ast.Kind
if hasTime {
if hasDate {
if hasTz {
kind = DateTime
kind = ast.DateTime
} else {
kind = LocalDateTime
kind = ast.LocalDateTime
}
} else {
kind = LocalTime
kind = ast.LocalTime
}
} else {
kind = LocalDate
kind = ast.LocalDate
}
return p.builder.Push(Node{
return p.builder.Push(ast.Node{
Kind: kind,
Data: b[:i],
Raw: p.Range(b[:i]),
}), b[i:], nil
}
//nolint:funlen,gocognit,cyclop
func (p *Parser) scanIntOrFloat(b []byte) (reference, []byte, error) {
func (p *parser) scanIntOrFloat(b []byte) (ast.Reference, []byte, error) {
i := 0
if len(b) > 2 && b[0] == '0' && b[1] != '.' && b[1] != 'e' && b[1] != 'E' {
@@ -1052,9 +1027,10 @@ func (p *Parser) scanIntOrFloat(b []byte) (reference, []byte, error) {
}
}
return p.builder.Push(Node{
Kind: Integer,
return p.builder.Push(ast.Node{
Kind: ast.Integer,
Data: b[:i],
Raw: p.Range(b[:i]),
}), b[i:], nil
}
@@ -1075,42 +1051,45 @@ func (p *Parser) scanIntOrFloat(b []byte) (reference, []byte, error) {
if c == 'i' {
if scanFollowsInf(b[i:]) {
return p.builder.Push(Node{
Kind: Float,
return p.builder.Push(ast.Node{
Kind: ast.Float,
Data: b[:i+3],
Raw: p.Range(b[:i+3]),
}), b[i+3:], nil
}
return invalidReference, nil, NewParserError(b[i:i+1], "unexpected character 'i' while scanning for a number")
return ast.InvalidReference, b[i:], newDecodeError(b[i:i+1], "unexpected character 'i' while scanning for a number")
}
if c == 'n' {
if scanFollowsNan(b[i:]) {
return p.builder.Push(Node{
Kind: Float,
return p.builder.Push(ast.Node{
Kind: ast.Float,
Data: b[:i+3],
Raw: p.Range(b[:i+3]),
}), b[i+3:], nil
}
return invalidReference, nil, NewParserError(b[i:i+1], "unexpected character 'n' while scanning for a number")
return ast.InvalidReference, b[i:], newDecodeError(b[i:i+1], "unexpected character 'n' while scanning for a number")
}
break
}
if i == 0 {
return invalidReference, b, NewParserError(b, "incomplete number")
return ast.InvalidReference, b, newDecodeError(b, "incomplete number")
}
kind := Integer
kind := ast.Integer
if isFloat {
kind = Float
kind = ast.Float
}
return p.builder.Push(Node{
return p.builder.Push(ast.Node{
Kind: kind,
Data: b[:i],
Raw: p.Range(b[:i]),
}), b[i:], nil
}
@@ -1137,11 +1116,11 @@ func isValidBinaryRune(r byte) bool {
func expect(x byte, b []byte) ([]byte, error) {
if len(b) == 0 {
return nil, NewParserError(b, "expected character %c but the document ended here", x)
return b, newDecodeError(b, "expected character %c but the document ended here", x)
}
if b[0] != x {
return nil, NewParserError(b[0:1], "expected character %c", x)
return b, newDecodeError(b[0:1], "expected character %c", x)
}
return b[1:], nil
+72 -94
View File
@@ -1,142 +1,143 @@
package unstable
package toml
import (
"fmt"
"strconv"
"strings"
"testing"
"github.com/pelletier/go-toml/v2/internal/ast"
"github.com/stretchr/testify/require"
)
//nolint:funlen
func TestParser_AST_Numbers(t *testing.T) {
examples := []struct {
desc string
input string
kind Kind
kind ast.Kind
err bool
}{
{
desc: "integer just digits",
input: `1234`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer zero",
input: `0`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer sign",
input: `+99`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer hex uppercase",
input: `0xDEADBEEF`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer hex lowercase",
input: `0xdead_beef`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer octal",
input: `0o01234567`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "integer binary",
input: `0b11010110`,
kind: Integer,
kind: ast.Integer,
},
{
desc: "float zero",
input: `0.0`,
kind: Float,
kind: ast.Float,
},
{
desc: "float positive zero",
input: `+0.0`,
kind: Float,
kind: ast.Float,
},
{
desc: "float negative zero",
input: `-0.0`,
kind: Float,
kind: ast.Float,
},
{
desc: "float pi",
input: `3.1415`,
kind: Float,
kind: ast.Float,
},
{
desc: "float negative",
input: `-0.01`,
kind: Float,
kind: ast.Float,
},
{
desc: "float signed exponent",
input: `5e+22`,
kind: Float,
kind: ast.Float,
},
{
desc: "float exponent lowercase",
input: `1e06`,
kind: Float,
kind: ast.Float,
},
{
desc: "float exponent uppercase",
input: `-2E-2`,
kind: Float,
kind: ast.Float,
},
{
desc: "float fractional with exponent",
input: `6.626e-34`,
kind: Float,
kind: ast.Float,
},
{
desc: "float underscores",
input: `224_617.445_991_228`,
kind: Float,
kind: ast.Float,
},
{
desc: "inf",
input: `inf`,
kind: Float,
kind: ast.Float,
},
{
desc: "inf negative",
input: `-inf`,
kind: Float,
kind: ast.Float,
},
{
desc: "inf positive",
input: `+inf`,
kind: Float,
kind: ast.Float,
},
{
desc: "nan",
input: `nan`,
kind: Float,
kind: ast.Float,
},
{
desc: "nan negative",
input: `-nan`,
kind: Float,
kind: ast.Float,
},
{
desc: "nan positive",
input: `+nan`,
kind: Float,
kind: ast.Float,
},
}
for _, e := range examples {
e := e
t.Run(e.desc, func(t *testing.T) {
p := Parser{}
p := parser{}
p.Reset([]byte(`A = ` + e.input))
p.NextExpression()
err := p.Error()
@@ -146,10 +147,10 @@ func TestParser_AST_Numbers(t *testing.T) {
require.NoError(t, err)
expected := astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{Kind: e.kind, Data: []byte(e.input)},
{Kind: Key, Data: []byte(`A`)},
{Kind: ast.Key, Data: []byte(`A`)},
},
}
compareNode(t, expected, p.Expression())
@@ -160,13 +161,13 @@ func TestParser_AST_Numbers(t *testing.T) {
type (
astNode struct {
Kind Kind
Kind ast.Kind
Data []byte
Children []astNode
}
)
func compareNode(t *testing.T, e astNode, n *Node) {
func compareNode(t *testing.T, e astNode, n *ast.Node) {
t.Helper()
require.Equal(t, e.Kind, n.Kind)
require.Equal(t, e.Data, n.Data)
@@ -174,7 +175,7 @@ func compareNode(t *testing.T, e astNode, n *Node) {
compareIterator(t, e.Children, n.Children())
}
func compareIterator(t *testing.T, expected []astNode, actual Iterator) {
func compareIterator(t *testing.T, expected []astNode, actual ast.Iterator) {
t.Helper()
idx := 0
@@ -208,14 +209,14 @@ func TestParser_AST(t *testing.T) {
desc: "simple string assignment",
input: `A = "hello"`,
ast: astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{
Kind: String,
Kind: ast.String,
Data: []byte(`hello`),
},
{
Kind: Key,
Kind: ast.Key,
Data: []byte(`A`),
},
},
@@ -225,14 +226,14 @@ func TestParser_AST(t *testing.T) {
desc: "simple bool assignment",
input: `A = true`,
ast: astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{
Kind: Bool,
Kind: ast.Bool,
Data: []byte(`true`),
},
{
Kind: Key,
Kind: ast.Key,
Data: []byte(`A`),
},
},
@@ -242,24 +243,24 @@ func TestParser_AST(t *testing.T) {
desc: "array of strings",
input: `A = ["hello", ["world", "again"]]`,
ast: astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{
Kind: Array,
Kind: ast.Array,
Children: []astNode{
{
Kind: String,
Kind: ast.String,
Data: []byte(`hello`),
},
{
Kind: Array,
Kind: ast.Array,
Children: []astNode{
{
Kind: String,
Kind: ast.String,
Data: []byte(`world`),
},
{
Kind: String,
Kind: ast.String,
Data: []byte(`again`),
},
},
@@ -267,7 +268,7 @@ func TestParser_AST(t *testing.T) {
},
},
{
Kind: Key,
Kind: ast.Key,
Data: []byte(`A`),
},
},
@@ -277,23 +278,23 @@ func TestParser_AST(t *testing.T) {
desc: "array of arrays of strings",
input: `A = ["hello", "world"]`,
ast: astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{
Kind: Array,
Kind: ast.Array,
Children: []astNode{
{
Kind: String,
Kind: ast.String,
Data: []byte(`hello`),
},
{
Kind: String,
Kind: ast.String,
Data: []byte(`world`),
},
},
},
{
Kind: Key,
Kind: ast.Key,
Data: []byte(`A`),
},
},
@@ -303,29 +304,29 @@ func TestParser_AST(t *testing.T) {
desc: "inline table",
input: `name = { first = "Tom", last = "Preston-Werner" }`,
ast: astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{
Kind: InlineTable,
Kind: ast.InlineTable,
Children: []astNode{
{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{Kind: String, Data: []byte(`Tom`)},
{Kind: Key, Data: []byte(`first`)},
{Kind: ast.String, Data: []byte(`Tom`)},
{Kind: ast.Key, Data: []byte(`first`)},
},
},
{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{Kind: String, Data: []byte(`Preston-Werner`)},
{Kind: Key, Data: []byte(`last`)},
{Kind: ast.String, Data: []byte(`Preston-Werner`)},
{Kind: ast.Key, Data: []byte(`last`)},
},
},
},
},
{
Kind: Key,
Kind: ast.Key,
Data: []byte(`name`),
},
},
@@ -336,7 +337,7 @@ func TestParser_AST(t *testing.T) {
for _, e := range examples {
e := e
t.Run(e.desc, func(t *testing.T) {
p := Parser{}
p := parser{}
p.Reset([]byte(e.input))
p.NextExpression()
err := p.Error()
@@ -351,7 +352,7 @@ func TestParser_AST(t *testing.T) {
}
func BenchmarkParseBasicStringWithUnicode(b *testing.B) {
p := &Parser{}
p := &parser{}
b.Run("4", func(b *testing.B) {
input := []byte(`"\u1234\u5678\u9ABC\u1234\u5678\u9ABC"`)
b.ReportAllocs()
@@ -373,7 +374,7 @@ func BenchmarkParseBasicStringWithUnicode(b *testing.B) {
}
func BenchmarkParseBasicStringsEasy(b *testing.B) {
p := &Parser{}
p := &parser{}
for _, size := range []int{1, 4, 8, 16, 21} {
b.Run(strconv.Itoa(size), func(b *testing.B) {
@@ -393,40 +394,40 @@ func TestParser_AST_DateTimes(t *testing.T) {
examples := []struct {
desc string
input string
kind Kind
kind ast.Kind
err bool
}{
{
desc: "offset-date-time with delim 'T' and UTC offset",
input: `2021-07-21T12:08:05Z`,
kind: DateTime,
kind: ast.DateTime,
},
{
desc: "offset-date-time with space delim and +8hours offset",
input: `2021-07-21 12:08:05+08:00`,
kind: DateTime,
kind: ast.DateTime,
},
{
desc: "local-date-time with nano second",
input: `2021-07-21T12:08:05.666666666`,
kind: LocalDateTime,
kind: ast.LocalDateTime,
},
{
desc: "local-date-time",
input: `2021-07-21T12:08:05`,
kind: LocalDateTime,
kind: ast.LocalDateTime,
},
{
desc: "local-date",
input: `2021-07-21`,
kind: LocalDate,
kind: ast.LocalDate,
},
}
for _, e := range examples {
e := e
t.Run(e.desc, func(t *testing.T) {
p := Parser{}
p := parser{}
p.Reset([]byte(`A = ` + e.input))
p.NextExpression()
err := p.Error()
@@ -436,10 +437,10 @@ func TestParser_AST_DateTimes(t *testing.T) {
require.NoError(t, err)
expected := astNode{
Kind: KeyValue,
Kind: ast.KeyValue,
Children: []astNode{
{Kind: e.kind, Data: []byte(e.input)},
{Kind: Key, Data: []byte(`A`)},
{Kind: ast.Key, Data: []byte(`A`)},
},
}
compareNode(t, expected, p.Expression())
@@ -447,26 +448,3 @@ func TestParser_AST_DateTimes(t *testing.T) {
})
}
}
func ExampleParser() {
doc := `
hello = "world"
value = 42
`
p := Parser{}
p.Reset([]byte(doc))
for p.NextExpression() {
e := p.Expression()
fmt.Printf("Expression: %s\n", e.Kind)
value := e.Value()
it := e.Key()
k := it.Node() // shortcut: we know there is no dotted key in the example
fmt.Printf("%s -> (%s) %s\n", k.Data, value.Kind, value.Data)
}
// Output:
// Expression: KeyValue
// hello -> (String) world
// Expression: KeyValue
// value -> (Integer) 42
}
+24 -26
View File
@@ -1,6 +1,4 @@
package unstable
import "github.com/pelletier/go-toml/v2/internal/characters"
package toml
func scanFollows(b []byte, pattern string) bool {
n := len(pattern)
@@ -56,16 +54,16 @@ func scanLiteralString(b []byte) ([]byte, []byte, error) {
case '\'':
return b[:i+1], b[i+1:], nil
case '\n', '\r':
return nil, nil, NewParserError(b[i:i+1], "literal strings cannot have new lines")
return nil, b[i+1:], newDecodeError(b[i:i+1], "literal strings cannot have new lines")
}
size := characters.Utf8ValidNext(b[i:])
size := utf8ValidNext(b[i:])
if size == 0 {
return nil, nil, NewParserError(b[i:i+1], "invalid character")
return nil, b[i+1:], newDecodeError(b[i:i+1], "invalid character")
}
i += size
}
return nil, nil, NewParserError(b[len(b):], "unterminated literal string")
return nil, b[len(b):], newDecodeError(b[len(b):], "unterminated literal string")
}
func scanMultilineLiteralString(b []byte) ([]byte, []byte, error) {
@@ -100,39 +98,39 @@ func scanMultilineLiteralString(b []byte) ([]byte, []byte, error) {
i++
if i < len(b) && b[i] == '\'' {
return nil, nil, NewParserError(b[i-3:i+1], "''' not allowed in multiline literal string")
return nil, b[i:], newDecodeError(b[i-3:i+1], "''' not allowed in multiline literal string")
}
return b[:i], b[i:], nil
}
case '\r':
if len(b) < i+2 {
return nil, nil, NewParserError(b[len(b):], `need a \n after \r`)
return nil, b[i:], newDecodeError(b[len(b):], `need a \n after \r`)
}
if b[i+1] != '\n' {
return nil, nil, NewParserError(b[i:i+2], `need a \n after \r`)
return nil, b[i+2:], newDecodeError(b[i:i+2], `need a \n after \r`)
}
i += 2 // skip the \n
continue
}
size := characters.Utf8ValidNext(b[i:])
size := utf8ValidNext(b[i:])
if size == 0 {
return nil, nil, NewParserError(b[i:i+1], "invalid character")
return nil, b[i:], newDecodeError(b[i:i+1], "invalid character")
}
i += size
}
return nil, nil, NewParserError(b[len(b):], `multiline literal string not terminated by '''`)
return nil, b[len(b):], newDecodeError(b[len(b):], `multiline literal string not terminated by '''`)
}
func scanWindowsNewline(b []byte) ([]byte, []byte, error) {
const lenCRLF = 2
if len(b) < lenCRLF {
return nil, nil, NewParserError(b, "windows new line expected")
return nil, b, newDecodeError(b, "windows new line expected")
}
if b[1] != '\n' {
return nil, nil, NewParserError(b, `windows new line should be \r\n`)
return nil, b[2:], newDecodeError(b, `windows new line should be \r\n`)
}
return b[:lenCRLF], b[lenCRLF:], nil
@@ -167,11 +165,11 @@ func scanComment(b []byte) ([]byte, []byte, error) {
if i+1 < len(b) && b[i+1] == '\n' {
return b[:i+1], b[i+1:], nil
}
return nil, nil, NewParserError(b[i:i+1], "invalid character in comment")
return nil, nil, newDecodeError(b[i:i+1], "invalid character in comment")
}
size := characters.Utf8ValidNext(b[i:])
size := utf8ValidNext(b[i:])
if size == 0 {
return nil, nil, NewParserError(b[i:i+1], "invalid character in comment")
return nil, b[i+1:], newDecodeError(b[i:i+1], "invalid character in comment")
}
i += size
@@ -194,17 +192,17 @@ func scanBasicString(b []byte) ([]byte, bool, []byte, error) {
case '"':
return b[:i+1], escaped, b[i+1:], nil
case '\n', '\r':
return nil, escaped, nil, NewParserError(b[i:i+1], "basic strings cannot have new lines")
return nil, escaped, b[i+1:], newDecodeError(b[i:i+1], "basic strings cannot have new lines")
case '\\':
if len(b) < i+2 {
return nil, escaped, nil, NewParserError(b[i:i+1], "need a character after \\")
return nil, escaped, b[i+1:], newDecodeError(b[i:i+1], "need a character after \\")
}
escaped = true
i++ // skip the next character
}
}
return nil, escaped, nil, NewParserError(b[len(b):], `basic string not terminated by "`)
return nil, escaped, b[len(b):], newDecodeError(b[len(b):], `basic string not terminated by "`)
}
func scanMultilineBasicString(b []byte) ([]byte, bool, []byte, error) {
@@ -245,27 +243,27 @@ func scanMultilineBasicString(b []byte) ([]byte, bool, []byte, error) {
i++
if i < len(b) && b[i] == '"' {
return nil, escaped, nil, NewParserError(b[i-3:i+1], `""" not allowed in multiline basic string`)
return nil, escaped, b[i+1:], newDecodeError(b[i-3:i+1], `""" not allowed in multiline basic string`)
}
return b[:i], escaped, b[i:], nil
}
case '\\':
if len(b) < i+2 {
return nil, escaped, nil, NewParserError(b[len(b):], "need a character after \\")
return nil, escaped, b[len(b):], newDecodeError(b[len(b):], "need a character after \\")
}
escaped = true
i++ // skip the next character
case '\r':
if len(b) < i+2 {
return nil, escaped, nil, NewParserError(b[len(b):], `need a \n after \r`)
return nil, escaped, b[len(b):], newDecodeError(b[len(b):], `need a \n after \r`)
}
if b[i+1] != '\n' {
return nil, escaped, nil, NewParserError(b[i:i+2], `need a \n after \r`)
return nil, escaped, b[i+2:], newDecodeError(b[i:i+2], `need a \n after \r`)
}
i++ // skip the \n
}
}
return nil, escaped, nil, NewParserError(b[len(b):], `multiline basic string not terminated by """`)
return nil, escaped, b[len(b):], newDecodeError(b[len(b):], `multiline basic string not terminated by """`)
}
+17 -17
View File
@@ -1,9 +1,9 @@
package toml
import (
"github.com/pelletier/go-toml/v2/internal/ast"
"github.com/pelletier/go-toml/v2/internal/danger"
"github.com/pelletier/go-toml/v2/internal/tracker"
"github.com/pelletier/go-toml/v2/unstable"
)
type strict struct {
@@ -12,10 +12,10 @@ type strict struct {
// Tracks the current key being processed.
key tracker.KeyTracker
missing []unstable.ParserError
missing []decodeError
}
func (s *strict) EnterTable(node *unstable.Node) {
func (s *strict) EnterTable(node *ast.Node) {
if !s.Enabled {
return
}
@@ -23,7 +23,7 @@ func (s *strict) EnterTable(node *unstable.Node) {
s.key.UpdateTable(node)
}
func (s *strict) EnterArrayTable(node *unstable.Node) {
func (s *strict) EnterArrayTable(node *ast.Node) {
if !s.Enabled {
return
}
@@ -31,7 +31,7 @@ func (s *strict) EnterArrayTable(node *unstable.Node) {
s.key.UpdateArrayTable(node)
}
func (s *strict) EnterKeyValue(node *unstable.Node) {
func (s *strict) EnterKeyValue(node *ast.Node) {
if !s.Enabled {
return
}
@@ -39,7 +39,7 @@ func (s *strict) EnterKeyValue(node *unstable.Node) {
s.key.Push(node)
}
func (s *strict) ExitKeyValue(node *unstable.Node) {
func (s *strict) ExitKeyValue(node *ast.Node) {
if !s.Enabled {
return
}
@@ -47,27 +47,27 @@ func (s *strict) ExitKeyValue(node *unstable.Node) {
s.key.Pop(node)
}
func (s *strict) MissingTable(node *unstable.Node) {
func (s *strict) MissingTable(node *ast.Node) {
if !s.Enabled {
return
}
s.missing = append(s.missing, unstable.ParserError{
Highlight: keyLocation(node),
Message: "missing table",
Key: s.key.Key(),
s.missing = append(s.missing, decodeError{
highlight: keyLocation(node),
message: "missing table",
key: s.key.Key(),
})
}
func (s *strict) MissingField(node *unstable.Node) {
func (s *strict) MissingField(node *ast.Node) {
if !s.Enabled {
return
}
s.missing = append(s.missing, unstable.ParserError{
Highlight: keyLocation(node),
Message: "missing field",
Key: s.key.Key(),
s.missing = append(s.missing, decodeError{
highlight: keyLocation(node),
message: "missing field",
key: s.key.Key(),
})
}
@@ -88,7 +88,7 @@ func (s *strict) Error(doc []byte) error {
return err
}
func keyLocation(node *unstable.Node) []byte {
func keyLocation(node *ast.Node) []byte {
k := node.Key()
hasOne := k.Next()
+5 -5
View File
@@ -6,9 +6,9 @@ import (
"time"
)
var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}(nil))
var sliceInterfaceType = reflect.TypeOf([]interface{}(nil))
var timeType = reflect.TypeOf(time.Time{})
var textMarshalerType = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem()
var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{})
var sliceInterfaceType = reflect.TypeOf([]interface{}{})
var stringType = reflect.TypeOf("")
+72 -71
View File
@@ -12,16 +12,16 @@ import (
"sync/atomic"
"time"
"github.com/pelletier/go-toml/v2/internal/ast"
"github.com/pelletier/go-toml/v2/internal/danger"
"github.com/pelletier/go-toml/v2/internal/tracker"
"github.com/pelletier/go-toml/v2/unstable"
)
// Unmarshal deserializes a TOML document into a Go value.
//
// It is a shortcut for Decoder.Decode() with the default options.
func Unmarshal(data []byte, v interface{}) error {
p := unstable.Parser{}
p := parser{}
p.Reset(data)
d := decoder{p: &p}
@@ -60,7 +60,7 @@ func (d *Decoder) DisallowUnknownFields() *Decoder {
// are ignored. See Decoder.DisallowUnknownFields() to change this behavior.
//
// When a TOML local date, time, or date-time is decoded into a time.Time, its
// value is represented in time.Local timezone. Otherwise the appropriate Local*
// value is represented in time.Local timezone. Otherwise the approriate Local*
// structure is used. For time values, precision up to the nanosecond is
// supported by truncating extra digits.
//
@@ -101,7 +101,7 @@ func (d *Decoder) Decode(v interface{}) error {
return fmt.Errorf("toml: %w", err)
}
p := unstable.Parser{}
p := parser{}
p.Reset(b)
dec := decoder{
p: &p,
@@ -115,7 +115,7 @@ func (d *Decoder) Decode(v interface{}) error {
type decoder struct {
// Which parser instance in use for this decoding session.
p *unstable.Parser
p *parser
// Flag indicating that the current expression is stashed.
// If set to true, calling nextExpr will not actually pull a new expression
@@ -157,7 +157,7 @@ func (d *decoder) typeMismatchError(toml string, target reflect.Type) error {
return fmt.Errorf("toml: cannot decode TOML %s into a Go value of type %s", toml, target)
}
func (d *decoder) expr() *unstable.Node {
func (d *decoder) expr() *ast.Node {
return d.p.Expression()
}
@@ -208,12 +208,12 @@ func (d *decoder) FromParser(v interface{}) error {
err := d.fromParser(r)
if err == nil {
return d.strict.Error(d.p.Data())
return d.strict.Error(d.p.data)
}
var e *unstable.ParserError
var e *decodeError
if errors.As(err, &e) {
return wrapDecodeError(d.p.Data(), e)
return wrapDecodeError(d.p.data, e)
}
return err
@@ -234,16 +234,16 @@ func (d *decoder) fromParser(root reflect.Value) error {
Rules for the unmarshal code:
- The stack is used to keep track of which values need to be set where.
- handle* functions <=> switch on a given unstable.Kind.
- handle* functions <=> switch on a given ast.Kind.
- unmarshalX* functions need to unmarshal a node of kind X.
- An "object" is either a struct or a map.
*/
func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) error {
func (d *decoder) handleRootExpression(expr *ast.Node, v reflect.Value) error {
var x reflect.Value
var err error
if !(d.skipUntilTable && expr.Kind == unstable.KeyValue) {
if !(d.skipUntilTable && expr.Kind == ast.KeyValue) {
err = d.seen.CheckExpression(expr)
if err != nil {
return err
@@ -251,16 +251,16 @@ func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) err
}
switch expr.Kind {
case unstable.KeyValue:
case ast.KeyValue:
if d.skipUntilTable {
return nil
}
x, err = d.handleKeyValue(expr, v)
case unstable.Table:
case ast.Table:
d.skipUntilTable = false
d.strict.EnterTable(expr)
x, err = d.handleTable(expr.Key(), v)
case unstable.ArrayTable:
case ast.ArrayTable:
d.skipUntilTable = false
d.strict.EnterArrayTable(expr)
x, err = d.handleArrayTable(expr.Key(), v)
@@ -269,7 +269,7 @@ func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) err
}
if d.skipUntilTable {
if expr.Kind == unstable.Table || expr.Kind == unstable.ArrayTable {
if expr.Kind == ast.Table || expr.Kind == ast.ArrayTable {
d.strict.MissingTable(expr)
}
} else if err == nil && x.IsValid() {
@@ -279,14 +279,14 @@ func (d *decoder) handleRootExpression(expr *unstable.Node, v reflect.Value) err
return err
}
func (d *decoder) handleArrayTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleArrayTable(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
if key.Next() {
return d.handleArrayTablePart(key, v)
}
return d.handleKeyValues(v)
}
func (d *decoder) handleArrayTableCollectionLast(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleArrayTableCollectionLast(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
switch v.Kind() {
case reflect.Interface:
elem := v.Elem()
@@ -339,13 +339,13 @@ func (d *decoder) handleArrayTableCollectionLast(key unstable.Iterator, v reflec
case reflect.Array:
idx := d.arrayIndex(true, v)
if idx >= v.Len() {
return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx)
return v, fmt.Errorf("toml: cannot decode array table into %s at position %d", v.Type(), idx)
}
elem := v.Index(idx)
_, err := d.handleArrayTable(key, elem)
return v, err
default:
return reflect.Value{}, d.typeMismatchError("array table", v.Type())
return reflect.Value{}, fmt.Errorf("toml: cannot decode array table into a %s", v.Type())
}
}
@@ -353,7 +353,7 @@ func (d *decoder) handleArrayTableCollectionLast(key unstable.Iterator, v reflec
// evaluated like a normal key, but if it returns a collection, it also needs to
// point to the last element of the collection. Unless it is the last part of
// the key, then it needs to create a new element at the end.
func (d *decoder) handleArrayTableCollection(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleArrayTableCollection(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
if key.IsLast() {
return d.handleArrayTableCollectionLast(key, v)
}
@@ -390,7 +390,7 @@ func (d *decoder) handleArrayTableCollection(key unstable.Iterator, v reflect.Va
case reflect.Array:
idx := d.arrayIndex(false, v)
if idx >= v.Len() {
return v, fmt.Errorf("%s at position %d", d.typeMismatchError("array table", v.Type()), idx)
return v, fmt.Errorf("toml: cannot decode array table into %s at position %d", v.Type(), idx)
}
elem := v.Index(idx)
_, err := d.handleArrayTable(key, elem)
@@ -400,7 +400,7 @@ func (d *decoder) handleArrayTableCollection(key unstable.Iterator, v reflect.Va
return d.handleArrayTable(key, v)
}
func (d *decoder) handleKeyPart(key unstable.Iterator, v reflect.Value, nextFn handlerFn, makeFn valueMakerFn) (reflect.Value, error) {
func (d *decoder) handleKeyPart(key ast.Iterator, v reflect.Value, nextFn handlerFn, makeFn valueMakerFn) (reflect.Value, error) {
var rv reflect.Value
// First, dispatch over v to make sure it is a valid object.
@@ -518,7 +518,7 @@ func (d *decoder) handleKeyPart(key unstable.Iterator, v reflect.Value, nextFn h
// HandleArrayTablePart navigates the Go structure v using the key v. It is
// only used for the prefix (non-last) parts of an array-table. When
// encountering a collection, it should go to the last element.
func (d *decoder) handleArrayTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleArrayTablePart(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
var makeFn valueMakerFn
if key.IsLast() {
makeFn = makeSliceInterface
@@ -530,10 +530,10 @@ func (d *decoder) handleArrayTablePart(key unstable.Iterator, v reflect.Value) (
// HandleTable returns a reference when it has checked the next expression but
// cannot handle it.
func (d *decoder) handleTable(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleTable(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
if v.Kind() == reflect.Slice {
if v.Len() == 0 {
return reflect.Value{}, unstable.NewParserError(key.Node().Data, "cannot store a table in a slice")
return reflect.Value{}, newDecodeError(key.Node().Data, "cannot store a table in a slice")
}
elem := v.Index(v.Len() - 1)
x, err := d.handleTable(key, elem)
@@ -560,7 +560,7 @@ func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) {
var rv reflect.Value
for d.nextExpr() {
expr := d.expr()
if expr.Kind != unstable.KeyValue {
if expr.Kind != ast.KeyValue {
// Stash the expression so that fromParser can just loop and use
// the right handler.
// We could just recurse ourselves here, but at least this gives a
@@ -587,7 +587,7 @@ func (d *decoder) handleKeyValues(v reflect.Value) (reflect.Value, error) {
}
type (
handlerFn func(key unstable.Iterator, v reflect.Value) (reflect.Value, error)
handlerFn func(key ast.Iterator, v reflect.Value) (reflect.Value, error)
valueMakerFn func() reflect.Value
)
@@ -599,11 +599,11 @@ func makeSliceInterface() reflect.Value {
return reflect.MakeSlice(sliceInterfaceType, 0, 16)
}
func (d *decoder) handleTablePart(key unstable.Iterator, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleTablePart(key ast.Iterator, v reflect.Value) (reflect.Value, error) {
return d.handleKeyPart(key, v, d.handleTable, makeMapStringInterface)
}
func (d *decoder) tryTextUnmarshaler(node *unstable.Node, v reflect.Value) (bool, error) {
func (d *decoder) tryTextUnmarshaler(node *ast.Node, v reflect.Value) (bool, error) {
// Special case for time, because we allow to unmarshal to it from
// different kind of AST nodes.
if v.Type() == timeType {
@@ -613,7 +613,7 @@ func (d *decoder) tryTextUnmarshaler(node *unstable.Node, v reflect.Value) (bool
if v.CanAddr() && v.Addr().Type().Implements(textUnmarshalerType) {
err := v.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText(node.Data)
if err != nil {
return false, unstable.NewParserError(d.p.Raw(node.Raw), "%w", err)
return false, newDecodeError(d.p.Raw(node.Raw), "%w", err)
}
return true, nil
@@ -622,7 +622,7 @@ func (d *decoder) tryTextUnmarshaler(node *unstable.Node, v reflect.Value) (bool
return false, nil
}
func (d *decoder) handleValue(value *unstable.Node, v reflect.Value) error {
func (d *decoder) handleValue(value *ast.Node, v reflect.Value) error {
for v.Kind() == reflect.Ptr {
v = initAndDereferencePointer(v)
}
@@ -633,32 +633,32 @@ func (d *decoder) handleValue(value *unstable.Node, v reflect.Value) error {
}
switch value.Kind {
case unstable.String:
case ast.String:
return d.unmarshalString(value, v)
case unstable.Integer:
case ast.Integer:
return d.unmarshalInteger(value, v)
case unstable.Float:
case ast.Float:
return d.unmarshalFloat(value, v)
case unstable.Bool:
case ast.Bool:
return d.unmarshalBool(value, v)
case unstable.DateTime:
case ast.DateTime:
return d.unmarshalDateTime(value, v)
case unstable.LocalDate:
case ast.LocalDate:
return d.unmarshalLocalDate(value, v)
case unstable.LocalTime:
case ast.LocalTime:
return d.unmarshalLocalTime(value, v)
case unstable.LocalDateTime:
case ast.LocalDateTime:
return d.unmarshalLocalDateTime(value, v)
case unstable.InlineTable:
case ast.InlineTable:
return d.unmarshalInlineTable(value, v)
case unstable.Array:
case ast.Array:
return d.unmarshalArray(value, v)
default:
panic(fmt.Errorf("handleValue not implemented for %s", value.Kind))
}
}
func (d *decoder) unmarshalArray(array *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalArray(array *ast.Node, v reflect.Value) error {
switch v.Kind() {
case reflect.Slice:
if v.IsNil() {
@@ -729,7 +729,7 @@ func (d *decoder) unmarshalArray(array *unstable.Node, v reflect.Value) error {
return nil
}
func (d *decoder) unmarshalInlineTable(itable *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalInlineTable(itable *ast.Node, v reflect.Value) error {
// Make sure v is an initialized object.
switch v.Kind() {
case reflect.Map:
@@ -746,7 +746,7 @@ func (d *decoder) unmarshalInlineTable(itable *unstable.Node, v reflect.Value) e
}
return d.unmarshalInlineTable(itable, elem)
default:
return unstable.NewParserError(d.p.Raw(itable.Raw), "cannot store inline table in Go type %s", v.Kind())
return newDecodeError(itable.Data, "cannot store inline table in Go type %s", v.Kind())
}
it := itable.Children()
@@ -765,7 +765,7 @@ func (d *decoder) unmarshalInlineTable(itable *unstable.Node, v reflect.Value) e
return nil
}
func (d *decoder) unmarshalDateTime(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalDateTime(value *ast.Node, v reflect.Value) error {
dt, err := parseDateTime(value.Data)
if err != nil {
return err
@@ -775,7 +775,7 @@ func (d *decoder) unmarshalDateTime(value *unstable.Node, v reflect.Value) error
return nil
}
func (d *decoder) unmarshalLocalDate(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalLocalDate(value *ast.Node, v reflect.Value) error {
ld, err := parseLocalDate(value.Data)
if err != nil {
return err
@@ -792,28 +792,28 @@ func (d *decoder) unmarshalLocalDate(value *unstable.Node, v reflect.Value) erro
return nil
}
func (d *decoder) unmarshalLocalTime(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalLocalTime(value *ast.Node, v reflect.Value) error {
lt, rest, err := parseLocalTime(value.Data)
if err != nil {
return err
}
if len(rest) > 0 {
return unstable.NewParserError(rest, "extra characters at the end of a local time")
return newDecodeError(rest, "extra characters at the end of a local time")
}
v.Set(reflect.ValueOf(lt))
return nil
}
func (d *decoder) unmarshalLocalDateTime(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalLocalDateTime(value *ast.Node, v reflect.Value) error {
ldt, rest, err := parseLocalDateTime(value.Data)
if err != nil {
return err
}
if len(rest) > 0 {
return unstable.NewParserError(rest, "extra characters at the end of a local date time")
return newDecodeError(rest, "extra characters at the end of a local date time")
}
if v.Type() == timeType {
@@ -828,7 +828,7 @@ func (d *decoder) unmarshalLocalDateTime(value *unstable.Node, v reflect.Value)
return nil
}
func (d *decoder) unmarshalBool(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalBool(value *ast.Node, v reflect.Value) error {
b := value.Data[0] == 't'
switch v.Kind() {
@@ -837,13 +837,13 @@ func (d *decoder) unmarshalBool(value *unstable.Node, v reflect.Value) error {
case reflect.Interface:
v.Set(reflect.ValueOf(b))
default:
return unstable.NewParserError(value.Data, "cannot assign boolean to a %t", b)
return newDecodeError(value.Data, "cannot assign boolean to a %t", b)
}
return nil
}
func (d *decoder) unmarshalFloat(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalFloat(value *ast.Node, v reflect.Value) error {
f, err := parseFloat(value.Data)
if err != nil {
return err
@@ -854,13 +854,13 @@ func (d *decoder) unmarshalFloat(value *unstable.Node, v reflect.Value) error {
v.SetFloat(f)
case reflect.Float32:
if f > math.MaxFloat32 {
return unstable.NewParserError(value.Data, "number %f does not fit in a float32", f)
return newDecodeError(value.Data, "number %f does not fit in a float32", f)
}
v.SetFloat(f)
case reflect.Interface:
v.Set(reflect.ValueOf(f))
default:
return unstable.NewParserError(value.Data, "float cannot be assigned to %s", v.Kind())
return newDecodeError(value.Data, "float cannot be assigned to %s", v.Kind())
}
return nil
@@ -886,12 +886,7 @@ func init() {
}
}
func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error {
kind := v.Kind()
if kind == reflect.Float32 || kind == reflect.Float64 {
return d.unmarshalFloat(value, v)
}
func (d *decoder) unmarshalInteger(value *ast.Node, v reflect.Value) error {
i, err := parseInteger(value.Data)
if err != nil {
return err
@@ -899,7 +894,7 @@ func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error
var r reflect.Value
switch kind {
switch v.Kind() {
case reflect.Int64:
v.SetInt(i)
return nil
@@ -972,20 +967,20 @@ func (d *decoder) unmarshalInteger(value *unstable.Node, v reflect.Value) error
return nil
}
func (d *decoder) unmarshalString(value *unstable.Node, v reflect.Value) error {
func (d *decoder) unmarshalString(value *ast.Node, v reflect.Value) error {
switch v.Kind() {
case reflect.String:
v.SetString(string(value.Data))
case reflect.Interface:
v.Set(reflect.ValueOf(string(value.Data)))
default:
return unstable.NewParserError(d.p.Raw(value.Raw), "cannot store TOML string into a Go %s", v.Kind())
return newDecodeError(d.p.Raw(value.Raw), "cannot store TOML string into a Go %s", v.Kind())
}
return nil
}
func (d *decoder) handleKeyValue(expr *unstable.Node, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleKeyValue(expr *ast.Node, v reflect.Value) (reflect.Value, error) {
d.strict.EnterKeyValue(expr)
v, err := d.handleKeyValueInner(expr.Key(), expr.Value(), v)
@@ -999,7 +994,7 @@ func (d *decoder) handleKeyValue(expr *unstable.Node, v reflect.Value) (reflect.
return v, err
}
func (d *decoder) handleKeyValueInner(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleKeyValueInner(key ast.Iterator, value *ast.Node, v reflect.Value) (reflect.Value, error) {
if key.Next() {
// Still scoping the key
return d.handleKeyValuePart(key, value, v)
@@ -1009,7 +1004,7 @@ func (d *decoder) handleKeyValueInner(key unstable.Iterator, value *unstable.Nod
return reflect.Value{}, d.handleValue(value, v)
}
func (d *decoder) handleKeyValuePart(key unstable.Iterator, value *unstable.Node, v reflect.Value) (reflect.Value, error) {
func (d *decoder) handleKeyValuePart(key ast.Iterator, value *ast.Node, v reflect.Value) (reflect.Value, error) {
// contains the replacement for v
var rv reflect.Value
@@ -1039,9 +1034,15 @@ func (d *decoder) handleKeyValuePart(key unstable.Iterator, value *unstable.Node
mv := v.MapIndex(mk)
set := false
if !mv.IsValid() || key.IsLast() {
if !mv.IsValid() {
set = true
mv = reflect.New(v.Type().Elem()).Elem()
} else {
if key.IsLast() {
var x interface{}
mv = reflect.ValueOf(&x).Elem()
set = true
}
}
nv, err := d.handleKeyValueInner(key, value, mv)
@@ -1139,7 +1140,7 @@ func fieldByIndex(v reflect.Value, path []int) reflect.Value {
for i, x := range path {
v = v.Field(x)
if i < len(path)-1 && v.Kind() == reflect.Ptr {
if i < len(path)-1 && v.Kind() == reflect.Pointer {
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
@@ -1207,7 +1208,7 @@ func forEachField(t reflect.Type, path []int, do func(name string, path []int))
if f.Anonymous && name == "" {
t2 := f.Type
if t2.Kind() == reflect.Ptr {
if t2.Kind() == reflect.Pointer {
t2 = t2.Elem()
}
+2 -23
View File
@@ -2466,27 +2466,6 @@ func TestIssue807(t *testing.T) {
require.Equal(t, "foo", m.Name)
}
func TestIssue850(t *testing.T) {
data := make(map[string]string)
err := toml.Unmarshal([]byte("foo = {}"), &data)
require.Error(t, err)
}
func TestIssue851(t *testing.T) {
type Target struct {
Params map[string]string `toml:"params"`
}
content := "params = {a=\"1\",b=\"2\"}"
var target Target
err := toml.Unmarshal([]byte(content), &target)
require.NoError(t, err)
require.Equal(t, map[string]string{"a": "1", "b": "2"}, target.Params)
err = toml.Unmarshal([]byte(content), &target)
require.NoError(t, err)
require.Equal(t, map[string]string{"a": "1", "b": "2"}, target.Params)
}
func TestUnmarshalDecodeErrors(t *testing.T) {
examples := []struct {
desc string
@@ -2763,7 +2742,7 @@ world'`,
data: "a = \"aaaa\xE2\x80\x00\"",
},
{
desc: "invalid 4th byte of 4-byte utf8 character in string with no escape sequence",
desc: "invalid 4rd byte of 4-byte utf8 character in string with no escape sequence",
data: "a = \"aaaa\xF2\x81\x81\x00\"",
},
{
@@ -2779,7 +2758,7 @@ world'`,
data: "a = 'aaaa\xE2\x80\x00'",
},
{
desc: "invalid 4th byte of 4-byte utf8 character in literal string",
desc: "invalid 4rd byte of 4-byte utf8 character in literal string",
data: "a = 'aaaa\xF2\x81\x81\x00'",
},
{
-71
View File
@@ -1,71 +0,0 @@
package unstable
// root contains a full AST.
//
// It is immutable once constructed with Builder.
type root struct {
nodes []Node
}
// Iterator over the top level nodes.
func (r *root) Iterator() Iterator {
it := Iterator{}
if len(r.nodes) > 0 {
it.node = &r.nodes[0]
}
return it
}
func (r *root) at(idx reference) *Node {
return &r.nodes[idx]
}
type reference int
const invalidReference reference = -1
func (r reference) Valid() bool {
return r != invalidReference
}
type builder struct {
tree root
lastIdx int
}
func (b *builder) Tree() *root {
return &b.tree
}
func (b *builder) NodeAt(ref reference) *Node {
return b.tree.at(ref)
}
func (b *builder) Reset() {
b.tree.nodes = b.tree.nodes[:0]
b.lastIdx = 0
}
func (b *builder) Push(n Node) reference {
b.lastIdx = len(b.tree.nodes)
b.tree.nodes = append(b.tree.nodes, n)
return reference(b.lastIdx)
}
func (b *builder) PushAndChain(n Node) reference {
newIdx := len(b.tree.nodes)
b.tree.nodes = append(b.tree.nodes, n)
if b.lastIdx >= 0 {
b.tree.nodes[b.lastIdx].next = newIdx - b.lastIdx
}
b.lastIdx = newIdx
return reference(b.lastIdx)
}
func (b *builder) AttachChild(parent reference, child reference) {
b.tree.nodes[parent].child = int(child) - int(parent)
}
func (b *builder) Chain(from reference, to reference) {
b.tree.nodes[from].next = int(to) - int(from)
}
-3
View File
@@ -1,3 +0,0 @@
// Package unstable provides APIs that do not meet the backward compatibility
// guarantees yet.
package unstable
+47 -6
View File
@@ -1,4 +1,4 @@
package characters
package toml
import (
"unicode/utf8"
@@ -32,7 +32,7 @@ func (u utf8Err) Zero() bool {
// 0x9 => tab, ok
// 0xA - 0x1F => invalid
// 0x7F => invalid
func Utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) {
func utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) {
// Fast path. Check for and skip 8 bytes of ASCII characters per iteration.
offset := 0
for len(p) >= 8 {
@@ -48,7 +48,7 @@ func Utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) {
}
for i, b := range p[:8] {
if InvalidAscii(b) {
if invalidAscii(b) {
err.Index = offset + i
err.Size = 1
return
@@ -62,7 +62,7 @@ func Utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) {
for i := 0; i < n; {
pi := p[i]
if pi < utf8.RuneSelf {
if InvalidAscii(pi) {
if invalidAscii(pi) {
err.Index = offset + i
err.Size = 1
return
@@ -106,11 +106,11 @@ func Utf8TomlValidAlreadyEscaped(p []byte) (err utf8Err) {
}
// Return the size of the next rune if valid, 0 otherwise.
func Utf8ValidNext(p []byte) int {
func utf8ValidNext(p []byte) int {
c := p[0]
if c < utf8.RuneSelf {
if InvalidAscii(c) {
if invalidAscii(c) {
return 0
}
return 1
@@ -140,6 +140,47 @@ func Utf8ValidNext(p []byte) int {
return size
}
var invalidAsciiTable = [256]bool{
0x00: true,
0x01: true,
0x02: true,
0x03: true,
0x04: true,
0x05: true,
0x06: true,
0x07: true,
0x08: true,
// 0x09 TAB
// 0x0A LF
0x0B: true,
0x0C: true,
// 0x0D CR
0x0E: true,
0x0F: true,
0x10: true,
0x11: true,
0x12: true,
0x13: true,
0x14: true,
0x15: true,
0x16: true,
0x17: true,
0x18: true,
0x19: true,
0x1A: true,
0x1B: true,
0x1C: true,
0x1D: true,
0x1E: true,
0x1F: true,
// 0x20 - 0x7E Printable ASCII characters
0x7F: true,
}
func invalidAscii(b byte) bool {
return invalidAsciiTable[b]
}
// acceptRange gives the range of valid values for the second byte in a UTF-8
// sequence.
type acceptRange struct {