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
/*
 * Copyright (c) 2021-2021 Thomas Kramer.
 *
 * This file is part of LibrEDA 
 * (see https://codeberg.org/libreda/libreda-lefdef).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

//! Functions for parsing ASCII-based formats from iterators over bytes.

use itertools::{Itertools, PeekingNext};
use std::iter::Peekable;
use std::str::FromStr;
use std::fmt;
use std::num::ParseIntError;

/// Error while parsing LEF or DEF.
/// TODO: Separate lexer errors from LEF/DEF specific errors.
#[derive(Clone, Debug)]
pub enum LefDefParseError {
    /// Encountered invalid character.
    InvalidCharacter,
    /// Reached end of file before end of library arrived.
    UnexpectedEndOfFile,
    /// Expected and actual token.
    UnexpectedToken(String, String),
    /// Unknown token. The token is given as a string.
    UnknownToken(String),
    /// Unknown literal. The literal is given as a string.
    InvalidLiteral(String),
    /// Illegal value for bus bit chars.
    IllegalBusBitChars(char, char),
    /// Something is not yet implemented.
    NotImplemented(&'static str),
    /// Using a property name that has not been defined in PROPERTYDEFINITIONS.
    UndefinedProperty(String),
    /// Failed to parse an integer.
    ParseIntError(ParseIntError),
    /// Some other error defined by a string.
    Other(&'static str)
}

impl fmt::Display for LefDefParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LefDefParseError::InvalidCharacter => write!(f, "Invalid character."),
            LefDefParseError::UnexpectedEndOfFile => write!(f, "Unexpected end of file."),
            LefDefParseError::UnexpectedToken(actual, exp) =>
                write!(f,"Unexpected token. '{}' instead of '{}'", actual, exp),
            LefDefParseError::UnknownToken(t) =>  write!(f, "Unknown token: '{}'.", t),
            LefDefParseError::InvalidLiteral(n) => write!(f, "Invalid literal: '{}'.", n),
            LefDefParseError::IllegalBusBitChars(a, b) => write!(f, "Illegal bus bit chars: '{} {}'.", a, b),
            LefDefParseError::NotImplemented(n) => write!(f, "Not implemented: '{}'.", n),
            LefDefParseError::UndefinedProperty(p) => write!(f, "Undefined property: '{}'.", p),
            LefDefParseError::Other(msg) => write!(f, "'{}'.", msg),
            LefDefParseError::ParseIntError(e) => write!(f, "Illegal integer: '{}'", e)
        }
    }
}

impl From<ParseIntError> for LefDefParseError {
    fn from(e: ParseIntError) -> Self {
        Self::ParseIntError(e)
    }
}

// /// Check if a char is whitespace.
// fn is_whitespace(c: char) -> bool {
//     match c {
//         ' ' => true,
//         '\t' => true,
//         '\r' | '\n' => true,
//         _ => false
//     }
// }


/// Read a token into the buffer. Tokens are separated by white space. Comments are ignored.
/// Quoted tokens can contain white space.
pub(crate) fn read_token<'a, I>(iter: &mut I, buffer: &'a mut String) -> Option<&'a str>
    where I: Iterator<Item=char> + PeekingNext {
    buffer.clear();

    let iter = iter.by_ref();

    loop {
        // Skip whitespace.
        let _n = iter.peeking_take_while(|c| c.is_whitespace()).count();

        // Look ahead.
        if let Some(c) = iter.peeking_next(|_| true) {
            debug_assert!(!c.is_whitespace());

            match c {
                '#' => {
                    // Skip comments.
                    iter.peeking_take_while(|&c| c != '\n' && c != '\r').count();
                }
                '"' | '\'' => {
                    // Quoted string.
                    let quote_char = c;

                    let mut prev = None;
                    while let Some(c) = iter.next() {
                        if prev != Some('\\') && c == quote_char {
                            // Abort on quote char.
                            break;
                        }
                        buffer.push(c);
                        prev = Some(c);
                    }
                    return Some(buffer.as_str());
                }
                _ => {
                    // Normal token.
                    let mut prev = Some(c);
                    buffer.push(c);

                    while let Some(c) = iter.next() {
                        if prev != Some('\\') && c.is_whitespace() {
                            // Abort on unmasked whitespace.
                            break;
                        }

                        buffer.push(c);
                        prev = Some(c);
                    }
                    return Some(buffer.as_str());
                }
            }
        } else {
            return None;
        }
    }
}

/// Read simple tokens and skip comments.
#[test]
fn test_read_token() {
    let data = r#"
        # Comment 1

        # Comment 2

        token1

        # Comment 3

        token2 token3

        "quoted token"

        token4
    "#;

    let mut iter = data.chars()
        .inspect(|c| print!("{}", c))
        .peekable();

    let mut buffer = String::new();

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_some());
    assert_eq!(buffer, "token1");

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_some());
    assert_eq!(buffer, "token2");

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_some());
    assert_eq!(buffer, "token3");

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_some());
    assert_eq!(buffer, "quoted token");

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_some());
    assert_eq!(buffer, "token4");

    let result = read_token(&mut iter, &mut buffer);
    assert!(result.is_none());
}

/// Provide sequential access to tokens that are created on the fly by
/// splitting characters at whitespace.
pub struct Tokenized<I>
    where I: Iterator<Item=char> + PeekingNext {
    iter: I,
    has_current: bool,
    current_token: Option<String>,
}

impl<I> Tokenized<I>
    where I: Iterator<Item=char> + PeekingNext {
    pub fn next_str(&mut self) -> Option<&str> {
        self.advance();
        self.current_token_str()
    }

    pub fn next_string(&mut self) -> Option<String> {
        self.advance();
        self.current_token()
    }

    pub fn take(&mut self) -> Result<String, LefDefParseError> {
        let s = self.current_token();
        self.advance();
        if let Some(s) = s {
            Ok(s)
        } else {
            Err(LefDefParseError::UnexpectedEndOfFile)
        }
    }

    pub fn take_and_parse<F: FromStr>(&mut self) -> Result<F, LefDefParseError> {
        let result = if let Some(s) = self.current_token_str() {
            if let Ok(parsed) = s.parse::<F>() {
                Ok(parsed)
            } else {
                Err(LefDefParseError::InvalidLiteral(s.to_string()))
            }
        } else {
            Err(LefDefParseError::UnexpectedEndOfFile)
        };


        self.advance();

        result
    }

    /// Advance to the next token.
    pub fn advance(&mut self) {
        let mut buffer = self.current_token.take()
            .unwrap_or_else(|| String::new());

        let next_token = read_token(&mut self.iter, &mut buffer);
        let has_next = next_token.is_some();

        self.current_token = Some(buffer);
        self.has_current = has_next;
    }

    pub fn current_token_str(&self) -> Option<&str> {
        if self.has_current {
            self.current_token.as_ref().map(|s| s.as_str())
        } else {
            None
        }
    }

    pub fn current_token(&self) -> Option<String> {
        self.current_token_str().map(|s| s.to_string())
    }

    /// Test if the current token equals to the expected token.
    /// Returns `Ok(())` if the token matches and advances the iterator.
    /// Returns the actual token otherwise.
    pub fn expect(&mut self, s: &str) -> Result<(), LefDefParseError> {
        if self.current_token.is_none() {
            Err(LefDefParseError::UnexpectedEndOfFile)?;
        }

        if self.current_token_str() == Some(s) {
            self.advance();
            Ok(())
        } else {
            Err(LefDefParseError::UnexpectedToken(
                s.to_string(), self.current_token().unwrap().to_string(),
            ))
        }
    }

    /// Test if the current token matches with the string.
    /// The token is consumed only if it matches.
    pub fn test(&mut self, s: &str) -> Result<bool, LefDefParseError> {
        let result = self.peeking_test(s)?;
        if result {
            self.advance();
        }
        Ok(result)
    }

    /// Test if the current token matches with the string.
    /// The token is not consumed.
    pub fn peeking_test(&mut self, s: &str) -> Result<bool, LefDefParseError> {
        if self.current_token.is_none() {
            Err(LefDefParseError::UnexpectedEndOfFile)?;
        }

        if self.current_token_str() == Some(s) {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Consume all tokens until and including `s`.
    pub fn skip_until(&mut self, s: &str) -> Result<(), LefDefParseError> {
        while !self.test(s)? {
            self.advance()
        }
        Ok(())
    }
}

/// Split a stream of characters into tokens separated by whitespace.
/// Comments are ignored.
pub fn tokenize<I>(iter: I) -> Tokenized<Peekable<I>>
    where I: Iterator<Item=char> {
    Tokenized {
        iter: iter.peekable(),
        has_current: false,
        current_token: None,
    }
}

#[test]
fn test_tokenized() {
    let data = r#"
        # Comment 1

        # Comment 2

        token1

        # Comment 3

        token2 token3

        "quoted token"

        token4
    "#;

    let mut tokens = tokenize(data.chars());

    assert_eq!(tokens.next_str(), Some("token1"));
    assert_eq!(tokens.next_str(), Some("token2"));
}