Skip to main content

harn_stdlib/
lib.rs

1//! Canonical embedded Harn standard library source catalog.
2//!
3//! This crate intentionally contains only static source strings. The compiler,
4//! runtime, and tooling read them through `harn-stdlib-catalog` and never
5//! depend on this crate, so editing a stdlib module rebuilds only this crate
6//! and the binaries that link it. A host calls [`install`] once at startup.
7//! Loading this catalog is pure: modules cannot register ambient
8//! effects, and every effectful stdlib function must receive its typed Harness
9//! capability explicitly from the caller, including callbacks that may perform
10//! effects.
11//!
12//! The sources are embedded as one zstd archive, about a fifth of their size,
13//! which the first catalog read decodes for the rest of the process.
14
15use std::sync::LazyLock;
16
17pub use harn_stdlib_catalog::{
18    builtin_reexports, StdlibCatalog, StdlibCliScript, StdlibPromptAsset, StdlibSource,
19};
20
21macro_rules! catalog_entries {
22    (
23        sources: [$($module:literal => $_module_path:literal),* $(,)?],
24        prompt_assets: [$($asset:literal => $_asset_path:literal),* $(,)?],
25        cli_scripts: [$($script:literal => $_script_path:literal),* $(,)?] $(,)?
26    ) => {
27        const MODULES: &[&str] = &[$($module),*];
28        const PROMPT_ASSETS: &[&str] = &[$($asset),*];
29        const CLI_SCRIPTS: &[&str] = &[$($script),*];
30    };
31}
32
33include!("catalog_entries.rs");
34include!(concat!(env!("OUT_DIR"), "/stdlib_archive.rs"));
35
36/// Decode the archive and cut it into the catalog's entries, in the order
37/// `build.rs` wrote them. The text lives for the rest of the process.
38fn unpack() -> StdlibCatalog {
39    let bytes = zstd::bulk::decompress(ARCHIVE, ARCHIVE_TEXT_LEN)
40        .unwrap_or_else(|error| panic!("the embedded stdlib archive does not decode: {error}"));
41    let mut rest: &'static str = String::from_utf8(bytes)
42        .expect("build.rs packed UTF-8 text")
43        .leak();
44    let mut lengths = LENGTHS.iter();
45    let mut next = || {
46        let (source, tail) = rest.split_at(*lengths.next().expect("one length per entry"));
47        rest = tail;
48        source
49    };
50    let sources = MODULES
51        .iter()
52        .map(|&module| StdlibSource {
53            module,
54            source: next(),
55        })
56        .collect::<Vec<_>>();
57    let prompt_assets = PROMPT_ASSETS
58        .iter()
59        .map(|&path| StdlibPromptAsset {
60            path,
61            source: next(),
62        })
63        .collect::<Vec<_>>();
64    let cli_scripts = CLI_SCRIPTS
65        .iter()
66        .map(|&name| StdlibCliScript {
67            name,
68            source: next(),
69        })
70        .collect::<Vec<_>>();
71    assert!(
72        rest.is_empty() && lengths.next().is_none(),
73        "the embedded stdlib archive does not match its catalog"
74    );
75    StdlibCatalog {
76        sources: sources.leak(),
77        prompt_assets: prompt_assets.leak(),
78        cli_scripts: cli_scripts.leak(),
79    }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct StdlibPublicFunction {
84    pub name: String,
85    pub signature: String,
86    pub required_params: usize,
87    pub total_params: usize,
88    pub variadic: bool,
89    pub doc: Option<String>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct StdlibEntrypointModule {
94    pub import_path: String,
95    pub category: String,
96}
97
98/// Canonical normalized connector event schemas, authored as Harn `type`
99/// declarations. This is the SOURCE OF TRUTH for the Rust event-payload
100/// structs in `crates/harn-vm/src/triggers/event/schemas_generated.rs`, which
101/// are generated from these declarations by `harn connector-schema-codegen`.
102///
103/// It is intentionally NOT registered in [`CATALOG`]: it is a codegen
104/// input (like `crates/harn-serve/openapi.yaml`), not a module loaded into every
105/// program.
106/// Exposing it as an embedded string keeps the generator independent of the
107/// current working directory.
108pub const CONNECTOR_EVENT_SCHEMAS_SOURCE: &str = include_str!("stdlib/stdlib_event_schemas.harn");
109
110/// This crate's catalog: every embedded stdlib module, prompt asset, and CLI
111/// script, in the order `catalog_entries.rs` lists them.
112pub static CATALOG: LazyLock<StdlibCatalog> = LazyLock::new(unpack);
113
114/// Install [`CATALOG`] as the process's standard library. Hosts call this once
115/// at startup, before running Harn code; calling it again is a no-op.
116///
117/// # Errors
118///
119/// Refuses when a different catalog is already installed.
120pub fn install() -> Result<(), harn_stdlib_catalog::CatalogAlreadyInstalled> {
121    harn_stdlib_catalog::install(&CATALOG)
122}
123
124pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
125    CATALOG.source(module)
126}
127
128/// Find an embedded CLI subcommand script by name. Returns the embedded
129/// source string when present, or `None` if no script with that name is
130/// registered in [`CATALOG`].
131pub fn find_cli_script(name: &str) -> Option<&'static str> {
132    CATALOG.cli_script(name)
133}
134
135pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
136    CATALOG.prompt_asset(path)
137}
138
139pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
140    let Some(source) = get_stdlib_source(module) else {
141        return Vec::new();
142    };
143    public_functions_from_source(source)
144}
145
146pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
147    CATALOG
148        .sources
149        .iter()
150        .filter_map(|entry| {
151            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
152                import_path: format!("std/{}", entry.module),
153                category,
154            })
155        })
156        .collect()
157}
158
159fn entrypoint_category_from_source(source: &str) -> Option<String> {
160    for line in source.lines() {
161        let line = line.trim();
162        if line.is_empty() {
163            continue;
164        }
165        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
166            let category = category.trim();
167            return (!category.is_empty()).then(|| category.to_string());
168        }
169        if !line.starts_with("//") {
170            return None;
171        }
172    }
173    None
174}
175
176fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
177    let mut out = Vec::new();
178    let mut doc: Option<String> = None;
179    let lines = source.lines().collect::<Vec<_>>();
180    let mut index = 0usize;
181    while index < lines.len() {
182        let line = lines[index].trim();
183        if line.starts_with("/**") {
184            let (parsed, next) = parse_harndoc(&lines, index);
185            doc = parsed;
186            index = next;
187            continue;
188        }
189        if line.starts_with("pub fn ") {
190            let (signature_line, next) = collect_public_function_signature(&lines, index);
191            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
192                out.push(function);
193                index = next;
194                continue;
195            }
196        }
197        if let Some(function) = parse_public_function_line(line, doc.take()) {
198            out.push(function);
199        } else if !line.is_empty() && !line.starts_with("//") {
200            doc = None;
201        }
202        index += 1;
203    }
204    out
205}
206
207fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
208    let mut parts = Vec::new();
209    let mut index = start;
210    while index < lines.len() {
211        parts.push(lines[index].trim().to_string());
212        let candidate = parts.join(" ");
213        if public_function_signature_complete(&candidate) {
214            return (candidate, index + 1);
215        }
216        index += 1;
217    }
218    (parts.join(" "), index)
219}
220
221fn public_function_signature_complete(line: &str) -> bool {
222    let Some(rest) = line.strip_prefix("pub fn ") else {
223        return false;
224    };
225    let Some((_, after_paren)) = rest.split_once('(') else {
226        return false;
227    };
228    matching_paren_len(after_paren).is_some()
229}
230
231fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
232    let mut parts = Vec::new();
233    let mut index = start;
234    while index < lines.len() {
235        let mut line = lines[index].trim();
236        if index == start {
237            line = line.trim_start_matches("/**").trim();
238        }
239        let done = line.ends_with("*/");
240        line = line.trim_end_matches("*/").trim();
241        line = line.trim_start_matches('*').trim();
242        if !line.is_empty() {
243            parts.push(line.to_string());
244        }
245        index += 1;
246        if done {
247            break;
248        }
249    }
250    let text = parts.join("\n").trim().to_string();
251    ((!text.is_empty()).then_some(text), index)
252}
253
254#[expect(
255    clippy::string_slice,
256    reason = "bounds come from str::find and char_indices"
257)]
258fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
259    let rest = line.strip_prefix("pub fn ")?.trim();
260    let name_end = rest.find('(')?;
261    let declaration_name = rest[..name_end].trim();
262    let name = declaration_name
263        .split_once('<')
264        .map_or(declaration_name, |(name, _)| name.trim());
265    if name.is_empty() {
266        return None;
267    }
268    let params_start = name_end + 1;
269    let params_len = matching_paren_len(&rest[params_start..])?;
270    let params = &rest[params_start..params_start + params_len];
271    let after = rest[params_start + params_len + 1..].trim();
272    let return_type = after
273        .strip_prefix("->")
274        .and_then(|tail| tail.split('{').next())
275        .map(str::trim)
276        .filter(|value| !value.is_empty());
277    let signature = match return_type {
278        Some(ret) => format!("{declaration_name}({params}) -> {ret}"),
279        None => format!("{declaration_name}({params})"),
280    };
281    let param_parts = split_top_level_params(params);
282    let total_params = param_parts
283        .iter()
284        .filter(|param| !param.trim().is_empty())
285        .count();
286    let variadic = param_parts
287        .iter()
288        .any(|param| param.trim_start().starts_with("..."));
289    let required_params = param_parts
290        .iter()
291        .filter(|param| {
292            let param = param.trim();
293            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
294        })
295        .count();
296    Some(StdlibPublicFunction {
297        name: name.to_string(),
298        signature,
299        required_params,
300        total_params,
301        variadic,
302        doc,
303    })
304}
305
306fn matching_paren_len(input: &str) -> Option<usize> {
307    let mut depth = 1usize;
308    for (offset, ch) in input.char_indices() {
309        match ch {
310            '(' | '[' | '{' => depth += 1,
311            ')' | ']' | '}' => {
312                depth = depth.saturating_sub(1);
313                if depth == 0 {
314                    return Some(offset);
315                }
316            }
317            _ => {}
318        }
319    }
320    None
321}
322
323#[expect(
324    clippy::string_slice,
325    reason = "offsets come from char_indices and 1-byte ','"
326)]
327fn split_top_level_params(params: &str) -> Vec<&str> {
328    let mut out = Vec::new();
329    let mut depth = 0isize;
330    let mut start = 0usize;
331    for (offset, ch) in params.char_indices() {
332        match ch {
333            '(' | '[' | '{' => depth += 1,
334            ')' | ']' | '}' => depth -= 1,
335            ',' if depth == 0 => {
336                out.push(&params[start..offset]);
337                start = offset + 1;
338            }
339            _ => {}
340        }
341    }
342    out.push(&params[start..]);
343    out
344}
345
346#[cfg(test)]
347mod tests {
348    use std::collections::BTreeSet;
349
350    use super::{
351        entrypoint_modules, get_stdlib_prompt_asset, matching_paren_len,
352        parse_public_function_line, public_functions_for_module, CATALOG,
353    };
354
355    #[test]
356    fn stdlib_sources_are_non_empty() {
357        for entry in CATALOG.sources {
358            assert!(
359                !entry.source.trim().is_empty(),
360                "{} should have non-empty source",
361                entry.module
362            );
363        }
364    }
365
366    #[test]
367    fn cli_scripts_are_non_empty_and_uniquely_named() {
368        let mut seen = BTreeSet::new();
369        for entry in CATALOG.cli_scripts {
370            assert!(
371                !entry.source.trim().is_empty(),
372                "cli/{} should have non-empty source",
373                entry.name
374            );
375            assert!(
376                seen.insert(entry.name),
377                "cli/{} is registered more than once in CATALOG.cli_scripts",
378                entry.name
379            );
380        }
381    }
382
383    #[test]
384    fn stdlib_source_names_are_unique() {
385        let mut names = BTreeSet::new();
386        for entry in CATALOG.sources {
387            assert!(names.insert(entry.module), "duplicate {}", entry.module);
388        }
389    }
390
391    #[test]
392    fn stdlib_prompt_assets_are_non_empty() {
393        for entry in CATALOG.prompt_assets {
394            assert!(
395                !entry.source.trim().is_empty(),
396                "{} should have non-empty prompt asset source",
397                entry.path
398            );
399        }
400    }
401
402    #[test]
403    fn stdlib_prompt_asset_paths_are_unique() {
404        let mut paths = BTreeSet::new();
405        for entry in CATALOG.prompt_assets {
406            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
407        }
408    }
409
410    #[test]
411    fn key_stdlib_prompt_assets_resolve() {
412        for path in [
413            "std/agent/prompts/tool_contract_text.harn.prompt",
414            "std/agent/prompts/default_nudge.harn.prompt",
415            "std/agent/prompts/completion_judge_default.harn.prompt",
416            "std/llm/prompts/directive_envelope_instructions.harn.prompt",
417            "std/llm/prompts/directive_nonce_authority.harn.prompt",
418            "std/workflow/prompts/stage.harn.prompt",
419            "std/orchestration/prompts/compaction_summary.harn.prompt",
420            "std/orchestration/prompts/compaction_policy_extension.harn.prompt",
421            "std/orchestration/prompts/compaction_policy_replacement.harn.prompt",
422            "std/orchestration/prompts/compaction_state_grounding.harn.prompt",
423        ] {
424            assert!(
425                get_stdlib_prompt_asset(path).is_some(),
426                "{path} should resolve"
427            );
428        }
429    }
430
431    #[test]
432    fn public_function_catalog_derives_signatures_from_harn_source() {
433        let exports = public_functions_for_module("workflow/execute");
434        assert_eq!(exports.len(), 1);
435        assert_eq!(exports[0].name, "workflow_execute");
436        assert_eq!(
437            exports[0].signature,
438            "workflow_execute( harness: Harness, task: string, graph: dict, artifacts: list<unknown>? = nil, options: dict? = nil, )"
439        );
440        assert_eq!(exports[0].required_params, 3);
441        assert_eq!(exports[0].total_params, 5);
442    }
443
444    #[test]
445    fn tool_registry_from_catalog_includes_cli_metadata_parameter() {
446        let function = public_functions_for_module("tools")
447            .into_iter()
448            .find(|function| function.name == "tool_registry_from")
449            .expect("std/tools should export tool_registry_from");
450        assert_eq!(function.required_params, 1);
451        assert_eq!(function.total_params, 2);
452        assert!(function
453            .signature
454            .contains("options: ToolRegistryOptions? = nil"));
455    }
456
457    #[test]
458    fn pace_cut_rule_module_owns_public_functions() {
459        let cut_rule_exports = public_functions_for_module("agent/cut_rules")
460            .into_iter()
461            .map(|function| function.name)
462            .collect::<BTreeSet<_>>();
463        for name in [
464            "pace_cut_rule_action_of",
465            "pace_cut_rule_check_max_injections",
466            "pace_cut_rule_decision",
467            "pace_cut_rule_extend_max",
468        ] {
469            assert!(
470                cut_rule_exports.contains(name),
471                "std/agent/cut_rules should export {name}"
472            );
473        }
474    }
475
476    #[test]
477    fn command_stdlib_module_exports_step_helpers() {
478        let exports = public_functions_for_module("command")
479            .into_iter()
480            .map(|function| function.name)
481            .collect::<BTreeSet<_>>();
482        for name in [
483            "command_run",
484            "command_wait",
485            "command_wait_for_output",
486            "command_cancel",
487            "command_run_streaming",
488            "command_output_tail",
489            "command_json",
490            "command_json_step",
491            "command_try",
492            "command_step",
493            "command_steps_append",
494            "command_last_failed_step",
495            "command_step_ref",
496            "command_output_text",
497            "argv_label",
498            "shell_command_from_argv",
499            "shell_command_from_value",
500        ] {
501            assert!(exports.contains(name), "std/command should export {name}");
502        }
503    }
504
505    #[test]
506    fn disclosure_stdlib_module_exports_render_helpers() {
507        let exports = public_functions_for_module("disclosure")
508            .into_iter()
509            .map(|function| function.name)
510            .collect::<BTreeSet<_>>();
511        assert!(
512            exports.contains("render"),
513            "std/disclosure should export render"
514        );
515        assert!(
516            exports.contains("git_trailers"),
517            "std/disclosure should export git_trailers"
518        );
519        assert!(
520            exports.contains("slack_message_disclosure"),
521            "std/disclosure should export slack_message_disclosure"
522        );
523        assert!(
524            exports.contains("append_git_trailers"),
525            "std/disclosure should export append_git_trailers"
526        );
527    }
528
529    #[test]
530    fn async_stdlib_exports_predicate_backoff_name_only() {
531        let exports = public_functions_for_module("async")
532            .into_iter()
533            .map(|function| function.name)
534            .collect::<BTreeSet<_>>();
535        assert!(
536            exports.contains("retry_predicate_with_backoff"),
537            "std/async should export retry_predicate_with_backoff"
538        );
539        assert!(
540            !exports.contains("retry_with_backoff"),
541            "std/async should not retain the old retry_with_backoff export"
542        );
543    }
544
545    #[test]
546    fn signal_stdlib_module_exports_interrupt_helpers() {
547        let exports = public_functions_for_module("signal")
548            .into_iter()
549            .map(|function| function.name)
550            .collect::<BTreeSet<_>>();
551        for name in [
552            "on_interrupt",
553            "off_interrupt",
554            "interrupted",
555            "with_interrupt",
556        ] {
557            assert!(exports.contains(name), "std/signal should export {name}");
558        }
559    }
560
561    #[test]
562    fn git_stdlib_module_exports_local_wrappers() {
563        let exports = public_functions_for_module("git")
564            .into_iter()
565            .map(|function| function.name)
566            .collect::<BTreeSet<_>>();
567        for name in [
568            "git_run",
569            "git_status",
570            "git_current_branch",
571            "git_log",
572            "git_switch",
573            "git_pull_ff_only",
574            "git_find_tool",
575            "git_run_tool",
576            "git_tools",
577            "git_toolbox_tools",
578        ] {
579            assert!(exports.contains(name), "std/git should export {name}");
580        }
581    }
582
583    #[test]
584    fn agent_workers_exports_suspend_resume_wrappers() {
585        let exports = public_functions_for_module("agent/workers");
586        let suspend = exports
587            .iter()
588            .find(|function| function.name == "suspend_agent")
589            .expect("std/agent/workers should export suspend_agent");
590        assert_eq!(
591            suspend.signature,
592            "suspend_agent( agents: HarnessAgent, worker: unknown, reason: string = \"\", options: dict? = nil, ) -> unknown"
593        );
594        assert_eq!(suspend.required_params, 2);
595        assert_eq!(suspend.total_params, 4);
596
597        let resume = exports
598            .iter()
599            .find(|function| function.name == "resume_agent")
600            .expect("std/agent/workers should export resume_agent");
601        assert_eq!(
602            resume.signature,
603            "resume_agent( agents: HarnessAgent, worker_or_snapshot: unknown, resume_input: unknown = nil, continue_transcript: bool = true, ) -> unknown"
604        );
605        assert_eq!(resume.required_params, 2);
606        assert_eq!(resume.total_params, 4);
607
608        let stop = exports
609            .iter()
610            .find(|function| function.name == "agent_stop")
611            .expect("std/agent/workers should export agent_stop");
612        assert_eq!(
613            stop.signature,
614            "agent_stop( agents: HarnessAgent, worker: unknown, options: AgentStopOptions? = nil, ) -> unknown"
615        );
616        assert_eq!(stop.required_params, 2);
617        assert_eq!(stop.total_params, 3);
618
619        let parse_resume = exports
620            .iter()
621            .find(|function| function.name == "parse_resume_conditions")
622            .expect("std/agent/workers should export parse_resume_conditions");
623        assert_eq!(
624            parse_resume.signature,
625            "parse_resume_conditions( agents: HarnessAgent, conditions: ResumeConditions? = nil, ) -> ResumeConditions?"
626        );
627        assert_eq!(parse_resume.required_params, 1);
628        assert_eq!(parse_resume.total_params, 2);
629
630        let lifecycle = exports
631            .iter()
632            .find(|function| function.name == "agent_lifecycle_tools")
633            .expect("std/agent/workers should export agent_lifecycle_tools");
634        assert_eq!(
635            lifecycle.signature,
636            "agent_lifecycle_tools( agents: HarnessAgent, registry: ToolRegistry? = nil, options: AgentLifecycleToolsOptions? = nil, ) -> ToolRegistry"
637        );
638        assert_eq!(lifecycle.required_params, 1);
639        assert_eq!(lifecycle.total_params, 3);
640    }
641
642    #[test]
643    fn tui_stdlib_module_exports_terminal_helpers() {
644        let exports = public_functions_for_module("tui")
645            .into_iter()
646            .map(|function| function.name)
647            .collect::<BTreeSet<_>>();
648        for name in ["page", "terminal_width", "rule", "clear", "select_from"] {
649            assert!(exports.contains(name), "std/tui should export {name}");
650        }
651    }
652
653    #[test]
654    fn semver_stdlib_module_exports_release_helpers() {
655        let exports = public_functions_for_module("semver")
656            .into_iter()
657            .map(|function| function.name)
658            .collect::<BTreeSet<_>>();
659        for name in [
660            "strip_v",
661            "add_v",
662            "is_v_semver",
663            "is_v_release_semver",
664            "parse",
665            "parse_release",
666            "is_prerelease_identifier",
667            "is_prerelease",
668            "compare_release",
669            "max_canonical_tag",
670            "next",
671            "bump_type",
672            "version_from_release_branch",
673            "version_from_tag",
674        ] {
675            assert!(exports.contains(name), "std/semver should export {name}");
676        }
677    }
678
679    #[test]
680    fn changelog_stdlib_module_exports_typed_primitives() {
681        let exports = public_functions_for_module("changelog")
682            .into_iter()
683            .map(|function| function.name)
684            .collect::<BTreeSet<_>>();
685        for name in [
686            "changelog_validate_categories",
687            "changelog_parse_fragment",
688            "changelog_order_fragments",
689            "changelog_normalize_fragment_body",
690            "changelog_assemble_fragments",
691            "changelog_parse_sections",
692            "changelog_find_section",
693            "changelog_merge_unreleased",
694        ] {
695            assert!(exports.contains(name), "std/changelog should export {name}");
696        }
697    }
698
699    #[test]
700    fn text_stdlib_module_exports_regex_and_pad_helpers() {
701        let exports = public_functions_for_module("text")
702            .into_iter()
703            .map(|function| function.name)
704            .collect::<BTreeSet<_>>();
705        for name in [
706            "pad_left",
707            "pad_right",
708            "repeat_string",
709            "regex_first_capture",
710            "regex_capture_groups",
711            "regex_all_first_captures",
712        ] {
713            assert!(exports.contains(name), "std/text should export {name}");
714        }
715    }
716
717    #[test]
718    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
719        let modules = entrypoint_modules();
720        let entries = modules
721            .iter()
722            .map(|module| (module.import_path.as_str(), module.category.as_str()))
723            .collect::<BTreeSet<_>>();
724        for entry in [
725            ("std/agent/loop", "agent.stdlib"),
726            ("std/agent/primitives", "agent.stdlib"),
727            ("std/workflow/execute", "workflow.stdlib"),
728        ] {
729            assert!(entries.contains(&entry), "{entry:?} should be declared");
730        }
731    }
732
733    #[test]
734    fn matching_paren_len_closes_on_every_bracket_kind() {
735        // Each closer kind must terminate the scan once depth returns to zero,
736        // mirroring the symmetric opener arm and `split_top_level_params`.
737        assert_eq!(matching_paren_len("a, b)"), Some(4));
738        assert_eq!(matching_paren_len("x: [int])"), Some(8));
739        assert_eq!(matching_paren_len("x: {a: int})"), Some(11));
740        // A top-level `]`/`}` is the matching close for the consumed opener and
741        // must return rather than scanning to the end and yielding `None`.
742        assert_eq!(matching_paren_len("x]"), Some(1));
743        assert_eq!(matching_paren_len("x}"), Some(1));
744        assert_eq!(matching_paren_len("unterminated"), None);
745    }
746
747    #[test]
748    fn parse_public_function_line_handles_record_typed_params() {
749        let parsed =
750            parse_public_function_line("pub fn configure(opts: {retries: int}) -> bool", None)
751                .expect("signature with a record-typed parameter should parse");
752        assert_eq!(parsed.name, "configure");
753        assert_eq!(parsed.signature, "configure(opts: {retries: int}) -> bool");
754        assert_eq!(parsed.total_params, 1);
755        assert_eq!(parsed.required_params, 1);
756    }
757
758    #[test]
759    fn parse_public_function_line_indexes_generic_functions_by_base_name() {
760        let parsed = parse_public_function_line(
761            "pub fn map<T, U>(items: list<T>, project: fn(T) -> U) -> list<U>",
762            None,
763        )
764        .expect("generic public function should parse");
765        assert_eq!(parsed.name, "map");
766        assert_eq!(
767            parsed.signature,
768            "map<T, U>(items: list<T>, project: fn(T) -> U) -> list<U>"
769        );
770        assert_eq!(parsed.total_params, 2);
771        assert_eq!(parsed.required_params, 2);
772    }
773}