Files
AILang/crates/ailang-codegen/src/synth.rs
T
Brummel 84ba83dda3 codegen tidy: extract pure helpers into synth.rs + subst.rs
First slice of the codegen module split. Pulls the run of
free functions at the bottom of lib.rs into two purpose-named
submodules, with no behaviour change:

- synth.rs (216 lines): LLVM-IR shaping helpers — llvm_type,
  fn_sig_from_type, builtin_ail_type, builtin_effect_op_ret,
  type_descriptor, builtin_binop, c_byte_len, default_triple,
  ll_string_literal.

- subst.rs (319 lines): monomorphisation pipeline — the
  derive_substitution + unify_for_subst + apply_subst_to_*
  family, plus qualify_local_types_codegen and
  descriptor_for_subst.

lib.rs drops from 5295 → 4800 lines. Visibility is unchanged
(submodules see lib.rs's private Result/CodegenError/FnSig
through normal Rust scoping); call sites are unchanged in
behaviour, only re-imported via 'use' at the lib.rs head.

Motivation is the codebase-control conversation: lib.rs was
the one navigability outlier flagged in the size sanity-
check, and the 18g family closing left a clean window before
the next iter. The remaining bulk (drop emission, match
lowering, lambda lowering) will come out in follow-up
commits, each an independent move-only refactor with full
cargo test --workspace between.
2026-05-08 15:41:04 +02:00

217 lines
7.9 KiB
Rust

//! Pure type-synthesis and IR-shaping helpers.
//!
//! Free functions extracted from `lib.rs` during the 18g tidy split.
//! None of these touch the `Emitter` state — they map AILang `Type`s
//! to LLVM type strings, mangling descriptors, or built-in op
//! signatures. Submodule access to the parent module's private
//! `Result`, `CodegenError`, and `FnSig` works through normal Rust
//! visibility (a submodule sees its parent's private items).
use ailang_core::ast::*;
use super::{CodegenError, FnSig, Result};
pub(crate) fn llvm_type(t: &Type) -> Result<String> {
match t {
Type::Con { name, .. } => match name.as_str() {
"Int" => Ok("i64".into()),
"Bool" => Ok("i1".into()),
"Unit" => Ok("i8".into()),
"Str" => Ok("ptr".into()),
// All other type names are treated as ADT (boxed).
// If the typechecker didn't reject this earlier, it's
// intentional — otherwise `ptr` would mask a wrong value.
_ => Ok("ptr".into()),
},
// Function values (Iter 7): all fn-pointers are opaque `ptr`
// at the LLVM level. The actual signature travels via the
// emitter's `ssa_fn_sigs` sidetable.
Type::Fn { .. } => Ok("ptr".into()),
// Iter 13b: an unresolved rigid `Type::Var` reaching codegen is
// a substitution bug. Earlier this silently lowered as `ptr`
// (via the ADT fallback) and produced garbage IR; failing loudly
// here surfaces the bug in the test suite.
Type::Var { name } => Err(CodegenError::UnsupportedType(format!(
"unresolved type var `{name}` in codegen"
))),
other => Err(CodegenError::UnsupportedType(
ailang_core::pretty::type_to_string(other),
)),
}
}
/// Builds an `FnSig` (LLVM types only) from an AILang `Type::Fn`.
/// Returns `None` for non-function types or if any param/ret type fails
/// to lower (e.g. a residual `Type::Var` or `Forall` that the typechecker
/// would reject before us).
pub(crate) fn fn_sig_from_type(t: &Type) -> Option<FnSig> {
if let Type::Fn { params, ret, .. } = t {
let p: Result<Vec<String>> = params.iter().map(llvm_type).collect();
let r = llvm_type(ret);
if let (Ok(p), Ok(r)) = (p, r) {
return Some(FnSig { params: p, ret: r });
}
}
None
}
/// Iter 12b: AILang type of a builtin operator. Used by
/// `synth_arg_type` for arg-type inference at polymorphic call sites.
/// Mirrors what the typechecker installs in its env via `builtins`.
pub(crate) fn builtin_ail_type(name: &str) -> Option<Type> {
let int_int_int = || Type::Fn {
params: vec![Type::int(), Type::int()],
ret: Box::new(Type::int()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
};
let int_int_bool = || Type::Fn {
params: vec![Type::int(), Type::int()],
ret: Box::new(Type::bool_()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
};
Some(match name {
"+" | "-" | "*" | "/" | "%" => int_int_int(),
"!=" | "<" | "<=" | ">" | ">=" => int_int_bool(),
// Iter 16e: `==` is polymorphic — `forall a. (a, a) -> Bool`.
// The mono pipeline asks `synth_arg_type` for the actual arg
// types at the call site; `lower_app` then dispatches to the
// right LLVM instruction (icmp eq i64 / i1, @strcmp, or
// constant i1 1) on those resolved types.
"==" => Type::Forall {
vars: vec!["a".into()],
body: Box::new(Type::Fn {
params: vec![
Type::Var { name: "a".into() },
Type::Var { name: "a".into() },
],
ret: Box::new(Type::bool_()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
}),
},
"not" => Type::Fn {
params: vec![Type::bool_()],
ret: Box::new(Type::bool_()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
},
// Iter 16d: `__unreachable__` is the polymorphic bottom value
// (`forall a. a`). Mirrors the typechecker's `builtins::install`.
"__unreachable__" => Type::Forall {
vars: vec!["a".into()],
body: Box::new(Type::Var { name: "a".into() }),
},
_ => return None,
})
}
/// Iter 12b: AILang return type of a built-in effect op. The op's
/// param signature is irrelevant here since we only consume the ret.
pub(crate) fn builtin_effect_op_ret(op: &str) -> Option<Type> {
Some(match op {
"io/print_int" | "io/print_bool" | "io/print_str" => Type::unit(),
_ => return None,
})
}
/// Iter 12b: a stable, identifier-safe descriptor for a `Type`.
/// Maps `Int → I`, `Bool → B`, `Unit → U`, `Str → S`, ADT name `Foo →
/// FFoo`, fn → `F<params...>R<ret>` (no recursion guard since types in
/// the MVP are non-recursive at the type level).
pub(crate) fn type_descriptor(t: &Type) -> String {
match t {
Type::Con { name, args } => {
let head = match name.as_str() {
"Int" => "I".into(),
"Bool" => "B".into(),
"Unit" => "U".into(),
"Str" => "S".into(),
other => format!("F{other}"),
};
if args.is_empty() {
head
} else {
// Iter 13a: parameterised ADTs get their type-arg
// descriptors appended, e.g. `FBox` of `Int` → `FBox_I`.
let mut s = head;
for a in args {
s.push('_');
s.push_str(&type_descriptor(a));
}
s
}
}
Type::Fn { params, ret, .. } => {
let mut s = String::from("Fn");
for p in params {
s.push('_');
s.push_str(&type_descriptor(p));
}
s.push_str("__r_");
s.push_str(&type_descriptor(ret));
s
}
Type::Var { name } => format!("V{name}"),
Type::Forall { .. } => "FORALL".into(),
}
}
pub(crate) fn builtin_binop(name: &str) -> Option<(&'static str, &'static str)> {
Some(match name {
"+" => ("add", "i64"),
"-" => ("sub", "i64"),
"*" => ("mul", "i64"),
"/" => ("sdiv", "i64"),
"%" => ("srem", "i64"),
"==" => ("icmp eq", "i1"),
"!=" => ("icmp ne", "i1"),
"<" => ("icmp slt", "i1"),
"<=" => ("icmp sle", "i1"),
">" => ("icmp sgt", "i1"),
">=" => ("icmp sge", "i1"),
_ => return None,
})
}
pub(crate) fn c_byte_len(s: &str) -> usize {
s.len() + 1 // + NUL terminator
}
/// Escapes a string for LLVM IR `c"..."`. All bytes outside
/// 0x20..0x7E are escaped as `\HH`; `"` and `\` likewise. Ends with `\00`.
pub(crate) fn default_triple() -> &'static str {
// In the MVP we query the compile host. For cross-compilation this
// would need to be configurable — not needed now.
if cfg!(target_os = "linux") && cfg!(target_arch = "x86_64") {
"x86_64-pc-linux-gnu"
} else if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
"arm64-apple-darwin"
} else if cfg!(target_os = "macos") && cfg!(target_arch = "x86_64") {
"x86_64-apple-darwin"
} else if cfg!(target_arch = "aarch64") {
"aarch64-unknown-linux-gnu"
} else {
"x86_64-pc-linux-gnu"
}
}
pub(crate) fn ll_string_literal(s: &str) -> String {
let mut out = String::new();
for &b in s.as_bytes() {
match b {
b'"' => out.push_str("\\22"),
b'\\' => out.push_str("\\5C"),
0x20..=0x7E => out.push(b as char),
_ => out.push_str(&format!("\\{:02X}", b)),
}
}
out.push_str("\\00");
out
}