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
36pub const HARN_LEGACY_AMBIENT_CAPABILITIES_ENV: &str = "HARN_LEGACY_AMBIENT_CAPABILITIES";
44
45static 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
64pub 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
86pub 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
96pub 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
107static DECLARED_HOST_OPERATIONS: std::sync::RwLock<
115 Option<std::collections::HashSet<(String, String)>>,
116> = std::sync::RwLock::new(None);
117
118pub 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
138pub 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
151pub fn is_known_builtin(name: &str) -> bool {
153 builtin_signatures::is_builtin(name)
154}
155
156pub fn is_legacy_ambient_builtin(name: &str) -> bool {
159 legacy_ambient_capabilities_enabled() && is_known_builtin(name)
160}
161
162pub 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
172pub fn static_signature_names() -> impl Iterator<Item = &'static str> {
177 builtin_signatures::static_signature_names()
178}
179
180#[derive(Debug)]
183pub enum PipelineError {
184 Lex(harn_lexer::LexerError),
185 Parse(ParserError),
186 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 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
234pub 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
242pub 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
250pub 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 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}