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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
 Cargo KConfig - KConfig parser
 Copyright (C) 2022  Sjoerd van Leent

--------------------------------------------------------------------------------

Copyright Notice: Apache

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

--------------------------------------------------------------------------------

Copyright Notice: GPLv2

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

--------------------------------------------------------------------------------

Copyright Notice: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

//! This file contains the source lexer, which behaves like a regular lexer,
//! but inserts the contents of source files indicated by the "source ..."
//! directive.

use std::fmt::Display;

use super::{
    structs::{Keyword, Lexicon, Token},
    LexerBase,
};
use crate::parse_string;

/// The source lexer allows the source directive to be used to load
/// additional sources as part of the (currently) loaded Kconfig file.
pub struct SourceLexer<LB>
where
    LB: LexerBase,
{
    /// This stack is composed of the name of the stream and the lexer
    /// belonging to the stream. If the lexer has been depleted, it will
    /// be removed from the stack.
    stack: Vec<Table<LB>>,

    /// The source function takes the name of the source and returns a new
    /// lexer.
    source_function: fn(&str) -> Result<LB, String>,

    /// The resolve_name_function resolves the name of the source
    /// to a canonical name understood by the system. This is primarily
    /// used to discover source recursion (which wouldn't end).
    canonical_name_function: fn(&str) -> String,
}

struct Table<LB>
where
    LB: LexerBase,
{
    stream_name: String,
    lexer: LB,
}

/// Provides a basic error message when the source function for one
/// or the other reason fails.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
    msg: String,
}

impl Error {
    /// Creates a new error from a source function, and allows it to
    /// be passed as part of the source lexer error conditions.
    pub fn new(s: &str) -> Error {
        Error { msg: s.to_string() }
    }
}

impl Display for Error {
    /// Formats the error
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.msg)
    }
}

impl<LB> SourceLexer<LB>
where
    LB: LexerBase,
{
    /// Creates a new source lexer, given the stream's name. This will
    /// create the first source_function call, to actually load the
    /// stream.
    pub fn new(
        stream_name: &str,
        source_function: fn(&str) -> Result<LB, String>,
        canonical_name_function: fn(&str) -> String,
    ) -> Result<Self, Error> {
        match (source_function)(stream_name) {
            Ok(lexer) => Ok(Self {
                stack: vec![Table {
                    stream_name: stream_name.to_string(),
                    lexer: lexer,
                }],
                source_function,
                canonical_name_function,
            }),
            Err(s) => {
                Err(Error::new(&s))
            }
        }
    }
}

impl<LB> LexerBase for SourceLexer<LB>
where
    LB: LexerBase,
{
    fn next_token(&mut self) -> super::structs::Token {
        let last = self.stack.last_mut();
        match last {
            Some(table) => {
                let token = table.lexer.next_token();
                match token.term() {
                    Lexicon::EOT => {
                        self.stack.pop();
                        token
                    }
                    Lexicon::Keyword(k) => match k {
                        Keyword::Source => {
                            // read the next token, which should be a string,
                            // pointing to the stream to read.
                            let token = table.lexer.next_token();
                            match token.term() {
                                Lexicon::String(stream_name) => {
                                    let stream_name = match parse_string(&stream_name) {
                                        Ok(s) => s,
                                        Err(e) => {
                                            return Token::create(
                                                Lexicon::Error(e),
                                                token.column(),
                                                token.line(),
                                                &token.raw(),
                                            )
                                        }
                                    };
                                    let canonical_name =
                                        (self.canonical_name_function)(&stream_name);
                                    // Verify whether the the stream_name
                                    // does not already exist in the stack and creates
                                    // a circular load.
                                    for needle in &self.stack {
                                        if needle.stream_name.eq(&canonical_name) {
                                            return Token::create(
                                                Lexicon::Error(
                                                    "Circular source detected, abort load"
                                                        .to_string(),
                                                ),
                                                token.column(),
                                                token.line(),
                                                &token.raw(),
                                            );
                                        }
                                    }

                                    match (self.source_function)(&stream_name) {
                                        Ok(lb) => {
                                            let t = Table {
                                                stream_name: canonical_name,
                                                lexer: lb,
                                            };
        
                                            self.stack.push(t);
                                            self.next_token()
                                        },
                                        Err(s) => {
                                            Token::create(Lexicon::Error(s), token.column(), token.line(), &token.raw())
                                        }
                                    }
                                }
                                _ => Token::create(
                                    Lexicon::Error(
                                        "Expected string indicating source file or stream"
                                            .to_string(),
                                    ),
                                    token.column(),
                                    token.line(),
                                    &token.raw(),
                                ),
                            }
                        }
                        _ => token,
                    },
                    _ => token,
                }
            }
            None => Token::create(Lexicon::EOT, 0, 0, &""),
        }
    }

    fn current_stream(&self) -> Option<String> {
        let last = self.stack.last();
        match last {
            Some(table) => Some(table.stream_name.to_string()),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::Lexer;
    use super::super::LexerBase;
    use super::*;

    #[test]
    fn test_keywords() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "mainmenu config menuconfig choice endchoice menu endmenu if endif bool def_bool \
                                  tristate def_tristate string hex int default depends on select imply visible range prompt comment".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();
        assert_eq!(Lexicon::Keyword(Keyword::Mainmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Config), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menuconfig), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Choice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endchoice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::If), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endif), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Bool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::DefBool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Tristate), l.next_token().term());
        assert_eq!(
            Lexicon::Keyword(Keyword::DefTristate),
            l.next_token().term()
        );
        assert_eq!(Lexicon::Keyword(Keyword::String), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Hex), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Int), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Default), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Depends), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::On), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Select), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Imply), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Visible), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Range), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Prompt), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Comment), l.next_token().term());
        assert_eq!(Lexicon::EOT, l.next_token().term());
    }

    #[test]
    fn test_keywords_sub_lexer() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source \"bar\"".as_bytes();
                    Ok(Lexer::create(s))
                } else if stream_name == "bar" {
                    let s = &mut "mainmenu config menuconfig choice endchoice menu endmenu if endif bool def_bool \
                                  tristate def_tristate string hex int default depends on select imply visible range prompt comment".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();
        assert_eq!(Lexicon::Keyword(Keyword::Mainmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Config), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menuconfig), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Choice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endchoice), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Menu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endmenu), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::If), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Endif), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Bool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::DefBool), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Tristate), l.next_token().term());
        assert_eq!(
            Lexicon::Keyword(Keyword::DefTristate),
            l.next_token().term()
        );
        assert_eq!(Lexicon::Keyword(Keyword::String), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Hex), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Int), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Default), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Depends), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::On), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Select), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Imply), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Visible), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Range), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Prompt), l.next_token().term());
        assert_eq!(Lexicon::Keyword(Keyword::Comment), l.next_token().term());
        assert_eq!(Lexicon::EOT, l.next_token().term());
    }

    #[test]
    fn test_error_wrong_syntax() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source bla".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();

        let is_error = if let Lexicon::Error(_) = l.next_token().term() {
            true
        } else {
            false
        };
        assert_eq!(is_error, true);
    }

    #[test]
    fn test_error_circular_syntax() {
        let mut l = SourceLexer::<Lexer<&[u8]>>::new(
            "foo",
            |stream_name| {
                if stream_name == "foo" {
                    let s = &mut "source \"bar\"".as_bytes();
                    Ok(Lexer::create(s))
                } else if stream_name == "bar" {
                    let s = &mut "source \"foo\"".as_bytes();
                    Ok(Lexer::create(s))
                } else {
                    Err("Error".to_owned())
                }
            },
            |stream_name| stream_name.to_string(),
        ).unwrap();

        let is_error = if let Lexicon::Error(_) = l.next_token().term() {
            true
        } else {
            false
        };
        assert_eq!(is_error, true);
    }
}