bhc_session/lib.rs
1//! Compiler session state, options, and configuration for BHC.
2//!
3//! This crate provides the central session management for the BHC compiler,
4//! including compilation options, diagnostic configuration, and global state
5//! that persists throughout a compilation unit.
6//!
7//! # Overview
8//!
9//! The [`Session`] type is the primary entry point, holding all state needed
10//! for a single compilation. It includes:
11//!
12//! - Compiler options and flags
13//! - Target specification
14//! - Diagnostic handler
15//! - Search paths for modules and libraries
16//!
17//! # Profiles
18//!
19//! BHC supports multiple compilation profiles as specified in H26-SPEC:
20//!
21//! - **Default**: Standard lazy Haskell semantics
22//! - **Server**: Optimized for concurrent server workloads
23//! - **Numeric**: Strict-by-default with fusion guarantees
24//! - **Edge**: Minimal runtime for embedded/WASM targets
25
26#![warn(missing_docs)]
27
28use camino::{Utf8Path, Utf8PathBuf};
29use parking_lot::RwLock;
30use rustc_hash::FxHashSet;
31use serde::{Deserialize, Serialize};
32use std::sync::Arc;
33
34/// The compilation profile determines evaluation semantics and optimization strategy.
35///
36/// See H26-SPEC Section 4 for detailed profile specifications.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub enum Profile {
39 /// Standard lazy Haskell evaluation with GC-managed memory.
40 #[default]
41 Default,
42 /// Optimized for server workloads: concurrency, bounded latency, observability.
43 Server,
44 /// Numeric computing: strict-by-default, unboxed, fusion guaranteed.
45 Numeric,
46 /// Minimal runtime footprint for embedded and WASM targets.
47 Edge,
48 /// Realtime profile: bounded GC pauses (<1ms), arena per-frame.
49 Realtime,
50 /// Bare-metal microcontrollers: no GC, static allocation only.
51 /// Programs with escaping allocations are rejected at compile time.
52 Embedded,
53}
54
55impl Profile {
56 /// Returns true if this profile uses strict evaluation by default.
57 #[must_use]
58 pub const fn is_strict_by_default(self) -> bool {
59 matches!(self, Self::Numeric | Self::Edge | Self::Embedded)
60 }
61
62 /// Returns true if fusion is guaranteed for this profile.
63 #[must_use]
64 pub const fn has_fusion_guarantees(self) -> bool {
65 matches!(self, Self::Numeric)
66 }
67
68 /// Returns true if this profile requires escape analysis.
69 ///
70 /// For Embedded profile, programs with escaping allocations are rejected
71 /// at compile time since there is no GC to manage memory.
72 #[must_use]
73 pub const fn requires_escape_analysis(self) -> bool {
74 matches!(self, Self::Embedded)
75 }
76
77 /// Returns true if this profile has no garbage collector.
78 #[must_use]
79 pub const fn is_gc_free(self) -> bool {
80 matches!(self, Self::Embedded)
81 }
82}
83
84/// Optimization level for code generation.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
86pub enum OptLevel {
87 /// No optimizations (fastest compilation).
88 None,
89 /// Basic optimizations.
90 #[default]
91 Less,
92 /// Standard optimizations (default).
93 Default,
94 /// Aggressive optimizations.
95 Aggressive,
96 /// Size-optimized output.
97 Size,
98 /// Aggressively size-optimized output.
99 SizeMin,
100}
101
102/// Debug information level.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
104pub enum DebugInfo {
105 /// No debug information.
106 #[default]
107 None,
108 /// Line tables only.
109 LineTablesOnly,
110 /// Full debug information.
111 Full,
112}
113
114/// Output type for compilation.
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
116pub enum OutputType {
117 /// Object file (.o).
118 #[default]
119 Object,
120 /// Static library (.a).
121 StaticLib,
122 /// Dynamic library (.so/.dylib/.dll).
123 DynamicLib,
124 /// Executable binary.
125 Executable,
126 /// LLVM IR (.ll).
127 LlvmIr,
128 /// LLVM bitcode (.bc).
129 LlvmBitcode,
130 /// Assembly (.s).
131 Assembly,
132 /// WebAssembly module (.wasm).
133 Wasm,
134}
135
136/// Compiler options that can be set via CLI or configuration.
137#[derive(Clone, Debug, Serialize, Deserialize)]
138pub struct Options {
139 /// The compilation profile to use.
140 pub profile: Profile,
141 /// Optimization level.
142 pub opt_level: OptLevel,
143 /// Debug information level.
144 pub debug_info: DebugInfo,
145 /// Output type.
146 pub output_type: OutputType,
147 /// Target triple (e.g., "x86_64-unknown-linux-gnu").
148 pub target_triple: Option<String>,
149 /// Output path for compiled artifacts.
150 pub output_path: Option<Utf8PathBuf>,
151 /// Search paths for module imports.
152 pub import_paths: Vec<Utf8PathBuf>,
153 /// Search paths for libraries.
154 pub library_paths: Vec<Utf8PathBuf>,
155 /// Libraries to link.
156 pub libraries: Vec<String>,
157 /// Enable all warnings.
158 pub warn_all: bool,
159 /// Treat warnings as errors.
160 pub deny_warnings: bool,
161 /// Generate kernel reports (Numeric profile).
162 pub emit_kernel_report: bool,
163 /// Dump intermediate representations.
164 pub dump_ir: IrDumpOptions,
165 /// Path to the BHC standard library.
166 /// Used for implicit Prelude loading and module resolution.
167 pub stdlib_path: Option<Utf8PathBuf>,
168 /// Hackage package dependencies as "name:version" pairs.
169 /// Example: `["filepath:1.4.100.0", "directory:1.3.8.0"]`
170 pub hackage_packages: Vec<String>,
171 /// Compile-only mode: produce .o files without linking.
172 pub compile_only: bool,
173 /// Output directory for object files (used with compile_only).
174 pub output_object_dir: Option<Utf8PathBuf>,
175 /// Output directory for interface files (used with compile_only).
176 pub output_interface_dir: Option<Utf8PathBuf>,
177 /// Package database paths for dependency lookup.
178 pub package_dbs: Vec<Utf8PathBuf>,
179 /// Exposed dependency package IDs.
180 pub package_ids: Vec<String>,
181 /// Enabled language extensions (e.g., "OverloadedStrings").
182 pub extensions: Vec<String>,
183 /// CPP preprocessor defines (e.g., "FOO", "BAR=1").
184 pub cpp_defines: Vec<String>,
185}
186
187impl Default for Options {
188 fn default() -> Self {
189 Self {
190 profile: Profile::Default,
191 opt_level: OptLevel::Default,
192 debug_info: DebugInfo::None,
193 output_type: OutputType::Object,
194 target_triple: None,
195 output_path: None,
196 import_paths: Vec::new(),
197 library_paths: Vec::new(),
198 libraries: Vec::new(),
199 warn_all: false,
200 deny_warnings: false,
201 emit_kernel_report: false,
202 dump_ir: IrDumpOptions::default(),
203 stdlib_path: None,
204 hackage_packages: Vec::new(),
205 compile_only: false,
206 output_object_dir: None,
207 output_interface_dir: None,
208 package_dbs: Vec::new(),
209 package_ids: Vec::new(),
210 extensions: Vec::new(),
211 cpp_defines: Vec::new(),
212 }
213 }
214}
215
216/// Options for dumping intermediate representations.
217#[derive(Clone, Debug, Default, Serialize, Deserialize)]
218pub struct IrDumpOptions {
219 /// Dump AST after parsing.
220 pub dump_ast: bool,
221 /// Dump Core IR.
222 pub dump_core: bool,
223 /// Dump Core IR after specific passes.
224 pub dump_core_passes: Vec<String>,
225 /// Dump Tensor IR.
226 pub dump_tensor_ir: bool,
227 /// Dump Loop IR.
228 pub dump_loop_ir: bool,
229 /// Dump LLVM IR.
230 pub dump_llvm: bool,
231}
232
233/// Search path configuration for finding modules and libraries.
234#[derive(Clone, Debug, Default)]
235pub struct SearchPaths {
236 /// Paths to search for source modules.
237 pub module_paths: Vec<Utf8PathBuf>,
238 /// Paths to search for interface files (.bhi).
239 pub interface_paths: Vec<Utf8PathBuf>,
240 /// Paths to search for libraries.
241 pub library_paths: Vec<Utf8PathBuf>,
242}
243
244impl SearchPaths {
245 /// Create a new empty search path configuration.
246 #[must_use]
247 pub fn new() -> Self {
248 Self::default()
249 }
250
251 /// Add a module search path.
252 pub fn add_module_path(&mut self, path: impl Into<Utf8PathBuf>) {
253 self.module_paths.push(path.into());
254 }
255
256 /// Add an interface search path.
257 pub fn add_interface_path(&mut self, path: impl Into<Utf8PathBuf>) {
258 self.interface_paths.push(path.into());
259 }
260
261 /// Add a library search path.
262 pub fn add_library_path(&mut self, path: impl Into<Utf8PathBuf>) {
263 self.library_paths.push(path.into());
264 }
265}
266
267/// Errors that can occur during session operations.
268#[derive(Debug, thiserror::Error)]
269pub enum SessionError {
270 /// Configuration file not found.
271 #[error("configuration file not found: {0}")]
272 ConfigNotFound(Utf8PathBuf),
273 /// Invalid configuration file.
274 #[error("invalid configuration: {0}")]
275 InvalidConfig(String),
276 /// Target not supported.
277 #[error("unsupported target: {0}")]
278 UnsupportedTarget(String),
279 /// IO error.
280 #[error("IO error: {0}")]
281 Io(#[from] std::io::Error),
282}
283
284/// The compiler session holds all state for a compilation unit.
285///
286/// This is the primary type for managing compilation state and should be
287/// created at the start of compilation and passed through all phases.
288pub struct Session {
289 /// Compiler options.
290 pub options: Options,
291 /// Search paths for modules and libraries.
292 pub search_paths: SearchPaths,
293 /// Set of already-loaded module names (for cycle detection).
294 loaded_modules: RwLock<FxHashSet<String>>,
295 /// Working directory for the session.
296 working_dir: Utf8PathBuf,
297}
298
299impl Session {
300 /// Create a new session with the given options.
301 ///
302 /// # Errors
303 ///
304 /// Returns an error if the current working directory cannot be determined.
305 pub fn new(options: Options) -> Result<Self, SessionError> {
306 let working_dir = std::env::current_dir()
307 .map_err(SessionError::Io)?
308 .try_into()
309 .map_err(|e| SessionError::InvalidConfig(format!("invalid working dir: {e}")))?;
310
311 Ok(Self {
312 options,
313 search_paths: SearchPaths::default(),
314 loaded_modules: RwLock::new(FxHashSet::default()),
315 working_dir,
316 })
317 }
318
319 /// Create a new session with default options.
320 ///
321 /// # Errors
322 ///
323 /// Returns an error if the current working directory cannot be determined.
324 pub fn with_defaults() -> Result<Self, SessionError> {
325 Self::new(Options::default())
326 }
327
328 /// Get the working directory for this session.
329 #[must_use]
330 pub fn working_dir(&self) -> &Utf8Path {
331 &self.working_dir
332 }
333
334 /// Get the compilation profile.
335 #[must_use]
336 pub fn profile(&self) -> Profile {
337 self.options.profile
338 }
339
340 /// Check if a module has been loaded (for cycle detection).
341 #[must_use]
342 pub fn is_module_loaded(&self, name: &str) -> bool {
343 self.loaded_modules.read().contains(name)
344 }
345
346 /// Mark a module as loaded.
347 pub fn mark_module_loaded(&self, name: String) {
348 self.loaded_modules.write().insert(name);
349 }
350
351 /// Get the output path, computing a default if not specified.
352 #[must_use]
353 pub fn output_path(&self, input_name: &str) -> Utf8PathBuf {
354 if let Some(ref path) = self.options.output_path {
355 path.clone()
356 } else {
357 let stem = Utf8Path::new(input_name).file_stem().unwrap_or(input_name);
358 let ext = match self.options.output_type {
359 OutputType::Object => "o",
360 OutputType::StaticLib => "a",
361 OutputType::DynamicLib => {
362 if cfg!(target_os = "macos") {
363 "dylib"
364 } else if cfg!(target_os = "windows") {
365 "dll"
366 } else {
367 "so"
368 }
369 }
370 OutputType::Executable => "",
371 OutputType::LlvmIr => "ll",
372 OutputType::LlvmBitcode => "bc",
373 OutputType::Assembly => "s",
374 OutputType::Wasm => "wasm",
375 };
376 if ext.is_empty() {
377 Utf8PathBuf::from(stem)
378 } else {
379 Utf8PathBuf::from(format!("{stem}.{ext}"))
380 }
381 }
382 }
383}
384
385/// A shared, thread-safe reference to a session.
386pub type SessionRef = Arc<Session>;
387
388/// Create a shared session reference.
389pub fn create_session(options: Options) -> Result<SessionRef, SessionError> {
390 Ok(Arc::new(Session::new(options)?))
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn test_profile_properties() {
399 assert!(!Profile::Default.is_strict_by_default());
400 assert!(!Profile::Server.is_strict_by_default());
401 assert!(Profile::Numeric.is_strict_by_default());
402 assert!(Profile::Edge.is_strict_by_default());
403
404 assert!(Profile::Numeric.has_fusion_guarantees());
405 assert!(!Profile::Default.has_fusion_guarantees());
406 }
407
408 #[test]
409 fn test_session_module_tracking() {
410 let session = Session::with_defaults().unwrap();
411 assert!(!session.is_module_loaded("Data.List"));
412 session.mark_module_loaded("Data.List".to_string());
413 assert!(session.is_module_loaded("Data.List"));
414 }
415}