Struct cfg_expr::expr::lexer::Lexer

source ·
pub struct Lexer<'a> { /* private fields */ }
Expand description

Allows iteration through a cfg expression, yielding a token or a ParseError.

Prefer to use Expression::parse rather than directly using the lexer

Implementations§

Creates a Lexer over a cfg expression, it can either be a raw expression eg key or in attribute form, eg cfg(key)

Examples found in repository?
src/expr/parser.rs (line 18)
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    pub fn parse(original: &str) -> Result<Self, ParseError> {
        let lexer = Lexer::new(original);

        // The lexer automatically trims any cfg( ), so reacquire
        // the string before we start walking tokens
        let original = lexer.inner;

        #[derive(Debug)]
        struct FuncAndSpan {
            func: Func,
            parens_index: usize,
            span: std::ops::Range<usize>,
            predicates: SmallVec<[InnerPredicate; 5]>,
            nest_level: u8,
        }

        let mut func_stack = SmallVec::<[FuncAndSpan; 5]>::new();
        let mut expr_queue = SmallVec::<[ExprNode; 5]>::new();

        // Keep track of the last token to simplify validation of the token stream
        let mut last_token: Option<Token<'_>> = None;

        let parse_predicate = |key: (&str, std::ops::Range<usize>),
                               val: Option<(&str, std::ops::Range<usize>)>|
         -> Result<InnerPredicate, ParseError> {
            // Warning: It is possible for arbitrarily-set configuration
            // options to have the same value as compiler-set configuration
            // options. For example, it is possible to do rustc --cfg "unix" program.rs
            // while compiling to a Windows target, and have both unix and windows
            // configuration options set at the same time. It is unwise to actually
            // do this.
            //
            // rustc is very permissive in this regard, but I'd rather be really
            // strict, as it's much easier to loosen restrictions over time than add
            // new ones
            macro_rules! err_if_val {
                () => {
                    if let Some((_, vspan)) = val {
                        return Err(ParseError {
                            original: original.to_owned(),
                            span: vspan,
                            reason: Reason::Unexpected(&[]),
                        });
                    }
                };
            }

            let span = key.1;
            let key = key.0;

            use super::{InnerTarget, Which};

            Ok(match key {
                // These are special cases in the cfg language that are
                // semantically the same as `target_family = "<family>"`,
                // so we just make them not special
                // NOTE: other target families like "wasm" are NOT allowed
                // as naked predicates; they must be specified through
                // `target_family`
                "unix" | "windows" => {
                    err_if_val!();

                    InnerPredicate::Target(InnerTarget {
                        which: Which::Family,
                        span: Some(span),
                    })
                }
                "test" => {
                    err_if_val!();
                    InnerPredicate::Test
                }
                "debug_assertions" => {
                    err_if_val!();
                    InnerPredicate::DebugAssertions
                }
                "proc_macro" => {
                    err_if_val!();
                    InnerPredicate::ProcMacro
                }
                "feature" => {
                    // rustc allows bare feature without a value, but the only way
                    // such a predicate would ever evaluate to true would be if they
                    // explicitly set --cfg feature, which would be terrible, so we
                    // just error instead
                    match val {
                        Some((_, span)) => InnerPredicate::Feature(span),
                        None => {
                            return Err(ParseError {
                                original: original.to_owned(),
                                span,
                                reason: Reason::Unexpected(&["= \"<feature_name>\""]),
                            });
                        }
                    }
                }
                "panic" => match val {
                    Some((_, vspan)) => InnerPredicate::Target(InnerTarget {
                        which: Which::Panic,
                        span: Some(vspan),
                    }),
                    None => {
                        return Err(ParseError {
                            original: original.to_owned(),
                            span,
                            reason: Reason::Unexpected(&["= \"<panic_strategy>\""]),
                        });
                    }
                },
                target_key if key.starts_with("target_") => {
                    let (val, vspan) = match val {
                        None => {
                            return Err(ParseError {
                                original: original.to_owned(),
                                span,
                                reason: Reason::Unexpected(&["= \"<target_cfg_value>\""]),
                            });
                        }
                        Some((val, vspan)) => (val, vspan),
                    };

                    macro_rules! tp {
                        ($which:ident) => {
                            InnerTarget {
                                which: Which::$which,
                                span: Some(vspan),
                            }
                        };
                    }

                    let tp = match &target_key[7..] {
                        "abi" => tp!(Abi),
                        "arch" => tp!(Arch),
                        "feature" => {
                            if val.is_empty() {
                                return Err(ParseError {
                                    original: original.to_owned(),
                                    span: vspan,
                                    reason: Reason::Unexpected(&["<feature>"]),
                                });
                            }

                            return Ok(InnerPredicate::TargetFeature(vspan));
                        }
                        "os" => tp!(Os),
                        "family" => tp!(Family),
                        "env" => tp!(Env),
                        "endian" => InnerTarget {
                            which: Which::Endian(val.parse().map_err(|_err| ParseError {
                                original: original.to_owned(),
                                span: vspan,
                                reason: Reason::InvalidInteger,
                            })?),
                            span: None,
                        },
                        "has_atomic" => InnerTarget {
                            which: Which::HasAtomic(val.parse().map_err(|_err| ParseError {
                                original: original.to_owned(),
                                span: vspan,
                                reason: Reason::InvalidHasAtomic,
                            })?),
                            span: None,
                        },
                        "pointer_width" => InnerTarget {
                            which: Which::PointerWidth(val.parse().map_err(|_err| ParseError {
                                original: original.to_owned(),
                                span: vspan,
                                reason: Reason::InvalidInteger,
                            })?),
                            span: None,
                        },
                        "vendor" => tp!(Vendor),
                        _ => {
                            return Err(ParseError {
                                original: original.to_owned(),
                                span,
                                reason: Reason::Unexpected(&[
                                    "target_arch",
                                    "target_feature",
                                    "target_os",
                                    "target_family",
                                    "target_env",
                                    "target_endian",
                                    "target_has_atomic",
                                    "target_pointer_width",
                                    "target_vendor",
                                ]),
                            })
                        }
                    };

                    InnerPredicate::Target(tp)
                }
                _other => InnerPredicate::Other {
                    identifier: span,
                    value: val.map(|(_, span)| span),
                },
            })
        };

        macro_rules! token_err {
            ($span:expr) => {{
                let expected: &[&str] = match last_token {
                    None => &["<key>", "all", "any", "not"],
                    Some(Token::All | Token::Any | Token::Not) => &["("],
                    Some(Token::CloseParen) => &[")", ","],
                    Some(Token::Comma) => &[")", "<key>"],
                    Some(Token::Equals) => &["\""],
                    Some(Token::Key(_)) => &["=", ",", ")"],
                    Some(Token::Value(_)) => &[",", ")"],
                    Some(Token::OpenParen) => &["<key>", ")", "all", "any", "not"],
                };

                return Err(ParseError {
                    original: original.to_owned(),
                    span: $span,
                    reason: Reason::Unexpected(&expected),
                });
            }};
        }

        let mut pred_key: Option<(&str, _)> = None;
        let mut pred_val: Option<(&str, _)> = None;

        let mut root_predicate_count = 0;

        // Basic implementation of the https://en.wikipedia.org/wiki/Shunting-yard_algorithm
        'outer: for lt in lexer {
            let lt = lt?;
            match &lt.token {
                Token::Key(k) => {
                    if matches!(last_token, None | Some(Token::OpenParen | Token::Comma)) {
                        pred_key = Some((k, lt.span.clone()));
                    } else {
                        token_err!(lt.span)
                    }
                }
                Token::Value(v) => {
                    if matches!(last_token, Some(Token::Equals)) {
                        // We only record the span for keys and values
                        // so that the expression doesn't need a lifetime
                        // but in the value case we need to strip off
                        // the quotes so that the proper raw string is
                        // provided to callers when evaluating the expression
                        pred_val = Some((v, lt.span.start + 1..lt.span.end - 1));
                    } else {
                        token_err!(lt.span)
                    }
                }
                Token::Equals => {
                    if !matches!(last_token, Some(Token::Key(_))) {
                        token_err!(lt.span)
                    }
                }
                Token::All | Token::Any | Token::Not => {
                    if matches!(last_token, None | Some(Token::OpenParen | Token::Comma)) {
                        let new_fn = match lt.token {
                            // the 0 is a dummy value -- it will be substituted for the real
                            // number of predicates in the `CloseParen` branch below.
                            Token::All => Func::All(0),
                            Token::Any => Func::Any(0),
                            Token::Not => Func::Not,
                            _ => unreachable!(),
                        };

                        if let Some(fs) = func_stack.last_mut() {
                            fs.nest_level += 1;
                        }

                        func_stack.push(FuncAndSpan {
                            func: new_fn,
                            span: lt.span,
                            parens_index: 0,
                            predicates: SmallVec::new(),
                            nest_level: 0,
                        });
                    } else {
                        token_err!(lt.span)
                    }
                }
                Token::OpenParen => {
                    if matches!(last_token, Some(Token::All | Token::Any | Token::Not)) {
                        if let Some(ref mut fs) = func_stack.last_mut() {
                            fs.parens_index = lt.span.start;
                        }
                    } else {
                        token_err!(lt.span)
                    }
                }
                Token::CloseParen => {
                    if matches!(
                        last_token,
                        None | Some(Token::All | Token::Any | Token::Not | Token::Equals)
                    ) {
                        token_err!(lt.span)
                    } else {
                        if let Some(top) = func_stack.pop() {
                            let key = pred_key.take();
                            let val = pred_val.take();

                            // In this context, the boolean to int conversion is confusing.
                            #[allow(clippy::bool_to_int_with_if)]
                            let num_predicates = top.predicates.len()
                                + if key.is_some() { 1 } else { 0 }
                                + top.nest_level as usize;

                            let func = match top.func {
                                Func::All(_) => Func::All(num_predicates),
                                Func::Any(_) => Func::Any(num_predicates),
                                Func::Not => {
                                    // not() doesn't take a predicate list, but only a single predicate,
                                    // so ensure we have exactly 1
                                    if num_predicates != 1 {
                                        return Err(ParseError {
                                            original: original.to_owned(),
                                            span: top.span.start..lt.span.end,
                                            reason: Reason::InvalidNot(num_predicates),
                                        });
                                    }

                                    Func::Not
                                }
                            };

                            for pred in top.predicates {
                                expr_queue.push(ExprNode::Predicate(pred));
                            }

                            if let Some(key) = key {
                                let inner_pred = parse_predicate(key, val)?;
                                expr_queue.push(ExprNode::Predicate(inner_pred));
                            }

                            expr_queue.push(ExprNode::Fn(func));

                            // This is the only place we go back to the top of the outer loop,
                            // so make sure we correctly record this token
                            last_token = Some(Token::CloseParen);
                            continue 'outer;
                        }

                        // We didn't have an opening parentheses if we get here
                        return Err(ParseError {
                            original: original.to_owned(),
                            span: lt.span,
                            reason: Reason::UnopenedParens,
                        });
                    }
                }
                Token::Comma => {
                    if matches!(
                        last_token,
                        None | Some(
                            Token::OpenParen | Token::All | Token::Any | Token::Not | Token::Equals
                        )
                    ) {
                        token_err!(lt.span)
                    } else {
                        let key = pred_key.take();
                        let val = pred_val.take();

                        let inner_pred = key.map(|key| parse_predicate(key, val)).transpose()?;

                        match (inner_pred, func_stack.last_mut()) {
                            (Some(pred), Some(func)) => {
                                func.predicates.push(pred);
                            }
                            (Some(pred), None) => {
                                root_predicate_count += 1;

                                expr_queue.push(ExprNode::Predicate(pred));
                            }
                            _ => {}
                        }
                    }
                }
            }

            last_token = Some(lt.token);
        }

        if let Some(Token::Equals) = last_token {
            return Err(ParseError {
                original: original.to_owned(),
                span: original.len()..original.len(),
                reason: Reason::Unexpected(&["\"<value>\""]),
            });
        }

        // If we still have functions on the stack, it means we have an unclosed parens
        if let Some(top) = func_stack.pop() {
            if top.parens_index != 0 {
                Err(ParseError {
                    original: original.to_owned(),
                    span: top.parens_index..original.len(),
                    reason: Reason::UnclosedParens,
                })
            } else {
                Err(ParseError {
                    original: original.to_owned(),
                    span: top.span,
                    reason: Reason::Unexpected(&["("]),
                })
            }
        } else {
            let key = pred_key.take();
            let val = pred_val.take();

            if let Some(key) = key {
                root_predicate_count += 1;
                expr_queue.push(ExprNode::Predicate(parse_predicate(key, val)?));
            }

            if expr_queue.is_empty() {
                Err(ParseError {
                    original: original.to_owned(),
                    span: 0..original.len(),
                    reason: Reason::Empty,
                })
            } else if root_predicate_count > 1 {
                Err(ParseError {
                    original: original.to_owned(),
                    span: 0..original.len(),
                    reason: Reason::MultipleRootPredicates,
                })
            } else {
                Ok(Expression {
                    original: original.to_owned(),
                    expr: expr_queue,
                })
            }
        }
    }

Trait Implementations§

The type of the elements being iterated over.
Advances the iterator and returns the next value. Read more
🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
Returns the bounds on the remaining length of the iterator. Read more
Consumes the iterator, counting the number of iterations and returning it. Read more
Consumes the iterator, returning the last element. Read more
🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
Returns the nth element of the iterator. Read more
Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more
Takes two iterators and creates a new iterator over both in sequence. Read more
‘Zips up’ two iterators into a single iterator of pairs. Read more
🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator between adjacent items of the original iterator. Read more
Takes a closure and creates an iterator which calls that closure on each element. Read more
Calls a closure on each element of an iterator. Read more
Creates an iterator which uses a closure to determine if an element should be yielded. Read more
Creates an iterator that both filters and maps. Read more
Creates an iterator which gives the current iteration count as well as the next value. Read more
Creates an iterator which can use the peek and peek_mut methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more
Creates an iterator that skips elements based on a predicate. Read more
Creates an iterator that yields elements based on a predicate. Read more
Creates an iterator that both yields elements based on a predicate and maps. Read more
Creates an iterator that skips the first n elements. Read more
Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. Read more
An iterator adapter similar to fold that holds internal state and produces a new iterator. Read more
Creates an iterator that works like map, but flattens nested structure. Read more
Creates an iterator which ends after the first None. Read more
Does something with each element of an iterator, passing the value on. Read more
Borrows an iterator, rather than consuming it. Read more
Transforms an iterator into a collection. Read more
🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
Consumes an iterator, creating two collections from it. Read more
🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return true precede all those that return false. Read more
An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more
An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more
Folds every element into an accumulator by applying an operation, returning the final result. Read more
Reduces the elements to a single one, by repeatedly applying a reducing operation. Read more
🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more
Tests if every element of the iterator matches a predicate. Read more
Tests if any element of the iterator matches a predicate. Read more
Searches for an element of an iterator that satisfies a predicate. Read more
Applies function to the elements of iterator and returns the first non-none result. Read more
🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns the first true result or the first error. Read more
Searches for an element in an iterator, returning its index. Read more
Returns the element that gives the maximum value from the specified function. Read more
Returns the element that gives the maximum value with respect to the specified comparison function. Read more
Returns the element that gives the minimum value from the specified function. Read more
Returns the element that gives the minimum value with respect to the specified comparison function. Read more
Converts an iterator of pairs into a pair of containers. Read more
Creates an iterator which copies all of its elements. Read more
Creates an iterator which clones all of its elements. Read more
🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
Sums the elements of an iterator. Read more
Iterates over the entire iterator, multiplying all the elements Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more
Lexicographically compares the elements of this Iterator with those of another. Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more
Determines if the elements of this Iterator are equal to those of another. Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this Iterator are equal to those of another with respect to the specified equality function. Read more
Determines if the elements of this Iterator are unequal to those of another. Read more
Determines if the elements of this Iterator are lexicographically less than those of another. Read more
Determines if the elements of this Iterator are lexicographically less or equal to those of another. Read more
Determines if the elements of this Iterator are lexicographically greater than those of another. Read more
Determines if the elements of this Iterator are lexicographically greater than or equal to those of another. Read more
🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction function. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.