use crate::getter::{BracedWordKinds, node_text};
use crate::node::{Ancestors, Cursor, MemoQuestion, Node};
crate::observation::counter!(
argument_slot_scans,
cfg(any(test, feature = "test-support"))
);
const SCRIPT_TAKING_COMMANDS: [(&str, ScriptSlots); 8] = [
("after", ScriptSlots::EveryButFirst),
("eval", ScriptSlots::Every),
("for", ScriptSlots::Every),
("on", ScriptSlots::LastOf(HANDLER_CLAUSE_ARITY)),
(SWITCH_COMMAND, ScriptSlots::SwitchArms),
("time", ScriptSlots::Only(0)),
("trap", ScriptSlots::LastOf(HANDLER_CLAUSE_ARITY)),
("uplevel", ScriptSlots::EveryButLeadingLevel),
];
const HANDLER_CLAUSE_ARITY: usize = 3;
pub(crate) const SWITCH_COMMAND: &str = "switch";
const NAMESPACE_SCRIPT_SUBCOMMANDS: [(&str, ScriptSlots); 3] = [
("code", ScriptSlots::Every),
("eval", ScriptSlots::EveryButFirst),
("inscope", ScriptSlots::Only(1)),
];
const SWITCH_OPTIONS_TAKING_A_WORD: [&str; 2] = ["-indexvar", "-matchvar"];
const SWITCH_OPTION_TERMINATOR: &str = "--";
#[derive(Clone, Copy)]
pub(crate) enum ScriptSlots {
Every,
NoneOfThem,
EveryButFirst,
Only(usize),
LastOf(usize),
EveryButLeadingLevel,
SwitchArms,
}
#[derive(Clone, Copy)]
pub(crate) struct Dialect<'a> {
pub(crate) code: &'a [u8],
pub(crate) kinds: &'a BracedWordKinds,
}
#[inline]
#[must_use]
pub fn strip_global_qualifier(name: &str) -> &str {
name.strip_prefix("::").unwrap_or(name)
}
pub(crate) fn script_slots(command: &str) -> Option<ScriptSlots> {
SCRIPT_TAKING_COMMANDS
.iter()
.find_map(|&(name, slots)| (name == command).then_some(slots))
}
pub(crate) fn namespace_script_slots(
word_list: &Node<'_>,
dialect: Dialect<'_>,
) -> Option<ScriptSlots> {
let subcommand = word_list.child(0)?;
if subcommand.kind_id() != dialect.kinds.simple_word {
return None;
}
let subcommand = node_text(dialect.code, &subcommand)?;
Some(
NAMESPACE_SCRIPT_SUBCOMMANDS
.iter()
.find_map(|&(name, slots)| (name == subcommand).then_some(slots))
.unwrap_or(ScriptSlots::NoneOfThem),
)
}
#[derive(Clone, Copy)]
pub(crate) struct ArgumentRoles {
pub(crate) slots: ScriptSlots,
pub(crate) first: usize,
}
pub(crate) fn argument_slots_are_readable(
owner: &Node<'_>,
arguments: &Node<'_>,
ancestors: Ancestors<'_, '_>,
) -> bool {
if !owner.has_error() {
return true;
}
ancestors.memoised(MemoQuestion::ArgumentSlotsReadable, arguments, || {
argument_slot_scans::record();
!arguments
.children()
.any(|slot| slot.is_error() || slot.is_missing())
})
}
pub(crate) fn fills_script_slot<'t>(
word: &Node<'t>,
arguments: &Node<'t>,
roles: ArgumentRoles,
dialect: Dialect<'_>,
) -> bool {
let mut cursor = arguments.cursor();
let index = cursor.goto_first_child_for_byte(word.start_byte());
let Some(index) = index.filter(|_| cursor.node().id() == word.id()) else {
return true;
};
let Some(position) = index.checked_sub(roles.first) else {
return true;
};
match roles.slots {
ScriptSlots::Every => true,
ScriptSlots::NoneOfThem => false,
ScriptSlots::EveryButFirst => position > 0,
ScriptSlots::Only(evaluated) => position == evaluated,
ScriptSlots::LastOf(arity) => arguments
.child_count()
.checked_sub(roles.first)
.is_none_or(|count| count != arity || position + 1 == count),
ScriptSlots::EveryButLeadingLevel => {
position > 0 || !reads_as_uplevel_level(word, dialect.code)
}
ScriptSlots::SwitchArms => switch_arm_slot(arguments, index, dialect, &mut cursor),
}
}
fn reads_as_uplevel_level(word: &Node<'_>, code: &[u8]) -> bool {
let Some(inner) = node_text(code, word)
.and_then(|text| text.strip_prefix('{'))
.and_then(|inner| inner.strip_suffix('}'))
else {
return false;
};
let inner = inner.trim();
let digits = inner.strip_prefix('#').map_or(inner, str::trim_start);
!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
}
fn switch_arm_slot<'t>(
arguments: &Node<'t>,
index: usize,
dialect: Dialect<'_>,
cursor: &mut Cursor<'t>,
) -> bool {
let Some(subject) = switch_subject_index(arguments, dialect, cursor) else {
return true;
};
if index <= subject {
return false;
}
if arguments.child_count() == subject + 2 {
return true;
}
(index - subject).is_multiple_of(2)
}
fn switch_subject_index<'t>(
arguments: &Node<'t>,
dialect: Dialect<'_>,
cursor: &mut Cursor<'t>,
) -> Option<usize> {
let mut skip_operand = false;
for (index, child) in arguments.children_with(cursor).enumerate() {
if skip_operand {
skip_operand = false;
continue;
}
let Some(word) = (child.kind_id() == dialect.kinds.simple_word)
.then(|| node_text(dialect.code, &child))
.flatten()
else {
return Some(index);
};
if word == SWITCH_OPTION_TERMINATOR {
return Some(index + 1);
}
if !word.starts_with('-') {
return Some(index);
}
skip_operand = SWITCH_OPTIONS_TAKING_A_WORD.contains(&word);
}
None
}
#[cfg(test)]
#[cfg(feature = "tcl")]
mod tests {
use super::{
ArgumentRoles, Dialect, ScriptSlots, fills_script_slot, node_text, reads_as_uplevel_level,
};
use crate::Tcl;
use crate::lang_helpers::tcl::BRACED_WORD_KINDS;
use crate::node::{Node, Tree};
fn braced_words<'a>(root: &Node<'a>, out: &mut Vec<Node<'a>>) {
if root.kind_id() == Tcl::BracedWord as u16 {
out.push(*root);
}
for child in root.children() {
braced_words(&child, out);
}
}
fn first_word_list<'a>(root: &Node<'a>) -> Option<Node<'a>> {
if root.kind_id() == Tcl::WordList as u16 {
return Some(*root);
}
root.children().find_map(|child| first_word_list(&child))
}
#[test]
fn an_unplaceable_word_keeps_the_script_answer() {
let code = b"namespace {export} {a {b c}}\n";
let tree = Tree::new::<crate::langs::TclCode>(code);
let root = tree.get_root();
let dialect = Dialect {
code,
kinds: &BRACED_WORD_KINDS,
};
let mut words = Vec::new();
braced_words(&root, &mut words);
let texts: Vec<&str> = words
.iter()
.map(|word| node_text(code, word).expect("ascii fixture"))
.collect();
assert_eq!(
texts,
["{export}", "{a {b c}}", "{b c}"],
"the fixture must hold the subcommand, slot 1, and a word \
nested inside slot 1"
);
let arguments = first_word_list(&root).expect("the namespace has an argument list");
let roles = ArgumentRoles {
slots: ScriptSlots::NoneOfThem,
first: 1,
};
assert!(
fills_script_slot(&words[0], &arguments, roles, dialect),
"a word before the construct's first argument keeps the script answer"
);
assert!(
!fills_script_slot(&words[1], &arguments, roles, dialect),
"the fixture's placeable word must answer the other way, or the \
rows around it are asserting a constant"
);
assert!(
fills_script_slot(&words[2], &arguments, roles, dialect),
"a word that is not one of these arguments keeps the script \
answer, rather than borrowing the slot it is nested in"
);
}
#[test]
fn a_level_specifier_is_an_integer_and_nothing_else() {
let code = b"uplevel {1} { 2 } {a} {} {1x} plain\n";
let tree = Tree::new::<crate::langs::TclCode>(code);
let root = tree.get_root();
let mut words = Vec::new();
braced_words(&root, &mut words);
let read: Vec<bool> = words
.iter()
.map(|word| reads_as_uplevel_level(word, code))
.collect();
assert_eq!(
read,
[true, true, false, false, false],
"`{{1}}` and `{{ 2 }}` are levels; a word, an empty word and \
`1x` are not"
);
let arguments = first_word_list(&root).expect("the command has an argument list");
let plain = arguments
.children()
.find(|node| node.kind_id() == Tcl::SimpleWord as u16)
.expect("the fixture ends in a bare word");
assert!(
!reads_as_uplevel_level(&plain, code),
"a word that is not brace-delimited carries no level"
);
}
}
#[cfg(test)]
#[cfg(any(feature = "tcl", feature = "irules"))]
mod readable_slot_tests {
use super::argument_slot_scans;
use crate::getter::{BracedWordKinds, Getter};
use crate::node::{Ancestors, FoldCache, MemoQuestion, Node, Tree};
use crate::traits::LanguageInfo;
fn braced_words(root: Node<'_>, script: u16) -> Vec<(Node<'_>, Vec<Node<'_>>)> {
let mut out = Vec::new();
let mut stack = vec![(root, Vec::new())];
while let Some((node, chain)) = stack.pop() {
if node.kind_id() == script {
out.push((node, chain.clone()));
}
let mut below = chain;
below.push(node);
stack.extend(node.children().map(|child| (child, below.clone())));
}
out.sort_by_key(|(node, _)| node.start_byte());
out
}
fn scans_once_per_list<L: LanguageInfo + Getter>(label: &str, kinds: &BracedWordKinds) {
let width = 200;
let code = crate::test_support::tcl_wide_erroring_eval(width);
let code = code.as_bytes();
let tree = Tree::new::<L>(code);
let root = tree.get_root();
let words = braced_words(root, kinds.script);
assert_eq!(
words.len(),
width,
"{label}: the fixture must spell {width} words"
);
let cache = FoldCache::default();
let before = argument_slot_scans::observed();
let cached: Vec<bool> = words
.iter()
.map(|(word, chain)| {
L::is_braced_literal_slot(
word,
code,
Ancestors::known(chain).with_folds(&cache),
kinds,
)
})
.collect();
assert_eq!(
argument_slot_scans::observed() - before,
1,
"{label}: a walk lending a FoldCache scans the list once"
);
let before = argument_slot_scans::observed();
let uncached: Vec<bool> = words
.iter()
.map(|(word, chain)| {
L::is_braced_literal_slot(word, code, Ancestors::known(chain), kinds)
})
.collect();
assert_eq!(
argument_slot_scans::observed() - before,
width,
"{label}: without a cache every word scans the list"
);
assert_eq!(
cached, uncached,
"{label}: the cached and uncached walks must agree on the fixture"
);
}
fn a_clean_list_is_never_scanned<L: LanguageInfo + Getter>(
label: &str,
kinds: &BracedWordKinds,
) {
let width = 200;
let code = format!("eval {}\n", "{a b} ".repeat(width));
let code = code.as_bytes();
let tree = Tree::new::<L>(code);
let root = tree.get_root();
assert!(!root.has_error(), "{label}: the fixture must parse cleanly");
let words = braced_words(root, kinds.script);
assert_eq!(
words.len(),
width,
"{label}: the fixture must spell {width} words"
);
let list = words[0]
.1
.last()
.copied()
.expect("a braced argument sits under a word_list");
let cache = FoldCache::default();
let before = argument_slot_scans::observed();
for (word, chain) in &words {
let cached = Ancestors::known(chain).with_folds(&cache);
let uncached = Ancestors::known(chain);
assert!(
!L::is_braced_literal_slot(word, code, cached, kinds)
&& !L::is_braced_literal_slot(word, code, uncached, kinds),
"{label}: every `eval` argument is a script"
);
}
assert_eq!(
argument_slot_scans::observed() - before,
0,
"{label}: a list whose owner has no error is never scanned"
);
assert!(
Ancestors::known(&words[0].1)
.with_folds(&cache)
.node_memo(MemoQuestion::ArgumentSlotsReadable)
.expect("the chain lent a cache")
.get(&list)
.is_none(),
"{label}: a list that was never scanned has no stored answer"
);
}
fn a_cached_answer_is_the_list_s_own<L: LanguageInfo + Getter>(
label: &str,
kinds: &BracedWordKinds,
) {
let code = b"after {100} ] {puts hi}\nafter {100} {puts ]}\n";
let tree = Tree::new::<L>(code);
let root = tree.get_root();
let words = braced_words(root, kinds.script);
let texts: Vec<&str> = words
.iter()
.map(|(word, _)| word.utf8_text(code).expect("ascii fixture"))
.collect();
assert_eq!(
texts,
["{100}", "{puts hi}", "{100}", "{puts ]}"],
"{label}: the fixture must spell a `{{100}}` on each line"
);
let cache = FoldCache::default();
let before = argument_slot_scans::observed();
let ask = || -> Vec<bool> {
words
.iter()
.map(|(word, chain)| {
L::is_braced_literal_slot(
word,
code,
Ancestors::known(chain).with_folds(&cache),
kinds,
)
})
.collect()
};
let first = ask();
let again = ask();
assert_eq!(
first,
[false, false, true, false],
"{label}: the `{{100}}` after a stray `]` keeps the script answer; \
the one beside an error *inside* a script is the value its slot names"
);
assert_eq!(again, first, "{label}: a second ask answers from the memo");
assert_eq!(
argument_slot_scans::observed() - before,
2,
"{label}: each erroring list is scanned once across both asks"
);
}
#[test]
#[cfg(feature = "tcl")]
fn tcl_scans_an_erroring_list_once_per_walk() {
scans_once_per_list::<crate::langs::TclCode>(
"tcl",
&crate::lang_helpers::tcl::BRACED_WORD_KINDS,
);
}
#[test]
#[cfg(feature = "tcl")]
fn tcl_a_cached_answer_is_the_list_s_own() {
a_cached_answer_is_the_list_s_own::<crate::langs::TclCode>(
"tcl",
&crate::lang_helpers::tcl::BRACED_WORD_KINDS,
);
}
#[test]
#[cfg(feature = "tcl")]
fn tcl_a_clean_list_is_never_scanned() {
a_clean_list_is_never_scanned::<crate::langs::TclCode>(
"tcl",
&crate::lang_helpers::tcl::BRACED_WORD_KINDS,
);
}
#[test]
#[cfg(feature = "irules")]
fn irules_a_clean_list_is_never_scanned() {
a_clean_list_is_never_scanned::<crate::langs::IrulesCode>(
"irules",
&crate::lang_helpers::irules::BRACED_WORD_KINDS,
);
}
#[test]
#[cfg(feature = "irules")]
fn irules_scans_an_erroring_list_once_per_walk() {
scans_once_per_list::<crate::langs::IrulesCode>(
"irules",
&crate::lang_helpers::irules::BRACED_WORD_KINDS,
);
}
#[test]
#[cfg(feature = "irules")]
fn irules_a_cached_answer_is_the_list_s_own() {
a_cached_answer_is_the_list_s_own::<crate::langs::IrulesCode>(
"irules",
&crate::lang_helpers::irules::BRACED_WORD_KINDS,
);
}
}