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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//! # Light Ini file parser.
//!
//! `light-ini` implements an event-driven parser for the [INI file format](https://en.wikipedia.org/wiki/INI_file).
//! The handler must implement `IniHandler`.
//!
//! ```
//! use light_ini::{IniHandler, IniParser, IniHandlerError};
//!
//! struct Handler {}
//!
//! impl IniHandler for Handler {
//!     type Error = IniHandlerError;
//!
//!     fn section(&mut self, name: &str) -> Result<(), Self::Error> {
//!         println!("section {}", name);
//!         Ok(())
//!     }
//!
//!     fn option(&mut self, key: &str, value: &str) -> Result<(), Self::Error> {
//!         println!("option {} is {}", key, value);
//!         Ok(())
//!     }
//!
//!     fn comment(&mut self, comment: &str) -> Result<(), Self::Error> {
//!         println!("comment: {}", comment);
//!         Ok(())
//!     }
//! }
//!
//! let mut handler = Handler{};
//! let mut parser = IniParser::new(&mut handler);
//! parser.parse_file("example.ini");
//! ```

use nom::{
    call, char,
    character::complete::{multispace0, space0},
    combinator::all_consuming,
    do_parse, is_not, named, opt,
};
use std::error;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;

#[derive(Debug)]
/// Convenient error type for handlers that don't need detailed errors.
pub struct IniHandlerError {}

impl fmt::Display for IniHandlerError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "handler failure")
    }
}

impl error::Error for IniHandlerError {}

#[derive(Debug)]
/// Errors for INI format parsing
pub enum IniError<HandlerError: fmt::Debug + error::Error> {
    InvalidLine(String),
    Handler(HandlerError),
    Io(io::Error),
}

impl<HandlerError: fmt::Debug + error::Error> fmt::Display for IniError<HandlerError> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IniError::InvalidLine(line) => write!(f, "invalid line: {}", line),
            IniError::Handler(err) => write!(f, "handler error: {:?}", err),
            IniError::Io(err) => write!(f, "io error: {:?}", err),
        }
    }
}

impl<HandlerError: fmt::Debug + error::Error> error::Error for IniError<HandlerError> {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            IniError::InvalidLine(_) => None,
            IniError::Handler(err) => err.source(),
            IniError::Io(err) => err.source(),
        }
    }
}

/// Interface for the INI format handler
pub trait IniHandler {
    type Error: fmt::Debug;

    /// Called when a section is found
    fn section(&mut self, name: &str) -> Result<(), Self::Error>;

    /// Called when an option is found
    fn option(&mut self, key: &str, value: &str) -> Result<(), Self::Error>;

    /// Called for each comment
    fn comment(&mut self, _: &str) -> Result<(), Self::Error> {
        Ok(())
    }
}

// Parse comments starting with a semi colon.
named!(parse_comment<&str,&str>,
  do_parse!(
      space0
      >> char!(';')
      >> space0
      >> ("")
  )
);

// Parse a section between square brackets.
named!(parse_section<&str, &str>,
  do_parse!(
     char!('[')
     >> opt!(space0)
     >> name: is_not!(" \t\r\n]")
     >> opt!(space0)
     >> char!(']')
     >> multispace0
     >> (name)
  )
);

// Parse an option as "key = value"
named!(parse_option<&str, &str>,
  do_parse!(
     key: is_not!(" ;=")
     >> opt!(space0)
     >> char!('=')
     >> opt!(space0)
     >> (key)
  )
);

// Parse a blank line
named!(parse_blank<&str,&str>,
   call!(multispace0)
);

// Convert nom errors to crate errors.
macro_rules! map_herror {
    ($res:expr) => {
        $res.map_err(|err| IniError::Handler(err))
    };
}

/// INI format parser.
pub struct IniParser<'a, Error: fmt::Debug + error::Error> {
    handler: &'a mut dyn IniHandler<Error = Error>,
}

impl<'a, Error: fmt::Debug + error::Error> IniParser<'a, Error> {
    /// Create a parser using the given handler.
    pub fn new(handler: &'a mut dyn IniHandler<Error = Error>) -> IniParser<'a, Error> {
        IniParser { handler }
    }

    /// Parse one line without trailing newline character.
    fn parse_ini_line(&mut self, line: &str) -> Result<(), IniError<Error>> {
        match parse_comment(line) {
            Ok((comment, _)) => map_herror!(self.handler.comment(comment)),
            Err(_) => match all_consuming(parse_section)(line) {
                Ok((_, name)) => map_herror!(self.handler.section(name)),
                Err(_) => match parse_option(line) {
                    Ok((value, key)) => map_herror!(self.handler.option(key, value)),
                    Err(_) => match all_consuming(parse_blank)(line) {
                        Ok(_) => Ok(()),
                        Err(_) => Err(IniError::InvalidLine(line.to_string())),
                    },
                },
            },
        }
    }

    /// Parse input from a buffered reader.
    pub fn parse_buffered<B: BufRead>(&mut self, input: B) -> Result<(), IniError<Error>> {
        for res in input.lines() {
            match res {
                Ok(line) => self.parse_ini_line(line.trim_end())?,
                Err(err) => return Err(IniError::Io(err)),
            }
        }
        Ok(())
    }

    /// Parse input from a reader.
    pub fn parse<R: Read>(&mut self, input: R) -> Result<(), IniError<Error>> {
        let mut reader = BufReader::new(input);
        self.parse_buffered(&mut reader)
    }

    /// Parse a file.
    pub fn parse_file<P>(&mut self, path: P) -> Result<(), IniError<Error>>
    where
        P: AsRef<Path>,
    {
        let file = File::open(path).map_err(|err| IniError::Io(err))?;
        self.parse(file)
    }
}

#[cfg(test)]
mod tests {

    use super::{
        all_consuming, parse_blank, parse_comment, parse_option, parse_section, IniHandler,
        IniParser,
    };
    use std::error;
    use std::fmt;
    use std::io::{self, Seek, Write};

    #[test]
    fn parse_sections() {
        for line in &["[one]\n", "[ one ]  "] {
            let (_, name) = all_consuming(parse_section)(line).unwrap();
            assert_eq!("one", name);
        }
        for line in &["[one\n", "name = value"] {
            let res = all_consuming(parse_section)(line);
            assert!(res.is_err(), "parsing should have failed for: {}", line);
        }
    }

    #[test]
    fn parse_options() {
        for line in &["name = test", "name = one two three  "] {
            let (value, key) = parse_option(line).unwrap();
            assert_eq!("name", key);
            assert!(value.len() > 0);
        }
    }

    #[test]
    fn parse_blank_lines() {
        for line in &["\n", "  \t  \n"] {
            all_consuming(parse_blank)(line).unwrap();
        }
    }

    #[test]
    fn parse_comments() {
        for line in &["; comment", "  ; comment"] {
            let (comment, _) = parse_comment(line).unwrap();
            assert_eq!("comment", comment);
        }
    }

    #[derive(Debug)]
    enum ConfigError {
        InvalidSection,
        InvalidOption,
    }

    impl fmt::Display for ConfigError {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                ConfigError::InvalidSection => write!(fmt, "invalid section"),
                ConfigError::InvalidOption => write!(fmt, "invalid option"),
            }
        }
    }

    impl error::Error for ConfigError {}

    enum ConfigSection {
        Default,
        Logging,
    }

    struct Config {
        section: ConfigSection,
        pub name: Option<String>,
        pub level: Option<String>,
        pub has_comments: bool,
    }

    impl Config {
        fn new() -> Config {
            Config {
                section: ConfigSection::Default,
                name: None,
                level: None,
                has_comments: false,
            }
        }
    }

    impl IniHandler for Config {
        type Error = ConfigError;

        fn section(&mut self, name: &str) -> Result<(), Self::Error> {
            match name {
                "logging" => {
                    self.section = ConfigSection::Logging;
                    Ok(())
                }
                _ => Err(ConfigError::InvalidSection),
            }
        }

        fn option(&mut self, key: &str, value: &str) -> Result<(), Self::Error> {
            match self.section {
                ConfigSection::Default if key == "name" => self.name = Some(value.to_string()),
                ConfigSection::Logging if key == "level" => self.level = Some(value.to_string()),
                _ => return Err(ConfigError::InvalidOption),
            }
            Ok(())
        }

        fn comment(&mut self, _: &str) -> Result<(), Self::Error> {
            self.has_comments = true;
            Ok(())
        }
    }

    const VALID_INI: &str = "name = test suite

; logging section
[logging]
level = error
";

    #[test]
    fn parse_valid_ini() -> io::Result<()> {
        let mut buf = io::Cursor::new(Vec::<u8>::new());
        writeln!(buf, "{}", VALID_INI)?;
        buf.seek(io::SeekFrom::Start(0))?;
        let mut handler = Config::new();
        let mut parser = IniParser::new(&mut handler);
        parser.parse(buf).unwrap();
        assert_eq!(Some("test suite".to_string()), handler.name);
        assert!(handler.has_comments);
        Ok(())
    }

    const INVALID_SECTION: &str = "name = test suite

[unknown]
level = error
";

    #[test]
    fn parse_invalid_section() -> io::Result<()> {
        let mut buf = io::Cursor::new(Vec::<u8>::new());
        writeln!(buf, "{}", INVALID_SECTION)?;
        buf.seek(io::SeekFrom::Start(0))?;
        let mut handler = Config::new();
        let mut parser = IniParser::new(&mut handler);
        assert!(parser.parse(buf).is_err());
        Ok(())
    }
}