Repository navigation
Value Tree
When the shape of a document is not known in advance, parse it into a dynamic tree of rustyon.Value nodes instead of a Go struct. The tree keeps everything the source says: struct and tuple names, map order, integer size, the difference between chars and strings, and between tuples and lists. Comments and literal spellings (such as 0x10 versus 16) are not kept; use the Formatter for source-preserving work.
| Function | Description |
|---|---|
Parse(data []byte) (Value, error) |
Parses a document into a Value. Extension attributes are accepted but not returned. |
ParseDocument(data []byte) (*Document, error) |
Parses a document including its #![enable(...)] attributes. |
Valid(data []byte) bool |
Reports whether data is a syntactically valid RON document. |
Syntax problems are returned as *SyntaxError.
v, err := rustyon.Parse([]byte(`Point(x: 1, y: -2)`))
if err != nil {
log.Fatal(err)
}
s := v.(rustyon.Struct)
y, _ := s.Get("y")
fmt.Println(v.Kind(), s.Name, len(s.Fields), y) // struct Point 2 -2fmt.Println(rustyon.Valid([]byte(`(a: [1, 2])`)), rustyon.Valid([]byte(`(a: [1, 2)`)))
// true falsetype Document struct {
Extensions Extensions
Value Value
}Extensions is a bit set with these constants:
| Constant | RON name | Meaning |
|---|---|---|
ImplicitSome |
implicit_some |
Some(x) may be written as x
|
UnwrapNewtypes |
unwrap_newtypes |
newtype structs such as Meters(5.0) may be written as 5.0
|
UnwrapVariantNewtypes |
unwrap_variant_newtypes |
newtype variants that wrap a struct may omit the inner parentheses: Shape(x: 1) instead of Shape((x: 1))
|
ExplicitStructNames |
explicit_struct_names |
struct names must be written |
Extensions.Names() returns the RON names of the enabled bits. Several attributes are combined.
doc, err := rustyon.ParseDocument([]byte("#![enable(implicit_some, unwrap_newtypes)]\n(volume: 5)"))
if err != nil {
log.Fatal(err)
}
fmt.Println(doc.Extensions.Names()) // [implicit_some unwrap_newtypes]
fmt.Println(doc.Extensions&rustyon.ImplicitSome != 0,
doc.Extensions&rustyon.ExplicitStructNames != 0) // true false
fmt.Println(doc.Value.Kind()) // structThe parser records the extensions but does not change how it parses: the value tree always reflects the text as written. Decoding into Go types accepts the implicit and unwrapped forms whether or not they are enabled. Unmarshal and Decoder enforce explicit_struct_names: a Go struct target then needs a named struct, tuple or unit in the input.
Value is an interface implemented by these types:
| Type | Go definition | Kind | RON |
|---|---|---|---|
Unit |
struct{} |
KindUnit |
() |
Bool |
bool |
KindBool |
true |
Int |
128-bit capable integer | KindInt |
42, -0x2A, 1_000u32
|
Float |
float64 |
KindFloat |
1.5, -inf, NaN
|
String |
string |
KindString |
"text", r#"raw"#
|
Char |
rune |
KindChar |
'c' |
Bytes |
[]byte |
KindBytes |
b"bytes" |
List |
[]Value |
KindList |
[a, b] |
Map |
[]MapEntry (Key, Value) |
KindMap |
{k: v} |
Tuple |
struct{ Name string; Values []Value } |
KindTuple |
(a, b), Name(a, b)
|
Struct |
struct{ Name string; Fields []Field }, Field is Name, Value
|
KindStruct |
(f: v), Name(f: v)
|
Option |
struct{ Value Value }, nil Value is None |
KindOption |
None, Some(v)
|
Ident |
string |
KindIdent |
Red (unit struct or unit variant) |
Kind() returns the kind, and Kind.String() gives a readable name such as "byte string". Helpers for options: rustyon.None (the empty option), rustyon.Some(v) and Option.IsNone().
Notes on what the parser produces:
- Byte literals such as
b'a'becomeInt. -
Name()andName( )are aTuplewith a name and no values;()isUnit, while( )(whitespace or a comment between the parentheses) is aTuplewith no name and no values. - Ranges become maps with
startandendstring keys (1..2), orUnitfor... - Unsuffixed integers beyond the 128-bit range become
Float. - A parenthesized group is a
Structwhen its first token is an identifier followed by:, otherwise aTuple. -
Mapentries keep the document order and keys can be any value.
A type switch walks the tree:
v, _ := rustyon.Parse([]byte(`[(), true, 1, 1.5, "s", 'c', b"b", [1], {1: 2}, (1, 2), Point(1, 2), (x: 1), Some(1), None, Red]`))
for _, e := range v.(rustyon.List) {
switch e := e.(type) {
case rustyon.Tuple:
fmt.Printf("%-11s name=%q values=%d\n", e.Kind(), e.Name, len(e.Values))
case rustyon.Option:
fmt.Printf("%-11s none=%v\n", e.Kind(), e.IsNone())
default:
fmt.Printf("%-11s %T\n", e.Kind(), e)
}
}unit rustyon.Unit
bool rustyon.Bool
integer rustyon.Int
float rustyon.Float
string rustyon.String
char rustyon.Char
byte string rustyon.Bytes
list rustyon.List
map rustyon.Map
tuple name="" values=2
tuple name="Point" values=2
struct rustyon.Struct
option none=false
option none=true
identifier rustyon.Ident
The composite value types have a String() method that returns compact RON, so fmt.Println, %v and %s show RON instead of Go's struct syntax ({Player [{name ...}]}). The types are Unit, Option, List, Map, MapEntry, Tuple, Field and Struct.
v, _ := rustyon.Parse([]byte(`Player(name: "Ferris", pos: (1.5, -2), items: ["a", "b"], scores: {"x": 1, "y": 2}, nick: Some("fe"), none: None, unit: ())`))
s := v.(rustyon.Struct)
fmt.Println(s)
for _, f := range s.Fields {
fmt.Printf("%-6s %-14T %v\n", f.Name, f.Value, f.Value)
}
fmt.Println(s.Fields[3].Value.(rustyon.Map)[0]) // a MapEntry
fmt.Println(s.Fields[0]) // a FieldPlayer(name:"Ferris",pos:(1.5,-2),items:["a","b"],scores:{"x":1,"y":2},nick:Some("fe"),none:None,unit:())
name rustyon.String Ferris
pos rustyon.Tuple (1.5,-2)
items rustyon.List ["a","b"]
scores rustyon.Map {"x":1,"y":2}
nick rustyon.Option Some("fe")
none rustyon.Option None
unit rustyon.Unit ()
"x":1
name:"Ferris"
MapEntry prints as key:value and Field as name:value. The output is the compact form of Marshal, without spaces.
The scalar types Bool, Float, String, Char, Bytes and Ident have no String() method on purpose: their Go formatting is what code that prints them expects, so a String prints as Ferris without quotes, as seen above. Inside a list or struct the same string appears as "Ferris", because the container prints RON. Int prints its number. To get the RON text of any single value, scalars included, pass it to rustyon.Marshal.
RON integers can be 128 bits wide, so Int is not a Go integer type. Values that fit into an int64 are stored inline; larger ones use a big.Int. The zero value is 0.
| Function or method | Description |
|---|---|
NewInt(v int64) Int |
Int from an int64
|
NewUint(v uint64) Int |
Int from a uint64
|
NewBigInt(v *big.Int) Int |
Int holding a copy of v
|
(Int) Int64() (int64, bool) |
the value and whether it fits |
(Int) Uint64() (uint64, bool) |
the value and whether it fits |
(Int) Big() *big.Int |
a copy as *big.Int
|
(Int) Float64() float64 |
the nearest float64
|
(Int) Sign() int |
-1, 0 or 1 |
(Int) Cmp(j Int) int |
-1, 0 or 1 |
(Int) String() string |
decimal representation |
v, _ := rustyon.Parse([]byte(`[42, 18446744073709551615, -170141183460469231731687303715884105728i128]`))
l := v.(rustyon.List)
for _, e := range l {
i := e.(rustyon.Int)
n64, ok64 := i.Int64()
u64, okU := i.Uint64()
fmt.Println(i, n64, ok64, u64, okU, i.Sign())
}
a, b := l[0].(rustyon.Int), l[1].(rustyon.Int)
fmt.Println(a.Cmp(b), b.Big().BitLen(), b.Float64())
fmt.Println(rustyon.NewInt(-1), rustyon.NewUint(math.MaxUint64))42 42 true 42 true 1
18446744073709551615 0 false 18446744073709551615 true 1
-170141183460469231731687303715884105728 0 false 0 false -1
-1 64 1.8446744073709552e+19
-1 18446744073709551615
| Method | Description |
|---|---|
(Struct) Get(name string) (Value, bool) |
value of the field name
|
(*Struct) Set(name string, v Value) |
replaces the field, or appends it if missing |
(Map) Get(key Value) (Value, bool) |
value stored under a key Equal to key
|
(*Map) Set(key, v Value) |
replaces the entry, or appends it if missing |
Lookups are linear scans, which keeps document order and is fast for the small collections typical in configuration files.
Building a tree by hand and printing it:
s := rustyon.Struct{Name: "Config"}
s.Set("title", rustyon.String("demo"))
s.Set("size", rustyon.Tuple{Values: []rustyon.Value{rustyon.NewInt(800), rustyon.NewInt(600)}})
s.Set("title", rustyon.String("renamed")) // replaces the existing field
var keys rustyon.Map
keys.Set(rustyon.String("up"), rustyon.Ident("Up"))
keys.Set(rustyon.Char('d'), rustyon.Ident("Down"))
s.Set("keys", keys)
s.Set("fps", rustyon.Some(rustyon.NewInt(60)))
s.Set("icon", rustyon.None)
out, _ := rustyon.MarshalIndent(s, "", " ")
fmt.Println(string(out))
down, ok := keys.Get(rustyon.Char('d'))
fmt.Println(down, ok)Config(
title: "renamed",
size: (800, 600),
keys: {
"up": Up,
'd': Down,
},
fps: Some(60),
icon: None,
)
Down trueA Value passed to Marshal is written as it is. A Map keeps its order; only Go maps are sorted. A named Struct with no fields prints as a bare name, an anonymous one as (). A Tuple with no values prints as ( ), or Name() when it has a name, so the empty tuple stays distinct from Unit.
Equal(a, b Value) bool compares two trees structurally:
- Kinds must match:
Int(1)andFloat(1)are not equal. - Integers compare by value, regardless of how they were written.
- Floats compare by value, except that
NaNequalsNaN, so a document containingNaNequals itself. - Struct fields and map entries compare in order.
- Names of tuples and structs must match.
-
nilequals onlynil.
a, _ := rustyon.Parse([]byte(`(x: NaN, n: 0x10)`))
b, _ := rustyon.Parse([]byte(`(x: NaN, n: 16)`))
c, _ := rustyon.Parse([]byte(`(n: 16, x: NaN)`))
fmt.Println(rustyon.Equal(a, b), rustyon.Equal(a, c)) // true false
fmt.Println(rustyon.Equal(rustyon.NewInt(1), rustyon.Float(1))) // false| Function | Description |
|---|---|
ToValue(v any) (Value, error) |
converts a Go value into a tree using the rules of Marshal
|
FromValue(v Value, target any) error |
stores a tree in the Go value target points to, using the rules of Unmarshal
|
Both use DefaultRegistry for enums. Together they allow edits on the tree level:
type Player struct {
Name string
MaxHP int
}
v, _ := rustyon.ToValue(Player{Name: "Ferris", MaxHP: 100})
s := v.(rustyon.Struct)
s.Set("max_hp", rustyon.NewInt(150))
var p Player
rustyon.FromValue(s, &p)
fmt.Printf("%+v\n", p) // {Name:Ferris MaxHP:150}A struct field of type rustyon.Value receives the subtree unchanged and is written back as it is; see Type Mapping. Decoding into any instead gives plain Go maps and slices without names; see Type Mapping.
rustyon is licensed under the BSD-3-Clause license. It is an independent implementation of RON and is not affiliated with the ron-rs project.