use std::ops::Range;
use super::lex::{self, Tok, Token};
use super::parse::{RESERVED, Refusal};
use crate::path::Path;
const BINDERS: &[&str] = &[
"all",
"exists",
"exists_one",
"existsOne",
"map",
"filter",
"transformList",
"transformMap",
"transformMapEntry",
];
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Names<'a> {
pub fields: Vec<Path>,
pub calls: Vec<Call<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Call<'a> {
pub name: &'a str,
pub span: Range<usize>,
pub method: bool,
}
pub fn names(text: &str) -> Result<Names<'_>, Refusal> {
let tokens = lex::tokens(text).map_err(|e| Refusal {
span: e.span,
why: e.why,
})?;
let mut out = Names {
fields: Vec::new(),
calls: Vec::new(),
};
let mut bound: Vec<(&str, usize)> = Vec::new();
let mut depth = 0;
let mut i = 0;
while let Some(token) = tokens.get(i) {
match &token.tok {
Tok::LParen => depth += 1,
Tok::RParen => {
bound.retain(|&(_, d)| d != depth);
depth = depth.saturating_sub(1);
}
Tok::Ident(w) if !RESERVED.contains(w) => {
let method = i > 0 && tokens[i - 1].tok == Tok::Dot;
if is_tok(&tokens, i + 1, &Tok::LParen) {
out.calls.push(Call {
name: w,
span: token.span.clone(),
method,
});
if method
&& BINDERS.contains(w)
&& let Some(Tok::Ident(v)) = tokens.get(i + 2).map(|t| &t.tok)
&& is_tok(&tokens, i + 3, &Tok::Comma)
{
bound.push((v, depth + 1));
}
} else if !method {
i = field(&tokens, i, &bound, &mut out.fields);
continue;
}
}
_ => {}
}
i += 1;
}
Ok(out)
}
fn is_tok(tokens: &[Token<'_>], i: usize, tok: &Tok<'_>) -> bool {
tokens.get(i).is_some_and(|t| t.tok == *tok)
}
fn field(tokens: &[Token<'_>], i: usize, bound: &[(&str, usize)], fields: &mut Vec<Path>) -> usize {
let tok = |j: usize| tokens.get(j).map(|t| &t.tok);
let Some(Tok::Ident(root)) = tok(i) else {
return i + 1;
};
let mut keys: Vec<String> = vec![(*root).to_owned()];
let mut j = i + 1;
loop {
match (tok(j), tok(j + 1), tok(j + 2)) {
(Some(Tok::Dot), Some(Tok::Ident(_)), Some(Tok::LParen)) => break,
(Some(Tok::Dot), Some(Tok::Ident(w)), _) if !RESERVED.contains(w) => {
keys.push((*w).to_owned());
j += 2;
}
(Some(Tok::LBracket), Some(Tok::Str(s)), Some(Tok::RBracket)) => {
keys.push(s.to_string());
j += 3;
}
_ => break,
}
}
if !bound.iter().any(|&(v, _)| v == *root)
&& let Ok(path) = Path::from_keys(keys)
&& !fields.contains(&path)
{
fields.push(path);
}
j
}
#[cfg(test)]
mod tests {
use super::*;
type Read<'a> = (Vec<String>, Vec<(&'a str, bool)>);
fn read(text: &str) -> Read<'_> {
let n = names(text).unwrap();
let fields = n.fields.iter().map(ToString::to_string).collect();
let calls = n.calls.iter().map(|c| (c.name, c.method)).collect();
(fields, calls)
}
#[test]
fn fields_and_calls_read_from_tokens() {
let rows: &[(&str, &[&str], &[(&str, bool)])] = &[
(
r#"tags == owner && source != "internal""#,
&["tags", "owner", "source"],
&[],
),
(r#"'"' == host || port > 1"#, &["host", "port"], &[]),
(
r#"r"severity" == name && b'x' != tag"#,
&["name", "tag"],
&[],
),
(
"level > 1 // and source\n || other",
&["level", "other"],
&[],
),
(
r#"msg.contains("x") && a.b.startsWith("y")"#,
&["msg", "a.b"],
&[("contains", true), ("startsWith", true)],
),
(
"has(a.b) && size(c) > 1",
&["a.b", "c"],
&[("has", false), ("size", false)],
),
(
r#"labels["app.kind"] == "x""#,
&[r#"labels["app.kind"]"#],
&[],
),
(
r#"tags.exists(t, t == "x") && t > 1"#,
&["tags", "t"],
&[("exists", true)],
),
("xs.map(v, v.n + k)", &["xs", "k"], &[("map", true)]),
("f(x).y == z", &["x", "z"], &[("f", false)]),
("x in [1, 2] && true != null", &["x"], &[]),
("x ? `a.b` : c", &["x", r#"["a.b"]"#, "c"], &[]),
("a == a && a.b == a", &["a", "a.b"], &[]),
];
for &(text, fields, calls) in rows {
let (got_fields, got_calls) = read(text);
assert_eq!(got_fields, fields, "{text}");
assert_eq!(got_calls, calls, "{text}");
}
}
#[test]
fn calls_past_literals_and_gaps() {
for text in [
"x.matches (\"a\")",
"x.matches\t(\"a\")",
"x.matches // note\n(\"a\")",
r#"r"\" == "x" || x.matches("a")"#,
r#"'"' == x || y.matches("a")"#,
r#""""a"b""" == x || [1].map(v, v) == [1]"#,
] {
let calls = read(text).1;
assert!(
calls.contains(&("matches", true)) || calls.contains(&("map", true)),
"{text}"
);
}
for text in [
r#"r"x.matches(" == y || z > 1"#,
"'''map(v, v)''' == y || z > 1",
"x > 1 // y.matches(\"a\")",
] {
assert_eq!(read(text).1, [], "{text}");
}
}
#[test]
fn text_the_lexer_rejects_is_refused() {
assert!(names(r#"x == "open"#).is_err());
assert!(names("x == `").is_err());
}
}