Skip to main content

harn_parser/
lib.rs

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