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
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
use crate::{
    error::{ParseError, Reason},
    expr::{
        lexer::{Lexer, Token},
        ExprNode, Expression, Func, InnerPredicate,
    },
};
use smallvec::SmallVec;

impl Expression {
    /// Given a cfg() expression (the cfg( and ) are optional), attempts to
    /// parse it into a form where it can be evaluated
    ///
    /// ```
    /// assert!(cfg_expr::Expression::parse(r#"cfg(all(unix, target_arch = "x86_64"))"#).is_ok());
    /// ```
    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>\""]),
                            });
                        }
                    }
                }
                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..] {
                        "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,
                        },
                        "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_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) | Some(Token::Any) | Some(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) => match last_token {
                    None | Some(Token::OpenParen) | Some(Token::Comma) => {
                        pred_key = Some((k, lt.span.clone()));
                    }
                    _ => token_err!(lt.span),
                },
                Token::Value(v) => match 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));
                    }
                    _ => token_err!(lt.span),
                },
                Token::Equals => match last_token {
                    Some(Token::Key(_)) => {}
                    _ => token_err!(lt.span),
                },
                Token::All | Token::Any | Token::Not => match last_token {
                    None | Some(Token::OpenParen) | Some(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,
                        });
                    }
                    _ => token_err!(lt.span),
                },
                Token::OpenParen => match last_token {
                    Some(Token::All) | Some(Token::Any) | Some(Token::Not) => {
                        if let Some(ref mut fs) = func_stack.last_mut() {
                            fs.parens_index = lt.span.start;
                        }
                    }
                    _ => token_err!(lt.span),
                },
                Token::CloseParen => match last_token {
                    None | Some(Token::All) | Some(Token::Any) | Some(Token::Not)
                    | Some(Token::Equals) => {
                        token_err!(lt.span)
                    }
                    _ => {
                        if let Some(top) = func_stack.pop() {
                            let key = pred_key.take();
                            let val = pred_val.take();

                            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 => match last_token {
                    None
                    | Some(Token::OpenParen)
                    | Some(Token::All)
                    | Some(Token::Any)
                    | Some(Token::Not)
                    | Some(Token::Equals) => token_err!(lt.span),
                    _ => {
                        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
        match func_stack.pop() {
            Some(top) => {
                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(&["("]),
                    })
                }
            }
            None => {
                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,
                    })
                }
            }
        }
    }
}