macro_rules! js_family_modifiers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)* Static,] $($rest)*);
};
}
macro_rules! js_family_decl_keywords {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)* Function, Class2, Let, Var, Const,] $($rest)*);
};
}
pub(crate) use {js_family_decl_keywords, js_family_modifiers};
macro_rules! js_family_func_openers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
FunctionDeclaration(callable opens Function),
GeneratorFunctionDeclaration(callable opens Function),
MethodDefinition(callable opens Function),
FunctionExpression(opens Function callable_when bound_function),
GeneratorFunction(opens Function callable_when bound_function),
ArrowFunction(opens Function callable_when bound_arrow),
ClassStaticBlock(opens Function),
] $($rest)*);
};
}
macro_rules! js_family_closures {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
FunctionExpression(gated_by unbound_function),
GeneratorFunction(gated_by unbound_function),
ArrowFunction(gated_by unbound_arrow),
] $($rest)*);
};
}
macro_rules! js_family_containers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
Program(opens Unit),
ClassDeclaration(opens Class),
Class(opens Class),
] $($rest)*);
};
}
macro_rules! js_family_binding_gates {
($lang:ident, $code:ident, $field:ident) => {
fn bound<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
extra: impl FnOnce() -> bool,
) -> bool {
use $lang::*;
ancestors.ancestor_before_stop::<$crate::$code>(
node,
$crate::node::FoldLane::NamedBinding,
|node| {
matches!(
node.kind_id().into(),
VariableDeclarator
| AssignmentExpression
| LabeledStatement
| Pair
| $field
)
},
|node| {
matches!(
node.kind_id().into(),
StatementBlock
| ReturnStatement
| NewExpression
| CallExpression
| Arguments
)
},
) || extra()
}
fn bound_function<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
) -> bool {
bound(node, ancestors, || node.is_child($lang::Identifier as u16))
}
fn bound_arrow<'a>(node: &$crate::Node<'a>, ancestors: $crate::Ancestors<'a, '_>) -> bool {
bound(node, ancestors, || {
ancestors.parent(node).is_some_and(|parent| {
ancestors.memoised($crate::node::MemoQuestion::NamesAnArrow, &parent, || {
parent.is_child($lang::PropertyIdentifier as u16)
})
})
})
}
fn unbound_function<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
) -> bool {
!bound_function(node, ancestors)
}
fn unbound_arrow<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
) -> bool {
!bound_arrow(node, ancestors)
}
};
}
macro_rules! js_family_strings {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)* String, TemplateString,] $($rest)*);
};
}
pub(crate) use {
js_family_binding_gates, js_family_closures, js_family_containers, js_family_func_openers,
js_family_strings,
};
macro_rules! ts_family_gates {
($lang:ident) => {
fn declares_a_type<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
) -> bool {
let mut up = ancestors.iter(node).map(|(ancestor, _)| ancestor);
!up.next().is_some_and(|parent| {
if parent.is_error() {
up.next()
.is_some_and(|clause| clause.kind_id() == $lang::ExportClause as u16)
} else {
parent.kind_id() == $lang::ExportSpecifier as u16 && parent.has_error()
}
})
}
fn names_a_type_not_void(node: &$crate::Node<'_>) -> bool {
!node
.child(0)
.is_some_and(|child| child.kind_id() == $lang::Void as u16)
}
};
}
macro_rules! ts_family_modifiers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
Public, Private, Protected, Override, Readonly, Abstract, Accessor, Declare,
] $($rest)*);
};
}
macro_rules! ts_family_decl_keywords {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
Interface, Enum, Type(gated_by declares_a_type), Namespace, Module2, Global,
] $($rest)*);
};
}
macro_rules! js_family_comparison_payers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
EQEQ, EQEQEQ, BANGEQ, BANGEQEQ, LTEQ, GTEQ, Instanceof,
LT under [BinaryExpression], GT under [BinaryExpression],
] $($rest)*);
};
}
macro_rules! js_family_short_circuit_payers {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)* AMPAMP, PIPEPIPE,] $($rest)*);
};
}
macro_rules! js_family_loops {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
ForStatement, ForInStatement, WhileStatement, DoStatement,
] $($rest)*);
};
}
macro_rules! js_family_exits {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
ReturnStatement, ThrowStatement, YieldExpression,
] $($rest)*);
};
}
pub(crate) use {
js_family_comparison_payers, js_family_exits, js_family_loops, js_family_short_circuit_payers,
ts_family_decl_keywords, ts_family_gates, ts_family_modifiers,
};
macro_rules! js_family_doc_targets {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
FunctionDeclaration,
GeneratorFunctionDeclaration,
ClassDeclaration,
MethodDefinition,
Pair,
ShorthandPropertyIdentifier,
VariableDeclaration(gated_by first_declarator_binds_a_name no_chain),
LexicalDeclaration(gated_by first_declarator_binds_a_name no_chain),
] $($rest)*);
};
}
macro_rules! js_family_doc_gates {
($lang:ident, $block:ident) => {
$crate::roles::byte_gate!(
opens_with_doc_block_marker,
$crate::lang_helpers::doc_comment::$block
);
fn first_declarator_binds_a_name(node: &$crate::Node<'_>) -> bool {
node.children()
.find(|c| c.kind_id() == $lang::VariableDeclarator as u16)
.and_then(|d| d.child_by_field_name("name"))
.is_some_and(|name| name.kind_id() == $lang::Identifier as u16)
}
};
}
macro_rules! js_doc_gates {
($lang:ident) => {
fn export_declares(node: &$crate::Node<'_>) -> bool {
!node.is_child($lang::ExportClause as u16)
}
fn assigns_to_a_name_or_member(node: &$crate::Node<'_>) -> bool {
use $lang::*;
let mut expr = node.child(0);
while let Some(e) = expr.filter(|e| e.kind_id() == ParenthesizedExpression) {
expr = e.children().find(|c| c.is_named() && !c.is_extra());
}
expr.filter(|e| {
matches!(
e.kind_id().into(),
AssignmentExpression | AugmentedAssignmentExpression
)
})
.and_then(|e| e.child_by_field_name("left"))
.is_some_and(|left| !matches!(left.kind_id().into(), ObjectPattern | ArrayPattern))
}
};
}
macro_rules! ts_family_doc_targets {
(@splice $cont:tt [$($acc:tt)*] $($rest:tt)*) => {
$crate::role_table!(@owners $cont [$($acc)*
AbstractClassDeclaration,
InterfaceDeclaration,
TypeAliasDeclaration,
EnumDeclaration,
Module,
AmbientDeclaration,
FunctionSignature,
MethodSignature,
AbstractMethodSignature,
PublicFieldDefinition,
PropertySignature,
IndexSignature,
CallSignature,
ConstructSignature,
EnumAssignment,
RequiredParameter,
RequiredParameter2,
OptionalParameter,
OptionalParameter2,
ExportStatement(gated_by export_declares_to_tsc),
ExpressionStatement(gated_by using_declares no_chain),
PropertyIdentifier(under [EnumBody]),
ComputedPropertyName(under [EnumBody]),
] $($rest)*);
};
}
macro_rules! ts_doc_gates {
($lang:ident, $roles:ident) => {
fn export_declares_to_tsc<'a>(
node: &$crate::Node<'a>,
ancestors: $crate::Ancestors<'a, '_>,
) -> bool {
use $lang::*;
const _: () = assert!(
!$crate::roles::$roles::doc_target::TEXT_GATED,
"a TS `DocTarget` row reads bytes; `export_declares_to_tsc` cannot forward with `&[]`"
);
node.child_by_field_name("declaration").map_or_else(
|| {
node.is_child(ExportClause as u16)
|| node.child_by_field_name("value").is_some_and(|value| {
matches!(
value.kind_id().into(),
FunctionExpression | GeneratorFunction | Class
)
})
},
|inner| {
$crate::roles::$roles::doc_target::owns(&inner, &[], ancestors)
|| inner.kind_id() == InternalModule as u16
},
)
}
fn using_declares(node: &$crate::Node<'_>) -> bool {
use $lang::*;
node.child(0).is_some_and(|e| {
if e.kind_id() == InternalModule {
return true;
}
let assignment = if e.kind_id() == AwaitExpression {
e.children().find(|c| c.is_named() && !c.is_extra())
} else {
Some(e)
};
assignment.is_some_and(|a| {
a.kind_id() == AssignmentExpression
&& a.child(0).is_some_and(|u| u.kind_id() == Using)
&& a.child_by_field_name("left")
.is_some_and(|left| left.kind_id() == Identifier)
})
})
}
};
}
pub(crate) use {
js_doc_gates, js_family_doc_gates, js_family_doc_targets, ts_doc_gates, ts_family_doc_targets,
};
#[cfg(test)]
mod tests {
use crate::test_support::for_each_node_with_chain;
use crate::{Ancestors, Checker, Getter, LanguageInfo, Node, SpaceKind};
#[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
const SOURCE: &str = "function f(a) { return a; }\n\
function* gen() { yield 1; }\n\
const g = function (b) { return b; };\n\
const h = function named(c) { return c; };\n\
const gg = function* (c) { yield c; };\n\
const i = (d) => d;\n\
const j = e => e;\n\
let l; l = function () {};\n\
label: function m() {}\n\
const o = { p: function () {}, q: () => 1, \"r\": () => 2, [s]: () => 3 };\n\
class K extends Object {\n\
static { let z = 1; }\n\
fld = () => 1;\n\
\"str\" = function () {};\n\
[\"comp\"] = () => 3;\n\
constructor() { super(); }\n\
method() { return f(1); }\n\
}\n\
const K2 = class {};\n\
run(function () {});\n\
run(function named2() {});\n\
run(x => x);\n\
run((x) => x);\n\
(function () {})();\n\
(() => {})();\n\
new Foo(() => 1);\n\
run(function* () {});\n";
#[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
const FORMS: &[(&str, char)] = &[
("function f(a) { return a; }", 'F'),
("function* gen() { yield 1; }", 'F'),
("function (b) { return b; }", 'F'),
("function named(c) { return c; }", 'F'),
("function* (c) { yield c; }", 'F'),
("(d) => d", 'F'),
("e => e", 'F'),
("function () {}", 'F'),
("function m() {}", 'F'),
("function () {}", 'F'),
("() => 1", 'F'),
("() => 2", 'F'),
("() => 3", 'F'),
("() => 1", 'F'),
("function () {}", 'F'),
("() => 3", 'F'),
("constructor() { super(); }", 'F'),
("method() { return f(1); }", 'F'),
("function () {}", 'C'),
("function named2() {}", 'F'),
("x => x", 'C'),
("(x) => x", 'C'),
("function () {}", 'C'),
("() => {}", 'C'),
("() => 1", 'C'),
("function* () {}", 'C'),
];
#[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))]
fn check<L: LanguageInfo + Checker + Getter>(
opens_space: fn(&Node<'_>, &[u8], Ancestors<'_, '_>) -> SpaceKind,
func_owners: &[u16],
closure_owners: &[u16],
) {
let source = SOURCE.as_bytes();
let mut seen = Vec::new();
for_each_node_with_chain::<L>(source, |node, chain| {
let ancestors = Ancestors::known(chain);
let kind = node.kind();
let got = (
L::is_func_with_code(node, source, ancestors),
L::is_closure(node, ancestors),
L::promotes_to_func_space_with_code(node, source, ancestors),
L::get_space_kind_with_code(node, source, ancestors),
);
let text = node.utf8_text(source).expect("fixture is UTF-8");
if matches!(
kind,
"function_declaration"
| "generator_function_declaration"
| "function_expression"
| "generator_function"
| "arrow_function"
| "method_definition"
) {
let (form, verdict) = FORMS[seen.len()];
assert_eq!(text, form, "form #{} of the fixture", seen.len());
let want = match verdict {
'F' => (true, false, true, SpaceKind::Function),
_ => (false, true, true, SpaceKind::Function),
};
assert_eq!(got, want, "{kind} `{text}`");
seen.push(text.to_owned());
} else if kind == "class_static_block" {
assert_eq!(got, (false, false, true, SpaceKind::Function), "{kind}");
} else if kind == "class_declaration" || (kind == "class" && node.is_named()) {
assert_eq!(got, (false, false, true, SpaceKind::Class), "{kind}");
} else if kind == "program" {
assert_eq!(got, (false, false, true, SpaceKind::Unit));
} else {
assert_eq!(
got,
(false, false, false, SpaceKind::Unknown),
"{kind} `{text}`"
);
}
assert_eq!(
got.3 != SpaceKind::Unknown,
got.2,
"{kind}: opens_space vs promotion"
);
assert_eq!(
(L::is_func_space(node), L::get_space_kind(node)),
(got.2, got.3),
"{kind}: the byte-less spellings are the kind table"
);
assert_eq!(
got.3,
opens_space(node, source, ancestors),
"{kind}: the getter reads the fold"
);
});
assert_eq!(seen.len(), FORMS.len(), "{seen:?}");
let kinds: std::collections::BTreeSet<u16> = {
let mut k = std::collections::BTreeSet::new();
for_each_node_with_chain::<L>(source, |node, _| {
k.insert(node.kind_id());
});
k
};
for &owner in func_owners.iter().chain(closure_owners) {
assert!(kinds.contains(&owner), "fixture never emits kind {owner}");
}
}
#[cfg(feature = "javascript")]
#[test]
fn javascript_binding_shapes() {
use crate::roles::javascript::{closure, func_opener, opens_space};
check::<crate::JavascriptCode>(opens_space, func_opener::OWNERS, closure::OWNERS);
}
#[cfg(feature = "mozjs")]
#[test]
fn mozjs_binding_shapes() {
use crate::roles::mozjs::{closure, func_opener, opens_space};
check::<crate::MozjsCode>(opens_space, func_opener::OWNERS, closure::OWNERS);
}
#[cfg(feature = "typescript")]
#[test]
fn typescript_binding_shapes() {
use crate::roles::typescript::{closure, func_opener, opens_space};
check::<crate::TypescriptCode>(opens_space, func_opener::OWNERS, closure::OWNERS);
}
#[cfg(feature = "typescript")]
#[test]
fn tsx_binding_shapes() {
use crate::roles::tsx::{closure, func_opener, opens_space};
check::<crate::TsxCode>(opens_space, func_opener::OWNERS, closure::OWNERS);
}
}