Skip to main content

harn_parser/
lib.rs

1pub mod acp_ambient_globals;
2pub mod analysis;
3mod ast;
4pub mod ast_json;
5pub mod builtin_signatures;
6pub mod const_eval;
7pub mod diagnostic;
8pub mod diagnostic_codes;
9pub mod interpolation;
10pub mod lexical;
11mod namespace_demand;
12pub mod param_annotations;
13mod parser;
14pub mod stdlib_metadata;
15pub mod typechecker;
16pub mod visit;
17
18pub use ast::*;
19pub use diagnostic_codes::{
20    Category as DiagnosticCodeCategory, Code as DiagnosticCode, ParseRepairSafetyError, Repair,
21    RepairId, RepairSafety, RepairTemplate, REPAIR_REGISTRY,
22};
23pub use namespace_demand::{namespace_import_demands, NamespaceDemand};
24pub use parser::*;
25pub use stdlib_metadata::{
26    parse_for_span as parse_stdlib_metadata, synthesize_example, StdlibMetadata,
27};
28pub use typechecker::{
29    block_definitely_exits, format_type, stmt_definitely_exits, substitute_type_expr,
30    BindingTypeInfo, DiagnosticDetails, DiagnosticSeverity, InlayHintInfo, NamespaceImportBinding,
31    TypeCheckFacts, TypeChecker, TypeDiagnostic,
32};
33
34pub use builtin_signatures::install_builtin_manifest;
35
36/// Explicit process-level bridge for downstream packages that have not yet
37/// completed the typed `Harness` capability migration.
38///
39/// The bridge is intentionally opt-in and keeps the strict source surface as
40/// the default. Defining the variable is not enough: it must be set to one of
41/// `1`, `true`, `yes`, or `on`, so an empty or `0` value leaves strict
42/// enforcement in place.
43pub const HARN_LEGACY_AMBIENT_CAPABILITIES_ENV: &str = "HARN_LEGACY_AMBIENT_CAPABILITIES";
44
45/// Cached parse of [`HARN_LEGACY_AMBIENT_CAPABILITIES_ENV`].
46///
47/// `0` = not read yet, `1` = disabled, `2` = enabled. The bridge flag is
48/// consulted on every builtin-name lookup the type checker performs, and
49/// `getenv` rescans the whole process environment per call — measurably hot
50/// on whole-file typechecks. A process cannot have its environment changed
51/// from outside once started, so one read is authoritative; the only writers
52/// are tests, which go through [`refresh_legacy_ambient_capabilities`].
53static LEGACY_AMBIENT_CAPABILITIES: std::sync::atomic::AtomicU8 =
54    std::sync::atomic::AtomicU8::new(0);
55
56pub fn legacy_ambient_capabilities_enabled() -> bool {
57    match LEGACY_AMBIENT_CAPABILITIES.load(std::sync::atomic::Ordering::Relaxed) {
58        1 => false,
59        2 => true,
60        _ => refresh_legacy_ambient_capabilities(),
61    }
62}
63
64/// Re-read the legacy-bridge flag from the process environment and update the
65/// cached value, returning the fresh result.
66///
67/// Only needed by code that mutates `HARN_LEGACY_AMBIENT_CAPABILITIES` inside
68/// the running process — in practice, tests. Call it after every
69/// `set_var`/`remove_var` of the flag so later reads observe the change.
70pub fn refresh_legacy_ambient_capabilities() -> bool {
71    let enabled = std::env::var_os(HARN_LEGACY_AMBIENT_CAPABILITIES_ENV).is_some_and(|value| {
72        value.to_str().is_some_and(|value| {
73            matches!(
74                value.trim().to_ascii_lowercase().as_str(),
75                "1" | "true" | "yes" | "on"
76            )
77        })
78    });
79    LEGACY_AMBIENT_CAPABILITIES.store(
80        if enabled { 2 } else { 1 },
81        std::sync::atomic::Ordering::Relaxed,
82    );
83    enabled
84}
85
86/// Whether an old hostlib wire name projects a method from the authoritative
87/// typed host-capability registry. This keeps compatibility recognition exact:
88/// arbitrary `hostlib_*` spellings remain undefined.
89pub fn is_registered_legacy_hostlib_name(name: &str) -> bool {
90    if name == "hostlib_enable" {
91        return true;
92    }
93    harn_builtin_meta::host_capabilities::capability_binding_for_legacy_hostlib_name(name).is_some()
94}
95
96/// Exact behavior-preserving spellings removed during the typed-Harness
97/// cutover. The compiler lowers these to the canonical manifest name only in
98/// compatibility mode; strict source continues to reject them.
99pub fn legacy_builtin_alias_target(name: &str) -> Option<&'static str> {
100    match name {
101        "regex_replace_all" => Some("regex_replace"),
102        "task_current" => Some("runtime_context"),
103        _ => None,
104    }
105}
106
107/// Host operations the embedding project declared, as `(capability, method)`.
108///
109/// A host registers these at runtime, so no static contract in this workspace
110/// owns them and the capability-method check would otherwise report every one
111/// as undeclared. `[check].host_capabilities` / `host_capabilities_path` is
112/// exactly that declaration, so the command that resolves it installs it here
113/// and the checker treats the pair as known.
114static DECLARED_HOST_OPERATIONS: std::sync::RwLock<
115    Option<std::collections::HashSet<(String, String)>>,
116> = std::sync::RwLock::new(None);
117
118/// Install the resolved host-capability declaration for this process.
119///
120/// Entries accumulate rather than replace: one invocation may check files that
121/// resolve different manifests, and dropping the earlier set would make the
122/// diagnostic depend on file ordering.
123pub fn install_declared_host_operations<I, C, M>(operations: I)
124where
125    I: IntoIterator<Item = (C, M)>,
126    C: Into<String>,
127    M: Into<String>,
128{
129    let Ok(mut guard) = DECLARED_HOST_OPERATIONS.write() else {
130        return;
131    };
132    let declared = guard.get_or_insert_with(std::collections::HashSet::new);
133    for (capability, method) in operations {
134        declared.insert((capability.into(), method.into()));
135    }
136}
137
138/// Did the embedding project declare `capability.method` as a host operation?
139pub fn is_declared_host_operation(capability: &str, method: &str) -> bool {
140    DECLARED_HOST_OPERATIONS
141        .read()
142        .ok()
143        .and_then(|guard| {
144            guard
145                .as_ref()
146                .map(|declared| declared.contains(&(capability.to_string(), method.to_string())))
147        })
148        .unwrap_or(false)
149}
150
151/// Returns `true` if `name` is a builtin recognized by the parser's static analyzer.
152pub fn is_known_builtin(name: &str) -> bool {
153    builtin_signatures::is_builtin(name)
154}
155
156/// Opt-in ambient bridge: treat a registered builtin as known without a typed
157/// `Harness` capability import.
158pub fn is_legacy_ambient_builtin(name: &str) -> bool {
159    legacy_ambient_capabilities_enabled() && is_known_builtin(name)
160}
161
162/// Every builtin name known to the parser, alphabetically. Enables bidirectional
163/// drift checks against the VM's runtime registry.
164pub fn known_builtin_names() -> impl Iterator<Item = &'static str> {
165    builtin_signatures::iter_builtin_names()
166}
167
168pub fn known_builtin_metadata() -> impl Iterator<Item = builtin_signatures::BuiltinMetadata> {
169    builtin_signatures::iter_builtin_metadata()
170}
171
172/// Names sourced only from the parser's hand-written static fallback tables
173/// (not the driver-installed `#[harn_builtin]` registry). Lets cross-crate
174/// drift guards assert the static tables don't overlap with macro-published
175/// or `runtime_only` builtins.
176pub fn static_signature_names() -> impl Iterator<Item = &'static str> {
177    builtin_signatures::static_signature_names()
178}
179
180/// Error from a source processing pipeline stage. Wraps the inner error
181/// types so callers can dispatch on the failing stage.
182#[derive(Debug)]
183pub enum PipelineError {
184    Lex(harn_lexer::LexerError),
185    Parse(ParserError),
186    /// Boxed to keep the enum small on the stack — TypeDiagnostic contains
187    /// a Vec<FixEdit>.
188    TypeCheck(Box<TypeDiagnostic>),
189}
190
191impl std::fmt::Display for PipelineError {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        match self {
194            PipelineError::Lex(e) => e.fmt(f),
195            PipelineError::Parse(e) => e.fmt(f),
196            PipelineError::TypeCheck(diag) => write!(f, "type error: {}", diag.message),
197        }
198    }
199}
200
201impl std::error::Error for PipelineError {}
202
203impl From<harn_lexer::LexerError> for PipelineError {
204    fn from(e: harn_lexer::LexerError) -> Self {
205        PipelineError::Lex(e)
206    }
207}
208
209impl From<ParserError> for PipelineError {
210    fn from(e: ParserError) -> Self {
211        PipelineError::Parse(e)
212    }
213}
214
215impl PipelineError {
216    /// Extract the source span, if any, for diagnostic rendering.
217    pub fn span(&self) -> Option<&harn_lexer::Span> {
218        match self {
219            PipelineError::Lex(e) => match e {
220                harn_lexer::LexerError::UnexpectedCharacter(_, span)
221                | harn_lexer::LexerError::UnterminatedString(span)
222                | harn_lexer::LexerError::IntegerLiteralOutOfRange(_, span)
223                | harn_lexer::LexerError::UnterminatedBlockComment(span) => Some(span),
224            },
225            PipelineError::Parse(e) => match e {
226                ParserError::Unexpected { span, .. } => Some(span),
227                ParserError::UnexpectedEof { span, .. } => Some(span),
228            },
229            PipelineError::TypeCheck(diag) => diag.span.as_ref(),
230        }
231    }
232}
233
234/// Lex and parse source into an AST.
235pub fn parse_source(source: &str) -> Result<Vec<SNode>, PipelineError> {
236    let mut lexer = harn_lexer::Lexer::new(source);
237    let tokens = lexer.tokenize()?;
238    let mut parser = Parser::new(tokens);
239    Ok(parser.parse()?)
240}
241
242/// Lex, parse, and type-check source. Returns the AST and any type
243/// diagnostics (which may include warnings even on success).
244pub fn check_source(source: &str) -> Result<(Vec<SNode>, Vec<TypeDiagnostic>), PipelineError> {
245    let program = parse_source(source)?;
246    let diagnostics = TypeChecker::new().check_with_source(&program, source);
247    Ok((program, diagnostics))
248}
249
250/// Lex, parse, and type-check, bailing on the first type error.
251pub fn check_source_strict(source: &str) -> Result<Vec<SNode>, PipelineError> {
252    let (program, diagnostics) = check_source(source)?;
253    for diag in &diagnostics {
254        if diag.severity == DiagnosticSeverity::Error {
255            return Err(PipelineError::TypeCheck(Box::new(diag.clone())));
256        }
257    }
258    Ok(program)
259}
260
261#[cfg(test)]
262mod pipeline_tests {
263    use super::*;
264
265    #[test]
266    fn parse_source_valid() {
267        let program = parse_source("const x = 1").unwrap();
268        assert!(!program.is_empty());
269    }
270
271    #[test]
272    fn parse_source_lex_error() {
273        let err = parse_source("let x = `").unwrap_err();
274        assert!(matches!(err, PipelineError::Lex(_)));
275        assert!(err.span().is_some());
276        assert!(err.to_string().contains("Unexpected character"));
277    }
278
279    #[test]
280    fn parse_source_parse_error() {
281        let err = parse_source("let = 1").unwrap_err();
282        assert!(matches!(err, PipelineError::Parse(_)));
283        assert!(err.span().is_some());
284    }
285
286    #[test]
287    fn check_source_returns_diagnostics() {
288        let (program, _diagnostics) = check_source("const x = 1").unwrap();
289        assert!(!program.is_empty());
290    }
291
292    #[test]
293    fn check_source_strict_passes_valid_code() {
294        let program = check_source_strict("const x = 1\nlog(x)").unwrap();
295        assert!(!program.is_empty());
296    }
297
298    #[test]
299    fn check_source_strict_catches_lex_error() {
300        let err = check_source_strict("`").unwrap_err();
301        assert!(matches!(err, PipelineError::Lex(_)));
302    }
303
304    #[test]
305    fn pipeline_error_display_is_informative() {
306        let err = parse_source("`").unwrap_err();
307        let msg = err.to_string();
308        assert!(!msg.is_empty());
309        assert!(msg.contains('`') || msg.contains("Unexpected"));
310    }
311
312    #[test]
313    fn pipeline_error_size_is_bounded() {
314        // TypeCheck is boxed; guard against accidental growth of the other variants.
315        assert!(
316            std::mem::size_of::<PipelineError>() <= 96,
317            "PipelineError grew to {} bytes — consider boxing large variants",
318            std::mem::size_of::<PipelineError>()
319        );
320    }
321
322    #[test]
323    fn legacy_hostlib_names_must_resolve_through_the_typed_registry() {
324        assert!(is_registered_legacy_hostlib_name(
325            "hostlib_terminal_session_capture"
326        ));
327        assert!(is_registered_legacy_hostlib_name(
328            "hostlib_code_index_agent_heartbeat"
329        ));
330        assert!(is_registered_legacy_hostlib_name("hostlib_enable"));
331        assert!(!is_registered_legacy_hostlib_name(
332            "hostlib_terminal_session_not_registered"
333        ));
334        assert!(!is_registered_legacy_hostlib_name("hostlib_unknown_ping"));
335    }
336}