simple_toml_parser/
lib.rs1#[derive(Debug, Clone, PartialEq, Eq)]
2pub enum TOMLKey<'a> {
3 Slice(&'a str),
4 Index(usize),
5}
6
7#[derive(Debug, PartialEq, Eq)]
8pub enum RootTOMLValue<'a> {
9 String(&'a str),
10 Number(&'a str),
11 Boolean(bool),
12 Null,
13}
14
15#[derive(Debug)]
16pub enum TOMLParseErrorReason {
17 ExpectedColon,
18 ExpectedEndOfValue,
19 ExpectedBracket,
20 ExpectedTrueFalseNull,
21 ExpectedValue,
22}
23
24#[derive(Debug)]
25pub struct TOMLParseError {
26 pub at: usize,
27 pub reason: TOMLParseErrorReason,
28}
29
30impl std::error::Error for TOMLParseError {}
31
32impl std::fmt::Display for TOMLParseError {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
34 f.write_fmt(format_args!(
35 "TOMLParseError: {:?} at {:?}",
36 self.reason, self.at
37 ))
38 }
39}
40
41pub fn parse<'a>(
46 on: &'a str,
47 mut cb: impl for<'b> FnMut(&'b [TOMLKey<'a>], RootTOMLValue<'a>),
48) -> Result<(), TOMLParseError> {
49 parse_with_exit_signal(on, |k, v| {
50 cb(k, v);
51 false
52 })
53}
54
55#[allow(clippy::too_many_lines)]
60pub fn parse_with_exit_signal<'a>(
61 on: &'a str,
62 mut cb: impl for<'b> FnMut(&'b [TOMLKey<'a>], RootTOMLValue<'a>) -> bool,
63) -> Result<(), TOMLParseError> {
64 let mut key_chain = Vec::new();
65 let lines = on.lines();
66
67 for line in lines {
68 if line.starts_with("[[") {
69 let _ = key_chain.drain(..);
70 assert!(line.ends_with("]]"), "TODO error");
71
72 let idx = if let Some(TOMLKey::Index(idx)) = key_chain.last() {
73 idx + 1
74 } else {
75 0
76 };
77 for part in line[1..(line.len() - "]]".len())].split('.') {
79 key_chain.push(TOMLKey::Slice(part));
80 }
81 key_chain.push(TOMLKey::Index(idx));
82 } else if line.starts_with('[') {
83 let _ = key_chain.drain(..);
84 assert!(line.ends_with(']'), "TODO error");
85 for part in line[1..(line.len() - "]".len())].split('.') {
87 key_chain.push(TOMLKey::Slice(part));
88 }
89 } else {
90 if line.starts_with('#') || line.is_empty() {
91 continue;
92 }
93 if let Some((key, value)) = line.split_once('=') {
94 let length = key_chain.len();
95 for part in key.trim().split('.') {
96 key_chain.push(TOMLKey::Slice(part));
97 }
98
99 let value = value.trim();
100 let value = if let "true" | "false" = value {
101 RootTOMLValue::Boolean(value == "true")
102 } else if value.starts_with(['"', '\'']) {
103 assert!(
104 value.ends_with(value.chars().next().unwrap()),
105 "TODO unclosed string"
106 );
107 RootTOMLValue::String(&value[1..(value.len() - 1)])
108 } else if value.starts_with(char::is_numeric) {
109 RootTOMLValue::Number(value)
110 } else {
111 eprintln!("here {value}");
112 continue;
113 };
114
115 let _result = cb(&key_chain, value);
116
117 let _ = key_chain.drain(length..);
118 } else {
119 panic!("bad key")
120 }
121 }
122 }
123
124 Ok(())
125}