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 ms = i64::try_from(*ms).map_err(|_| CompileError {
139 message: "duration literal is too large".to_string(),
140 line: self.line,
141 })?;
142 let idx = self.chunk.add_constant(Constant::Duration(ms));
143 self.chunk.emit_u16(Op::Constant, idx, self.line);
144 }
145 Node::Identifier(name) => {
146 self.emit_get_binding(name);
147 }
148 Node::LetBinding { pattern, value, .. } => {
149 let binding_type = match &snode.node {
150 Node::LetBinding {
151 type_ann: Some(type_ann),
152 ..
153 } => Some(type_ann.clone()),
154 _ => self.infer_expr_type(value),
155 };
156 self.compile_node(value)?;
157 self.compile_destructuring(pattern, false)?;
158 self.record_binding_type(pattern, binding_type);
159 }
160 Node::VarBinding { pattern, value, .. } => {
161 let binding_type = match &snode.node {
162 Node::VarBinding {
163 type_ann: Some(type_ann),
164 ..
165 } => Some(type_ann.clone()),
166 _ => self.infer_expr_type(value),
167 };
168 self.compile_node(value)?;
169 self.compile_destructuring(pattern, true)?;
170 self.record_binding_type(pattern, binding_type);
171 }
172 Node::Assignment {
173 target, value, op, ..
174 } => {
175 self.compile_assignment(target, value, op)?;
176 }
177 Node::BinaryOp { op, left, right } => {
178 self.compile_binary_op(op, left, right)?;
179 }
180 Node::UnaryOp { op, operand } => {
181 self.compile_node(operand)?;
182 match op.as_str() {
183 "-" => self.chunk.emit(Op::Negate, self.line),
184 "!" => self.chunk.emit(Op::Not, self.line),
185 _ => {}
186 }
187 }
188 Node::Ternary {
189 condition,
190 true_expr,
191 false_expr,
192 } => {
193 self.compile_node(condition)?;
194 let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
195 self.chunk.emit(Op::Pop, self.line);
196 self.compile_node(true_expr)?;
197 let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
198 self.chunk.patch_jump(else_jump);
199 self.chunk.emit(Op::Pop, self.line);
200 self.compile_node(false_expr)?;
201 self.chunk.patch_jump(end_jump);
202 }
203 Node::FunctionCall { name, args } => {
204 self.compile_function_call(name, args)?;
205 }
206 Node::MethodCall {
207 object,
208 method,
209 args,
210 } => {
211 self.compile_method_call(object, method, args)?;
212 }
213 Node::OptionalMethodCall {
214 object,
215 method,
216 args,
217 } => {
218 self.compile_node(object)?;
219 for arg in args {
220 self.compile_node(arg)?;
221 }
222 let name_idx = self.chunk.add_constant(Constant::String(method.clone()));
223 self.chunk
224 .emit_method_call_opt(name_idx, args.len() as u8, self.line);
225 }
226 Node::PropertyAccess { object, property } => {
227 self.compile_property_access(object, property)?;
228 }
229 Node::OptionalPropertyAccess { object, property } => {
230 self.compile_node(object)?;
231 let idx = self.chunk.add_constant(Constant::String(property.clone()));
232 self.chunk.emit_u16(Op::GetPropertyOpt, idx, self.line);
233 }
234 Node::SubscriptAccess { object, index } => {
235 self.compile_node(object)?;
236 self.compile_node(index)?;
237 self.chunk.emit(Op::Subscript, self.line);
238 }
239 Node::OptionalSubscriptAccess { object, index } => {
240 self.compile_node(object)?;
241 self.compile_node(index)?;
242 self.chunk.emit(Op::SubscriptOpt, self.line);
243 }
244 Node::SliceAccess { object, start, end } => {
245 self.compile_node(object)?;
246 if let Some(s) = start {
247 self.compile_node(s)?;
248 } else {
249 self.chunk.emit(Op::Nil, self.line);
250 }
251 if let Some(e) = end {
252 self.compile_node(e)?;
253 } else {
254 self.chunk.emit(Op::Nil, self.line);
255 }
256 self.chunk.emit(Op::Slice, self.line);
257 }
258 Node::IfElse {
259 condition,
260 then_body,
261 else_body,
262 } => {
263 self.compile_if_else(condition, then_body, else_body)?;
264 }
265 Node::WhileLoop { condition, body } => {
266 self.compile_while_loop(condition, body)?;
267 }
268 Node::ForIn {
269 pattern,
270 iterable,
271 body,
272 } => {
273 self.compile_for_in(pattern, iterable, body)?;
274 }
275 Node::ReturnStmt { value } => {
276 self.compile_return_stmt(value)?;
277 }
278 Node::BreakStmt => {
279 self.compile_break_stmt()?;
280 }
281 Node::ContinueStmt => {
282 self.compile_continue_stmt()?;
283 }
284 Node::ListLiteral(elements) => {
285 self.compile_list_literal(elements)?;
286 }
287 Node::DictLiteral(entries) => {
288 self.compile_dict_literal(entries)?;
289 }
290 Node::InterpolatedString(segments) => {
291 self.compile_interpolated_string(segments)?;
292 }
293 Node::FnDecl {
294 name, params, body, ..
295 } => {
296 self.compile_fn_decl(name, params, body)?;
297 }
298 Node::ToolDecl {
299 name,
300 description,
301 params,
302 return_type,
303 body,
304 ..
305 } => {
306 self.compile_tool_decl(name, description, params, return_type, body)?;
307 }
308 Node::SkillDecl { name, fields, .. } => {
309 self.compile_skill_decl(name, fields)?;
310 }
311 Node::Closure { params, body, .. } => {
312 self.compile_closure(params, body)?;
313 }
314 Node::ThrowStmt { value } => {
315 self.compile_throw_stmt(value)?;
316 }
317 Node::MatchExpr { value, arms } => {
318 self.compile_match_expr(value, arms)?;
319 }
320 Node::RangeExpr {
321 start,
322 end,
323 inclusive,
324 } => {
325 let name_idx = self
326 .chunk
327 .add_constant(Constant::String("__range__".to_string()));
328 self.chunk.emit_u16(Op::Constant, name_idx, self.line);
329 self.compile_node(start)?;
330 self.compile_node(end)?;
331 if *inclusive {
332 self.chunk.emit(Op::True, self.line);
333 } else {
334 self.chunk.emit(Op::False, self.line);
335 }
336 self.chunk.emit_u8(Op::Call, 3, self.line);
337 }
338 Node::GuardStmt {
339 condition,
340 else_body,
341 } => {
342 self.compile_guard_stmt(condition, else_body)?;
343 }
344 Node::RequireStmt { condition, message } => {
345 self.compile_node(condition)?;
346 let ok_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
347 self.chunk.emit(Op::Pop, self.line);
348 if let Some(message) = message {
349 self.compile_node(message)?;
350 } else {
351 let idx = self
352 .chunk
353 .add_constant(Constant::String("require condition failed".to_string()));
354 self.chunk.emit_u16(Op::Constant, idx, self.line);
355 }
356 self.chunk.emit(Op::Throw, self.line);
357 self.chunk.patch_jump(ok_jump);
358 self.chunk.emit(Op::Pop, self.line);
359 }
360 Node::Block(stmts) => {
361 self.compile_scoped_block(stmts)?;
362 }
363 Node::DeadlineBlock { duration, body } => {
364 self.compile_node(duration)?;
365 self.chunk.emit(Op::DeadlineSetup, self.line);
366 self.compile_scoped_block(body)?;
367 self.chunk.emit(Op::DeadlineEnd, self.line);
368 }
369 Node::MutexBlock { body } => {
370 self.begin_scope();
371 let key_idx = self
372 .chunk
373 .add_constant(Constant::String("__default__".to_string()));
374 self.chunk.emit_u16(Op::SyncMutexEnter, key_idx, self.line);
375 for sn in body {
376 self.compile_node(sn)?;
377 if Self::produces_value(&sn.node) {
378 self.chunk.emit(Op::Pop, self.line);
379 }
380 }
381 self.chunk.emit(Op::Nil, self.line);
382 self.end_scope();
383 }
384 Node::DeferStmt { body } => {
385 self.finally_bodies
387 .push(FinallyEntry::Finally(body.clone()));
388 self.chunk.emit(Op::Nil, self.line);
389 }
390 Node::YieldExpr { value } => {
391 if let Some(val) = value {
392 self.compile_node(val)?;
393 } else {
394 self.chunk.emit(Op::Nil, self.line);
395 }
396 self.chunk.emit(Op::Yield, self.line);
397 }
398 Node::EnumConstruct {
399 enum_name,
400 variant,
401 args,
402 } => {
403 self.compile_enum_construct(enum_name, variant, args)?;
404 }
405 Node::StructConstruct {
406 struct_name,
407 fields,
408 } => {
409 self.compile_struct_construct(struct_name, fields)?;
410 }
411 Node::ImportDecl { path, .. } => {
412 let idx = self.chunk.add_constant(Constant::String(path.clone()));
413 self.chunk.emit_u16(Op::Import, idx, self.line);
414 }
415 Node::SelectiveImport { names, path, .. } => {
416 let path_idx = self.chunk.add_constant(Constant::String(path.clone()));
417 let names_str = names.join(",");
418 let names_idx = self.chunk.add_constant(Constant::String(names_str));
419 self.chunk
420 .emit_u16(Op::SelectiveImport, path_idx, self.line);
421 let hi = (names_idx >> 8) as u8;
422 let lo = names_idx as u8;
423 self.chunk.code.push(hi);
424 self.chunk.code.push(lo);
425 self.chunk.lines.push(self.line);
426 self.chunk.columns.push(self.column);
427 self.chunk.lines.push(self.line);
428 self.chunk.columns.push(self.column);
429 }
430 Node::TryOperator { operand } => {
431 self.compile_node(operand)?;
432 self.chunk.emit(Op::TryUnwrap, self.line);
433 }
434 Node::TryStar { operand } => {
450 self.compile_try_star(operand)?;
451 }
452 Node::ImplBlock { type_name, methods } => {
453 self.compile_impl_block(type_name, methods)?;
454 }
455 Node::StructDecl { name, fields, .. } => {
456 self.compile_struct_decl(name, fields)?;
457 }
458 Node::Pipeline { .. }
460 | Node::OverrideDecl { .. }
461 | Node::TypeDecl { .. }
462 | Node::EnumDecl { .. }
463 | Node::InterfaceDecl { .. } => {
464 self.chunk.emit(Op::Nil, self.line);
465 }
466 Node::TryCatch {
467 body,
468 error_var,
469 error_type,
470 catch_body,
471 finally_body,
472 } => {
473 self.compile_try_catch(body, error_var, error_type, catch_body, finally_body)?;
474 }
475 Node::TryExpr { body } => {
476 self.compile_try_expr(body)?;
477 }
478 Node::Retry { count, body } => {
479 self.compile_retry(count, body)?;
480 }
481 Node::Parallel {
482 mode,
483 expr,
484 variable,
485 body,
486 options,
487 } => {
488 self.compile_parallel(mode, expr, variable, body, options)?;
489 }
490 Node::SpawnExpr { body } => {
491 self.compile_spawn_expr(body)?;
492 }
493 Node::SelectExpr {
494 cases,
495 timeout,
496 default_body,
497 } => {
498 self.compile_select_expr(cases, timeout, default_body)?;
499 }
500 Node::Spread(_) => {
501 return Err(CompileError {
502 message: "spread (...) can only be used inside list literals, dict literals, or function call arguments".into(),
503 line: self.line,
504 });
505 }
506 Node::AttributedDecl { attributes, inner } => {
507 self.compile_attributed_decl(attributes, inner)?;
508 }
509 Node::OrPattern(_) => {
510 return Err(CompileError {
511 message: "or-pattern (|) can only appear as a match arm pattern".into(),
512 line: self.line,
513 });
514 }
515 }
516 Ok(())
517 }
518}