use crate::parse::Token;
use crate::pathgate::{Role, RoleSpec, Shape, walk_for};
const DIRECTIVES: &[&str] = &["import", "include"];
const MODULE_FNS: &[&str] = &["modulemeta"];
const YQ_LOADERS: &[&str] = &["load", "eval"];
const YQ_SUBCOMMANDS: &[&str] = &["e", "eval", "ea", "eval-all"];
pub(super) struct Arities {
pub(super) two: &'static [&'static str],
pub(super) one: &'static [&'static str],
pub(super) program: &'static [&'static str],
}
pub(super) const JQ: Arities = Arities {
two: &["--arg", "--argjson", "--rawfile", "--slurpfile"],
one: &["--indent", "--library-path", "--from-file", "-L", "-f"],
program: &[],
};
pub(super) const PY_YQ: Arities = Arities {
two: JQ.two,
one: &["--indent", "--library-path", "--from-file", "-L", "-f", "--width", "-w", "--xml-item-depth", "--xml-root", "--xml-force-list"],
program: &[],
};
pub(super) const YQ: Arities = Arities {
two: JQ.two,
one: &[
"--indent", "--front-matter", "--input-format", "--output-format", "--from-file", "-I", "-p", "-o", "-f", "-L", "--library-path",
],
program: &["--expression"],
};
pub(super) fn jq_program(tokens: &[Token]) -> bool {
let name = tokens.first().map(|t| t.command_name().to_ascii_lowercase()).unwrap_or_default();
let arities = if matches!(name.as_str(), "xq" | "tomlq") { &PY_YQ } else { &JQ };
let args = words(tokens);
jq_reads_beyond_operands(&args, &filter_words(&args, arities, false)) || read_operands(tokens)
}
pub(super) fn yq_program(tokens: &[Token]) -> bool {
let args = words(tokens);
let filters = filter_words(&args, &YQ, true);
yq_reads_beyond_operands(&args, &filters) || jq_reads_beyond_operands(&args, &filters) || read_operands(tokens)
}
fn words(tokens: &[Token]) -> Vec<&str> {
tokens.iter().skip(1).map(Token::as_str).collect()
}
fn read_operands(tokens: &[Token]) -> bool {
walk_for(&RoleSpec::simple(Role::Read, Shape::Plain), tokens, &|flag| crate::registry::policy::declares_standalone("jq", flag))
}
pub(super) fn filter_words<'a>(args: &[&'a str], arities: &Arities, subcommands: bool) -> Vec<&'a str> {
let mut out = Vec::new();
let mut operands = Vec::new();
let mut i = 0;
let mut options_end = false;
while i < args.len() {
let w = args[i];
i += 1;
if !options_end && w == "--" {
options_end = true;
} else if !options_end && w.len() > 1 && w.starts_with('-') {
out.extend(program_value(w, args.get(i).copied(), arities));
i += option_values(w, arities);
} else {
operands.push(w);
}
}
let leading = usize::from(subcommands && operands.first().is_some_and(|w| YQ_SUBCOMMANDS.contains(w)));
out.extend(operands.into_iter().take(leading + 1));
out
}
fn program_value<'a>(word: &'a str, next: Option<&'a str>, arities: &Arities) -> Option<&'a str> {
match word.split_once('=') {
Some((name, value)) => arities.program.contains(&name).then_some(value),
None => next.filter(|_| arities.program.contains(&word)),
}
}
fn option_values(word: &str, arities: &Arities) -> usize {
let listed = |w: &str| {
if arities.two.contains(&w) { 2 } else { usize::from(arities.one.contains(&w) || arities.program.contains(&w)) }
};
if word.starts_with("--") {
return match word.split_once('=') {
Some((name, _)) => listed(name).saturating_sub(1),
None => listed(word),
};
}
let letters: Vec<char> = word[1..].chars().collect();
match letters.iter().position(|c| listed(&format!("-{c}")) > 0) {
Some(at) if at + 1 == letters.len() => listed(&format!("-{}", letters[at])),
_ => 0,
}
}
pub(crate) fn jq_reads_beyond_operands(args: &[&str], filters: &[&str]) -> bool {
args.iter().any(|w| names_program_file(w) || names_module_path(w)) || filters.iter().any(|w| loads_module(w))
}
pub(crate) fn yq_reads_beyond_operands(args: &[&str], filters: &[&str]) -> bool {
args.iter().any(|w| w.starts_with("--from-file")) || filters.iter().any(|w| !YQ_SUBCOMMANDS.contains(w) && yq_loads(w))
}
fn names_program_file(word: &str) -> bool {
word.starts_with("--from-file") || short_cluster_has(word, 'f')
}
fn names_module_path(word: &str) -> bool {
word.starts_with("--library-path") || short_cluster_has(word, 'L')
}
fn short_cluster_has(word: &str, flag: char) -> bool {
word.strip_prefix('-').is_some_and(|rest| !rest.starts_with('-') && rest.contains(flag))
}
fn loads_module(word: &str) -> bool {
if crate::parse::has_unknown_content(word) {
return true;
}
let lower = word.to_ascii_lowercase();
DIRECTIVES
.iter()
.any(|kw| occurrences(&lower, kw).any(|at| directive_could_start(&lower, at, kw.len())))
|| MODULE_FNS.iter().any(|f| occurrences(&lower, f).any(|at| name_could_start(&lower, at, f.len())))
}
fn yq_loads(word: &str) -> bool {
if crate::parse::has_unknown_content(word) {
return true;
}
let lower = word.to_ascii_lowercase();
YQ_LOADERS
.iter()
.any(|op| occurrences(&lower, op).any(|at| !is_field_or_variable(&lower, name_start(&lower, at))))
}
fn occurrences<'a>(hay: &'a str, needle: &'a str) -> impl Iterator<Item = usize> + 'a {
hay.match_indices(needle).map(|(at, _)| at)
}
fn is_name_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn directive_could_start(s: &str, at: usize, len: usize) -> bool {
let bytes = s.as_bytes();
if bytes.get(at + len).copied().is_some_and(is_name_byte) {
return false;
}
match at.checked_sub(1).map(|i| bytes[i]) {
None => true,
Some(b) if b.is_ascii_alphabetic() || b == b'_' => false,
Some(b'$' | b'/' | b'-' | b'"') => false,
Some(b'.') => !is_single_dot_before(bytes, at),
Some(_) => true,
}
}
fn name_could_start(s: &str, at: usize, len: usize) -> bool {
let bytes = s.as_bytes();
if bytes.get(at + len).copied().is_some_and(is_name_byte) {
return false;
}
match at.checked_sub(1).map(|i| bytes[i]) {
Some(b) if b.is_ascii_alphabetic() || b == b'_' => false,
_ => !is_field_or_variable(s, at),
}
}
fn name_start(s: &str, at: usize) -> usize {
let bytes = s.as_bytes();
let mut start = at;
while start > 0 && is_name_byte(bytes[start - 1]) {
start -= 1;
}
start
}
fn is_field_or_variable(s: &str, start: usize) -> bool {
let bytes = s.as_bytes();
match start.checked_sub(1).map(|i| bytes[i]) {
Some(b'$') => true,
Some(b'.') => is_single_dot_before(bytes, start),
_ => false,
}
}
fn is_single_dot_before(bytes: &[u8], at: usize) -> bool {
at >= 1 && bytes[at - 1] == b'.' && (at < 2 || bytes[at - 2] != b'.')
}
#[cfg(test)]
#[path = "jq_tests.rs"]
mod tests;