| 1 |
// SPDX-License-Identifier: Apache-2.0 OR MIT |
| 2 |
|
| 3 |
use alloc::{borrow::ToOwned as _, vec, vec::Vec}; |
| 4 |
|
| 5 |
use crate::cfg_expr::{ |
| 6 |
error::{ParseError, Reason}, |
| 7 |
expr::{ |
| 8 |
ExprNode, Expression, Func, InnerPredicate, |
| 9 |
lexer::{Lexer, Token}, |
| 10 |
}, |
| 11 |
}; |
| 12 |
|
| 13 |
impl Expression { |
| 14 |
/// Given a cfg() expression (the cfg( and ) are optional), attempts to |
| 15 |
/// parse it into a form where it can be evaluated |
| 16 |
pub(crate) fn parse(original: &str) -> Result<Self, ParseError> { |
| 17 |
#[derive(Debug)] |
| 18 |
struct FuncAndSpan { |
| 19 |
func: Func, |
| 20 |
parens_index: usize, |
| 21 |
span: core::ops::Range<usize>, |
| 22 |
predicates: Vec<InnerPredicate>, |
| 23 |
nest_level: u8, |
| 24 |
} |
| 25 |
|
| 26 |
let lexer = Lexer::new(original); |
| 27 |
|
| 28 |
// The lexer automatically trims any cfg( ), so reacquire |
| 29 |
// the string before we start walking tokens |
| 30 |
let original = lexer.inner; |
| 31 |
|
| 32 |
let mut func_stack: Vec<FuncAndSpan> = Vec::with_capacity(5); |
| 33 |
let mut expr_queue = Vec::with_capacity(5); |
| 34 |
|
| 35 |
// Keep track of the last token to simplify validation of the token stream |
| 36 |
let mut last_token: Option<Token<'_>> = None; |
| 37 |
|
| 38 |
let parse_predicate = |key: (&str, core::ops::Range<usize>), |
| 39 |
val: Option<(&str, core::ops::Range<usize>)>| |
| 40 |
-> Result<InnerPredicate, ParseError> { |
| 41 |
let span = key.1; |
| 42 |
Ok(InnerPredicate { identifier: span, value: val.map(|(_, span)| span) }) |
| 43 |
}; |
| 44 |
|
| 45 |
macro_rules! token_err { |
| 46 |
($span:expr) => {{ |
| 47 |
let expected: &[&str] = match last_token { |
| 48 |
None => &["<key>", "all", "any", "not"], |
| 49 |
Some(Token::All | Token::Any | Token::Not) => &["("], |
| 50 |
Some(Token::CloseParen) => &[")", ","], |
| 51 |
Some(Token::Comma) => &[")", "<key>"], |
| 52 |
Some(Token::Equals) => &["\""], |
| 53 |
Some(Token::Key(_)) => &["=", ",", ")"], |
| 54 |
Some(Token::Value(_)) => &[",", ")"], |
| 55 |
Some(Token::OpenParen) => &["<key>", ")", "all", "any", "not"], |
| 56 |
}; |
| 57 |
|
| 58 |
return Err(ParseError { |
| 59 |
original: original.into(), |
| 60 |
span: $span, |
| 61 |
reason: Reason::Unexpected(&expected), |
| 62 |
}); |
| 63 |
}}; |
| 64 |
} |
| 65 |
|
| 66 |
let mut pred_key: Option<(&str, _)> = None; |
| 67 |
let mut pred_val: Option<(&str, _)> = None; |
| 68 |
|
| 69 |
let mut root_predicate_count = 0; |
| 70 |
|
| 71 |
// Basic implementation of the https://en.wikipedia.org/wiki/Shunting-yard_algorithm |
| 72 |
'outer: for lt in lexer { |
| 73 |
let lt = lt?; |
| 74 |
match <.token { |
| 75 |
Token::Key(k) => { |
| 76 |
if matches!(last_token, None | Some(Token::OpenParen | Token::Comma)) { |
| 77 |
pred_key = Some((k, lt.span.clone())); |
| 78 |
} else { |
| 79 |
token_err!(lt.span) |
| 80 |
} |
| 81 |
} |
| 82 |
Token::Value(v) => { |
| 83 |
if matches!(last_token, Some(Token::Equals)) { |
| 84 |
// We only record the span for keys and values |
| 85 |
// so that the expression doesn't need a lifetime |
| 86 |
// but in the value case we need to strip off |
| 87 |
// the quotes so that the proper raw string is |
| 88 |
// provided to callers when evaluating the expression |
| 89 |
pred_val = Some((v, lt.span.start + 1..lt.span.end - 1)); |
| 90 |
} else { |
| 91 |
token_err!(lt.span) |
| 92 |
} |
| 93 |
} |
| 94 |
Token::Equals => { |
| 95 |
if !matches!(last_token, Some(Token::Key(_))) { |
| 96 |
token_err!(lt.span) |
| 97 |
} |
| 98 |
} |
| 99 |
Token::All | Token::Any | Token::Not => { |
| 100 |
if matches!(last_token, None | Some(Token::OpenParen | Token::Comma)) { |
| 101 |
let new_fn = match lt.token { |
| 102 |
// the 0 is a dummy value -- it will be substituted for the real |
| 103 |
// number of predicates in the `CloseParen` branch below. |
| 104 |
Token::All => Func::All(0), |
| 105 |
Token::Any => Func::Any(0), |
| 106 |
Token::Not => Func::Not, |
| 107 |
_ => unreachable!(), |
| 108 |
}; |
| 109 |
|
| 110 |
if let Some(fs) = func_stack.last_mut() { |
| 111 |
fs.nest_level += 1; |
| 112 |
} |
| 113 |
|
| 114 |
func_stack.push(FuncAndSpan { |
| 115 |
func: new_fn, |
| 116 |
span: lt.span, |
| 117 |
parens_index: 0, |
| 118 |
predicates: vec![], |
| 119 |
nest_level: 0, |
| 120 |
}); |
| 121 |
} else { |
| 122 |
token_err!(lt.span) |
| 123 |
} |
| 124 |
} |
| 125 |
Token::OpenParen => { |
| 126 |
if matches!(last_token, Some(Token::All | Token::Any | Token::Not)) { |
| 127 |
if let Some(ref mut fs) = func_stack.last_mut() { |
| 128 |
fs.parens_index = lt.span.start; |
| 129 |
} |
| 130 |
} else { |
| 131 |
token_err!(lt.span) |
| 132 |
} |
| 133 |
} |
| 134 |
Token::CloseParen => { |
| 135 |
if matches!( |
| 136 |
last_token, |
| 137 |
None | Some(Token::All | Token::Any | Token::Not | Token::Equals) |
| 138 |
) { |
| 139 |
token_err!(lt.span) |
| 140 |
} |
| 141 |
if let Some(top) = func_stack.pop() { |
| 142 |
let key = pred_key.take(); |
| 143 |
let val = pred_val.take(); |
| 144 |
|
| 145 |
let num_predicates = |
| 146 |
top.predicates.len() + key.is_some() as usize + top.nest_level as usize; |
| 147 |
|
| 148 |
let func = match top.func { |
| 149 |
Func::All(_) => Func::All(num_predicates), |
| 150 |
Func::Any(_) => Func::Any(num_predicates), |
| 151 |
Func::Not => { |
| 152 |
// not() doesn't take a predicate list, but only a single predicate, |
| 153 |
// so ensure we have exactly 1 |
| 154 |
if num_predicates != 1 { |
| 155 |
return Err(ParseError { |
| 156 |
original: original.into(), |
| 157 |
span: top.span.start..lt.span.end, |
| 158 |
reason: Reason::InvalidNot(num_predicates), |
| 159 |
}); |
| 160 |
} |
| 161 |
|
| 162 |
Func::Not |
| 163 |
} |
| 164 |
}; |
| 165 |
|
| 166 |
for pred in top.predicates { |
| 167 |
expr_queue.push(ExprNode::Predicate(pred)); |
| 168 |
} |
| 169 |
|
| 170 |
if let Some(key) = key { |
| 171 |
let inner_pred = parse_predicate(key, val)?; |
| 172 |
expr_queue.push(ExprNode::Predicate(inner_pred)); |
| 173 |
} |
| 174 |
|
| 175 |
expr_queue.push(ExprNode::Fn(func)); |
| 176 |
|
| 177 |
// This is the only place we go back to the top of the outer loop, |
| 178 |
// so make sure we correctly record this token |
| 179 |
last_token = Some(Token::CloseParen); |
| 180 |
continue 'outer; |
| 181 |
} |
| 182 |
|
| 183 |
// We didn't have an opening parentheses if we get here |
| 184 |
return Err(ParseError { |
| 185 |
original: original.into(), |
| 186 |
span: lt.span, |
| 187 |
reason: Reason::UnopenedParens, |
| 188 |
}); |
| 189 |
} |
| 190 |
Token::Comma => { |
| 191 |
if matches!( |
| 192 |
last_token, |
| 193 |
None | Some( |
| 194 |
Token::OpenParen | Token::All | Token::Any | Token::Not | Token::Equals |
| 195 |
) |
| 196 |
) { |
| 197 |
token_err!(lt.span) |
| 198 |
} |
| 199 |
let key = pred_key.take(); |
| 200 |
let val = pred_val.take(); |
| 201 |
|
| 202 |
let inner_pred = key.map(|key| parse_predicate(key, val)).transpose()?; |
| 203 |
|
| 204 |
match (inner_pred, func_stack.last_mut()) { |
| 205 |
(Some(pred), Some(func)) => { |
| 206 |
func.predicates.push(pred); |
| 207 |
} |
| 208 |
(Some(pred), None) => { |
| 209 |
root_predicate_count += 1; |
| 210 |
|
| 211 |
expr_queue.push(ExprNode::Predicate(pred)); |
| 212 |
} |
| 213 |
_ => {} |
| 214 |
} |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
last_token = Some(lt.token); |
| 219 |
} |
| 220 |
|
| 221 |
if let Some(Token::Equals) = last_token { |
| 222 |
return Err(ParseError { |
| 223 |
original: original.into(), |
| 224 |
span: original.len()..original.len(), |
| 225 |
reason: Reason::Unexpected(&["\"<value>\""]), |
| 226 |
}); |
| 227 |
} |
| 228 |
|
| 229 |
// If we still have functions on the stack, it means we have an unclosed parens |
| 230 |
if let Some(top) = func_stack.pop() { |
| 231 |
if top.parens_index == 0 { |
| 232 |
Err(ParseError { |
| 233 |
original: original.into(), |
| 234 |
span: top.span, |
| 235 |
reason: Reason::Unexpected(&["("]), |
| 236 |
}) |
| 237 |
} else { |
| 238 |
Err(ParseError { |
| 239 |
original: original.into(), |
| 240 |
span: top.parens_index..original.len(), |
| 241 |
reason: Reason::UnclosedParens, |
| 242 |
}) |
| 243 |
} |
| 244 |
} else { |
| 245 |
let key = pred_key.take(); |
| 246 |
let val = pred_val.take(); |
| 247 |
|
| 248 |
if let Some(key) = key { |
| 249 |
root_predicate_count += 1; |
| 250 |
expr_queue.push(ExprNode::Predicate(parse_predicate(key, val)?)); |
| 251 |
} |
| 252 |
|
| 253 |
if expr_queue.is_empty() { |
| 254 |
Err(ParseError { |
| 255 |
original: original.into(), |
| 256 |
span: 0..original.len(), |
| 257 |
reason: Reason::Empty, |
| 258 |
}) |
| 259 |
} else if root_predicate_count > 1 { |
| 260 |
Err(ParseError { |
| 261 |
original: original.into(), |
| 262 |
span: 0..original.len(), |
| 263 |
reason: Reason::MultipleRootPredicates, |
| 264 |
}) |
| 265 |
} else { |
| 266 |
Ok(Expression { original: original.to_owned(), expr: expr_queue }) |
| 267 |
} |
| 268 |
} |
| 269 |
} |
| 270 |
} |