use crate::Tcl;
use crate::getter::BracedWordKinds;
use crate::node::{Ancestors, Node, WordSlot};
pub(crate) const BRACED_WORD_KINDS: BracedWordKinds = BracedWordKinds {
value: Tcl::BracedWordSimple as u16,
script: Tcl::BracedWord as u16,
comment: Tcl::Comment as u16,
command: Tcl::Command as u16,
word_list: Tcl::WordList as u16,
simple_word: Tcl::SimpleWord as u16,
argument: Tcl::Argument as u16,
procedure: Tcl::Procedure as u16,
namespace: Tcl::Namespace as u16,
open_brace: Tcl::LBRACE as u16,
};
#[inline]
#[must_use]
pub fn tcl_command_name<'a>(node: &'a Node<'a>, code: &'a [u8]) -> Option<&'a str> {
if node.kind_id() != Tcl::Command as u16 {
return None;
}
command_name_reads::record();
let name = node.child_by_field_name("name")?;
if name.kind_id() != Tcl::SimpleWord as u16 {
return None;
}
name.utf8_text(code)
.map(crate::lang_helpers::strip_global_qualifier)
}
crate::observation::counter!(command_name_reads, cfg(any(test, feature = "test-support")));
pub fn tcl_try_handler_bodies<'a>(node: &Node<'a>) -> impl Iterator<Item = Node<'a>> + 'a {
let mut after_arguments = false;
node.children().filter(move |child| {
let is_body = after_arguments;
after_arguments = child.kind_id() == Tcl::Arguments as u16;
is_body
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
#[non_exhaustive]
pub enum TclCommandWord {
Other = 0,
Switch,
For,
Return,
Error,
Throw,
Exit,
Incr,
Append,
Lappend,
}
impl TclCommandWord {
const ALL: [Self; 10] = [
Self::Other,
Self::Switch,
Self::For,
Self::Return,
Self::Error,
Self::Throw,
Self::Exit,
Self::Incr,
Self::Append,
Self::Lappend,
];
#[must_use]
pub fn from_text(text: &str) -> Self {
match text {
"switch" => Self::Switch,
"for" => Self::For,
"return" => Self::Return,
"error" => Self::Error,
"throw" => Self::Throw,
"exit" => Self::Exit,
"incr" => Self::Incr,
"append" => Self::Append,
"lappend" => Self::Lappend,
_ => Self::Other,
}
}
#[inline]
#[must_use]
pub fn is_exit(self) -> bool {
matches!(self, Self::Return | Self::Error | Self::Throw | Self::Exit)
}
fn from_slot(value: u8) -> Self {
Self::ALL
.get(usize::from(value))
.copied()
.unwrap_or(Self::Other)
}
}
#[inline]
#[must_use]
pub fn tcl_command_word<'a>(
node: &Node<'a>,
code: &[u8],
ancestors: Ancestors<'a, '_>,
) -> TclCommandWord {
if node.kind_id() != Tcl::Command as u16 {
return TclCommandWord::Other;
}
TclCommandWord::from_slot(ancestors.classified(WordSlot::TclCommandWord, node, || {
tcl_command_name(node, code).map_or(TclCommandWord::Other, TclCommandWord::from_text) as u8
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::TclCode;
use crate::test_support::for_each_node_with_chain;
#[cfg(feature = "tcl")]
#[test]
fn command_word_is_read_once_per_command_under_a_cache() {
use crate::node::FoldCache;
const ASKS: usize = 4;
let source = b"proc f {a} {\n switch $a { x { ::return 1 } }\n for {set i 0} {$i < 3} {incr i} { }\n puts error\n $a 1\n}\n";
let cache = FoldCache::default();
let mut commands = 0;
let mut enclosing_asks = 0;
let mut answers = std::collections::HashMap::new();
let mut cached = Vec::new();
let before = command_name_reads::observed();
for_each_node_with_chain::<TclCode>(source, |node, chain| {
if node.kind_id() != Tcl::Command as u16 {
return;
}
commands += 1;
let walk = Ancestors::for_walk_without_siblings(chain, node, &cache);
let first = tcl_command_word(node, source, walk);
let enclosing = chain
.iter()
.rev()
.find(|ancestor| ancestor.kind_id() == Tcl::Command as u16);
for _ in 1..ASKS {
if let Some(enclosing) = enclosing {
enclosing_asks += 1;
let recorded = answers[&enclosing.id()];
assert_eq!(tcl_command_word(enclosing, source, walk), recorded);
}
assert_eq!(tcl_command_word(node, source, walk), first);
}
answers.insert(node.id(), first);
cached.push(first);
});
let cached_reads = command_name_reads::observed() - before;
let mut uncached = Vec::new();
let before = command_name_reads::observed();
for_each_node_with_chain::<TclCode>(source, |node, chain| {
if node.kind_id() == Tcl::Command as u16 {
let chain = Ancestors::known(chain);
for _ in 0..ASKS {
uncached.push(tcl_command_word(node, source, chain));
}
}
});
let uncached_reads = command_name_reads::observed() - before;
assert_eq!(
cached,
[
TclCommandWord::Switch,
TclCommandWord::Other, TclCommandWord::Return, TclCommandWord::For,
TclCommandWord::Other, TclCommandWord::Incr,
TclCommandWord::Other, TclCommandWord::Other, ]
);
assert_eq!(commands, cached.len());
assert_eq!(
uncached,
cached
.iter()
.flat_map(|&w| std::iter::repeat_n(w, ASKS))
.collect::<Vec<_>>()
);
assert_eq!(enclosing_asks, 4 * (ASKS - 1));
assert_eq!(
(cached_reads, uncached_reads),
(commands + enclosing_asks, ASKS * commands),
"one read per visited command plus one per ask about its enclosing command"
);
}
#[cfg(feature = "tcl")]
#[test]
fn command_word_of_a_non_command_is_other_without_a_read() {
let source = b"proc f {a} { return $a }\n";
let before = command_name_reads::observed();
let mut seen = Vec::new();
for_each_node_with_chain::<TclCode>(source, |node, chain| {
if node.kind_id() != Tcl::Command as u16 {
seen.push((
node.kind(),
tcl_command_name(node, source).is_some(),
command_name_reads::observed() - before,
tcl_command_word(node, source, Ancestors::known(chain)),
));
}
});
assert!(
seen.len() > 5,
"the fixture has non-command nodes to ask about"
);
let read = seen
.iter()
.filter(|&&(_, name, reads, word)| name || reads != 0 || word != TclCommandWord::Other)
.map(|&(kind, ..)| kind)
.collect::<Vec<_>>();
assert_eq!(
read,
Vec::<&str>::new(),
"a non-command was read or classified"
);
assert_eq!(command_name_reads::observed(), before);
}
#[test]
fn command_word_round_trips_through_the_slot() {
for word in TclCommandWord::ALL {
assert_eq!(TclCommandWord::from_slot(word as u8), word);
}
assert_eq!(
TclCommandWord::from_slot(u8::try_from(TclCommandWord::ALL.len()).expect("fits")),
TclCommandWord::Other
);
for (index, word) in TclCommandWord::ALL.iter().enumerate() {
assert_eq!(*word as usize, index, "`ALL` is in discriminant order");
}
}
}