Debian Codegraph @

third_party/rust/ron/README.md

raw
1 # Rusty Object Notation
2
3 [![MSRV](https://img.shields.io/badge/MSRV-1.64.0-orange)](https://github.com/ron-rs/ron)
4 [![Crates.io](https://img.shields.io/crates/v/ron.svg)](https://crates.io/crates/ron)
5 [![Docs](https://docs.rs/ron/badge.svg)](https://docs.rs/ron)
6
7 [![CI](https://github.com/ron-rs/ron/actions/workflows/ci.yaml/badge.svg)](https://github.com/ron-rs/ron/actions/workflows/ci.yaml)
8 [![Coverage](https://img.shields.io/endpoint?url=https%3A%2F%2Fron-rs.github.io%2Fron%2Fcoverage%2Fcoverage.json)](https://ron-rs.github.io/ron/coverage/)
9 [![Fuzzing](https://oss-fuzz-build-logs.storage.googleapis.com/badges/ron.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:ron)
10
11 [![Matrix](https://img.shields.io/matrix/ron-rs:matrix.org.svg)](https://matrix.to/#/#ron-rs:matrix.org)
12
13 RON is a simple readable data serialization format that looks similar to Rust syntax.
14 It's designed to support all of [Serde's data model](https://serde.rs/data-model.html), so
15 structs, enums, tuples, arrays, generic maps, and primitive values.
16
17 ## Example
18
19 ```ron
20 GameConfig( // optional struct name
21 window_size: (800, 600),
22 window_title: "PAC-MAN",
23 fullscreen: false,
24
25 mouse_sensitivity: 1.4,
26 key_bindings: {
27 "up": Up,
28 "down": Down,
29 "left": Left,
30 "right": Right,
31
32 // Uncomment to enable WASD controls
33 /*
34 "W": Up,
35 "S": Down,
36 "A": Left,
37 "D": Right,
38 */
39 },
40
41 difficulty_options: (
42 start_difficulty: Easy,
43 adaptive: false,
44 ),
45 )
46 ```
47
48 ## RON syntax overview
49
50 * Numbers: `42`, `3.14`, `0xFF`, `0b0110`
51 * Strings: `"Hello"`, `"with\\escapes\n"`, `r#"raw string, great for regex\."#`
52 * Byte Strings: `b"Hello"`, `b"with \x65\x73\x63\x61\x70\x65\x73\n"`, `br#"raw, too"#`
53 * Booleans: `true`, `false`
54 * Chars: `'e'`, `'\n'`
55 * Optionals: `Some("string")`, `Some(Some(1.34))`, `None`
56 * Tuples: `("abc", 1.23, true)`, `()`
57 * Lists: `["abc", "def"]`
58 * Structs: `( foo: 1.0, bar: ( baz: "I'm nested" ) )`
59 * Maps: `{ "arbitrary": "keys", "are": "allowed" }`
60
61 > **Note:** Serde's data model represents fixed-size Rust arrays as tuple (instead of as list)
62
63 RON also supports several extensions, which are documented [here](docs/extensions.md).
64
65 ## Specification
66
67 RON's formal and complete grammar is available [here](docs/grammar.md).
68
69 There also is a very basic, work in progress specification available on
70 [the wiki page](https://github.com/ron-rs/ron/wiki/Specification).
71
72 ## Why RON?
73
74 ### Example in JSON
75
76 ```json
77 {
78 "materials": {
79 "metal": {
80 "reflectivity": 1.0
81 },
82 "plastic": {
83 "reflectivity": 0.5
84 }
85 },
86 "entities": [
87 {
88 "name": "hero",
89 "material": "metal"
90 },
91 {
92 "name": "monster",
93 "material": "plastic"
94 }
95 ]
96 }
97 ```
98
99 ### Same example in RON
100
101 ```ron
102 Scene( // class name is optional
103 materials: { // this is a map
104 "metal": (
105 reflectivity: 1.0,
106 ),
107 "plastic": (
108 reflectivity: 0.5,
109 ),
110 },
111 entities: [ // this is an array
112 (
113 name: "hero",
114 material: "metal",
115 ),
116 (
117 name: "monster",
118 material: "plastic",
119 ),
120 ],
121 )
122 ```
123
124 Note the following advantages of RON over JSON:
125
126 * trailing commas allowed
127 * single- and multi-line comments
128 * field names aren't quoted, so it's less verbose
129 * optional struct names improve readability
130 * enums are supported (and less verbose than their JSON representation)
131
132 ## Quickstart
133
134 ### `Cargo.toml`
135
136 ```toml
137 [dependencies]
138 ron = "0.8"
139 serde = { version = "1", features = ["derive"] }
140 ```
141
142 ### `main.rs`
143
144 ```rust
145 use serde::{Deserialize, Serialize};
146
147 #[derive(Debug, Deserialize, Serialize)]
148 struct MyStruct {
149 boolean: bool,
150 float: f32,
151 }
152
153 fn main() {
154 let x: MyStruct = ron::from_str("(boolean: true, float: 1.23)").unwrap();
155
156 println!("RON: {}", ron::to_string(&x).unwrap());
157
158 println!("Pretty RON: {}", ron::ser::to_string_pretty(
159 &x, ron::ser::PrettyConfig::default()).unwrap(),
160 );
161 }
162 ```
163
164 ## Tooling
165
166 | Editor | Plugin |
167 | ------------ | ----------------------------------------------------------- |
168 | IntelliJ | [intellij-ron](https://github.com/ron-rs/intellij-ron) |
169 | VS Code | [a5huynh/vscode-ron](https://github.com/a5huynh/vscode-ron) |
170 | Sublime Text | [RON](https://packagecontrol.io/packages/RON) |
171 | Atom | [language-ron](https://atom.io/packages/language-ron) |
172 | Vim | [ron-rs/ron.vim](https://github.com/ron-rs/ron.vim) |
173 | EMACS | [emacs-ron] |
174
175 [emacs-ron]: https://chiselapp.com/user/Hutzdog/repository/ron-mode/home
176
177 ## Limitations
178
179 RON requires struct, enum, and variant names to be valid Rust identifiers and will reject invalid ones created by `#[serde(rename = "...")]` at serialization / deserialization time.
180
181 RON is not designed to be a fully self-describing format (unlike JSON) and is thus not guaranteed to work when [`deserialize_any`](https://docs.rs/serde/latest/serde/trait.Deserializer.html#tymethod.deserialize_any) is used instead of its typed alternatives. In particular, the following Serde attributes only have limited support:
182
183 - `#[serde(tag = "tag")]`, i.e. internally tagged enums [^serde-enum-hack]
184 - `#[serde(tag = "tag", content = "content")]`, i.e. adjacently tagged enums [^serde-enum-hack]
185 - `#[serde(untagged)]`, i.e. untagged enums [^serde-enum-hack]
186 - `#[serde(flatten)]`, i.e. flattening of structs into maps [^serde-flatten-hack]
187
188 While data structures with any of these attributes should generally roundtrip through RON, some restrictions apply [^serde-restrictions] and their textual representation may not always match your expectation:
189
190 - ron only supports string keys inside maps flattened into structs
191 - internally (or adjacently) tagged or untagged enum variants or `#[serde(flatten)]`ed fields must not contain:
192 - struct names, e.g. by enabling the `#[enable(explicit_struct_names)]` extension or the `PrettyConfig::struct_names` setting
193 - newtypes
194 - zero-length arrays / tuples / tuple structs / structs / tuple variants / struct variants
195 - `Option`s with `#[enable(implicit_some)]` must not contain any of these or a unit, unit struct, or an untagged unit variant
196 - externally tagged tuple variants with just one field (that are not newtype variants)
197 - tuples or arrays or tuple structs with just one element are not supported inside newtype variants with `#[enable(unwrap_variant_newtypes)]` (including `Some`)
198 - a `ron::value::RawValue`
199 - untagged tuple / struct variants with no fields are not supported
200 - untagged tuple variants with just one field (that are not newtype variants) are not supported when the `#![enable(unwrap_variant_newtypes)]` extension is enabled
201 - serializing a `ron::value::RawValue` using a `PrettyConfig` may add leading and trailing whitespace and comments, which the `ron::value::RawValue` absorbs upon deserialization
202
203 Furthermore, serde imposes the following restrictions for data to roundtrip:
204
205 - structs or struct variants that contain a `#[serde(flatten)]`ed field:
206 - are only serialised as maps and deserialised from maps
207 - must not contain duplicate fields / keys, e.g. where an inner-struct field matches an outer-struct or inner-struct field
208 - must not contain more than one (within the super-struct of all flattened structs) `#[serde(flatten)]`ed map field, which collects all unknown fields
209 - if they contain a `#[serde(flatten)]`ed map, they must not contain:
210 - a struct that is not flattened itself but contains some flattened fields and is flattened into the outer struct (variant)
211 - an untagged struct variant that contains some flattened fields
212 - a flattened externally tagged newtype, tuple, or struct variant, flattened internally tagged unit, newtype, or struct variant, or any flattened adjacently tagged variant
213 - a flattened tagged struct
214 - internally (or adjacently) tagged or untagged enum variants or `#[serde(flatten)]`ed fields must not contain:
215 - `i128` or `u128` values
216 - internally tagged newtype variants and `#[serde(flatten)]`ed fields must not contain:
217 - a unit or a unit struct inside an untagged newtype variant
218 - an untagged unit variant
219 - internally tagged newtype variants, which are `#[serde(flatten)]`ed together with other fields, must not contain:
220 - a unit or unit struct or an untagged unit variant
221
222 While RON offers a best-effort implementation for `#[serde(flatten)]`, it may be unsupported in further cases and combinations not listed above. These limitations stem primarily from serde rather than RON. Enumerating all such cases based on serde's behavior is nontrivial, so the lists above are not exhaustive.
223
224 Please file a [new issue](https://github.com/ron-rs/ron/issues/new) if you come across a use case which is not listed among the above restrictions but still breaks.
225
226 While RON guarantees roundtrips like Rust -> RON -> Rust for Rust types using non-`deserialize_any`-based implementations, RON does not yet make any guarantees about roundtrips through `ron::Value`. For instance, even when RON -> Rust works, RON -> `ron::Value` -> Rust, or RON -> `ron::Value` -> RON -> Rust may not work. We plan on improving `ron::Value` in an upcoming version of RON, though this work is partially blocked on [serde#1183](https://github.com/serde-rs/serde/issues/1183).
227
228 [^serde-enum-hack]: Deserialising an internally, adjacently, or un-tagged enum requires detecting `serde`'s internal `serde::__private::de::content::Content` content type so that RON can describe the deserialised data structure in serde's internal JSON-like format. This detection only works for the automatically-derived [`Deserialize`](https://docs.rs/serde/latest/serde/de/trait.Deserialize.html) impls on enums. See [#451](https://github.com/ron-rs/ron/pull/451) for more details.
229
230 [^serde-flatten-hack]: Deserialising a flattened struct from a map requires that the struct's [`Visitor::expecting`](https://docs.rs/serde/latest/serde/de/trait.Visitor.html#tymethod.expecting) implementation formats a string starting with `"struct "`. This is the case for automatically-derived [`Deserialize`](https://docs.rs/serde/latest/serde/de/trait.Deserialize.html) impls on structs. See [#455](https://github.com/ron-rs/ron/pull/455) for more details.
231
232 [^serde-restrictions]: Most of these restrictions are currently blocked on [serde#1183](https://github.com/serde-rs/serde/issues/1183), which limits non-self-describing formats from roundtripping format-specific information through internally (or adjacently) tagged or untagged enums or `#[serde(flatten)]`ed fields.
233
234 ## License
235
236 RON is dual-licensed under Apache-2.0 and MIT.
237
238 Any contribution intentionally submitted for inclusion in the work must be provided under the same dual-license terms.