Debian Codegraph @

src/cfg_expr/expr/lexer.rs

raw
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2
3 use core::fmt;
4
5 use crate::cfg_expr::error::{ParseError, Reason};
6
7 /// A single token in a cfg expression
8 /// <https://doc.rust-lang.org/reference/conditional-compilation.html>
9 #[derive(Clone, Debug, PartialEq, Eq)]
10 pub(crate) enum Token<'a> {
11 /// A single contiguous term
12 Key(&'a str),
13 /// A single contiguous value, without its surrounding quotes
14 Value(&'a str),
15 /// A '=', joining a key and a value
16 Equals,
17 /// Beginning of an all() predicate list
18 All,
19 /// Beginning of an any() predicate list
20 Any,
21 /// Beginning of a not() predicate
22 Not,
23 /// A `(` for starting a predicate list
24 OpenParen,
25 /// A `)` for ending a predicate list
26 CloseParen,
27 /// A `,` for separating predicates in a predicate list
28 Comma,
29 }
30
31 impl fmt::Display for Token<'_> {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 fmt::Debug::fmt(self, f)
34 }
35 }
36
37 impl Token<'_> {
38 fn len(&self) -> usize {
39 match self {
40 Token::Key(s) => s.len(),
41 Token::Value(s) => s.len() + 2,
42 Token::Equals | Token::OpenParen | Token::CloseParen | Token::Comma => 1,
43 Token::All | Token::Any | Token::Not => 3,
44 }
45 }
46 }
47
48 /// Allows iteration through a cfg expression, yielding
49 /// a token or a `ParseError`.
50 ///
51 /// Prefer to use `Expression::parse` rather than directly
52 /// using the lexer
53 pub(crate) struct Lexer<'a> {
54 pub(super) inner: &'a str,
55 original: &'a str,
56 offset: usize,
57 }
58
59 impl<'a> Lexer<'a> {
60 /// Creates a Lexer over a cfg expression, it can either be
61 /// a raw expression eg `key` or in attribute form, eg `cfg(key)`
62 pub(crate) fn new(text: &'a str) -> Self {
63 let text = if text.starts_with("cfg(") && text.ends_with(')') {
64 &text[4..text.len() - 1]
65 } else {
66 text
67 };
68
69 Self { inner: text, original: text, offset: 0 }
70 }
71 }
72
73 /// A wrapper around a particular token that includes the span of the characters
74 /// in the original string, for diagnostic purposes
75 #[derive(Debug)]
76 pub(crate) struct LexerToken<'a> {
77 /// The token that was lexed
78 pub(crate) token: Token<'a>,
79 /// The range of the token characters in the original license expression
80 pub(crate) span: core::ops::Range<usize>,
81 }
82
83 impl<'a> Iterator for Lexer<'a> {
84 type Item = Result<LexerToken<'a>, ParseError>;
85
86 fn next(&mut self) -> Option<Self::Item> {
87 #[inline]
88 fn is_ident_start(ch: char) -> bool {
89 ch == '_' || ch.is_ascii_lowercase() || ch.is_ascii_uppercase()
90 }
91
92 #[inline]
93 fn is_ident_rest(ch: char) -> bool {
94 is_ident_start(ch) || ch.is_ascii_digit()
95 }
96
97 // Jump over any whitespace, updating `self.inner` and `self.offset` appropriately
98 let non_whitespace_index = match self.inner.find(|c: char| !c.is_whitespace()) {
99 Some(idx) => idx,
100 None => self.inner.len(),
101 };
102
103 self.inner = &self.inner[non_whitespace_index..];
104 self.offset += non_whitespace_index;
105
106 match self.inner.chars().next() {
107 None => None,
108 Some('=') => Some(Ok(Token::Equals)),
109 Some('(') => Some(Ok(Token::OpenParen)),
110 Some(')') => Some(Ok(Token::CloseParen)),
111 Some(',') => Some(Ok(Token::Comma)),
112 Some(c) => {
113 if c == '"' {
114 match self.inner[1..].find('"') {
115 Some(ind) => Some(Ok(Token::Value(&self.inner[1..=ind]))),
116 None => Some(Err(ParseError {
117 original: self.original.into(),
118 span: self.offset..self.original.len(),
119 reason: Reason::UnclosedQuotes,
120 })),
121 }
122 } else if is_ident_start(c) {
123 let sub_str = match self.inner[1..].find(|c: char| !is_ident_rest(c)) {
124 Some(ind) => &self.inner[..=ind],
125 None => self.inner,
126 };
127
128 match sub_str {
129 "all" => Some(Ok(Token::All)),
130 "any" => Some(Ok(Token::Any)),
131 "not" => Some(Ok(Token::Not)),
132 other => Some(Ok(Token::Key(other))),
133 }
134 } else {
135 Some(Err(ParseError {
136 original: self.original.into(),
137 span: self.offset..self.offset + 1,
138 reason: Reason::Unexpected(&["<key>", "all", "any", "not"]),
139 }))
140 }
141 }
142 }
143 .map(|tok| {
144 tok.map(|tok| {
145 let len = tok.len();
146
147 let start = self.offset;
148 self.inner = &self.inner[len..];
149 self.offset += len;
150
151 LexerToken { token: tok, span: start..self.offset }
152 })
153 })
154 }
155 }