1use harn_parser::{Node, SNode, TypeExpr};
2
3mod closures;
4mod concurrency;
5mod decls;
6mod error;
7mod error_handling;
8mod expressions;
9mod patterns;
10mod pipe;
11mod state;
12mod statements;
13#[cfg(test)]
14mod tests;
15mod type_facts;
16mod yield_scan;
17
18pub use error::CompileError;
19
20use crate::chunk::{Chunk, Constant, Op};
21
22fn peel_node(sn: &SNode) -> &Node {
26 match &sn.node {
27 Node::AttributedDecl { inner, .. } => &inner.node,
28 other => other,
29 }
30}
31
32#[derive(Clone, Debug)]
35enum FinallyEntry {
36 Finally(Vec<SNode>),
37 CatchBarrier,
38}
39
40struct LoopContext {
42 start_offset: usize,
44 break_patches: Vec<usize>,
46 has_iterator: bool,
48 handler_depth: usize,
50 finally_depth: usize,
52 scope_depth: usize,
54}
55
56#[derive(Clone, Copy, Debug)]
57struct LocalBinding {
58 slot: u16,
59 mutable: bool,
60}
61
62pub struct Compiler {
64 chunk: Chunk,
65 line: u32,
66 column: u32,
67 enum_names: std::collections::HashSet<String>,
69 struct_layouts: std::collections::HashMap<String, Vec<String>>,
71 interface_methods: std::collections::HashMap<String, Vec<String>>,
73 loop_stack: Vec<LoopContext>,
75 handler_depth: usize,
77 finally_bodies: Vec<FinallyEntry>,
89 temp_counter: usize,
91 scope_depth: usize,
93 type_aliases: std::collections::HashMap<String, TypeExpr>,
96 type_scopes: Vec<std::collections::HashMap<String, TypeExpr>>,
101 local_scopes: Vec<std::collections::HashMap<String, LocalBinding>>,
105 module_level: bool,
111}
112
113impl Compiler {
114 fn compile_node(&mut self, snode: &SNode) -> Result<(), CompileError> {
118 self.line = snode.span.line as u32;
119 self.column = snode.span.column as u32;
120 self.chunk.set_column(self.column);
121 match &snode.node {
122 Node::IntLiteral(n) => {
123 let idx = self.chunk.add_constant(Constant::Int(*n));
124 self.chunk.emit_u16(Op::Constant, idx, self.line);
125 }
126 Node::FloatLiteral(n) => {
127 let idx = self.chunk.add_constant(Constant::Float(*n));
128 self.chunk.emit_u16(Op::Constant, idx, self.line);
129 }
130 Node::StringLiteral(s) | Node::RawStringLiteral(s) => {
131 let idx = self.chunk.add_constant(Constant::String(s.clone()));
132 self.chunk.emit_u16(Op::Constant, idx, self.line);
133 }
134 Node::BoolLiteral(true) => self.chunk.emit(Op::True, self.line),
135 Node::BoolLiteral(false) => self.chunk.emit(Op::False, self.line),
136 Node::NilLiteral => self.chunk.emit(Op::Nil, self.line),
137 Node::DurationLiteral(ms) => {
138 let idx = self.chunk.add_constant(Constant::Duration(*ms));
139 self.chunk.emit_u16(Op::Constant, idx, self.line);
140 }
141 Node::Identifier(name) => {
142 self.emit_get_binding(name);
143 }
144 Node::LetBinding { pattern, value, .. } => {
145 let binding_type = match &snode.node {
146 Node::LetBinding {
147 type_ann: Some(type_ann),
148 ..
149 } => Some(type_ann.clone()),
150 _ => self.infer_expr_type(value),
151 };
152 self.compile_node(value)?;
153 self.compile_destructuring(pattern, false)?;
154 self.record_binding_type(pattern, binding_type);
155 }
156 Node::VarBinding { pattern, value, .. } => {
157 let binding_type = match &snode.node {
158 Node::VarBinding {
159 type_ann: Some(type_ann),
160 ..
161 } => Some(type_ann.clone()),
162 _ => self.infer_expr_type(value),
163 };
164 self.compile_node(value)?;
165 self.compile_destructuring(pattern, true)?;
166 self.record_binding_type(pattern, binding_type);
167 }
168 Node::Assignment {
169 target, value, op, ..
170 } => {
171 self.compile_assignment(target, value, op)?;
172 }
173 Node::BinaryOp { op, left, right } => {
174 self.compile_binary_op(op, left, right)?;
175 }
176 Node::UnaryOp { op, operand } => {
177 self.compile_node(operand)?;
178 match op.as_str() {
179 "-" => self.chunk.emit(Op::Negate, self.line),
180 "!" => self.chunk.emit(Op::Not, self.line),
181 _ => {}
182 }
183 }
184 Node::Ternary {
185 condition,
186 true_expr,
187 false_expr,
188 } => {
189 self.compile_node(condition)?;
190 let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
191 self.chunk.emit(Op::Pop, self.line);
192 self.compile_node(true_expr)?;
193 let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
194 self.chunk.patch_jump(else_jump);
195 self.chunk.emit(Op::Pop, self.line);
196 self.compile_node(false_expr)?;
197 self.chunk.patch_jump(end_jump);
198 }
199 Node::FunctionCall { name, args } => {
200 self.compile_function_call(name, args)?;
201 }
202 Node::MethodCall {
203 object,
204 method,
205 args,
206 } => {
207 self.compile_method_call(object, method, args)?;
208 }
209 Node::OptionalMethodCall {
210 object,
211 method,
212 args,
213 } => {
214 self.compile_node(object)?;
215 for arg in args {
216 self.compile_node(arg)?;
217 }
218 let name_idx = self.chunk.add_constant(Constant::String(method.clone()));
219 self.chunk
220 .emit_method_call_opt(name_idx, args.len() as u8, self.line);
221 }
222 Node::PropertyAccess { object, property } => {
223 self.compile_property_access(object, property)?;
224 }
225 Node::OptionalPropertyAccess { object, property } => {
226 self.compile_node(object)?;
227 let idx = self.chunk.add_constant(Constant::String(property.clone()));
228 self.chunk.emit_u16(Op::GetPropertyOpt, idx, self.line);
229 }
230 Node::SubscriptAccess { object, index } => {
231 self.compile_node(object)?;
232 self.compile_node(index)?;
233 self.chunk.emit(Op::Subscript, self.line);
234 }
235 Node::SliceAccess { object, start, end } => {
236 self.compile_node(object)?;
237 if let Some(s) = start {
238 self.compile_node(s)?;
239 } else {
240 self.chunk.emit(Op::Nil, self.line);
241 }
242 if let Some(e) = end {
243 self.compile_node(e)?;
244 } else {
245 self.chunk.emit(Op::Nil, self.line);
246 }
247 self.chunk.emit(Op::Slice, self.line);
248 }
249 Node::IfElse {
250 condition,
251 then_body,
252 else_body,
253 } => {
254 self.compile_if_else(condition, then_body, else_body)?;
255 }
256 Node::WhileLoop { condition, body } => {
257 self.compile_while_loop(condition, body)?;
258 }
259 Node::ForIn {
260 pattern,
261 iterable,
262 body,
263 } => {
264 self.compile_for_in(pattern, iterable, body)?;
265 }
266 Node::ReturnStmt { value } => {
267 self.compile_return_stmt(value)?;
268 }
269 Node::BreakStmt => {
270 self.compile_break_stmt()?;
271 }
272 Node::ContinueStmt => {
273 self.compile_continue_stmt()?;
274 }
275 Node::ListLiteral(elements) => {
276 self.compile_list_literal(elements)?;
277 }
278 Node::DictLiteral(entries) => {
279 self.compile_dict_literal(entries)?;
280 }
281 Node::InterpolatedString(segments) => {
282 self.compile_interpolated_string(segments)?;
283 }
284 Node::FnDecl {
285 name, params, body, ..
286 } => {
287 self.compile_fn_decl(name, params, body)?;
288 }
289 Node::ToolDecl {
290 name,
291 description,
292 params,
293 return_type,
294 body,
295 ..
296 } => {
297 self.compile_tool_decl(name, description, params, return_type, body)?;
298 }
299 Node::SkillDecl { name, fields, .. } => {
300 self.compile_skill_decl(name, fields)?;
301 }
302 Node::Closure { params, body, .. } => {
303 self.compile_closure(params, body)?;
304 }
305 Node::ThrowStmt { value } => {
306 self.compile_throw_stmt(value)?;
307 }
308 Node::MatchExpr { value, arms } => {
309 self.compile_match_expr(value, arms)?;
310 }
311 Node::RangeExpr {
312 start,
313 end,
314 inclusive,
315 } => {
316 let name_idx = self
317 .chunk
318 .add_constant(Constant::String("__range__".to_string()));
319 self.chunk.emit_u16(Op::Constant, name_idx, self.line);
320 self.compile_node(start)?;
321 self.compile_node(end)?;
322 if *inclusive {
323 self.chunk.emit(Op::True, self.line);
324 } else {
325 self.chunk.emit(Op::False, self.line);
326 }
327 self.chunk.emit_u8(Op::Call, 3, self.line);
328 }
329 Node::GuardStmt {
330 condition,
331 else_body,
332 } => {
333 self.compile_guard_stmt(condition, else_body)?;
334 }
335 Node::RequireStmt { condition, message } => {
336 self.compile_node(condition)?;
337 let ok_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
338 self.chunk.emit(Op::Pop, self.line);
339 if let Some(message) = message {
340 self.compile_node(message)?;
341 } else {
342 let idx = self
343 .chunk
344 .add_constant(Constant::String("require condition failed".to_string()));
345 self.chunk.emit_u16(Op::Constant, idx, self.line);
346 }
347 self.chunk.emit(Op::Throw, self.line);
348 self.chunk.patch_jump(ok_jump);
349 self.chunk.emit(Op::Pop, self.line);
350 }
351 Node::Block(stmts) => {
352 self.compile_scoped_block(stmts)?;
353 }
354 Node::DeadlineBlock { duration, body } => {
355 self.compile_node(duration)?;
356 self.chunk.emit(Op::DeadlineSetup, self.line);
357 self.compile_scoped_block(body)?;
358 self.chunk.emit(Op::DeadlineEnd, self.line);
359 }
360 Node::MutexBlock { body } => {
361 self.begin_scope();
363 for sn in body {
364 self.compile_node(sn)?;
365 if Self::produces_value(&sn.node) {
366 self.chunk.emit(Op::Pop, self.line);
367 }
368 }
369 self.chunk.emit(Op::Nil, self.line);
370 self.end_scope();
371 }
372 Node::DeferStmt { body } => {
373 self.finally_bodies
375 .push(FinallyEntry::Finally(body.clone()));
376 self.chunk.emit(Op::Nil, self.line);
377 }
378 Node::YieldExpr { value } => {
379 if let Some(val) = value {
380 self.compile_node(val)?;
381 } else {
382 self.chunk.emit(Op::Nil, self.line);
383 }
384 self.chunk.emit(Op::Yield, self.line);
385 }
386 Node::EnumConstruct {
387 enum_name,
388 variant,
389 args,
390 } => {
391 self.compile_enum_construct(enum_name, variant, args)?;
392 }
393 Node::StructConstruct {
394 struct_name,
395 fields,
396 } => {
397 self.compile_struct_construct(struct_name, fields)?;
398 }
399 Node::ImportDecl { path } => {
400 let idx = self.chunk.add_constant(Constant::String(path.clone()));
401 self.chunk.emit_u16(Op::Import, idx, self.line);
402 }
403 Node::SelectiveImport { names, path } => {
404 let path_idx = self.chunk.add_constant(Constant::String(path.clone()));
405 let names_str = names.join(",");
406 let names_idx = self.chunk.add_constant(Constant::String(names_str));
407 self.chunk
408 .emit_u16(Op::SelectiveImport, path_idx, self.line);
409 let hi = (names_idx >> 8) as u8;
410 let lo = names_idx as u8;
411 self.chunk.code.push(hi);
412 self.chunk.code.push(lo);
413 self.chunk.lines.push(self.line);
414 self.chunk.columns.push(self.column);
415 self.chunk.lines.push(self.line);
416 self.chunk.columns.push(self.column);
417 }
418 Node::TryOperator { operand } => {
419 self.compile_node(operand)?;
420 self.chunk.emit(Op::TryUnwrap, self.line);
421 }
422 Node::TryStar { operand } => {
438 self.compile_try_star(operand)?;
439 }
440 Node::ImplBlock { type_name, methods } => {
441 self.compile_impl_block(type_name, methods)?;
442 }
443 Node::StructDecl { name, fields, .. } => {
444 self.compile_struct_decl(name, fields)?;
445 }
446 Node::Pipeline { .. }
448 | Node::OverrideDecl { .. }
449 | Node::TypeDecl { .. }
450 | Node::EnumDecl { .. }
451 | Node::InterfaceDecl { .. } => {
452 self.chunk.emit(Op::Nil, self.line);
453 }
454 Node::TryCatch {
455 body,
456 error_var,
457 error_type,
458 catch_body,
459 finally_body,
460 } => {
461 self.compile_try_catch(body, error_var, error_type, catch_body, finally_body)?;
462 }
463 Node::TryExpr { body } => {
464 self.compile_try_expr(body)?;
465 }
466 Node::Retry { count, body } => {
467 self.compile_retry(count, body)?;
468 }
469 Node::Parallel {
470 mode,
471 expr,
472 variable,
473 body,
474 options,
475 } => {
476 self.compile_parallel(mode, expr, variable, body, options)?;
477 }
478 Node::SpawnExpr { body } => {
479 self.compile_spawn_expr(body)?;
480 }
481 Node::SelectExpr {
482 cases,
483 timeout,
484 default_body,
485 } => {
486 self.compile_select_expr(cases, timeout, default_body)?;
487 }
488 Node::Spread(_) => {
489 return Err(CompileError {
490 message: "spread (...) can only be used inside list literals, dict literals, or function call arguments".into(),
491 line: self.line,
492 });
493 }
494 Node::AttributedDecl { attributes, inner } => {
495 self.compile_attributed_decl(attributes, inner)?;
496 }
497 Node::OrPattern(_) => {
498 return Err(CompileError {
499 message: "or-pattern (|) can only appear as a match arm pattern".into(),
500 line: self.line,
501 });
502 }
503 }
504 Ok(())
505 }
506}