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
/*
 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 pub structures necessary for the lexer
//! to lex the tokens found within a Kconfig file.

use std::fmt::Display;

/// An equality operator is used for testing two expressions. These
/// expressions should be valid expressions according to the Kconfig
/// grammar.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum EqualityOperator {
    /// Lesser than or equal to (<=)
    Lte,
    /// Greater than or equal to (>=)
    Lt,
    /// Lesser than (<)
    Gte,
    /// Greater than (>)
    Gt,
    /// Equal to (==)
    Eq,
    /// Not equal to (!=)
    Ne,
}

impl Display for EqualityOperator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EqualityOperator::Lte => f.write_str("<="),
            EqualityOperator::Lt => f.write_str("<"),
            EqualityOperator::Gte => f.write_str(">="),
            EqualityOperator::Gt => f.write_str(">"),
            EqualityOperator::Eq => f.write_str("=="),
            EqualityOperator::Ne => f.write_str("!="),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Keyword {
    /// source
    Source,

    /// mainmenu
    Mainmenu,
    /// config
    Config,
    /// menuconfig
    Menuconfig,
    /// choice
    Choice,
    /// endchoide
    Endchoice,
    /// menu
    Menu,
    /// endmenu
    Endmenu,

    /// if
    If,
    /// endif
    Endif,

    /// bool
    Bool,
    /// def_bool
    DefBool,
    /// tristate
    Tristate,
    /// def_tristate
    DefTristate,
    /// string
    String,
    /// hex
    Hex,
    /// int
    Int,

    /// default
    Default,

    /// depends
    Depends,
    /// on
    On,
    /// select
    Select,
    /// imply
    Imply,

    /// visible
    Visible,

    /// range
    Range,

    /// prompt
    Prompt,
    /// comment
    Comment,
}

impl Display for Keyword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Keyword::Source => f.write_str("source"),
            Keyword::Mainmenu => f.write_str("mainmenu"),
            Keyword::Config => f.write_str("config"),
            Keyword::Menuconfig => f.write_str("menuconfic"),
            Keyword::Choice => f.write_str("choice"),
            Keyword::Endchoice => f.write_str("endchoice"),
            Keyword::Menu => f.write_str("menu"),
            Keyword::Endmenu => f.write_str("endmenu"),
            Keyword::If => f.write_str("if"),
            Keyword::Endif => f.write_str("endif"),
            Keyword::Bool => f.write_str("bool"),
            Keyword::DefBool => f.write_str("def_bool"),
            Keyword::Tristate => f.write_str("tristate"),
            Keyword::DefTristate => f.write_str("def_tristate"),
            Keyword::String => f.write_str("string"),
            Keyword::Hex => f.write_str("hex"),
            Keyword::Int => f.write_str("int"),
            Keyword::Default => f.write_str("default"),
            Keyword::Depends => f.write_str("depends"),
            Keyword::On => f.write_str("on"),
            Keyword::Select => f.write_str("select"),
            Keyword::Imply => f.write_str("imply"),
            Keyword::Visible => f.write_str("visible"),
            Keyword::Range => f.write_str("range"),
            Keyword::Prompt => f.write_str("prompt"),
            Keyword::Comment => f.write_str("comment"),
        }
    }
}

/// There are a certain amount of basic tokens found within a stream
/// of tokens belonging to a Kconfig configuration specification.
/// These tokens are outlined here.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum Lexicon {
    /// Keywords such as config, menuconfig, if, comment, source ...
    Keyword(Keyword),
    /// Identifier, specifically used for assignment and evaluation
    Identifier(String),
    /// Strings, encapsulated in double quotes
    String(String),
    /// Help text, indented when a "Help" section was started
    Help(String),
    /// An equality operator, such as <=, ==, etc.
    EqualityOperator(EqualityOperator),
    /// An immediate assignment, e.g.: :=
    ImmediateAssignment,
    /// A normal assignment, e.g.: =
    Assignment,
    /// An appendage assignment, e.g.: +=
    AppendAssignment,
    /// An inverse of an expression
    Not,
    /// Start a macro definition with "$("
    MacroOpen,
    /// Start a normal definition with "("
    Open,
    /// Ends a definition (either macro or normal) with ")"
    Close,
    /// A comma, typically used as an argument separator
    Comma,
    /// End of transmission, used when no more tokens can be found
    EOT,
    /// Error, used when the found token is illegal
    Error(String),
    /// The '&&' expression
    And,
    /// The '||' expression
    Or,
}

impl Display for Lexicon {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Lexicon::Keyword(k) => f.write_str(&format!("{}", k)),
            Lexicon::Identifier(s) => f.write_str(s),
            Lexicon::String(s) => f.write_str(s),
            Lexicon::Help(s) => f.write_str(s),
            Lexicon::EqualityOperator(o) => f.write_str(&format!("{}", o)),
            Lexicon::ImmediateAssignment => f.write_str(":="),
            Lexicon::Assignment => f.write_str("="),
            Lexicon::AppendAssignment => f.write_str("+="),
            Lexicon::Not => f.write_str("+="),
            Lexicon::MacroOpen => f.write_str("$("),
            Lexicon::Open => f.write_str("("),
            Lexicon::Close => f.write_str(")"),
            Lexicon::Comma => f.write_str(","),
            Lexicon::EOT => f.write_str("[End Of Transmission/File]"),
            Lexicon::Error(s) => f.write_str(&format!("Error: {}", s)),
            Lexicon::And => f.write_str("&"),
            Lexicon::Or => f.write_str("|"),
        }
    }
}

/// A token describes the found verb, the column and line where it has
/// been found.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Token {
    /// Contains the specific token from the lexicon
    term: Lexicon,
    /// Contains the column position of the token from the current
    /// position, if line > 0, then the column position will be from
    /// the start of the line the token was found on.
    column: usize,
    /// Contains the line number of the token from the current
    /// position.
    line: usize,
    /// Contains the raw string of the token
    raw: String,
}

impl Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("{}", self.term))
    }
}

impl Token {
    /// Creates a token, using a term from the `Lexicon`, at the given column
    /// (minus the term), at the specified line with the given string. The string
    /// is only used to determine the length of the token.
    pub(super) fn create(term: Lexicon, column: usize, line: usize, raw: &str) -> Self {
        Self {
            term,
            column,
            line,
            raw: raw.to_string(),
        }
    }

    /// Creates a token representing an error, at the given column (minus the term),
    /// at the specified line with the given string. The string is only used to
    /// determine the length of the token.
    pub(crate) fn create_error(column: usize, line: usize, s: &str) -> Self {
        Self {
            term: Lexicon::Error(s.to_string()),
            column,
            line,
            raw: s.to_string(),
        }
    }

    /// Creates a token representing end-of-transmission, typically at the end of
    /// the file, end of stream or end of buffer, at the given column and line.
    pub(super) fn create_eot(column: usize, line: usize) -> Self {
        Self {
            term: Lexicon::EOT,
            column,
            line,
            raw: "".to_owned(),
        }
    }

    pub fn term(&self) -> Lexicon {
        self.term.clone()
    }

    pub fn column(&self) -> usize {
        self.column
    }

    pub fn line(&self) -> usize {
        self.line
    }

    pub fn raw(&self) -> String {
        self.raw.clone()
    }

    /// Returns if the token's term indicates EOT (End of transmission,
    /// most likely End of file).
    pub fn eot(&self) -> bool {
        match self.term {
            Lexicon::EOT => return true,
            _ => return false,
        }
    }
}

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

    #[test]
    fn test_token_creation() {
        let expected = Token {
            term: Lexicon::EOT,
            column: 0,
            line: 0,
            raw: "".to_owned(),
        };
        let got = Token::create(Lexicon::EOT, 0, 0, &"");
        assert_eq!(expected, got);
    }
}