1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
//! # UCL for Rust
//!
//! A reader and writer for UCL (Universal Configuration Language), the configuration format of
//! libucl, with serde integration. The crate reads and writes UCL as libucl does: the
//! repository's conformance suite compares its results, and its output in every format, with
//! libucl's own. [COMPATIBILITY.md] lists the places where the crate deliberately differs, and
//! the `README.md` of the repository describes the crate at more length.
//!
//! [COMPATIBILITY.md]: https://github.com/AnderEnder/serde_ucl/blob/HEAD/docs/COMPATIBILITY.md
//!
//! ## Reading configuration
//!
//! ```rust
//! use serde::Deserialize;
//!
//! #[derive(Debug, Deserialize)]
//! struct Config {
//! name: String,
//! port: u16,
//! timeout: f64,
//! max_body: u64,
//! upstream: Vec<String>,
//! }
//!
//! let text = r#"
//! name = "my-server"
//! port = 8080
//! # A time, read as seconds.
//! timeout = 30s
//! # A multiplier: 512 * 1024.
//! max_body = 512kb
//! # A repeated key holds several values.
//! upstream = a.example
//! upstream = b.example
//! "#;
//!
//! let config: Config = serde_ucl::from_str(text)?;
//! assert_eq!(config.port, 8080);
//! assert_eq!(config.timeout, 30.0);
//! assert_eq!(config.max_body, 512 * 1024);
//! assert_eq!(config.upstream, ["a.example", "b.example"]);
//! # Ok::<(), serde_ucl::UclError>(())
//! ```
//!
//! [`from_str`], [`from_slice`], [`from_reader`] and [`from_file`] parse with a default
//! [`parse::Parser`]: no parser flags, no registered variables, and the macros of the format
//! enabled. Text input has no file access: an `.include` in a string finds no file. Only
//! [`from_file`] reads the filesystem, for the file and for its includes, whose relative paths
//! resolve against the file's directory. [`de`] describes this and how UCL values map onto
//! serde.
//!
//! ## Parser settings
//!
//! Parser flags, duplicate-key strategies, priorities, variables, a variable handler, the
//! loader that include macros read files from, their search directories and an input size limit
//! are settings of [`parse::Parser`], set with its setters or with [`parse::ParserBuilder`]. A
//! parser reads files only through a loader that holds them, such as [`parse::FsLoader`]. There
//! is no input limit by default, as in libucl; see [`parse::Parser::set_max_input_bytes`]. Parse
//! to a [`UclValue`], then deserialize it with [`from_value`]:
//!
//! ```rust
//! use serde::Deserialize;
//! use serde_ucl::parse::ParserBuilder;
//! use serde_ucl::{DuplicateStrategy, from_value};
//!
//! #[derive(Deserialize)]
//! struct Config {
//! url: String,
//! workers: u32,
//! }
//!
//! let mut parser = ParserBuilder::new()
//! .with_strategy(DuplicateStrategy::Rewrite)
//! .with_variable("HOST", "example.org")
//! .build();
//! let value = parser.parse(b"url = \"https://$HOST/\"\nworkers = 2\nworkers = 8")?;
//! let config: Config = from_value(value)?;
//! assert_eq!(config.url, "https://example.org/");
//! assert_eq!(config.workers, 8);
//! # Ok::<(), serde_ucl::UclError>(())
//! ```
//!
//! ## Several inputs and custom macros
//!
//! A parser can read several inputs into one result, each with its own priority and duplicate
//! strategy ([`parse::Parser::inputs`], [`parse::Input`]; spec §13.1). Defaults can so be
//! layered under a user's file: at a higher priority the user's values win, and under `merge`
//! objects combine.
//!
//! ```rust
//! use serde_ucl::parse::{Input, MemoryLoader, ParserBuilder};
//! use serde_ucl::DuplicateStrategy;
//!
//! let mut files = MemoryLoader::new();
//! files.add_file("/usr/share/app/app.conf", "workers = 4\nlog { level = info }\n");
//! files.add_file("/etc/app/app.conf", "workers = 16\nlog { file = /var/log/app.log }\n");
//! let mut parser = ParserBuilder::new().with_loader(files).build();
//! let mut inputs = parser.inputs();
//! inputs.add(Input::file("/usr/share/app/app.conf"))?;
//! inputs.add(
//! Input::file("/etc/app/app.conf")
//! .with_priority(1)
//! .with_strategy(DuplicateStrategy::Merge),
//! )?;
//! let value = inputs.finish()?;
//! let root = value.as_object().unwrap();
//! assert_eq!(root["workers"].as_integer(), Some(16));
//! let log = root["log"].as_object().unwrap();
//! assert_eq!(log["level"].as_str(), Some("info"));
//! assert_eq!(log["file"].as_str(), Some("/var/log/app.log"));
//! # Ok::<(), serde_ucl::parse::Error>(())
//! ```
//!
//! An application can also register macros of its own ([`parse::ParserBuilder::with_macro`];
//! spec §13.2). A handler adds entries where the macro stands, has text parsed in place of the
//! macro, stops the parse silently or fails with a message ([`parse::MacroCall`],
//! [`parse::MacroError`]):
//!
//! ```rust
//! use serde_ucl::parse::{MacroError, ParserBuilder};
//! use serde_ucl::UclValue;
//!
//! let mut parser = ParserBuilder::new()
//! // `.version`: adds the application's version where the macro stands.
//! .with_macro("version", |call| {
//! call.add("version", UclValue::String("1.4.2".into()))
//! })
//! // `.feature NAME`: the settings of a named feature, parsed in place.
//! .with_macro("feature", |call| match call.value_str() {
//! Some("tls") => call.parse("tls { enabled = true; port = 443 }"),
//! _ => Err(MacroError::new("unknown feature")),
//! })
//! .build();
//! let value = parser.parse(b".version {}\nserver { .feature tls\n}")?;
//! let root = value.as_object().unwrap();
//! assert_eq!(root["version"].as_str(), Some("1.4.2"));
//! let tls = root["server"].as_object().unwrap()["tls"].as_object().unwrap();
//! assert_eq!(tls["port"].as_integer(), Some(443));
//! # Ok::<(), serde_ucl::parse::Error>(())
//! ```
//!
//! ## Errors
//!
//! Every function returns [`UclError`]. A document the parser rejects is
//! [`UclError::Syntax`], whose [`parse::Error`] has an [`parse::ErrorKind`] and the
//! [`Position`] where the error was found:
//!
//! ```rust
//! use serde_ucl::UclError;
//! use serde_ucl::parse::ErrorKind;
//!
//! let err = serde_ucl::from_str::<serde_json::Value>("a = 1\nb = \"open").unwrap_err();
//! let UclError::Syntax(e) = err else { panic!("{err}") };
//! assert_eq!(e.kind(), &ErrorKind::UnterminatedString);
//! assert_eq!((e.position().line, e.position().column), (2, 5));
//! ```
//!
//! A document that parses but does not fit the target type is [`UclError::Deserialize`]. Its
//! [`error::DeserializeError`] has serde's error, the path of the value it is about, and where
//! that value was written, in the document or in the included file it came from, also when the
//! duplicate rules merged or moved it or `.inherit` copied it. [`UclError::position`] and
//! [`UclError::file`] give the position of both kinds:
//!
//! ```rust
//! #[derive(Debug, serde::Deserialize)]
//! struct Config {
//! #[allow(dead_code)]
//! port: u16,
//! }
//!
//! let err = serde_ucl::from_str::<Config>("# the port\nport = http").unwrap_err();
//! let position = err.position().unwrap();
//! assert_eq!((position.line, position.column), (2, 8));
//! assert_eq!(
//! err.to_string(),
//! "Deserialization error: invalid type: string \"http\", expected u16 at port (line 2, column 8)"
//! );
//! ```
//!
//! The text functions find the path and position only when deserialization fails, by parsing and
//! deserializing a second time, so they cost nothing while it succeeds. To use other parser
//! settings and keep positions, deserialize with [`UclDeserializer::from_parser`], which records
//! paths as it goes. [`from_value`] records nothing: its errors have neither a path nor a
//! position. [`de`] describes this in full.
//!
//! ## Writing
//!
//! [`to_string`] writes any `Serialize` value in the UCL config format; [`to_json_string`],
//! [`to_json_string_compact`] and [`to_yaml_string`] write the other output formats, and
//! [`to_writer`] writes the config format to an `io::Write`. The output reads back, in libucl and
//! in this crate, as exactly the value written, floats included; the JSON output is valid JSON, in
//! which a time is its number of seconds and reads back as a float. See [`ser`] for the forms used
//! and the values that have none. [`to_value`] and [`from_value`] convert between Rust values and
//! the [`UclValue`] tree. [`emit`] writes a parsed value as libucl writes it.
//!
//! ```rust
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Debug, PartialEq, Serialize, Deserialize)]
//! struct Limits {
//! name: String,
//! ratio: f64,
//! }
//!
//! let limits = Limits { name: "$HOME/db".into(), ratio: 0.1 };
//! let text = serde_ucl::to_string(&limits)?;
//! assert_eq!(text, "name = '$HOME/db';\nratio = 0.1;\n");
//! let back: Limits = serde_ucl::from_str(&text)?;
//! assert_eq!(back, limits);
//! # Ok::<(), serde_ucl::UclError>(())
//! ```
//!
//! ## Cargo features
//!
//! - `fs` (default): the filesystem loader [`parse::FsLoader`] and [`from_file`].
//! - `load` (off by default): the `.load` macro (spec §9.6). Without it, `.load` fails with an
//! "unsupported" error.
// The code examples of README.md run as doctests.
;
pub use ;
pub use from_file;
pub use ;
pub use ;
pub use ;