Skip to main content

rust_anything/lang/
powershell.rs

1//! PowerShell: script modules (`.psm1`) and scripts (`.ps1`), their `Import-Module`, `using
2//! module` and dot-sourced imports, risks, and the functions a module exports with their
3//! `param()` types mapped into the TS-like type dialect.
4
5use std::collections::HashMap;
6use std::path::Path;
7
8use anyhow::Result;
9use tree_sitter::Node;
10
11use super::syntax::{self, named_children, text};
12use crate::risks::{Risk, regex_needs_fancy};
13use crate::ts::deps::CrateMatch;
14use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
15use crate::ts::exports::{ExportedFn, Param};
16use crate::ts::scan::{FileFacts, Import};
17
18fn language() -> tree_sitter::Language {
19    tree_sitter_powershell::LANGUAGE.into()
20}
21
22const SKIP_DIRS: &[&str] = &["node_modules", "target", "bin", "obj", "out", "Output"];
23
24// ---- discovery -------------------------------------------------------------------------------
25
26/// The module names a `.psd1` manifest lists under `RequiredModules`, as plain names or
27/// `@{ ModuleName = 'x'; ... }` entries.
28fn required_modules(text: &str) -> Vec<String> {
29    static ENTRY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
30    let entry = ENTRY.get_or_init(|| {
31        regex::Regex::new(r#"(?i)ModuleName\s*=\s*['"]([^'"]+)['"]|['"]([^'"]+)['"]"#)
32            .expect("valid regex")
33    });
34    let lower = text.to_ascii_lowercase();
35    let Some(start) = lower.find("requiredmodules") else {
36        return Vec::new();
37    };
38    let rest = &text[start..];
39    let Some(open) = rest.find(['(', '\'', '"', '@']) else {
40        return Vec::new();
41    };
42    let mut depth = 0i32;
43    let mut end = rest.len();
44    for (i, c) in rest[open..].char_indices() {
45        match c {
46            '(' | '{' => depth += 1,
47            ')' | '}' => depth -= 1,
48            '\n' if depth <= 0 => {
49                end = open + i;
50                break;
51            }
52            _ => {}
53        }
54        if depth < 0 {
55            end = open + i;
56            break;
57        }
58    }
59    let body: String = rest[open..end]
60        .lines()
61        .map(|l| l.split('#').next().unwrap_or(""))
62        .collect::<Vec<_>>()
63        .join("\n");
64    let mut names = Vec::new();
65    for c in entry.captures_iter(&body) {
66        if let Some(name) = c.get(1) {
67            names.push(name.as_str().to_string());
68        } else if let Some(name) = c.get(2)
69            && !body[..c.get(0).map_or(0, |m| m.start())]
70                .trim_end()
71                .to_ascii_lowercase()
72                .ends_with('=')
73        {
74            names.push(name.as_str().to_string());
75        }
76    }
77    names.dedup();
78    names
79}
80
81fn is_test(rel: &str, name: &str) -> bool {
82    let lower = name.to_ascii_lowercase();
83    lower.ends_with(".tests.ps1")
84        || lower.ends_with(".test.ps1")
85        || rel
86            .split('/')
87            .any(|p| matches!(p.to_ascii_lowercase().as_str(), "test" | "tests"))
88}
89
90pub fn discover(root: &Path) -> Result<Workspace> {
91    let mut packages: Vec<Package> = Vec::new();
92    let mut files = Vec::new();
93    let walker = crate::walk::filtered(root, |e| {
94        !(e.file_type().is_some_and(|t| t.is_dir())
95            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
96    })
97    .hidden(true)
98    .require_git(false)
99    .build();
100    for entry in walker.flatten() {
101        if !entry.file_type().is_some_and(|t| t.is_file()) {
102            continue;
103        }
104        let Ok(rel) = entry.path().strip_prefix(root) else {
105            continue;
106        };
107        let rel = rel.to_string_lossy().replace('\\', "/");
108        let name = rel.rsplit('/').next().unwrap_or(&rel).to_string();
109        let dir = rel
110            .rsplit_once('/')
111            .map_or(String::new(), |(d, _)| d.to_string());
112        let lower = name.to_ascii_lowercase();
113        if lower.ends_with(".psd1") {
114            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
115            if !text.to_ascii_lowercase().contains("moduleversion") {
116                continue;
117            }
118            let deps = required_modules(&text);
119            let module = name[..name.len() - ".psd1".len()].to_string();
120            match packages.iter_mut().find(|p| p.dir == dir) {
121                Some(p) => {
122                    p.deps.extend(deps);
123                    p.name = module;
124                }
125                None => packages.push(Package {
126                    name: module,
127                    src_root: dir.clone(),
128                    dir,
129                    deps,
130                    dev_deps: Vec::new(),
131                    namespaces: Vec::new(),
132                }),
133            }
134        } else if lower.ends_with(".ps1") || lower.ends_with(".psm1") {
135            let kind = if is_test(&rel, &name) {
136                FileKind::Test
137            } else {
138                FileKind::Source
139            };
140            files.push((rel, kind));
141        }
142    }
143    if !packages.iter().any(|p| p.dir.is_empty()) {
144        packages.push(Package {
145            name: root
146                .file_name()
147                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
148            dir: String::new(),
149            src_root: String::new(),
150            deps: Vec::new(),
151            dev_deps: Vec::new(),
152            namespaces: Vec::new(),
153        });
154    }
155    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
156    files.sort_by(|a, b| a.0.cmp(&b.0));
157    let files = files
158        .into_iter()
159        .map(|(path, kind)| {
160            let package = packages
161                .iter()
162                .enumerate()
163                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
164                .max_by_key(|(_, p)| p.dir.len())
165                .map_or(0, |(i, _)| i);
166            SourceFile {
167                path,
168                package,
169                kind,
170            }
171        })
172        .collect();
173    Ok(Workspace { packages, files })
174}
175
176fn join(dir: &str, rest: &str) -> String {
177    if dir.is_empty() {
178        rest.to_string()
179    } else {
180        format!("{dir}/{rest}")
181    }
182}
183
184// ---- risks and imports -----------------------------------------------------------------------
185
186/// The command a `command` node runs, lower-cased (`import-module`), or `None` for `& $x` and
187/// `. path`.
188fn command_name(node: Node, source: &str) -> Option<String> {
189    let name = node.child_by_field_name("command_name")?;
190    (name.kind() == "command_name").then(|| text(name, source).to_ascii_lowercase())
191}
192
193/// The arguments of a command that are not `-Parameter` names, in order.
194fn command_words<'s>(node: Node, source: &'s str) -> Vec<&'s str> {
195    let Some(elements) = node.child_by_field_name("command_elements") else {
196        return Vec::new();
197    };
198    let mut words = Vec::new();
199    for child in named_children(elements) {
200        match child.kind() {
201            "command_argument_sep" | "command_parameter" | "redirection" => {}
202            "generic_token" | "string_literal" | "array_literal_expression" => {
203                words.push(text(child, source).trim().trim_matches(['\'', '"']));
204            }
205            _ => {}
206        }
207    }
208    words
209}
210
211/// A path as written after `.` or `Import-Module`, relative to the file: `$PSScriptRoot/x.ps1`
212/// and `.\x.ps1` become `./x.ps1`.
213fn local_path(spec: &str) -> Option<String> {
214    let spec = spec.trim().trim_matches(['\'', '"']).replace('\\', "/");
215    let rest = ["$PSScriptRoot/", "${PSScriptRoot}/", "./"]
216        .iter()
217        .find_map(|p| {
218            spec.get(..p.len())
219                .filter(|head| head.eq_ignore_ascii_case(p))
220                .map(|_| &spec[p.len()..])
221        })
222        .map(str::to_string)
223        .or_else(|| spec.starts_with("../").then(|| spec.clone()))?;
224    if rest.contains('$') || rest.contains('(') {
225        return None;
226    }
227    Some(if rest.starts_with("../") {
228        rest
229    } else {
230        format!("./{rest}")
231    })
232}
233
234const COMPARISONS: &[&str] = &[
235    "-eq",
236    "-ne",
237    "-gt",
238    "-ge",
239    "-lt",
240    "-le",
241    "-like",
242    "-notlike",
243    "-match",
244    "-notmatch",
245    "-contains",
246    "-notcontains",
247    "-in",
248    "-notin",
249    "-replace",
250    "-split",
251];
252
253/// Whether a statement of a function body sends a value to the pipeline without `return`,
254/// `Write-Output` or an assignment: PowerShell's implicit output.
255fn implicit_output(node: Node, source: &str) -> bool {
256    if node.kind() != "pipeline" {
257        return false;
258    }
259    let mut assigns = false;
260    let mut silent = false;
261    syntax::walk(node, |n| match n.kind() {
262        "assignment_expression" => assigns = true,
263        "command" => {
264            if let Some(name) = command_name(n, source)
265                && (name.starts_with("write-host")
266                    || name.starts_with("out-null")
267                    || name.starts_with("set-")
268                    || name.starts_with("remove-")
269                    || name.starts_with("add-")
270                    || name == "throw")
271            {
272                silent = true;
273            }
274        }
275        _ => {}
276    });
277    !assigns && !silent && !text(node, source).trim_start().starts_with("[void]")
278}
279
280pub fn scan(source: &str) -> FileFacts {
281    let mut facts = FileFacts {
282        loc: syntax::loc(source, crate::lang::Lang::Powershell),
283        ..FileFacts::default()
284    };
285    let Some(tree) = syntax::parse(&language(), source) else {
286        return facts;
287    };
288    let root = tree.root_node();
289    facts.parse_errors = usize::from(root.has_error());
290    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
291        facts
292            .risks
293            .entry(risk)
294            .or_default()
295            .push(syntax::line(node))
296    };
297    syntax::walk(root, |node| match node.kind() {
298        "command" => {
299            let invoked = node
300                .child(0)
301                .filter(|c| c.kind() == "command_invokation_operator")
302                .map(|c| text(c, source).trim().to_string());
303            if invoked.as_deref() == Some(".") {
304                let target = node
305                    .child_by_field_name("command_name")
306                    .map_or("", |n| text(n, source));
307                match local_path(target) {
308                    Some(spec) => facts.imports.push(Import {
309                        specifier: spec,
310                        type_only: false,
311                        dynamic: false,
312                    }),
313                    None => add(&mut facts, Risk::DynamicCode, node),
314                }
315                return;
316            }
317            if invoked.as_deref() == Some("&") {
318                add(&mut facts, Risk::Callbacks, node);
319                return;
320            }
321            let Some(name) = command_name(node, source) else {
322                return;
323            };
324            match name.as_str() {
325                "import-module" | "ipmo" | "using" => {
326                    let words = command_words(node, source);
327                    let spec = if name == "using" {
328                        match words.as_slice() {
329                            [kind, spec, ..] if kind.eq_ignore_ascii_case("module") => Some(*spec),
330                            _ => None,
331                        }
332                    } else {
333                        words.first().copied()
334                    };
335                    if let Some(spec) = spec {
336                        if spec.contains('$') && local_path(spec).is_none() {
337                            add(&mut facts, Risk::DynamicCode, node);
338                        } else {
339                            facts.imports.push(Import {
340                                specifier: local_path(spec).unwrap_or_else(|| spec.to_string()),
341                                type_only: false,
342                                dynamic: false,
343                            });
344                        }
345                    }
346                }
347                "invoke-expression" | "iex" | "invoke-command" | "start-job" | "add-type" => {
348                    add(&mut facts, Risk::DynamicCode, node)
349                }
350                "foreach-object" | "%" | "where-object" | "?" => {
351                    facts.loops += 1;
352                    add(&mut facts, Risk::Callbacks, node);
353                }
354                "sort-object" | "sort" | "group-object" | "group" => {
355                    add(&mut facts, Risk::OrderedCollections, node)
356                }
357                "write-output" | "echo" => add(&mut facts, Risk::PipelineOutput, node),
358                "get-date" | "get-random" | "new-guid" => {
359                    add(&mut facts, Risk::ClockAndRandom, node)
360                }
361                "convertto-json" | "convertfrom-json" => add(&mut facts, Risk::Json, node),
362                "write-error" => add(&mut facts, Risk::Exceptions, node),
363                "start-threadjob" | "start-process" => add(&mut facts, Risk::Concurrency, node),
364                _ => {}
365            }
366        }
367        "comparison_operator" => {
368            let op = text(node, source).to_ascii_lowercase();
369            if COMPARISONS.contains(&op.as_str()) {
370                add(&mut facts, Risk::CaseInsensitive, node);
371            }
372            if matches!(op.as_str(), "-match" | "-notmatch" | "-replace" | "-split")
373                && let Some(pattern) = node.next_named_sibling()
374            {
375                let mut literal = None;
376                syntax::walk(pattern, |n| {
377                    if literal.is_none() && n.kind() == "string_literal" {
378                        literal = Some(text(n, source));
379                    }
380                });
381                match literal {
382                    Some(p)
383                        if regex_needs_fancy(p.trim_matches(['\'', '"']), "")
384                            || p.contains("(?<") =>
385                    {
386                        add(&mut facts, Risk::RegexSyntax, node)
387                    }
388                    Some(_) => {}
389                    None => add(&mut facts, Risk::DynamicRegex, node),
390                }
391            }
392        }
393        "switch_statement" => add(&mut facts, Risk::CaseInsensitive, node),
394        "variable" => {
395            let v = text(node, source).to_ascii_lowercase();
396            if v == "$null" {
397                add(&mut facts, Risk::NullReferences, node);
398            } else if v.starts_with("$script:") || v.starts_with("$global:") {
399                add(&mut facts, Risk::DynamicTyping, node);
400            }
401        }
402        "hash_literal_expression" => {
403            let ordered = node
404                .parent()
405                .and_then(|p| p.parent())
406                .filter(|p| p.kind() == "cast_expression")
407                .is_some_and(|p| {
408                    text(p, source)
409                        .to_ascii_lowercase()
410                        .starts_with("[ordered]")
411                });
412            if ordered {
413                add(&mut facts, Risk::OrderedCollections, node);
414            } else {
415                add(&mut facts, Risk::UnorderedIteration, node);
416            }
417        }
418        "cast_expression" => add(&mut facts, Risk::LooseConversion, node),
419        "multiplicative_expression" | "multiplicative_argument_expression"
420            if named_children(node).len() > 1 && text(node, source).contains('/') =>
421        {
422            add(&mut facts, Risk::LooseConversion, node)
423        }
424        "try_statement" | "trap_statement" => add(&mut facts, Risk::Exceptions, node),
425        "flow_control_statement"
426            if text(node, source).to_ascii_lowercase().starts_with("throw") =>
427        {
428            add(&mut facts, Risk::Exceptions, node)
429        }
430        "script_block_expression" => add(&mut facts, Risk::Callbacks, node),
431        "class_statement" => add(&mut facts, Risk::ClassInheritance, node),
432        "foreach_statement" | "for_statement" | "while_statement" | "do_statement" => {
433            facts.loops += 1
434        }
435        "function_statement" => {
436            let body = node
437                .named_children(&mut node.walk())
438                .find(|c| c.kind() == "script_block")
439                .and_then(|b| b.child_by_field_name("script_block_body"));
440            if let Some(statements) = body.and_then(|b| {
441                named_children(b)
442                    .into_iter()
443                    .find(|c| c.kind() == "statement_list")
444            }) && named_children(statements)
445                .into_iter()
446                .any(|s| implicit_output(s, source))
447            {
448                add(&mut facts, Risk::PipelineOutput, node);
449            }
450        }
451        _ => {}
452    });
453    facts
454}
455
456/// Modules that ship with PowerShell: no crate needed to replace an import of them.
457fn builtin(module: &str) -> bool {
458    let m = module.to_ascii_lowercase();
459    m.starts_with("microsoft.powershell.")
460        || matches!(
461            m.as_str(),
462            "psreadline" | "packagemanagement" | "powershellget" | "threadjob" | "cimcmdlets"
463        )
464}
465
466pub fn resolve(
467    from: &str,
468    spec: &str,
469    index: &HashMap<&str, usize>,
470    _ws: &Workspace,
471) -> super::Resolution {
472    if spec.starts_with("./") || spec.starts_with("../") {
473        let dir = from.rsplit_once('/').map_or("", |(d, _)| d);
474        let joined = join(dir, spec.trim_start_matches("./"));
475        let Some(path) = normalize(&joined) else {
476            return super::Resolution::Unresolved;
477        };
478        for candidate in [
479            path.clone(),
480            format!("{path}.psm1"),
481            format!("{path}.ps1"),
482            format!("{path}/{}.psm1", path.rsplit('/').next().unwrap_or(&path)),
483        ] {
484            if let Some(i) = index.get(candidate.as_str()) {
485                return super::Resolution::File(*i);
486            }
487        }
488        if let Some(manifest) = path.strip_suffix(".psd1") {
489            let module = manifest.rsplit('/').next().unwrap_or(manifest);
490            if let Some(i) = index.get(format!("{manifest}.psm1").as_str()).or_else(|| {
491                let dir = manifest.rsplit_once('/').map_or("", |(d, _)| d);
492                index.get(join(dir, &format!("{module}.psm1")).as_str())
493            }) {
494                return super::Resolution::File(*i);
495            }
496        }
497        return super::Resolution::Unresolved;
498    }
499    if builtin(spec) {
500        return super::Resolution::Stdlib;
501    }
502    super::Resolution::External(spec.to_string())
503}
504
505fn normalize(path: &str) -> Option<String> {
506    let mut parts: Vec<&str> = Vec::new();
507    for part in path.split('/') {
508        match part {
509            "" | "." => {}
510            ".." => {
511                parts.pop()?;
512            }
513            _ => parts.push(part),
514        }
515    }
516    Some(parts.join("/"))
517}
518
519/// Rust counterparts of common PowerShell Gallery modules.
520pub fn lookup(module: &str) -> Option<CrateMatch> {
521    crate::crates::find("powershell", module)
522}
523
524// ---- exports ---------------------------------------------------------------------------------
525
526/// A PowerShell type as written inside `[...]` (`string`, `int[]`, `System.Int64`), in the
527/// dialect; `None` for a .NET object that does not cross as JSON.
528pub fn ps_to_ts(t: &str) -> Option<String> {
529    let t = t.trim();
530    if let Some(inner) = t.strip_suffix("[]") {
531        let inner = ps_to_ts(inner)?;
532        return Some(if inner.contains(' ') {
533            format!("({inner})[]")
534        } else {
535            format!("{inner}[]")
536        });
537    }
538    let lower = t.to_ascii_lowercase();
539    let lower = lower.strip_prefix("system.").unwrap_or(&lower);
540    Some(
541        match lower {
542            "string" | "char" => "string",
543            "int" | "int32" | "long" | "int64" | "int16" | "short" | "byte" | "sbyte"
544            | "uint16" | "ushort" | "uint32" | "uint" | "uint64" | "ulong" => "int",
545            "double" | "single" | "float" | "decimal" => "number",
546            "bool" | "boolean" | "switch" | "management.automation.switchparameter" => "boolean",
547            "array" | "object[]" | "collections.arraylist" => "unknown[]",
548            "hashtable"
549            | "collections.hashtable"
550            | "collections.idictionary"
551            | "ordered"
552            | "collections.specialized.ordereddictionary"
553            | "pscustomobject"
554            | "management.automation.pscustomobject" => "Record<string, unknown>",
555            "object" | "psobject" | "management.automation.psobject" => "unknown",
556            _ => return None,
557        }
558        .to_string(),
559    )
560}
561
562/// The type a `[...]` constraint names, without brackets (`[string[]]` gives `string[]`).
563fn type_of(attribute: Node, source: &str) -> Option<String> {
564    let literal = named_children(attribute)
565        .into_iter()
566        .find(|c| c.kind() == "type_literal")?;
567    let t = text(literal, source).trim();
568    Some(
569        t.strip_prefix('[')
570            .and_then(|r| r.strip_suffix(']'))
571            .unwrap_or(t)
572            .trim()
573            .to_string(),
574    )
575}
576
577/// The name of a `[Name(...)]` attribute, lower-cased.
578fn attribute_name(attribute: Node, source: &str) -> Option<String> {
579    let name = named_children(attribute)
580        .into_iter()
581        .find(|c| c.kind() == "attribute_name")?;
582    Some(text(name, source).trim().to_ascii_lowercase())
583}
584
585fn attributes<'t>(list: Option<Node<'t>>) -> Vec<Node<'t>> {
586    list.map(|l| {
587        named_children(l)
588            .into_iter()
589            .filter(|a| a.kind() == "attribute")
590            .collect()
591    })
592    .unwrap_or_default()
593}
594
595/// The param block of a function: `param(...)` in its body, or `function f(...)`.
596fn param_block<'t>(function: Node<'t>) -> Option<Node<'t>> {
597    let children = named_children(function);
598    if let Some(declared) = children
599        .iter()
600        .find(|c| c.kind() == "function_parameter_declaration")
601    {
602        return Some(*declared);
603    }
604    for c in children {
605        if matches!(c.kind(), "script_block" | "ERROR")
606            && let Some(block) = named_children(c)
607                .into_iter()
608                .find(|n| n.kind() == "param_block")
609        {
610            return Some(block);
611        }
612    }
613    None
614}
615
616/// The names `Export-ModuleMember -Function` lists at the top level of a module, or `None`
617/// when it has none (every function is exported).
618fn exported_names(root: Node, source: &str) -> Option<Vec<String>> {
619    let mut names: Option<Vec<String>> = None;
620    for statement in named_children(root)
621        .into_iter()
622        .filter(|n| n.kind() == "statement_list")
623        .flat_map(named_children)
624        .filter(|n| n.kind() != "function_statement")
625    {
626        let mut commands = Vec::new();
627        syntax::walk(statement, |n| {
628            if n.kind() == "command" {
629                commands.push(n);
630            }
631        });
632        for command in commands {
633            if command_name(command, source).as_deref() != Some("export-modulemember") {
634                continue;
635            }
636            let list = names.get_or_insert_with(Vec::new);
637            let elements = command
638                .child_by_field_name("command_elements")
639                .map_or("", |e| text(e, source));
640            list.extend(function_list(elements));
641        }
642    }
643    names
644}
645
646/// `text` with up to `column` leading spaces taken off every line after the first, which starts
647/// at that column in the source.
648fn dedent(text: &str, column: usize) -> String {
649    let mut lines = text.lines();
650    let mut out = lines.next().unwrap_or("").to_string();
651    for line in lines {
652        let spaces = line.len() - line.trim_start_matches([' ', '\t']).len();
653        out.push('\n');
654        out.push_str(&line[spaces.min(column)..]);
655    }
656    out
657}
658
659/// The names after `-Function` (or in the first position) of `Export-ModuleMember`'s arguments:
660/// a word that starts with `-` after a space is the next parameter, unless a comma comes before it.
661fn function_list(arguments: &str) -> Vec<String> {
662    let mut param = "-function".to_string();
663    let mut list = Vec::new();
664    let mut continues = false;
665    for word in arguments.split_whitespace() {
666        if word.starts_with('-') && !continues {
667            param = word.to_ascii_lowercase();
668            continue;
669        }
670        continues = word.ends_with(',');
671        if param.starts_with("-f") {
672            list.extend(
673                word.split(',')
674                    .map(|w| w.trim().trim_matches(['\'', '"', '@', '(', ')']))
675                    .filter(|w| !w.is_empty())
676                    .map(str::to_string),
677            );
678        }
679        if !continues {
680            param = "-cmdlet".into();
681        }
682    }
683    list
684}
685
686fn wildcard(pattern: &str, name: &str) -> bool {
687    let pattern = regex::escape(&pattern.to_ascii_lowercase())
688        .replace(r"\*", ".*")
689        .replace(r"\?", ".");
690    regex::Regex::new(&format!("^{pattern}$"))
691        .is_ok_and(|re| re.is_match(&name.to_ascii_lowercase()))
692}
693
694/// What keeps a parameter of type `t` in PowerShell, if anything.
695fn parameter_blocker(name: &str, t: &str) -> String {
696    let lower = t.to_ascii_lowercase();
697    if lower == "scriptblock" || lower.ends_with(".scriptblock") {
698        format!("takes a script block `${name}`")
699    } else if lower == "ref" {
700        format!("takes `${name}` by reference (`[ref]`)")
701    } else {
702        format!("takes a .NET object `${name}` (`[{t}]`)")
703    }
704}
705
706fn function_fn(path: &str, node: Node, source: &str) -> Option<ExportedFn> {
707    let name = named_children(node)
708        .into_iter()
709        .find(|c| c.kind() == "function_name")
710        .map(|n| text(n, source).trim().to_string())?;
711    let keyword = text(node, source)
712        .split_whitespace()
713        .next()
714        .unwrap_or("")
715        .to_ascii_lowercase();
716    let mut blocker = None;
717    if keyword == "filter" {
718        blocker = Some("a filter: it runs once per pipeline item".to_string());
719    } else if keyword == "workflow" {
720        blocker = Some("a workflow".to_string());
721    }
722    let block = param_block(node);
723    let declared = block.is_some_and(|b| b.kind() == "function_parameter_declaration");
724    let list = block.and_then(|b| {
725        named_children(b)
726            .into_iter()
727            .find(|c| c.kind() == "parameter_list")
728    });
729    let block_attributes = block.filter(|b| b.kind() == "param_block").and_then(|b| {
730        named_children(b)
731            .into_iter()
732            .find(|c| c.kind() == "attribute_list")
733    });
734    let mut returns = "unknown".to_string();
735    for attribute in attributes(block_attributes) {
736        if attribute_name(attribute, source).as_deref() == Some("outputtype") {
737            let mut found = None;
738            syntax::walk(attribute, |n| {
739                if found.is_none() && n.kind() == "type_literal" {
740                    let t = text(n, source).trim();
741                    found = Some(t.trim_start_matches('[').trim_end_matches(']').to_string());
742                }
743            });
744            if let Some(t) = found.and_then(|t| ps_to_ts(&t)) {
745                returns = t;
746            }
747        }
748    }
749    let mut params = Vec::new();
750    for p in list
751        .map(named_children)
752        .unwrap_or_default()
753        .into_iter()
754        .filter(|p| p.kind() == "script_parameter")
755    {
756        let Some(var) = named_children(p)
757            .into_iter()
758            .find(|c| c.kind() == "variable")
759        else {
760            continue;
761        };
762        let pname = text(var, source)
763            .trim_start_matches('$')
764            .trim_start_matches('{')
765            .trim_end_matches('}')
766            .to_string();
767        let attrs = attributes(
768            named_children(p)
769                .into_iter()
770                .find(|c| c.kind() == "attribute_list"),
771        );
772        let declared_type = attrs.iter().rev().find_map(|a| type_of(*a, source));
773        let mut mandatory = false;
774        for a in &attrs {
775            let Some(aname) = attribute_name(*a, source) else {
776                continue;
777            };
778            let atext = text(*a, source).to_ascii_lowercase().replace(' ', "");
779            if aname == "parameter" {
780                if atext.contains("mandatory") && !atext.contains("mandatory=$false") {
781                    mandatory = true;
782                }
783                if atext.contains("valuefrompipeline") {
784                    blocker.get_or_insert_with(|| format!("takes pipeline input `${pname}`"));
785                }
786            }
787        }
788        let default = named_children(p)
789            .into_iter()
790            .find(|c| c.kind() == "script_parameter_default")
791            .map(|d| {
792                text(d, source)
793                    .trim()
794                    .trim_start_matches('=')
795                    .trim()
796                    .to_string()
797            });
798        let ts_type = match &declared_type {
799            Some(t) => match ps_to_ts(t) {
800                Some(ts) => ts,
801                None => {
802                    blocker.get_or_insert_with(|| parameter_blocker(&pname, t));
803                    "unknown".into()
804                }
805            },
806            None => "unknown".into(),
807        };
808        let by_reference = matches!(ts_type.as_str(), "unknown" | "Record<string, unknown>")
809            || ts_type.ends_with("[]");
810        let null_default = default
811            .as_deref()
812            .is_none_or(|d| d.eq_ignore_ascii_case("$null"));
813        params.push(Param {
814            name: pname,
815            ts_type,
816            optional: !mandatory && by_reference && null_default,
817            rest: false,
818            default,
819            keyword_only: false,
820            native_type: declared_type.map(|t| format!("[{t}]")),
821        });
822    }
823    let mut named_blocks = false;
824    let mut pipeline_input = false;
825    let mut dynamic = false;
826    syntax::walk(node, |n| match n.kind() {
827        "named_block" => {
828            let block = text(n, source).trim_start().to_ascii_lowercase();
829            if !block.starts_with("end") {
830                named_blocks = true;
831            }
832        }
833        "variable" => {
834            let v = text(n, source).to_ascii_lowercase();
835            if v == "$input" {
836                pipeline_input = true;
837            }
838            if v == "$pscmdlet" || v == "$args" {
839                dynamic = true;
840            }
841        }
842        _ => {}
843    });
844    if named_blocks {
845        blocker
846            .get_or_insert_with(|| "has `begin`/`process` blocks: it streams the pipeline".into());
847    }
848    if pipeline_input {
849        blocker.get_or_insert_with(|| "reads pipeline input (`$input`)".into());
850    }
851    if dynamic {
852        blocker.get_or_insert_with(|| "reads `$PSCmdlet` or `$args`".into());
853    }
854    let prototype = match block {
855        Some(_) if declared => Some(format!("param({})", list.map_or("", |l| text(l, source)))),
856        Some(b) => Some(dedent(text(b, source), b.start_position().column)),
857        None => Some("param()".to_string()),
858    };
859    Some(ExportedFn {
860        name,
861        file: path.to_string(),
862        line: syntax::line(node),
863        params,
864        returns,
865        blocker,
866        prototype,
867        ..ExportedFn::default()
868    })
869}
870
871pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
872    let lower = path.to_ascii_lowercase();
873    if !(lower.ends_with(".psm1") || lower.ends_with(".ps1")) {
874        return Vec::new();
875    }
876    let Some(tree) = syntax::parse(&language(), source) else {
877        return Vec::new();
878    };
879    let root = tree.root_node();
880    let listed = if lower.ends_with(".psm1") {
881        exported_names(root, source)
882    } else {
883        None
884    };
885    let mut out = Vec::new();
886    for statement in named_children(root)
887        .into_iter()
888        .filter(|n| n.kind() == "statement_list")
889        .flat_map(named_children)
890    {
891        if statement.kind() != "function_statement" {
892            continue;
893        }
894        let Some(f) = function_fn(path, statement, source) else {
895            continue;
896        };
897        if let Some(names) = &listed
898            && !names.iter().any(|n| wildcard(n, &f.name))
899        {
900            continue;
901        }
902        out.push(f);
903    }
904    out
905}
906
907/// The byte offset just past the line where the last top-level function ends: where `enable`
908/// puts its block, after every function it redefines and before the script's own code runs.
909pub fn after_functions(source: &str) -> Option<usize> {
910    let tree = syntax::parse(&language(), source)?;
911    let end = named_children(tree.root_node())
912        .into_iter()
913        .filter(|n| n.kind() == "statement_list")
914        .flat_map(named_children)
915        .filter(|n| n.kind() == "function_statement")
916        .map(|n| n.end_byte())
917        .max()?;
918    Some(
919        source[end..]
920            .find('\n')
921            .map_or(source.len(), |i| end + i + 1),
922    )
923}
924
925/// The parameter block a generated wrapper declares, as the original wrote it.
926pub fn param_text(f: &ExportedFn) -> &str {
927    f.prototype.as_deref().unwrap_or("param()")
928}
929
930#[cfg(test)]
931mod tests {
932    use super::*;
933
934    const MODULE: &str = include_str!("../../tests/fixtures/powershell-module/TextTools.psm1");
935
936    fn find<'a>(fns: &'a [ExportedFn], name: &str) -> &'a ExportedFn {
937        fns.iter().find(|f| f.name == name).unwrap_or_else(|| {
938            panic!(
939                "{name} not in {:?}",
940                fns.iter().map(|f| &f.name).collect::<Vec<_>>()
941            )
942        })
943    }
944
945    #[test]
946    fn module_functions_and_their_parameter_types() {
947        let fns = exports("TextTools.psm1", MODULE);
948        let slug = find(&fns, "ConvertTo-Slug");
949        let params: Vec<(&str, &str, bool, Option<&str>)> = slug
950            .params
951            .iter()
952            .map(|p| {
953                (
954                    p.name.as_str(),
955                    p.ts_type.as_str(),
956                    p.optional,
957                    p.default.as_deref(),
958                )
959            })
960            .collect();
961        assert_eq!(
962            params,
963            [
964                ("Text", "string", false, None),
965                ("Separator", "string", false, Some("'-'")),
966                ("MaxLength", "int", false, Some("0")),
967            ]
968        );
969        assert_eq!(slug.returns, "string");
970        assert!(slug.blocker.is_none());
971        assert!(
972            slug.prototype
973                .as_deref()
974                .unwrap()
975                .starts_with("[CmdletBinding()]"),
976            "{:?}",
977            slug.prototype
978        );
979        let mean = find(&fns, "Measure-Mean");
980        assert_eq!(mean.params[0].ts_type, "number[]");
981        assert!(mean.params[0].optional);
982        assert_eq!(mean.returns, "number");
983        let initials = find(&fns, "Get-Initials");
984        assert_eq!(
985            initials
986                .params
987                .iter()
988                .map(|p| p.ts_type.as_str())
989                .collect::<Vec<_>>(),
990            ["string[]", "boolean"]
991        );
992        let setting = find(&fns, "Get-Setting");
993        assert_eq!(setting.params[0].ts_type, "Record<string, unknown>");
994        assert_eq!(setting.params[2].ts_type, "unknown");
995        assert!(setting.params[2].optional);
996        assert_eq!(find(&fns, "Test-Equal").returns, "boolean");
997    }
998
999    #[test]
1000    fn what_stays_in_powershell_says_why() {
1001        let fns = exports("TextTools.psm1", MODULE);
1002        let reasons: Vec<(&str, &str)> = fns
1003            .iter()
1004            .filter_map(|f| Some((f.name.as_str(), f.blocker.as_deref()?)))
1005            .collect();
1006        assert_eq!(
1007            reasons,
1008            [
1009                ("Get-Lines", "takes pipeline input `$Line`"),
1010                ("Format-Stamp", "takes a .NET object `$At` (`[datetime]`)"),
1011                ("Invoke-Twice", "takes a script block `$Action`"),
1012            ]
1013        );
1014    }
1015
1016    #[test]
1017    fn export_module_member_limits_the_exports() {
1018        let text = "function Public-One { 1 }\nfunction helper { 2 }\nfunction Public-Two { 3 }\nExport-ModuleMember -Function Public-*\n";
1019        let names: Vec<String> = exports("m.psm1", text)
1020            .into_iter()
1021            .map(|f| f.name)
1022            .collect();
1023        assert_eq!(names, ["Public-One", "Public-Two"]);
1024        let all: Vec<String> = exports("m.psm1", "function a { 1 }\nfunction b { 2 }\n")
1025            .into_iter()
1026            .map(|f| f.name)
1027            .collect();
1028        assert_eq!(all, ["a", "b"]);
1029        let script: Vec<String> = exports("s.ps1", text).into_iter().map(|f| f.name).collect();
1030        assert_eq!(script.len(), 3, "a script has no export list");
1031    }
1032
1033    #[test]
1034    fn inline_parameters_and_nested_functions() {
1035        let text = "function Add([int]$a, [int]$b = 2) {\n    function inner { 1 }\n    $a + $b\n}\nfilter Odd { if ($_ % 2) { $_ } }\nfunction Stream {\n    param([int[]]$xs)\n    begin { $n = 0 }\n    process { $n++ }\n    end { $n }\n}\n";
1036        let fns = exports("x.ps1", text);
1037        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
1038        assert_eq!(names, ["Add", "Odd", "Stream"]);
1039        assert_eq!(fns[0].params[1].default.as_deref(), Some("2"));
1040        assert_eq!(
1041            fns[0].prototype.as_deref(),
1042            Some("param([int]$a, [int]$b = 2)")
1043        );
1044        assert!(fns[1].blocker.as_deref().unwrap().starts_with("a filter"));
1045        assert!(fns[2].blocker.as_deref().unwrap().contains("process"));
1046    }
1047
1048    #[test]
1049    fn types_map_into_the_dialect() {
1050        assert_eq!(ps_to_ts("string").as_deref(), Some("string"));
1051        assert_eq!(ps_to_ts("System.Int64").as_deref(), Some("int"));
1052        assert_eq!(ps_to_ts("double[]").as_deref(), Some("number[]"));
1053        assert_eq!(
1054            ps_to_ts("hashtable[]").as_deref(),
1055            Some("(Record<string, unknown>)[]")
1056        );
1057        assert_eq!(ps_to_ts("switch").as_deref(), Some("boolean"));
1058        assert_eq!(ps_to_ts("DateTime"), None);
1059    }
1060
1061    #[test]
1062    fn imports_and_risks() {
1063        let text = "using module ./Other.psm1\n. \"$PSScriptRoot/Helpers.ps1\"\nImport-Module PSReadLine\nImport-Module Pester\nfunction F {\n    param([string]$a)\n    if ($a -eq 'x') { $null }\n    $h = @{ a = 1 }\n    $a -replace '(?<=a)b', 'c'\n    $a\n}\n";
1064        let facts = scan(text);
1065        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1066        assert_eq!(
1067            specs,
1068            ["./Other.psm1", "./Helpers.ps1", "PSReadLine", "Pester"]
1069        );
1070        for risk in [
1071            Risk::CaseInsensitive,
1072            Risk::NullReferences,
1073            Risk::UnorderedIteration,
1074            Risk::RegexSyntax,
1075            Risk::PipelineOutput,
1076        ] {
1077            assert!(
1078                facts.risks.contains_key(&risk),
1079                "{risk:?}: {:?}",
1080                facts.risks
1081            );
1082        }
1083    }
1084
1085    #[test]
1086    fn a_manifest_names_its_required_modules() {
1087        let text = "@{\n    ModuleVersion = '1.0'\n    RequiredModules = @('PSReadLine', @{ ModuleName = 'Pester'; ModuleVersion = '5.0' })\n}\n";
1088        assert_eq!(required_modules(text), ["PSReadLine", "Pester"]);
1089    }
1090}