Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! Commands and flags: commander, yargs, `util.parseArgs`; arguments read by hand and parsers
//! without a detector.
use std::collections::{HashMap, HashSet};
use oxc_ast::ast::Program;
use oxc_ast::ast::{
AssignmentExpression, AssignmentOperator, AssignmentTarget, BindingPattern, CallExpression,
Expression, MemberExpression, NewExpression, ObjectExpression, ObjectPropertyKind,
VariableDeclarator,
};
use oxc_ast_visit::{Visit, walk};
use oxc_span::{GetSpan, Span};
use super::syntax::{
arg_object, arg_text, as_call, as_member, callee_ident_name, ident, is_function, key_name,
last_name, member_name, method, method_span, object_of, prop, receiver, text, texts,
};
use super::{COMMANDER, Collector, MAX_DEPTH, UNSUPPORTED_PARSERS};
use crate::obligations::Family;
use crate::obligations::surface::Found;
const NOT_LITERAL_FLAG: &str = "option flags are not a string literal";
const NOT_LITERAL_NAME: &str = "option name is not a string literal";
const NOT_LITERAL_POSITIONAL: &str = "positional argument is not a string literal";
const NOT_LITERAL_COMMAND: &str = "command name is not a string literal";
/// Which command what a call chain declares belongs to.
#[derive(Clone)]
pub(super) enum Scope {
/// The program itself.
Global,
Command(String),
/// A command whose name is not a literal.
Unknown,
}
/// The reason why reading this property of a global object is a raw read.
fn argv_reason(object: &str, property: &str) -> Option<&'static str> {
match (object, property) {
("process", "argv") => Some("process.argv is read directly"),
("Bun", "argv") => Some("Bun.argv is read directly"),
("Deno", "args") => Some("Deno.args is read directly"),
_ => None,
}
}
/// The first word of a spec (`serve <dir>` → `serve`) and the rest.
fn split_spec(spec: &str) -> Option<(String, Option<String>)> {
let mut words = spec.split_whitespace();
let name = words.next()?.to_string();
let rest = words.collect::<Vec<_>>().join(" ");
Some((name, (!rest.is_empty()).then_some(rest)))
}
/// `$0` or `*` as the first word: yargs's default command.
fn is_default_spec(spec: &str) -> bool {
split_spec(spec).is_some_and(|(name, _)| name == "$0" || name == "*")
}
/// The positional arguments of a signature (`<file> [dir] <items...>`), brackets included.
fn positional_tokens(signature: &str) -> Vec<String> {
signature
.split_whitespace()
.filter(|t| t.starts_with(['<', '[']))
.map(str::to_string)
.collect()
}
/// The name of a positional without its brackets or trailing dots: `<items...>` → `items`.
fn bare_name(token: &str) -> &str {
token
.trim_matches(['<', '>', '[', ']'])
.trim_end_matches('.')
}
fn join_detail(parts: Vec<String>) -> Option<String> {
let parts: Vec<String> = parts.into_iter().filter(|p| !p.is_empty()).collect();
(!parts.is_empty()).then(|| parts.join("; "))
}
/// A commander flag: `-p, --port <n>` → (`--port`, `-p <n>`); `-v` alone stays `-v`.
fn parse_flag_spec(spec: &str) -> Option<(String, Option<String>)> {
let cut = spec.find(['<', '[']).unwrap_or(spec.len());
let (flags, value) = spec.split_at(cut);
let tokens: Vec<&str> = flags
.split(|c: char| c.is_whitespace() || c == ',' || c == '|')
.filter(|t| t.starts_with('-') && t.len() > 1)
.collect();
let name = tokens
.iter()
.find(|t| t.starts_with("--"))
.or_else(|| tokens.first())?;
let mut detail: Vec<&str> = tokens.iter().filter(|t| *t != name).copied().collect();
let value = value.trim();
if !value.is_empty() {
detail.push(value);
}
Some((
(*name).to_string(),
(!detail.is_empty()).then(|| detail.join(" ")),
))
}
/// `p` → `-p`, `port` → `--port`.
fn dashed(name: &str) -> String {
if name.starts_with('-') {
name.to_string()
} else if name.chars().count() == 1 {
format!("-{name}")
} else {
format!("--{name}")
}
}
/// The yargs methods that make a key an option (yargs 17 API documentation: `.alias`,
/// `.array`, `.boolean`, `.choices`, `.coerce`, `.config`, `.conflicts`, `.count`, `.default`,
/// `.demandOption`, `.describe`, `.deprecateOption`, `.group`, `.hide`, `.global`, `.implies`,
/// `.nargs`, `.normalize`, `.number`, `.requiresArg`, `.skipValidation`, `.string`; and
/// `.defaults`, `.demand`, `.require`, `.required`). `.env` is not in this list: it is a
/// prefix, not a key.
const KEY_METHODS: &[&str] = &[
"alias",
"array",
"boolean",
"choices",
"coerce",
"config",
"conflicts",
"count",
"default",
"defaults",
"demand",
"demandOption",
"describe",
"global",
"deprecateOption",
"group",
"hide",
"implies",
"nargs",
"normalize",
"number",
"require",
"required",
"requiresArg",
"skipValidation",
"string",
];
/// The names of a flag: its own and the aliases in its detail.
fn flag_names(found: &Found) -> impl Iterator<Item = &str> {
let detail = found.detail.as_deref().unwrap_or_default();
std::iter::once(found.name.as_str()).chain(detail.split(' ').filter(|t| t.starts_with('-')))
}
/// The detail of a flag: its aliases, then its type.
fn join_flag_detail(aliases: &[String], kind: Option<&str>) -> Option<String> {
let parts: Vec<&str> = aliases
.iter()
.map(String::as_str)
.chain(kind)
.filter(|p| !p.is_empty())
.collect();
(!parts.is_empty()).then(|| parts.join(" "))
}
/// What the file does with its `new Command(...)`: the subcommands passed to
/// `.addCommand(...)`, and the commands that are a root program (parsed here, or parent of
/// subcommands declared here). A `new Command("x")` that is neither is declared here and
/// attached elsewhere (or nowhere).
#[derive(Default)]
pub(super) struct Added {
idents: HashSet<String>,
spans: Vec<Span>,
/// The variables at the foot of a `.parse()`, `.command(...)` or `.addCommand(...)` chain.
root_names: HashSet<String>,
/// The starts of the `new Command(...)` at the foot of such a chain.
root_spans: HashSet<u32>,
/// The variable each `new Command(...)` initialises (start of the expression → name).
declared: HashMap<u32, String>,
}
/// The methods that make a command a root program or a parent.
const ROOT_METHODS: &[&str] = &["parse", "parseAsync", "command", "addCommand"];
impl Added {
pub(super) fn read(program: &Program<'_>) -> Self {
let mut added = Self::default();
added.visit_program(program);
added
}
fn contains_span(&self, span: Span) -> bool {
self.spans
.iter()
.any(|s| s.start <= span.start && span.end <= s.end)
}
/// A `new Command(...)` (its span) that is neither added nor a root in this file.
fn is_detached(&self, span: Span) -> bool {
if self.contains_span(span) || self.root_spans.contains(&span.start) {
return false;
}
match self.declared.get(&span.start) {
Some(var) => !self.idents.contains(var) && !self.root_names.contains(var),
None => true,
}
}
}
/// The foot of a chain of method calls: `program` in `program.command("x").option(...)`.
fn chain_foot<'e, 'a>(expr: &'e Expression<'a>) -> &'e Expression<'a> {
let mut current = expr;
for _ in 0..MAX_DEPTH {
match as_call(current).and_then(receiver) {
Some(next) => current = next,
None => break,
}
}
current.get_inner_expression()
}
impl<'a> Visit<'a> for Added {
fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
if method(it).as_deref() == Some("addCommand")
&& let Some(arg) = it.arguments.first().and_then(|a| a.as_expression())
{
self.spans.push(arg.get_inner_expression().span());
if let Some(name) = ident(arg) {
self.idents.insert(name.to_string());
}
}
if method(it).is_some_and(|m| ROOT_METHODS.contains(&m.as_str()))
&& let Some(object) = receiver(it)
{
match chain_foot(object) {
Expression::NewExpression(new) => {
self.root_spans.insert(new.span.start);
}
foot => {
if let Some(name) = ident(foot) {
self.root_names.insert(name.to_string());
}
}
}
}
walk::walk_call_expression(self, it);
}
fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
if let (BindingPattern::BindingIdentifier(id), Some(init)) = (&it.id, &it.init)
&& let Expression::NewExpression(new) = chain_foot(init)
{
self.declared
.insert(new.span.start, id.name.as_str().to_string());
}
walk::walk_variable_declarator(self, it);
}
}
fn constructs(new: &NewExpression<'_>, class: &str) -> bool {
last_name(&new.callee).as_deref() == Some(class)
}
const RECEIVED: &str = "the parser object comes from a parameter or another module, so the command its declarations belong to is decided elsewhere";
const UNDECLARED: &str =
"the parser accepts arguments it does not declare, so they are read by hand";
/// The commander and yargs methods that return the parser object (itself, or the subcommand
/// for `.command`): a chain that ends with one of them is still the parser.
const BUILDERS: &[&str] = &[
// commander
"command",
"addCommand",
"option",
"requiredOption",
"addOption",
"argument",
"arguments",
"addArgument",
"description",
"summary",
"usage",
"name",
"alias",
"aliases",
"version",
"action",
"hook",
"helpOption",
"helpCommand",
"addHelpCommand",
"addHelpText",
"showHelpAfterError",
"showSuggestionAfterError",
"allowUnknownOption",
"allowExcessArguments",
"passThroughOptions",
"enablePositionalOptions",
"combineFlagAndOptionalValue",
"configureOutput",
"configureHelp",
"exitOverride",
"storeOptionsAsProperties",
"copyInheritedSettings",
"executableDir",
// yargs
"options",
"positional",
"boolean",
"string",
"number",
"array",
"count",
"demandOption",
"demandCommand",
"epilog",
"epilogue",
"scriptName",
"middleware",
"check",
"commandDir",
"parserConfiguration",
"wrap",
"recommendCommands",
"completion",
"fail",
"locale",
"showHelpOnFail",
"default",
"describe",
"choices",
"coerce",
"conflicts",
"implies",
"group",
"hide",
"nargs",
"normalize",
"requiresArg",
"global",
"require",
"required",
"config",
"pkgConf",
"exitProcess",
"help",
"strict",
"strictOptions",
"strictCommands",
"env",
"example",
"deprecateOption",
"skipValidation",
"defaults",
"demand",
];
/// The methods that declare something on a parser.
const DECLARING: &[&str] = &[
"command",
"addCommand",
"option",
"requiredOption",
"addOption",
"argument",
"arguments",
"addArgument",
"positional",
"options",
"boolean",
"string",
"number",
"array",
"count",
"demandOption",
"commandDir",
];
/// Where the object at the foot of a parser call chain comes from.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Root {
/// A parser created here (`new Command()`, `yargs()`, a variable that holds one, the
/// parameter of a yargs options builder read here).
Known,
/// A parameter, an import from a module of the project, `this`, a variable of unknown
/// origin: the parser comes from elsewhere.
Received,
/// Something else (an unbound global name, an object of another library).
Other,
}
/// The foot of a chain of calls and accesses: `this` in `this.program.command("x")`.
pub(super) fn root_expr<'e, 'a>(expr: &'e Expression<'a>) -> &'e Expression<'a> {
let mut current = expr.get_inner_expression();
for _ in 0..MAX_DEPTH {
let next = match as_call(current) {
Some(call) => receiver(call),
None => as_member(current).map(MemberExpression::object),
};
match next {
Some(next) => current = next.get_inner_expression(),
None => break,
}
}
current
}
/// A call that, without a parser import, unambiguously has the form of a commander
/// declaration: `.command("x")` (not `.command("x", callback)`, which is a bot's),
/// `.option("-x")`, `.argument("<x>")`, `.addCommand(...)`.
fn strong_call(call: &CallExpression<'_>) -> bool {
let first = call.arguments.first().and_then(arg_text);
match method(call).as_deref() {
Some("command") => {
first.is_some()
&& call
.arguments
.get(1)
.and_then(|a| a.as_expression())
.is_none_or(|e| !is_function(e))
}
Some("option" | "requiredOption") => first.is_some_and(|f| f.starts_with('-')),
Some("argument") => first.is_some_and(|f| f.starts_with(['<', '['])),
Some("addCommand") => true,
_ => false,
}
}
/// Does a call of the chain (itself or one of those it starts from) have the form of a
/// declaration?
fn strong_chain(call: &CallExpression<'_>) -> bool {
let mut current = Some(call);
for _ in 0..MAX_DEPTH {
let Some(call) = current else { return false };
if strong_call(call) {
return true;
}
current = receiver(call).and_then(as_call);
}
false
}
/// commander's `.command("x", "description")`: an executable subcommand (another program), and
/// the call returns the parent, not the subcommand.
fn is_executable(call: &CallExpression<'_>) -> bool {
call.arguments
.get(1)
.and_then(|a| a.as_expression())
.is_some_and(|e| object_of(e).is_none() && !is_function(e))
}
/// The literal boolean value of property `name`; `None` if absent or computed.
fn bool_prop(object: &ObjectExpression<'_>, name: &str) -> Option<bool> {
match prop(object, name)?.get_inner_expression() {
Expression::BooleanLiteral(b) => Some(b.value),
_ => None,
}
}
/// `strict` of a `parseArgs` configuration (true by default); `None` if it is not known.
fn strictness(config: &ObjectExpression<'_>) -> Option<bool> {
match prop(config, "strict") {
Some(_) => bool_prop(config, "strict"),
None if config.properties.iter().any(|p| p.is_spread()) => None,
None => Some(true),
}
}
/// The first argument is the literal `false`.
pub(super) fn literal_false(call: &CallExpression<'_>) -> bool {
call.arguments
.first()
.and_then(|a| a.as_expression())
.is_some_and(
|e| matches!(e.get_inner_expression(), Expression::BooleanLiteral(b) if !b.value),
)
}
impl Collector {
pub(super) fn inspect_call(&mut self, it: &CallExpression<'_>) {
self.cli_call(it);
self.route_call(it);
self.server_call(it);
}
/// `require("yargs")(args)` or `require("commander").program.option(...)`: the parser is
/// used without having a local name.
pub(super) fn require_use(&mut self, it: &CallExpression<'_>) {
self.require_chain_use(&it.callee, it.span);
}
/// The same for an access without a call: `require("config").port`.
pub(super) fn require_chain_use(&mut self, start: &Expression<'_>, span: Span) {
let mut current = start;
for _ in 0..MAX_DEPTH {
let inner = current.get_inner_expression();
if let Some(call) = as_call(inner) {
if let Some(lit) = call.common_js_require() {
let package = super::imports::package_of(&lit.value.display().to_string());
let line = self.lines.of(span);
self.library_used(&package, line);
return;
}
current = &call.callee;
} else if let Some(member) = as_member(inner) {
current = member.object();
} else {
return;
}
}
}
pub(super) fn inspect_new(&mut self, it: &NewExpression<'_>) {
self.router_options_new(it);
self.detached_command(it);
}
/// A `new Command("sub")` neither added nor a root here: its flags carry the scope `sub`,
/// but the command itself (and its parent) is decided elsewhere.
fn detached_command(&mut self, it: &NewExpression<'_>) {
if !self.libs.commander || !constructs(it, "Command") || !self.added.is_detached(it.span) {
return;
}
let Some(name) = it
.arguments
.first()
.and_then(arg_text)
.and_then(|s| split_spec(&s))
.map(|(n, _)| n)
else {
return;
};
let reason = format!(
"command {name} is declared here but attached elsewhere or nowhere, so its parent command is unknown"
);
let line = self.lines.of(it.span);
self.unresolved_cli(line, &reason);
}
// --- the parser object as a value ---
/// Does the expression return the commander or yargs parser object (not its result)?
pub(super) fn parser_value(&self, expr: &Expression<'_>, depth: usize) -> bool {
if depth > MAX_DEPTH {
return false;
}
let inner = expr.get_inner_expression();
if let Some(name) = ident(inner) {
return self.parser_ident(name);
}
if let Expression::NewExpression(new) = inner {
return self.parser_new(new);
}
if let Some(call) = as_call(inner) {
return self.parser_call(call, depth);
}
as_member(inner).is_some_and(|m| {
member_name(m).as_deref() == Some("program") && self.is_commander_module(m.object())
})
}
/// A variable that holds the parser, or the `program` imported from commander.
pub(super) fn parser_ident(&self, name: &str) -> bool {
if self.bindings.is_ambiguous(name) {
return false;
}
self.parser_values.contains(name)
|| self.imports.local(name).is_some_and(|(package, imported)| {
COMMANDER.contains(&package) && imported == Some("program")
})
}
/// `new Command(...)` in a file that imports commander.
pub(super) fn parser_new(&self, new: &NewExpression<'_>) -> bool {
self.libs.commander && constructs(new, "Command")
}
/// `createCommand(...)`, `yargs(...)`, or a method that returns the parser, called on it.
pub(super) fn parser_call(&self, call: &CallExpression<'_>, depth: usize) -> bool {
match method(call) {
Some(name) => {
BUILDERS.contains(&name.as_str())
&& receiver(call).is_some_and(|r| self.parser_value(r, depth + 1))
}
None => self.parser_factory(call),
}
}
fn parser_factory(&self, call: &CallExpression<'_>) -> bool {
if let Some(name) = ident(&call.callee) {
return match self.imports.local(name) {
Some((package, imported)) if COMMANDER.contains(&package) => {
imported == Some("createCommand")
}
Some(("yargs", None)) => true,
_ => false,
};
}
as_call(&call.callee)
.and_then(|c| c.common_js_require())
.is_some_and(|s| super::imports::package_of(&s.value.display().to_string()) == "yargs")
}
/// The commander module itself (`import * as c`, `require("commander")`).
fn is_commander_module(&self, expr: &Expression<'_>) -> bool {
if let Some(name) = ident(expr) {
return matches!(self.imports.local(name), Some((p, None)) if COMMANDER.contains(&p));
}
as_call(expr)
.and_then(|c| c.common_js_require())
.is_some_and(|s| {
let package = super::imports::package_of(&s.value.display().to_string());
COMMANDER.contains(&package.as_str())
})
}
/// `p = new Command()`: the variable now holds the parser.
pub(super) fn track_parser_assignment(&mut self, it: &AssignmentExpression<'_>) {
if let (AssignmentOperator::Assign, AssignmentTarget::AssignmentTargetIdentifier(id)) =
(it.operator, &it.left)
&& self.parser_value(&it.right, 0)
{
self.parser_values.insert(id.name.as_str().to_string());
}
}
/// commander's `program.args` (and `rawArgs`): the undeclared arguments, read by hand.
pub(super) fn parser_args_read(&mut self, object: &Expression<'_>, property: &str, span: Span) {
if !self.libs.commander || !matches!(property, "args" | "rawArgs") {
return;
}
let parser = self.parser_value(object, 0)
|| ident(object).is_some_and(|n| self.commands.contains_key(n));
if parser {
let reason =
format!("arguments the parser does not declare are read from .{property} by hand");
let line = self.lines.of(span);
self.unresolved_cli(line, &reason);
}
}
pub(super) fn yargs_active(&self) -> bool {
self.libs.yargs && !self.libs.commander
}
/// The file imports no parser: only a chain that comes from elsewhere, with the
/// unambiguous form, is read (as commander).
fn parser_free(&self) -> bool {
!self.libs.commander && !self.libs.yargs
}
/// Does `.command("x")` open the scope `x` in a chain? Yes for commander and for a chain
/// read without a parser import; yargs declares its scopes through an options builder.
fn commander_scoping(&self) -> bool {
self.libs.commander || !self.libs.yargs
}
/// The origin of the object at the foot of the chain `expr`.
pub(super) fn chain_root(&self, expr: &Expression<'_>) -> Root {
if self.parser_root(expr, 0) {
return Root::Known;
}
match root_expr(expr) {
Expression::ThisExpression(_) => Root::Received,
Expression::Identifier(id) => {
let name = id.name.as_str();
if self.commands.contains_key(name) || self.parser_values.contains(name) {
return Root::Known;
}
let param = self.bindings.is_param(name);
// The parameter of a yargs options builder read here is the parser from here.
if param && !self.builder_scopes.is_empty() {
return Root::Known;
}
let unknown_local =
matches!(self.origins.get(name), Some(super::routes::Origin::Unknown));
if param || self.imports.is_relative(name) || unknown_local {
Root::Received
} else {
Root::Other
}
}
_ => Root::Other,
}
}
/// Without a parser import, is this call read as a commander declaration?
fn received_here(&self, it: &CallExpression<'_>) -> bool {
if !self.parser_free() {
return false;
}
match receiver(it).map_or(Root::Other, |r| self.chain_root(r)) {
Root::Known => true,
Root::Received => strong_chain(it),
Root::Other => false,
}
}
/// One site per line: what is declared here is declared on a parser that comes from
/// elsewhere.
fn received_site(&mut self, it: &CallExpression<'_>) {
let line = self.lines.of(method_span(it));
if self.received_lines.insert(line) {
self.unresolved_cli(line, RECEIVED);
}
}
fn cli_call(&mut self, it: &CallExpression<'_>) {
let Some(name) = method(it) else {
if self.is_parse_args(it, None) {
self.parse_args_call(it);
}
return;
};
let received_here = self.received_here(it);
let root = receiver(it).map_or(Root::Other, |r| self.chain_root(r));
let declaring = DECLARING.contains(&name.as_str());
if root == Root::Received && (received_here || (!self.parser_free() && declaring)) {
self.received_site(it);
}
let (commander, yargs) = (self.libs.commander || received_here, self.yargs_active());
match name.as_str() {
"allowUnknownOption" | "allowExcessArguments" | "passThroughOptions"
if commander && !literal_false(it) =>
{
self.unresolved(Family::Flag, method_span(it), UNDECLARED);
}
"parseOptions" if commander => {
let line = self.lines.of(method_span(it));
self.unresolved_cli(
line,
"arguments are split by parseOptions and read by hand",
);
}
"strict" | "strictOptions" if yargs && literal_false(it) => {
self.unresolved(Family::Flag, method_span(it), UNDECLARED);
}
"strictCommands" if yargs && literal_false(it) => self.unresolved(
Family::Command,
method_span(it),
"the parser accepts commands it does not declare, so they are read by hand",
),
"parserConfiguration" if yargs => self.unresolved(
Family::Flag,
method_span(it),
"the parser configuration changes how arguments are read, so the declared flags may not be all",
),
_ => {}
}
match name.as_str() {
"command" if commander => self.commander_command(it),
"addCommand" if commander => self.commander_add_command(it),
"alias" | "aliases" if commander => self.commander_alias(it),
"helpCommand" | "addHelpCommand" if commander => self.commander_help_command(it),
"helpOption" if commander => self.commander_help_option(it),
// `program.on("command:*", f)`: unknown commands are read by the listener.
"on" if commander
&& it.arguments.first().and_then(arg_text).as_deref() == Some("command:*") =>
{
self.unresolved(
Family::Command,
method_span(it),
"commands the parser does not declare are handled by a listener, so they are read by hand",
);
}
"option" | "requiredOption" if commander => self.commander_option(it),
"addOption" if commander => self.commander_add_option(it),
"argument" if commander => self.commander_argument(it, false),
"arguments" if commander => self.commander_argument(it, true),
"addArgument" if commander => self.commander_add_argument(it),
"positional" if yargs => self.yargs_positional(it),
"version" if commander => self.commander_version(it),
"env" if commander => self.commander_env(it),
"env" if yargs => self.unresolved(
Family::Env,
method_span(it),
"options are read from environment variables with a prefix, so their names cannot be listed",
),
"option" | "options" if yargs => self.yargs_option(it),
key if yargs && KEY_METHODS.contains(&key) => self.yargs_keys(it, key),
// The loaded modules declare their commands and flags (`builder`).
"commandDir" if yargs => {
let line = self.lines.of(method_span(it));
self.unresolved_cli(
line,
"commands are loaded from a directory, so their names and flags cannot be listed",
);
}
_ if self.is_parse_args(it, Some(&name)) => self.parse_args_call(it),
_ => {}
}
}
/// Tracks a variable that holds a command or an option that was built.
pub(super) fn track_declarator(&mut self, it: &VariableDeclarator<'_>) {
let (BindingPattern::BindingIdentifier(id), Some(init)) = (&it.id, &it.init) else {
return;
};
self.track_origin(it);
let name = id.name.as_str().to_string();
if self.parser_root(init, 0) {
self.parser_vars.insert(name.clone());
}
if self.parser_value(init, 0) {
self.parser_values.insert(name.clone());
}
let received = as_call(init).is_some_and(|c| self.received_here(c));
if !self.libs.commander && !received {
return;
}
let mut scope = self.chain_scope(init);
if matches!(scope, Scope::Global) && self.added.idents.contains(&name) {
scope = self.new_command_scope(init).unwrap_or(Scope::Global);
}
match scope {
Scope::Global => {
self.commands.remove(&name);
}
scope => {
self.commands.insert(name.clone(), scope);
}
}
if let Some(spec) = self.option_spec(init) {
self.options.insert(name, spec);
}
}
/// The command of a `new Command("x")` at the foot of a chain (variable passed to
/// `addCommand`).
fn new_command_scope(&self, expr: &Expression<'_>) -> Option<Scope> {
let mut current = expr;
for _ in 0..MAX_DEPTH {
if let Expression::NewExpression(new) = current.get_inner_expression() {
return constructs(new, "Command").then(|| {
match new.arguments.first().and_then(arg_text) {
Some(spec) => {
split_spec(&spec).map_or(Scope::Unknown, |(n, _)| Scope::Command(n))
}
None => Scope::Unknown,
}
});
}
current = receiver(as_call(current)?)?;
}
Some(Scope::Unknown)
}
/// The scope of what an expression stands for: climbs the call chain up to the command
/// that was created (`.command("x")`, `new Command("x")`) or to the variable that holds it.
fn chain_scope(&self, expr: &Expression<'_>) -> Scope {
self.chain_scope_at(expr, 0)
}
/// Like `chain_scope`, with the recursion depth: beyond the bound, the scope is unknown
/// (so the flag is not enumerated).
fn chain_scope_at(&self, expr: &Expression<'_>, depth: usize) -> Scope {
if depth > MAX_DEPTH {
return Scope::Unknown;
}
let named = |spec: Option<String>| match spec.as_deref().and_then(split_spec) {
Some((name, _)) => Scope::Command(name),
None => Scope::Unknown,
};
let mut current = expr;
for _ in 0..MAX_DEPTH {
if let Some(name) = ident(current) {
// A name bound several times may stand for another command depending on where.
if self.commander_scoping() && self.bindings.is_ambiguous(name) {
return Scope::Unknown;
}
return self.commands.get(name).cloned().unwrap_or(Scope::Global);
}
if let Expression::NewExpression(new) = current.get_inner_expression() {
// Added by `addCommand` or detached (neither added nor a root here), the command
// carries its name; otherwise it is the root program, whose name is not a
// command.
return match new.arguments.first() {
Some(arg)
if constructs(new, "Command")
&& (self.added.contains_span(new.span)
|| self.added.is_detached(new.span)) =>
{
named(arg_text(arg))
}
_ => Scope::Global,
};
}
let Some(call) = as_call(current) else {
return Scope::Global;
};
let first = call.arguments.first();
if self.commander_scoping() && method(call).as_deref() == Some("command") {
// `.command("x", "description")` returns the parent.
if is_executable(call) {
match receiver(call) {
Some(next) => {
current = next;
continue;
}
None => return Scope::Global,
}
}
return self.command_scope_at(call, depth + 1);
}
if ident(&call.callee) == Some("createCommand") {
return first.map_or(Scope::Global, |a| named(arg_text(a)));
}
match receiver(call) {
Some(next) => current = next,
None => return Scope::Global,
}
}
Scope::Unknown
}
/// The command a `.command("x")` call creates: its full path, parents included
/// (`remote add` for `program.command("remote").command("add")`).
fn command_scope(&self, call: &CallExpression<'_>) -> Scope {
self.command_scope_at(call, 0)
}
fn command_scope_at(&self, call: &CallExpression<'_>, depth: usize) -> Scope {
let spec = call.arguments.first().and_then(arg_text);
let Some((name, _)) = spec.as_deref().and_then(split_spec) else {
return Scope::Unknown;
};
match receiver(call).map(|r| self.chain_scope_at(r, depth + 1)) {
Some(Scope::Command(parent)) => Scope::Command(format!("{parent} {name}")),
Some(Scope::Unknown) => Scope::Unknown,
_ => Scope::Command(name),
}
}
/// The scope of a flag, or `None` (and an unenumerated site) when it is unknown.
fn resolve_scope(&mut self, scope: Scope, span: Span) -> Option<Option<String>> {
match scope {
Scope::Global => Some(self.builder_scopes.last().cloned().flatten()),
Scope::Command(name) => Some(Some(name)),
Scope::Unknown => {
self.unresolved(
Family::Flag,
span,
"flag belongs to a command whose name is not a string literal",
);
None
}
}
}
fn flag_scope(&mut self, it: &CallExpression<'_>) -> Option<Option<String>> {
let scope = receiver(it).map_or(Scope::Global, |r| self.chain_scope(r));
self.resolve_scope(scope, method_span(it))
}
fn add_flag(
&mut self,
name: String,
span: Span,
scope: Option<String>,
detail: Option<String>,
library: &str,
) {
self.add(Family::Flag, name, span, scope, detail);
self.recognise(Family::Flag, library);
}
/// A positional argument is an element of the flag family, named as declared.
fn add_positional(&mut self, name: String, span: Span, scope: Option<String>, library: &str) {
let known = self.out.found.iter().any(|f| {
f.family == Family::Flag
&& f.scope == scope
&& f.detail.as_deref() == Some("positional")
&& bare_name(&f.name) == bare_name(&name)
});
if !known {
// A key named earlier by `.default("x")` in the same scope was this positional, not a
// flag.
if library == "yargs" {
let flag = dashed(bare_name(&name));
self.out.found.retain(|f| {
!(f.family == Family::Flag
&& f.scope == scope
&& f.detail.as_deref() != Some("positional")
&& f.name == flag)
});
}
self.add_flag(name, span, scope, Some("positional".to_string()), library);
}
}
/// `.argument("<file>")` and `.arguments("<a> [b]")`.
fn commander_argument(&mut self, it: &CallExpression<'_>, plural: bool) {
let Some(arg) = it.arguments.first() else {
return;
};
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
match arg_text(arg) {
Some(spec) if plural => {
for token in positional_tokens(&spec) {
self.add_positional(token, span, scope.clone(), "commander");
}
}
Some(spec) if !spec.trim().is_empty() => {
self.add_positional(spec.trim().to_string(), span, scope, "commander");
}
_ => self.unresolved(Family::Flag, span, NOT_LITERAL_POSITIONAL),
}
}
/// `.addArgument(new Argument("<file>"))`.
fn commander_add_argument(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
let spec = it
.arguments
.first()
.and_then(|a| a.as_expression())
.and_then(|e| match e.get_inner_expression() {
Expression::NewExpression(new) if constructs(new, "Argument") => {
new.arguments.first().and_then(arg_text)
}
_ => None,
});
match spec {
Some(spec) if !spec.trim().is_empty() => {
self.add_positional(spec.trim().to_string(), span, scope, "commander");
}
_ => self.unresolved(Family::Flag, span, NOT_LITERAL_POSITIONAL),
}
}
/// yargs's `.positional("name", { ... })`: named `<name>` unless the command already has it.
fn yargs_positional(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
let Some(first) = it.arguments.first() else {
return;
};
let Some(scope) = self.flag_scope(it) else {
return;
};
match arg_text(first) {
Some(key) => self.add_positional(format!("<{key}>"), span, scope, "yargs"),
None => self.unresolved(Family::Flag, span, NOT_LITERAL_POSITIONAL),
}
}
fn has_command(&self, name: &str) -> bool {
self.out
.found
.iter()
.any(|f| f.family == Family::Command && f.name == name)
}
// --- commander ---
fn commander_command(&mut self, it: &CallExpression<'_>) {
let Some(arg) = it.arguments.first() else {
return;
};
let span = method_span(it);
match arg_text(arg) {
Some(spec) => match (split_spec(&spec), self.command_scope(it)) {
(Some((_, rest)), Scope::Command(path)) => {
let tokens = rest.as_deref().map(positional_tokens).unwrap_or_default();
if is_executable(it) {
let reason = format!(
"flags of executable subcommand {path} are read by another executable"
);
self.unresolved(Family::Flag, span, &reason);
}
self.add(Family::Command, path.clone(), span, None, rest);
self.recognise(Family::Command, "commander");
for token in tokens {
self.add_positional(token, span, Some(path.clone()), "commander");
}
}
(None, _) => self.unresolved(Family::Command, span, "command name is empty"),
_ => self.unresolved(
Family::Command,
span,
"command is nested under a command whose name is not a string literal",
),
},
None => self.unresolved(Family::Command, span, NOT_LITERAL_COMMAND),
}
}
/// `parent.addCommand(sub)`: the command is named `parent sub` (`sub` under the program),
/// like the scope of the flags set on `sub`. An unknown name or parent is not guessed.
fn commander_add_command(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
let sub = it.arguments.first().and_then(|a| a.as_expression());
let sub_scope = sub.map(|e| self.chain_scope(e));
let parent = receiver(it).map_or(Scope::Global, |r| self.chain_scope(r));
let path = match (&sub_scope, &parent) {
(Some(Scope::Command(leaf)), Scope::Global) => Some((leaf.clone(), leaf.clone())),
(Some(Scope::Command(leaf)), Scope::Command(p)) => {
Some((leaf.clone(), format!("{p} {leaf}")))
}
_ => None,
};
let Some((leaf, path)) = path else {
self.unresolved(
Family::Command,
span,
"command is added from a value or under a parent whose name is unknown",
);
return;
};
if self.has_command(&leaf) {
return;
}
self.rename_scope(&leaf, &path);
if let Some(var) = sub.and_then(ident) {
self.commands
.insert(var.to_string(), Scope::Command(path.clone()));
}
self.add(Family::Command, path, span, None, None);
self.recognise(Family::Command, "commander");
}
/// Gives their full path to the commands and flags already seen under the name `old`.
fn rename_scope(&mut self, old: &str, new: &str) {
let renamed = |name: &str| {
if name == old {
Some(new.to_string())
} else {
name.strip_prefix(old)
.filter(|rest| rest.starts_with(' '))
.map(|rest| format!("{new}{rest}"))
}
};
for found in &mut self.out.found {
if let Some(scope) = found.scope.as_deref().and_then(renamed) {
found.scope = Some(scope);
}
if found.family == Family::Command
&& let Some(name) = renamed(&found.name)
{
found.name = name;
}
}
}
/// `.alias("x")` and `.aliases(["x", "y"])` are added to the detail of the command the chain
/// comes from. A computed alias is a command name that is not seen; without an argument,
/// the call reads the aliases.
fn commander_alias(&mut self, it: &CallExpression<'_>) {
let Some(first) = it.arguments.first() else {
return;
};
let span = method_span(it);
let Some(aliases) = first.as_expression().and_then(texts) else {
self.unresolved(
Family::Command,
span,
"command alias is not a string literal",
);
return;
};
let scope = receiver(it).map(|r| self.chain_scope(r));
let name = match scope {
Some(Scope::Command(name)) => name,
// An alias of the program itself is not used on the command line.
Some(Scope::Global) | None => return,
Some(Scope::Unknown) => {
self.unresolved(
Family::Command,
span,
"command alias belongs to a command whose name is not a string literal",
);
return;
}
};
// `new Command("x").alias("y")` is read before the `addCommand` that declares `x`: the
// aliases are attached at the end of the file (`attach_aliases`).
let line = self.lines.of(span);
self.pending_aliases.push((name, aliases, line));
}
/// Adds the aliases that were read to the detail of their command, once all commands are
/// seen (and renamed by `addCommand`). An alias of a command declared elsewhere (a
/// `new Command("x")` attached in another file) is a name that cannot be attached.
pub(super) fn attach_aliases(&mut self) {
for (name, aliases, line) in std::mem::take(&mut self.pending_aliases) {
let suffix = format!(" {name}");
let found = self.out.found.iter_mut().rev().find(|f| {
f.family == Family::Command && (f.name == name || f.name.ends_with(&suffix))
});
let Some(found) = found else {
self.unresolved_at(
Family::Command,
line,
"command alias belongs to a command declared elsewhere",
);
continue;
};
for alias in aliases {
let alias = format!("alias {alias}");
found.detail = Some(match found.detail.take() {
Some(d) => format!("{d}; {alias}"),
None => alias,
});
}
}
}
/// `.helpCommand("assist [command]")` (and `addHelpCommand`): the renamed help command.
/// `helpCommand(true | false)` keeps or removes the implicit `help` command.
fn commander_help_command(&mut self, it: &CallExpression<'_>) {
let Some(first) = it.arguments.first().and_then(|a| a.as_expression()) else {
return;
};
if matches!(first.get_inner_expression(), Expression::BooleanLiteral(_)) {
return;
}
let span = method_span(it);
// `addHelpCommand(new Command("assist"))` (commander 12).
let spec = match first.get_inner_expression() {
Expression::NewExpression(new) if constructs(new, "Command") => {
new.arguments.first().and_then(arg_text)
}
other => text(other),
};
let Some((name, _)) = spec.as_deref().and_then(split_spec) else {
self.unresolved(Family::Command, span, NOT_LITERAL_COMMAND);
return;
};
let path = match receiver(it).map_or(Scope::Global, |r| self.chain_scope(r)) {
Scope::Global => name,
Scope::Command(parent) => format!("{parent} {name}"),
Scope::Unknown => {
self.unresolved(
Family::Command,
span,
"command is nested under a command whose name is not a string literal",
);
return;
}
};
self.add(
Family::Command,
path,
span,
None,
Some("help command".to_string()),
);
self.recognise(Family::Command, "commander");
}
/// `.helpOption("-e, --HELP")`: the renamed help flag; `helpOption(false)` removes it.
fn commander_help_option(&mut self, it: &CallExpression<'_>) {
let Some(first) = it.arguments.first() else {
return;
};
if first
.as_expression()
.is_some_and(|e| matches!(e.get_inner_expression(), Expression::BooleanLiteral(_)))
{
return;
}
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
match arg_text(first) {
Some(spec) => self.commander_flag(&spec, span, scope),
None => self.unresolved(Family::Flag, span, NOT_LITERAL_FLAG),
}
}
fn commander_option(&mut self, it: &CallExpression<'_>) {
let Some(arg) = it.arguments.first() else {
return;
};
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
match arg_text(arg) {
Some(spec) => self.commander_flag(&spec, span, scope),
None => self.unresolved(Family::Flag, span, NOT_LITERAL_FLAG),
}
}
fn commander_flag(&mut self, spec: &str, span: Span, scope: Option<String>) {
match parse_flag_spec(spec) {
Some((name, detail)) => self.add_flag(name, span, scope, detail, "commander"),
None => self.unresolved(Family::Flag, span, "option flags contain no flag name"),
}
}
/// `.addOption(new Option("-p, --port <n>").default(1))`, or a variable that holds it.
fn commander_add_option(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
let spec = it
.arguments
.first()
.and_then(|a| a.as_expression())
.and_then(|e| self.option_spec(e));
match spec {
Some(spec) => self.commander_flag(&spec, span, scope),
None => self.unresolved(
Family::Flag,
span,
"option is not built inline with `new Option(\"...\")`",
),
}
}
/// The flags text of a `new Option("...")`, through chained calls.
fn option_spec(&self, expr: &Expression<'_>) -> Option<String> {
let mut current = expr;
for _ in 0..MAX_DEPTH {
if let Some(name) = ident(current) {
if self.bindings.is_ambiguous(name) {
return None;
}
return self.options.get(name).cloned();
}
if let Expression::NewExpression(new) = current.get_inner_expression() {
return if constructs(new, "Option") {
new.arguments.first().and_then(arg_text)
} else {
None
};
}
current = receiver(as_call(current)?)?;
}
None
}
/// `.version(v, "-v, --version", "description")` declares a flag; by default
/// `-V, --version`. The version itself may be computed (`pkg.version`).
fn commander_version(&mut self, it: &CallExpression<'_>) {
// `.version()` without an argument reads the version, it declares nothing.
if it.arguments.is_empty() {
return;
}
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
match it.arguments.get(1).map(arg_text) {
None => self.commander_flag("-V, --version", span, scope),
Some(Some(spec)) => self.commander_flag(&spec, span, scope),
Some(None) => self.unresolved(Family::Flag, span, NOT_LITERAL_FLAG),
}
}
/// `new Option("-p, --port").env("PORT")` reads the variable `PORT`.
fn commander_env(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
match it.arguments.first().and_then(arg_text) {
Some(name) => {
self.add(Family::Env, name, span, None, None);
}
None => self.unresolved(
Family::Env,
span,
"environment variable name is not a string literal",
),
}
}
// --- yargs ---
/// yargs's `.command(...)`, whose options builder gives the flags of the command: the
/// arguments are read here to open the scope while the builder is visited.
pub(super) fn yargs_command<'a>(&mut self, it: &CallExpression<'a>) -> bool {
if !self.yargs_active() || method(it).as_deref() != Some("command") {
return false;
}
self.visit_expression(&it.callee);
// `Some(scope)`: the command is read, and its flags take this scope (`None` for the
// default command at the first level).
let scope = self.yargs_register(it);
for (index, arg) in it.arguments.iter().enumerate() {
let scoped = scope.is_some() && is_builder(it, index);
if let (true, Some(scope)) = (scoped, &scope) {
self.builder_scopes.push(scope.clone());
}
self.visit_argument(arg);
if scoped {
self.builder_scopes.pop();
}
}
true
}
/// Registers the command; returns the scope of its flags: its name, or for the default
/// command (`$0`, `*`) the scope where it is declared (`None` at the first level).
fn yargs_register(&mut self, it: &CallExpression<'_>) -> Option<Option<String>> {
let span = method_span(it);
let first = it.arguments.first().and_then(|a| a.as_expression())?;
let object = object_of(first);
let spec = object.map_or(Some(first), |o| prop(o, "command"));
let Some(specs) = spec.and_then(texts).filter(|s| !s.is_empty()) else {
let literal_like = matches!(
spec.map(Expression::get_inner_expression),
Some(Expression::TemplateLiteral(_) | Expression::BinaryExpression(_))
);
// A command module is the only argument (`.command(require("./serve"))`).
if object.is_some() || literal_like || it.arguments.len() > 1 {
self.unresolved(Family::Command, span, NOT_LITERAL_COMMAND);
} else {
// The module also holds the options builder: its flags are hidden.
let line = self.lines.of(span);
self.unresolved_cli(
line,
"command is defined by a module, so its name and flags are not visible here",
);
}
return None;
};
let parent = self.builder_scopes.last().cloned().flatten();
let mut aliases: Vec<String> = object
.and_then(|o| prop(o, "aliases"))
.and_then(texts)
.unwrap_or_default();
// `$0` and `*` stand for the default command (yargs docs, "Default Commands"), also
// among the aliases (`["serve", "$0"]`): it is not a named command.
let default =
specs.iter().any(|s| is_default_spec(s)) || aliases.iter().any(|a| is_default_spec(a));
aliases.retain(|a| !is_default_spec(a));
let Some(index) = specs
.iter()
.position(|s| split_spec(s).is_some() && !is_default_spec(s))
else {
let Some((_, positional)) = split_spec(&specs[0]) else {
self.unresolved(Family::Command, span, "command name is empty");
return None;
};
// Only the default command: its positionals and options are those of the level
// where it is declared.
self.recognise(Family::Command, "yargs");
for token in positional
.as_deref()
.map(positional_tokens)
.unwrap_or_default()
{
self.add_positional(token, span, parent.clone(), "yargs");
}
self.yargs_builder(it, object, parent.as_deref());
return Some(parent);
};
let Some((leaf, positional)) = split_spec(&specs[index]) else {
self.unresolved(Family::Command, span, "command name is empty");
return None;
};
let name = match &parent {
Some(parent) => format!("{parent} {leaf}"),
None => leaf,
};
aliases.splice(
0..0,
specs
.iter()
.enumerate()
.filter(|(i, s)| *i != index && !is_default_spec(s))
.filter_map(|(_, s)| split_spec(s).map(|(n, _)| n)),
);
let alias = (!aliases.is_empty()).then(|| format!("alias {}", aliases.join(", ")));
let tokens = positional
.as_deref()
.map(positional_tokens)
.unwrap_or_default();
let default_note = default.then(|| "default command".to_string());
let detail = join_detail(
positional
.into_iter()
.chain(alias)
.chain(default_note)
.collect(),
);
self.add(Family::Command, name.clone(), span, None, detail);
self.recognise(Family::Command, "yargs");
for token in tokens {
self.add_positional(token, span, Some(name.clone()), "yargs");
}
self.yargs_builder(it, object, Some(&name));
Some(Some(name))
}
/// The options builder of a command: a function (read during the visit), an object literal
/// (read here) or something else (not enumerable).
fn yargs_builder(
&mut self,
it: &CallExpression<'_>,
object: Option<&ObjectExpression<'_>>,
name: Option<&str>,
) {
let builder = match object {
Some(o) => prop(o, "builder"),
None => it.arguments.get(2).and_then(|a| a.as_expression()),
};
let Some(builder) = builder else { return };
if is_function(builder) || builder.get_inner_expression().is_null_or_undefined() {
return;
}
match object_of(builder) {
Some(options) => self.options_object(options, name.map(str::to_string), true),
None => self.unresolved(
Family::Flag,
method_span(it),
"command builder is not defined inline, so its options cannot be listed",
),
}
}
/// `.option("port", { alias: "p" })` and `.option({ port: {...} })`.
fn yargs_option(&mut self, it: &CallExpression<'_>) {
let span = method_span(it);
let Some(first) = it.arguments.first() else {
return;
};
let Some(scope) = self.flag_scope(it) else {
return;
};
if let Some(options) = arg_object(first) {
self.options_object(options, scope, true);
return;
}
match arg_text(first) {
Some(key) => {
let options = it.arguments.get(1).and_then(arg_object);
self.option_entry(&key, options, scope, span, true, "yargs");
}
None => self.unresolved(Family::Flag, span, NOT_LITERAL_NAME),
}
}
/// The yargs methods that make a key a parsed option without going through `.option()`:
/// `.boolean("x")`, `.default({ port: 80 })`, `.alias("p", "port")`, `.group(["a"], "G")`...
/// The key may be a string, an array of strings or the keys of an object.
fn yargs_keys(&mut self, it: &CallExpression<'_>, method_name: &str) {
// On the parser only: `.string("x")` of another object is not an option.
if receiver(it).is_none_or(|r| self.chain_root(r) != Root::Known) {
return;
}
let span = method_span(it);
let Some(scope) = self.flag_scope(it) else {
return;
};
let pairs = matches!(method_name, "implies" | "conflicts");
let Some(first) = it.arguments.first().and_then(|a| a.as_expression()) else {
// `.config()` without an argument declares `--config`.
if method_name == "config" {
self.yargs_flag("config", &[], None, scope, span);
}
return;
};
// `.demand(2)`: a number of commands, not a key.
if matches!(first.get_inner_expression(), Expression::NumericLiteral(_)) {
return;
}
if let Some(object) = object_of(first) {
// The object of `.config({...})` holds values, not options.
if method_name == "config" {
return;
}
for property in &object.properties {
let ObjectPropertyKind::ObjectProperty(p) = property else {
self.unresolved(Family::Flag, object.span, NOT_LITERAL_NAME);
continue;
};
let Some(key) = key_name(&p.key) else {
self.unresolved(Family::Flag, p.span, NOT_LITERAL_NAME);
continue;
};
let others = (method_name == "alias" || pairs).then(|| texts(&p.value));
if others.as_ref().is_some_and(Option::is_none) {
self.unresolved(Family::Flag, p.span, NOT_LITERAL_NAME);
}
let others = others.flatten().unwrap_or_default();
self.yargs_pair(method_name, &key, &others, scope.clone(), p.span);
}
return;
}
let Some(keys) = texts(first) else {
self.unresolved(Family::Flag, span, NOT_LITERAL_NAME);
return;
};
let second = it.arguments.get(1).and_then(|a| a.as_expression());
let others = if method_name == "alias" || pairs {
match second.map(|s| (s, texts(s))) {
Some((_, Some(others))) => others,
Some((s, None)) if !(pairs && is_function(s)) => {
self.unresolved(Family::Flag, span, NOT_LITERAL_NAME);
Vec::new()
}
_ => Vec::new(),
}
} else {
Vec::new()
};
for key in keys {
self.yargs_pair(method_name, &key, &others, scope.clone(), span);
}
}
/// `.alias(k, others)` joins the names; `.implies(k, others)` and `.conflicts` name two
/// distinct options; the other methods name `k` alone.
fn yargs_pair(
&mut self,
method_name: &str,
key: &str,
others: &[String],
scope: Option<String>,
span: Span,
) {
if method_name == "alias" {
self.yargs_flag(key, others, None, scope, span);
return;
}
self.yargs_flag(key, &[], None, scope.clone(), span);
for other in others {
// `implies("a", "no-b")` stands for the option `b`.
let other = other.strip_prefix("no-").unwrap_or(other);
self.yargs_flag(other, &[], None, scope.clone(), span);
}
}
/// A yargs option, merged with the one that already holds one of its names in the same
/// scope (`.option("port")` then `.default("port", 80)` or `.alias("p", "port")`).
fn yargs_flag(
&mut self,
key: &str,
aliases: &[String],
kind: Option<String>,
scope: Option<String>,
span: Span,
) {
// `.default("x", 1)` on the positional `x` of the command: it is the positional.
let positional = self.out.found.iter().any(|f| {
f.family == Family::Flag
&& f.scope == scope
&& f.detail.as_deref() == Some("positional")
&& bare_name(&f.name) == key
});
if positional {
return;
}
let name = dashed(key);
let mut names: Vec<String> = aliases.iter().map(|a| dashed(a)).collect();
names.retain(|a| *a != name);
let existing = self.out.found.iter_mut().find(|f| {
f.family == Family::Flag
&& f.scope == scope
&& f.detail.as_deref() != Some("positional")
&& flag_names(f).any(|n| n == name || names.contains(&n.to_string()))
});
let Some(existing) = existing else {
let detail = join_flag_detail(&names, kind.as_deref());
self.add_flag(name, span, scope, detail, "yargs");
return;
};
let detail = existing.detail.clone().unwrap_or_default();
let mut merged: Vec<String> = detail
.split(' ')
.filter(|t| t.starts_with('-'))
.map(str::to_string)
.collect();
let mut kinds: Vec<&str> = detail.split(' ').filter(|t| t.starts_with('(')).collect();
for n in std::iter::once(name).chain(names) {
if n != existing.name && !merged.contains(&n) {
merged.push(n);
}
}
if kinds.is_empty()
&& let Some(kind) = kind.as_deref()
{
kinds.push(kind);
}
let kind = (!kinds.is_empty()).then(|| kinds.join(" "));
existing.detail = join_flag_detail(&merged, kind.as_deref());
}
/// A flag described by a key and, possibly, an options object (`alias`, `type`).
fn option_entry(
&mut self,
key: &str,
options: Option<&ObjectExpression<'_>>,
scope: Option<String>,
span: Span,
short_style: bool,
library: &str,
) {
let name = if short_style {
dashed(key)
} else {
format!("--{key}")
};
let aliases = ["alias", "short"]
.iter()
.filter_map(|k| options.and_then(|o| prop(o, k)))
.filter_map(texts)
.flatten()
.map(|a| dashed(&a))
.collect::<Vec<_>>()
.join(" ");
let kind = options
.and_then(|o| prop(o, "type"))
.and_then(text)
.map(|t| format!("({t})"))
.unwrap_or_default();
if library == "yargs" {
let aliases: Vec<String> = aliases.split(' ').map(str::to_string).collect();
let aliases: Vec<String> = aliases.into_iter().filter(|a| !a.is_empty()).collect();
let kind = (!kind.is_empty()).then_some(kind);
// The alias names already have dashes: `dashed` leaves them as they are.
self.yargs_flag(key, &aliases, kind, scope, span);
return;
}
let detail = [aliases, kind]
.iter()
.filter(|p| !p.is_empty())
.cloned()
.collect::<Vec<_>>()
.join(" ");
self.add_flag(
name,
span,
scope,
(!detail.is_empty()).then_some(detail),
library,
);
}
/// The entries of an object `{ name: { alias, type }, ... }`.
fn options_object(
&mut self,
object: &ObjectExpression<'_>,
scope: Option<String>,
yargs: bool,
) {
let library = if yargs { "yargs" } else { "parseArgs" };
for property in &object.properties {
let ObjectPropertyKind::ObjectProperty(p) = property else {
self.unresolved(
Family::Flag,
object.span,
"options object contains a spread, so its flags cannot be listed",
);
continue;
};
match key_name(&p.key) {
Some(key) => {
let options = object_of(&p.value);
self.option_entry(&key, options, scope.clone(), p.span, yargs, library);
}
None => self.unresolved(Family::Flag, p.span, NOT_LITERAL_NAME),
}
}
}
// --- util.parseArgs ---
/// Is this `parseArgs` of `node:util` (imported under its name, or a member of the module)?
fn is_parse_args(&self, it: &CallExpression<'_>, member: Option<&str>) -> bool {
if !self.libs.util {
return false;
}
match member {
Some(name) => name == "parseArgs",
None => ident(&it.callee).is_some_and(|callee| {
callee == "parseArgs"
|| self
.imports
.locals(&["util"])
.any(|l| l.name == callee && l.imported.as_deref() == Some("parseArgs"))
}),
}
}
/// The positionals of `parseArgs`: without `allowPositionals` there is no command;
/// otherwise (or if it is not known) they are read by hand, so they are not enumerable.
fn parse_args_positionals(
&mut self,
it: &CallExpression<'_>,
config: Option<&ObjectExpression<'_>>,
) {
let allowed = match (it.arguments.first(), config) {
(None, _) => Some(false),
(Some(_), None) => None,
(Some(_), Some(config)) => match prop(config, "allowPositionals") {
Some(value) => match value.get_inner_expression() {
Expression::BooleanLiteral(flag) => Some(flag.value),
_ => None,
},
None if config.properties.iter().any(|p| p.is_spread()) => None,
// Without `strict`, positionals are allowed by default.
None => match strictness(config) {
Some(true) => Some(false),
Some(false) => Some(true),
None => None,
},
},
};
if allowed == Some(false) {
self.recognise(Family::Command, "parseArgs");
} else {
self.unresolved(
Family::Command,
it.span,
"positionals of parseArgs are read by hand",
);
}
}
fn parse_args_call(&mut self, it: &CallExpression<'_>) {
self.recognise(Family::Flag, "parseArgs");
let span = it.span;
let config = it.arguments.first().and_then(arg_object);
self.parse_args_positionals(it, config);
let Some(first) = it.arguments.first() else {
return;
};
let Some(config) = arg_object(first) else {
self.unresolved(
Family::Flag,
span,
"parseArgs configuration is not an object literal",
);
return;
};
if config.properties.iter().any(|p| p.is_spread()) {
self.unresolved(
Family::Flag,
span,
"parseArgs configuration contains a spread",
);
}
// `strict: false` accepts undeclared options; `tokens` leaves them to be read by hand.
if strictness(config) != Some(true) {
self.unresolved(Family::Flag, span, UNDECLARED);
}
if prop(config, "tokens").is_some() && bool_prop(config, "tokens") != Some(false) {
self.unresolved(Family::Flag, span, "parseArgs tokens are read by hand");
}
match prop(config, "options").map(|e| (e, object_of(e))) {
None => {}
Some((_, Some(options))) => self.options_object(options, None, false),
Some((_, None)) => {
self.unresolved(
Family::Flag,
span,
"parseArgs options is not an object literal",
);
}
}
}
// --- arguments read by hand, parsers without a detector ---
/// `process`, `Bun` or `Deno`: the global object whose arguments are read.
fn argv_owner(&self, object: &Expression<'_>) -> Option<&'static str> {
if self.is_process(object) {
return Some("process");
}
match ident(object) {
Some("Bun") => Some("Bun"),
Some("Deno") => Some("Deno"),
_ => None,
}
}
/// Where `expr` starts, if it reads the arguments (`process.argv`, `Bun.argv`,
/// `Deno.args`, or a name imported from `process` as `argv`).
fn argv_start(&self, expr: &Expression<'_>) -> Option<u32> {
if let Some(name) = ident(expr) {
return self
.argv_names
.contains(name)
.then(|| expr.get_inner_expression().span().start);
}
let member = as_member(expr)?;
let owner = self.argv_owner(member.object())?;
let property = member_name(member)?;
argv_reason(owner, &property).map(|_| member.span().start)
}
/// The arguments that `expr` returns as they are: `process.argv`, `process.argv.slice(2)`,
/// `hideBin(process.argv)`.
fn argv_passed(&self, expr: &Expression<'_>) -> Option<u32> {
let mut current = expr;
for _ in 0..MAX_DEPTH {
if let Some(start) = self.argv_start(current) {
return Some(start);
}
let call = as_call(current)?;
current = match method(call).as_deref() {
Some("slice") => receiver(call)?,
None if callee_ident_name(call) == Some("hideBin") => {
call.arguments.first()?.as_expression()?
}
_ => return None,
};
}
None
}
/// A parser that is called receives the arguments as they are: it is not a read by hand.
pub(super) fn mark_parser_args(&mut self, it: &CallExpression<'_>) {
let parse = matches!(method(it).as_deref(), Some("parse" | "parseAsync"))
&& receiver(it).is_some_and(|r| self.parser_root(r, 0));
let direct = method(it).is_none() && self.parser_root(&it.callee, 0);
let parse_args = self.is_parse_args(it, method(it).as_deref());
let expr = it.arguments.first().and_then(|a| a.as_expression());
let passed = match (expr, parse_args) {
(Some(config), true) => object_of(config).and_then(|o| prop(o, "args")),
(expr, false) if parse || direct => expr,
_ => None,
};
if let Some(start) = passed.and_then(|e| self.argv_passed(e)) {
self.allowed_argv.insert(start);
}
}
/// An expression that returns a commander or yargs object (at the foot of its chain).
pub(super) fn parser_root(&self, expr: &Expression<'_>, depth: usize) -> bool {
if depth > MAX_DEPTH {
return false;
}
let inner = expr.get_inner_expression();
if let Some(name) = ident(inner) {
return self.is_parser_name(name);
}
if let Expression::NewExpression(new) = inner {
return self.parser_root(&new.callee, depth + 1);
}
if let Some(call) = as_call(inner) {
if let Some(lit) = call.common_js_require() {
let package = super::imports::package_of(&lit.value.display().to_string());
return COMMANDER.contains(&package.as_str()) || package == "yargs";
}
return self.parser_root(&call.callee, depth + 1);
}
match as_member(inner) {
Some(member) => self.parser_root(member.object(), depth + 1),
None => false,
}
}
fn is_parser_name(&self, name: &str) -> bool {
if self.bindings.is_ambiguous(name) {
return false;
}
self.parser_vars.contains(name)
|| self
.imports
.package_for(name)
.is_some_and(|p| COMMANDER.contains(&p) || p == "yargs")
}
/// `process.argv`, `Bun.argv`, `Deno.args` read anywhere other than passed to a parser.
pub(super) fn argv_member(&mut self, object: &Expression<'_>, property: &str, span: Span) {
let reason = self
.argv_owner(object)
.and_then(|owner| argv_reason(owner, property));
if let Some(reason) = reason
&& !self.allowed_argv.contains(&span.start)
{
self.argv_sites.push((self.lines.of(span), reason));
}
}
/// `process.argv[0]` and `[1]` are the executable and the script, not arguments.
pub(super) fn allow_argv_index(&mut self, object: &Expression<'_>, index: &Expression<'_>) {
// `Deno.args` holds only the arguments: its index 0 is already one.
if as_member(object).is_some_and(|m| member_name(m).as_deref() == Some("args")) {
return;
}
if let Expression::NumericLiteral(n) = index.get_inner_expression()
&& (n.value == 0.0 || n.value == 1.0)
&& let Some(start) = self.argv_start(object)
{
self.allowed_argv.insert(start);
}
}
/// A name imported from `process` as `argv`, read anywhere other than passed to a parser.
pub(super) fn argv_name_use(&mut self, id: &oxc_ast::ast::IdentifierReference<'_>) {
if self.argv_names.contains(id.name.as_str())
&& !self.bindings.is_ambiguous(id.name.as_str())
&& !self.allowed_argv.contains(&id.span.start)
{
self.argv_sites
.push((self.lines.of(id.span), "process.argv is read directly"));
}
}
/// `const { argv } = process`.
pub(super) fn argv_declarator(&mut self, it: &VariableDeclarator<'_>) {
let (Some(init), BindingPattern::ObjectPattern(pattern)) = (&it.init, &it.id) else {
return;
};
let Some(owner) = self.argv_owner(init) else {
return;
};
for p in &pattern.properties {
let reason = key_name(&p.key).and_then(|k| argv_reason(owner, &k));
if let Some(reason) = reason {
self.argv_sites.push((self.lines.of(p.span), reason));
}
}
}
/// One site per argument-parsing package that no detector reads.
pub(super) fn report_unsupported_parsers(&mut self) {
let mut seen = HashSet::new();
let sites: Vec<(u32, String)> = self
.imports
.all()
.iter()
.filter(|i| UNSUPPORTED_PARSERS.contains(&i.package.as_str()))
.filter(|i| seen.insert(i.package.clone()))
.map(|i| (i.line, i.package.clone()))
.collect();
for (line, package) in sites {
let reason = format!("arguments are parsed by {package}, which has no detector");
self.unresolved_cli(line, &reason);
}
}
/// The direct reads of the arguments: they count even next to a parser, because an
/// `if (process.argv[2] === "doctor")` declares a command that the parser does not see.
pub(super) fn report_raw_arguments(&mut self) {
let sites = std::mem::take(&mut self.argv_sites);
for (line, reason) in sites {
self.unresolved_cli(line, reason);
}
}
/// Arguments that cannot be read hide flags as well as subcommands.
fn unresolved_cli(&mut self, line: u32, reason: &str) {
self.unresolved_at(Family::Flag, line, reason);
self.unresolved_at(Family::Command, line, reason);
}
}
/// Is the options builder of a yargs command the function at index `index`?
fn is_builder(it: &CallExpression<'_>, index: usize) -> bool {
let Some(expr) = it.arguments.get(index).and_then(|a| a.as_expression()) else {
return false;
};
match (index, object_of(expr)) {
(0, Some(object)) => prop(object, "builder").is_some_and(is_function),
(2, _) => is_function(expr),
_ => false,
}
}