rushls_common/config/
example.rs1use thiserror::Error;
10
11#[derive(Debug, Error)]
12pub enum ExampleError {
13 #[error("unfinished table header: {0}")]
14 Header(String),
15 #[error("example line {line:?} is not TOML: {source}")]
16 Toml {
17 line: String,
18 source: toml::de::Error,
19 },
20 #[error("example path {0} passes through a scalar")]
21 Scalar(String),
22}
23
24pub struct AnnotatedExample {
26 pub document: toml::Table,
29 pub examples: Vec<(String, toml::Value)>,
31}
32
33impl AnnotatedExample {
34 pub fn parse(text: &str) -> Result<Self, ExampleError> {
37 let mut example = Self {
38 document: toml::Table::new(),
39 examples: Vec::new(),
40 };
41 let mut section = "";
42 for line in text.lines() {
43 let line = line.trim().strip_prefix('#').unwrap_or(line).trim();
44 if let Some(header) = line.strip_prefix('[') {
45 section = header
46 .split_once(']')
47 .ok_or_else(|| ExampleError::Header(line.to_owned()))?
48 .0;
49 continue;
50 }
51 let Some((key, _)) = line.split_once('=') else {
52 continue;
53 };
54 let key = key.trim();
55 if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
56 continue;
57 }
58 let fields: toml::Table =
59 toml::from_str(line).map_err(|source| ExampleError::Toml {
60 line: line.to_owned(),
61 source,
62 })?;
63 for (key, value) in fields {
64 let path = if section.is_empty() {
65 key
66 } else {
67 format!("{section}.{key}")
68 };
69 set(&mut example.document, &path, value.clone())?;
70 example.examples.push((path, value));
71 }
72 }
73 Ok(example)
74 }
75}
76
77pub fn set(document: &mut toml::Table, path: &str, value: toml::Value) -> Result<(), ExampleError> {
79 let mut table = document;
80 let mut parts = path.split('.').peekable();
81 while let Some(part) = parts.next() {
82 if parts.peek().is_none() {
83 table.insert(part.to_owned(), value);
84 return Ok(());
85 }
86 table = table
87 .entry(part)
88 .or_insert_with(|| toml::Value::Table(toml::Table::new()))
89 .as_table_mut()
90 .ok_or_else(|| ExampleError::Scalar(path.to_owned()))?;
91 }
92 Ok(())
93}
94
95pub fn contains(document: &toml::Table, path: &str) -> bool {
97 let mut parts = path.split('.');
98 let Some(first) = parts.next() else {
99 return false;
100 };
101 let mut value = document.get(first);
102 for part in parts {
103 value = value.and_then(|value| value.get(part));
104 }
105 value.is_some()
106}