use std::collections::HashMap;
use std::path::{Path, PathBuf};
use bock_air::{
interpret_context, lower_module, resolve_names_with_registry, validate_context, ModuleRegistry,
NodeIdGen, StrictnessLevel, SymbolTable,
};
use bock_build::dep_graph::{self, DepGraph};
use bock_errors::{Diagnostic, DiagnosticBag, Severity, Span};
use bock_lexer::Lexer;
use bock_parser::Parser;
use bock_source::SourceMap;
use bock_types::{
collect_exports, seed_imports, seed_prelude, FnType, PrimitiveType, Strictness, Type,
TypeChecker,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Aspect {
Types,
Context,
}
impl Aspect {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Aspect::Types => "types",
Aspect::Context => "context",
}
}
#[must_use]
pub fn parse(name: &str) -> Option<Aspect> {
match name {
"types" => Some(Aspect::Types),
"context" => Some(Aspect::Context),
_ => None,
}
}
pub const ALL: [Aspect; 2] = [Aspect::Types, Aspect::Context];
#[must_use]
pub fn valid_list() -> String {
Self::ALL
.iter()
.map(|a| a.as_str())
.collect::<Vec<_>>()
.join(", ")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AspectSelection {
All,
Only(std::collections::HashSet<Aspect>),
}
impl AspectSelection {
pub fn from_raw(raw: &[String]) -> Result<AspectSelection, String> {
if raw.is_empty() {
return Ok(AspectSelection::All);
}
let mut set = std::collections::HashSet::new();
for value in raw {
for part in value.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
match Aspect::parse(part) {
Some(aspect) => {
set.insert(aspect);
}
None => return Err(part.to_string()),
}
}
}
if set.is_empty() {
return Ok(AspectSelection::All);
}
Ok(AspectSelection::Only(set))
}
#[must_use]
pub fn runs(&self, aspect: Aspect) -> bool {
match self {
AspectSelection::All => true,
AspectSelection::Only(set) => set.contains(&aspect),
}
}
#[must_use]
pub fn is_full(&self) -> bool {
matches!(self, AspectSelection::All)
}
}
pub struct CheckOptions {
pub aspects: AspectSelection,
pub brief: bool,
pub strict: bool,
}
impl CheckOptions {
#[must_use]
pub fn strictness(&self) -> Strictness {
if self.strict {
Strictness::Production
} else {
Strictness::Development
}
}
}
impl Default for CheckOptions {
fn default() -> Self {
Self {
aspects: AspectSelection::All,
brief: false,
strict: false,
}
}
}
fn context_strictness_level(strictness: Strictness) -> StrictnessLevel {
match strictness {
Strictness::Sketch => StrictnessLevel::Lax,
Strictness::Development => StrictnessLevel::Standard,
Strictness::Production => StrictnessLevel::Strict,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckOutcome {
Clean,
Failed,
}
impl CheckOutcome {
pub fn is_clean(self) -> bool {
matches!(self, CheckOutcome::Clean)
}
}
pub fn run(files: Vec<PathBuf>, options: &CheckOptions) -> anyhow::Result<CheckOutcome> {
let files = if files.is_empty() {
discover_bock_files(".")?
} else {
files
};
if files.is_empty() {
eprintln!("No .bock files found.");
return Ok(CheckOutcome::Failed);
}
let mut found_errors = false;
let mut source_map = SourceMap::new();
let mut parsed_files: Vec<ParsedFile> = Vec::new();
for src in crate::stdlib::core_sources() {
match parse_stdlib_source(&src, &mut source_map, !options.brief) {
Ok(pf) => parsed_files.push(pf),
Err(()) => found_errors = true,
}
}
for file_path in &files {
match parse_file(file_path, &mut source_map, !options.brief) {
Ok(pf) => parsed_files.push(pf),
Err(()) => found_errors = true,
}
}
if found_errors {
return Ok(CheckOutcome::Failed);
}
let mut dep_graph = DepGraph::new();
let mut id_to_index: HashMap<String, usize> = HashMap::new();
let core_module_ids: Vec<String> = parsed_files
.iter()
.enumerate()
.filter(|(_, pf)| pf.is_stdlib)
.map(|(i, pf)| dep_graph::module_id_from_module(&pf.module, i))
.collect();
for (i, pf) in parsed_files.iter().enumerate() {
let module_id = dep_graph::module_id_from_module(&pf.module, i);
let mut deps = dep_graph::extract_dependencies(&pf.module.imports);
if !pf.is_stdlib {
dep_graph::add_prelude_deps(&mut deps, &module_id, &core_module_ids);
}
dep_graph.add_module_with_deps(module_id.clone(), deps);
id_to_index.insert(module_id, i);
}
let topo_order = match dep_graph.topological_order() {
Some(order) => order,
None => {
report_module_cycle(
&dep_graph,
&id_to_index,
&parsed_files,
&source_map,
options,
);
return Ok(CheckOutcome::Failed);
}
};
let mut registry = ModuleRegistry::new();
for module_id in &topo_order {
let Some(&idx) = id_to_index.get(module_id) else {
continue; };
let pf = &parsed_files[idx];
let source_file = source_map.get_file(pf.file_id);
let mut all_diagnostics: Vec<Diagnostic> = Vec::new();
let mut symbols = SymbolTable::new();
let resolve_diags = resolve_names_with_registry(&pf.module, &mut symbols, ®istry);
collect_diagnostics(&mut all_diagnostics, &resolve_diags);
if has_errors(&all_diagnostics) {
let to_print = diagnostics_to_surface(&all_diagnostics, pf.is_stdlib);
print_diagnostics(
&to_print,
&pf.filename,
&source_file.content,
!options.brief,
);
found_errors = true;
continue;
}
let id_gen = NodeIdGen::new();
let mut air_module = lower_module(&pf.module, &id_gen, &symbols);
let context_diags = interpret_context(&mut air_module);
collect_diagnostics(&mut all_diagnostics, &context_diags);
let mut checker = TypeChecker::new();
register_type_builtins(&mut checker);
seed_prelude(&mut checker, ®istry);
seed_imports(&mut checker, &pf.module.imports, ®istry);
if options.aspects.runs(Aspect::Types) {
checker.check_module(&mut air_module);
collect_diagnostics(&mut all_diagnostics, &checker.diags);
}
let strictness = if pf.is_stdlib {
Strictness::Development
} else {
options.strictness()
};
if options.aspects.is_full() {
let ownership_diags = bock_types::analyze_ownership(&air_module);
collect_diagnostics(&mut all_diagnostics, &ownership_diags);
let effect_diags = bock_types::track_effects(&air_module, strictness);
collect_diagnostics(&mut all_diagnostics, &effect_diags);
}
if options.aspects.runs(Aspect::Context) {
let capability_diags = bock_types::verify_capabilities(&air_module, strictness);
collect_diagnostics(&mut all_diagnostics, &capability_diags);
let context_validation_diags =
validate_context(&air_module, context_strictness_level(strictness));
collect_diagnostics(&mut all_diagnostics, &context_validation_diags);
}
let module_has_errors = has_errors(&all_diagnostics);
let to_print = diagnostics_to_surface(&all_diagnostics, pf.is_stdlib);
if !to_print.is_empty() {
print_diagnostics(
&to_print,
&pf.filename,
&source_file.content,
!options.brief,
);
}
if module_has_errors {
found_errors = true;
} else {
let exports = collect_exports(module_id, &pf.path, &checker, &air_module);
registry.register(exports);
}
}
if found_errors {
return Ok(CheckOutcome::Failed);
}
let file_count = files.len();
let label = if file_count == 1 { "file" } else { "files" };
println!("check: {file_count} {label} checked, no errors.");
Ok(CheckOutcome::Clean)
}
struct ParsedFile {
path: PathBuf,
filename: String,
file_id: bock_errors::FileId,
module: bock_ast::Module,
is_stdlib: bool,
}
fn parse_file(
path: &Path,
source_map: &mut SourceMap,
show_context: bool,
) -> Result<ParsedFile, ()> {
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {}: {e}", path.display());
return Err(());
}
};
let filename = path.display().to_string();
let file_id = source_map.add_file(path.to_path_buf(), content);
let source_file = source_map.get_file(file_id);
let mut diags: Vec<Diagnostic> = Vec::new();
let mut lexer = Lexer::new(source_file);
let tokens = lexer.tokenize();
collect_diagnostics(&mut diags, lexer.diagnostics());
if has_errors(&diags) {
print_diagnostics(&diags, &filename, &source_file.content, show_context);
return Err(());
}
let mut parser = Parser::new(tokens, source_file);
let module = parser.parse_module();
collect_diagnostics(&mut diags, parser.diagnostics());
if has_errors(&diags) {
print_diagnostics(&diags, &filename, &source_file.content, show_context);
return Err(());
}
Ok(ParsedFile {
path: path.to_path_buf(),
filename,
file_id,
module,
is_stdlib: false,
})
}
fn parse_stdlib_source(
src: &crate::stdlib::StdlibSource,
source_map: &mut SourceMap,
show_context: bool,
) -> Result<ParsedFile, ()> {
let filename = src.logical_path.display().to_string();
let file_id = source_map.add_file(src.logical_path.clone(), src.source.clone());
let source_file = source_map.get_file(file_id);
let mut diags: Vec<Diagnostic> = Vec::new();
let mut lexer = Lexer::new(source_file);
let tokens = lexer.tokenize();
collect_diagnostics(&mut diags, lexer.diagnostics());
if has_errors(&diags) {
print_diagnostics(&diags, &filename, &source_file.content, show_context);
return Err(());
}
let mut parser = Parser::new(tokens, source_file);
let module = parser.parse_module();
collect_diagnostics(&mut diags, parser.diagnostics());
if has_errors(&diags) {
print_diagnostics(&diags, &filename, &source_file.content, show_context);
return Err(());
}
Ok(ParsedFile {
path: src.logical_path.clone(),
filename,
file_id,
module,
is_stdlib: true,
})
}
fn collect_diagnostics(acc: &mut Vec<Diagnostic>, bag: &DiagnosticBag) {
for diag in bag.iter() {
acc.push(diag.clone());
}
}
fn has_errors(diagnostics: &[Diagnostic]) -> bool {
diagnostics.iter().any(|d| d.severity == Severity::Error)
}
fn diagnostics_to_surface(diagnostics: &[Diagnostic], is_stdlib: bool) -> Vec<Diagnostic> {
if is_stdlib {
diagnostics
.iter()
.filter(|d| d.severity == Severity::Error)
.cloned()
.collect()
} else {
diagnostics.to_vec()
}
}
fn find_module_cycle(graph: &DepGraph) -> Option<Vec<String>> {
let mut roots: Vec<String> = graph.modules().into_iter().cloned().collect();
roots.sort();
let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
for root in &roots {
if visited.contains(root) {
continue;
}
let mut path: Vec<String> = Vec::new();
let mut on_path: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut stack: Vec<(String, Vec<String>, usize)> = Vec::new();
let sorted_deps = |node: &str| -> Vec<String> {
let mut deps: Vec<String> = graph
.dependencies(node)
.map(|d| d.iter().cloned().collect())
.unwrap_or_default();
deps.sort();
deps
};
stack.push((root.clone(), sorted_deps(root), 0));
path.push(root.clone());
on_path.insert(root.clone());
while let Some((node, children, idx)) = stack.last_mut() {
if *idx < children.len() {
let dep = children[*idx].clone();
*idx += 1;
if on_path.contains(&dep) {
let start = path.iter().position(|m| m == &dep).unwrap_or(0);
let mut cycle: Vec<String> = path[start..].to_vec();
cycle.push(dep);
return Some(cycle);
}
if !visited.contains(&dep) {
let deps = sorted_deps(&dep);
path.push(dep.clone());
on_path.insert(dep.clone());
stack.push((dep, deps, 0));
}
} else {
let node = node.clone();
visited.insert(node.clone());
on_path.remove(&node);
path.pop();
stack.pop();
}
}
}
None
}
fn report_module_cycle(
graph: &DepGraph,
id_to_index: &HashMap<String, usize>,
parsed_files: &[ParsedFile],
source_map: &SourceMap,
options: &CheckOptions,
) {
let code = bock_errors::DiagnosticCode {
prefix: 'E',
number: 1008,
};
let Some(cycle) = find_module_cycle(graph) else {
let mut bag = DiagnosticBag::new();
bag.error(
code,
"circular module dependency detected",
bock_errors::Span::dummy(),
);
let diags: Vec<Diagnostic> = bag.iter().cloned().collect();
eprintln!("{}", render_codeonly(&diags));
return;
};
let participants = &cycle[..cycle.len().saturating_sub(1)];
let chain = cycle.join(" -> ");
let mut primary: Option<(Span, String)> = None;
for window in cycle.windows(2) {
let (from, to) = (&window[0], &window[1]);
if let Some(&idx) = id_to_index.get(from) {
let pf = &parsed_files[idx];
for import in &pf.module.imports {
if &dep_graph::module_path_to_id(&import.path) == to {
primary = Some((import.span, pf.filename.clone()));
break;
}
}
}
if primary.is_some() {
break;
}
}
let mut bag = DiagnosticBag::new();
let span = primary.as_ref().map_or_else(Span::dummy, |(s, _)| *s);
let diag = bag.error(code, format!("circular module dependency: {chain}"), span);
diag.note(format!(
"the cycle involves {} module(s): {}. Break it by removing one of the \
`use` edges, or extract the shared items into a third module that both \
can import",
participants.len(),
participants.join(", ")
));
let diags: Vec<Diagnostic> = bag.iter().cloned().collect();
match primary {
Some((_, ref filename)) => {
if let Some(&idx) = id_to_index
.values()
.find(|&&i| &parsed_files[i].filename == filename)
{
let source = &source_map.get_file(parsed_files[idx].file_id).content;
print_diagnostics(&diags, filename, source, !options.brief);
} else {
eprintln!("{}", render_codeonly(&diags));
}
}
None => {
eprintln!("{}", render_codeonly(&diags));
}
}
}
fn render_codeonly(diagnostics: &[Diagnostic]) -> String {
let mut out = String::new();
for diag in diagnostics {
let severity = match diag.severity {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
Severity::Hint => "hint",
};
out.push_str(&format!("{severity}[{}]: {}\n", diag.code, diag.message));
for note in &diag.notes {
out.push_str(&format!(" note: {note}\n"));
}
}
out.trim_end().to_string()
}
fn byte_to_line_col(source: &str, offset: usize) -> (usize, usize) {
let clamped = offset.min(source.len());
let prefix = &source[..clamped];
let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1;
let line_start = prefix.rfind('\n').map_or(0, |i| i + 1);
let col = prefix[line_start..].chars().count() + 1;
(line, col)
}
fn print_diagnostics(diagnostics: &[Diagnostic], filename: &str, source: &str, context: bool) {
if context {
let rendered = bock_errors::render(diagnostics, filename, source);
eprint!("{rendered}");
} else {
for diag in diagnostics {
let severity = match diag.severity {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
Severity::Hint => "hint",
};
let (line, col) = byte_to_line_col(source, diag.span.start);
eprintln!(
"{severity}[{}]: {} (at {filename}:{line}:{col})",
diag.code, diag.message
);
}
}
}
pub(crate) fn discover_bock_files(dir: &str) -> anyhow::Result<Vec<PathBuf>> {
let mut files = Vec::new();
discover_bock_files_recursive(Path::new(dir), &mut files)?;
files.sort();
Ok(files)
}
fn discover_bock_files_recursive(dir: &Path, files: &mut Vec<PathBuf>) -> anyhow::Result<()> {
let entries = std::fs::read_dir(dir)
.map_err(|e| anyhow::anyhow!("could not read directory '{}': {e}", dir.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if !name_str.starts_with('.')
&& name_str != "build"
&& name_str != "target"
&& name_str != "node_modules"
{
discover_bock_files_recursive(&path, files)?;
}
} else if path.is_file() {
if let Some(ext) = path.extension() {
if ext == "bock" {
files.push(path);
}
}
}
}
Ok(())
}
pub(crate) fn register_type_builtins(checker: &mut TypeChecker) {
let io_fn_ty = Type::Function(FnType {
params: vec![Type::Primitive(PrimitiveType::String)],
ret: Box::new(Type::Primitive(PrimitiveType::Void)),
effects: vec![],
});
for name in ["print", "println", "debug"] {
checker.env.define(name, io_fn_ty.clone());
}
for name in ["Duration", "Instant", "Channel"] {
checker.env.define(name, Type::Error);
}
let sleep_fn_ty = Type::Function(FnType {
params: vec![Type::Error],
ret: Box::new(Type::Primitive(PrimitiveType::Void)),
effects: vec![],
});
checker.env.define("sleep", sleep_fn_ty);
let spawn_fn_ty = Type::Function(FnType {
params: vec![Type::Error],
ret: Box::new(Type::Error),
effects: vec![],
});
checker.env.define("spawn", spawn_fn_ty);
let assert_ty = Type::Function(FnType {
params: vec![Type::Primitive(PrimitiveType::Bool)],
ret: Box::new(Type::Primitive(PrimitiveType::Void)),
effects: vec![],
});
checker.env.define("assert", assert_ty);
let expect_fn_ty = Type::Function(FnType {
params: vec![Type::Error],
ret: Box::new(Type::Error),
effects: vec![],
});
checker.env.define("expect", expect_fn_ty);
let never_fn_ty = Type::Function(FnType {
params: vec![],
ret: Box::new(Type::Primitive(PrimitiveType::Never)),
effects: vec![],
});
for name in ["todo", "unreachable"] {
checker.env.define(name, never_fn_ty.clone());
}
let constructor_fn_ty = Type::Function(FnType {
params: vec![Type::Error],
ret: Box::new(Type::Error),
effects: vec![],
});
for name in ["Ok", "Err"] {
checker.env.define(name, constructor_fn_ty.clone());
}
checker.env.define("Some", constructor_fn_ty.clone());
checker.env.define("None", Type::Error);
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn byte_to_line_col_counts_chars_not_bytes() {
let s = "abc\ndef";
assert_eq!(byte_to_line_col(s, 0), (1, 1));
assert_eq!(byte_to_line_col(s, 2), (1, 3));
assert_eq!(byte_to_line_col(s, 4), (2, 1)); let m = "fée x"; assert_eq!(byte_to_line_col(m, 5), (1, 5)); assert_eq!(byte_to_line_col(m, 999), (1, 6));
}
#[test]
fn brief_diagnostic_renders_line_col_not_byte_offsets() {
let source = "module m\nfn main() -> Void {\n bad\n}\n";
let bad_offset = source.find("bad").unwrap();
let (line, col) = byte_to_line_col(source, bad_offset);
assert_eq!((line, col), (3, 3));
let rendered = format!("error[E4002]: undefined variable `bad` (at m.bock:{line}:{col})");
assert!(rendered.contains("m.bock:3:3"), "{rendered}");
assert!(
!rendered.contains(".."),
"must not contain a byte range: {rendered}"
);
}
#[test]
fn test_discover_bock_files_recursive() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
let nested = sub.join("nested");
fs::create_dir_all(&nested).unwrap();
fs::write(dir.path().join("a.bock"), "").unwrap();
fs::write(sub.join("b.bock"), "").unwrap();
fs::write(nested.join("c.bock"), "").unwrap();
fs::write(dir.path().join("d.txt"), "").unwrap();
let files = discover_bock_files(&dir.path().to_string_lossy()).unwrap();
assert_eq!(files.len(), 3);
assert!(files.iter().all(|f| f.extension().unwrap() == "bock"));
}
#[test]
fn test_discover_skips_hidden_and_build_dirs() {
let dir = tempfile::tempdir().unwrap();
let hidden = dir.path().join(".hidden");
let build_dir = dir.path().join("build");
let target = dir.path().join("target");
fs::create_dir_all(&hidden).unwrap();
fs::create_dir_all(&build_dir).unwrap();
fs::create_dir_all(&target).unwrap();
fs::write(hidden.join("x.bock"), "").unwrap();
fs::write(build_dir.join("y.bock"), "").unwrap();
fs::write(target.join("z.bock"), "").unwrap();
fs::write(dir.path().join("main.bock"), "").unwrap();
let files = discover_bock_files(&dir.path().to_string_lossy()).unwrap();
assert_eq!(files.len(), 1);
}
#[test]
fn run_clean_file_returns_clean() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ok.bock");
fs::write(&path, "fn add(a: Int, b: Int) -> Int { a + b }\n").unwrap();
let outcome = run(vec![path], &CheckOptions::default()).unwrap();
assert_eq!(outcome, CheckOutcome::Clean);
assert!(outcome.is_clean());
}
#[test]
fn run_parse_error_returns_failed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("broken.bock");
fs::write(&path, "fn { broken\n").unwrap();
let outcome = run(vec![path], &CheckOptions::default()).unwrap();
assert_eq!(outcome, CheckOutcome::Failed);
assert!(!outcome.is_clean());
}
#[test]
fn run_missing_file_returns_failed() {
let path = PathBuf::from("/nonexistent/definitely-not-here-12345.bock");
let outcome = run(vec![path], &CheckOptions::default()).unwrap();
assert_eq!(outcome, CheckOutcome::Failed);
}
#[test]
fn run_analysis_error_returns_failed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ownership.bock");
fs::write(
&path,
"record Thing { id: Int }\nfn process() {\n let data = Thing { id: 1 }\n let archive = data\n let x = data\n}\n",
)
.unwrap();
let outcome = run(vec![path], &CheckOptions::default()).unwrap();
assert_eq!(outcome, CheckOutcome::Failed);
}
#[test]
fn find_module_cycle_reports_participants_in_order() {
use std::collections::HashSet;
let mut g = DepGraph::new();
g.add_module_with_deps("a".into(), HashSet::from(["b".to_string()]));
g.add_module_with_deps("b".into(), HashSet::from(["c".to_string()]));
g.add_module_with_deps("c".into(), HashSet::from(["a".to_string()]));
let cycle = find_module_cycle(&g).expect("a 3-module cycle must be found");
assert_eq!(cycle.first(), cycle.last());
for m in ["a", "b", "c"] {
assert!(
cycle.contains(&m.to_string()),
"cycle missing {m}: {cycle:?}"
);
}
}
#[test]
fn find_module_cycle_none_for_acyclic_graph() {
use std::collections::HashSet;
let mut g = DepGraph::new();
g.add_module_with_deps("app".into(), HashSet::from(["lib".to_string()]));
g.add_module("lib".into());
assert!(find_module_cycle(&g).is_none());
}
#[test]
fn run_circular_module_dependency_returns_failed() {
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join("a.bock");
let b = dir.path().join("b.bock");
fs::write(
&a,
"module a\nuse b.{ fromB }\npublic fn fromA() -> Int { 1 }\n",
)
.unwrap();
fs::write(
&b,
"module b\nuse a.{ fromA }\npublic fn fromB() -> Int { 2 }\n",
)
.unwrap();
let outcome = run(vec![a, b], &CheckOptions::default()).unwrap();
assert_eq!(outcome, CheckOutcome::Failed);
}
#[test]
fn check_outcome_is_clean_helper() {
assert!(CheckOutcome::Clean.is_clean());
assert!(!CheckOutcome::Failed.is_clean());
}
#[test]
fn aspect_parse_recognizes_v1_aspects() {
assert_eq!(Aspect::parse("types"), Some(Aspect::Types));
assert_eq!(Aspect::parse("context"), Some(Aspect::Context));
}
#[test]
fn aspect_parse_rejects_lint_and_unknown_in_v1() {
assert_eq!(Aspect::parse("lint"), None);
assert_eq!(Aspect::parse("ownership"), None);
assert_eq!(Aspect::parse(""), None);
}
#[test]
fn aspect_as_str_round_trips() {
for aspect in Aspect::ALL {
assert_eq!(Aspect::parse(aspect.as_str()), Some(aspect));
}
let valid = Aspect::valid_list();
assert!(valid.contains("types"));
assert!(valid.contains("context"));
}
#[test]
fn aspect_selection_empty_is_full_check() {
assert_eq!(
AspectSelection::from_raw(&[]).unwrap(),
AspectSelection::All
);
assert_eq!(
AspectSelection::from_raw(&["".to_string()]).unwrap(),
AspectSelection::All
);
assert_eq!(
AspectSelection::from_raw(&[",".to_string()]).unwrap(),
AspectSelection::All
);
}
#[test]
fn aspect_selection_comma_list_and_repeated_are_equivalent() {
let comma = AspectSelection::from_raw(&["types,context".to_string()]).unwrap();
let repeated =
AspectSelection::from_raw(&["types".to_string(), "context".to_string()]).unwrap();
assert_eq!(comma, repeated);
assert!(comma.runs(Aspect::Types));
assert!(comma.runs(Aspect::Context));
assert!(!comma.is_full());
}
#[test]
fn aspect_selection_single_aspect_runs_only_that_aspect() {
let only_types = AspectSelection::from_raw(&["types".to_string()]).unwrap();
assert!(only_types.runs(Aspect::Types));
assert!(!only_types.runs(Aspect::Context));
let only_context = AspectSelection::from_raw(&["context".to_string()]).unwrap();
assert!(only_context.runs(Aspect::Context));
assert!(!only_context.runs(Aspect::Types));
}
#[test]
fn aspect_selection_trims_whitespace() {
let sel = AspectSelection::from_raw(&[" types , context ".to_string()]).unwrap();
assert!(sel.runs(Aspect::Types));
assert!(sel.runs(Aspect::Context));
}
#[test]
fn aspect_selection_unknown_value_errors_with_the_offending_name() {
let err = AspectSelection::from_raw(&["types,bogus".to_string()]).unwrap_err();
assert_eq!(err, "bogus");
assert_eq!(
AspectSelection::from_raw(&["lint".to_string()]).unwrap_err(),
"lint"
);
}
#[test]
fn full_check_runs_every_aspect() {
let full = AspectSelection::All;
assert!(full.is_full());
assert!(full.runs(Aspect::Types));
assert!(full.runs(Aspect::Context));
}
#[test]
fn run_only_types_on_clean_file_returns_clean() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ok.bock");
fs::write(&path, "fn add(a: Int, b: Int) -> Int { a + b }\n").unwrap();
let options = CheckOptions {
aspects: AspectSelection::Only([Aspect::Types].into_iter().collect()),
brief: false,
strict: false,
};
let outcome = run(vec![path], &options).unwrap();
assert_eq!(outcome, CheckOutcome::Clean);
}
#[test]
fn run_only_context_on_clean_file_returns_clean() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ok.bock");
fs::write(&path, "fn add(a: Int, b: Int) -> Int { a + b }\n").unwrap();
let options = CheckOptions {
aspects: AspectSelection::Only([Aspect::Context].into_iter().collect()),
brief: false,
strict: false,
};
let outcome = run(vec![path], &options).unwrap();
assert_eq!(outcome, CheckOutcome::Clean);
}
#[test]
fn run_brief_on_clean_file_returns_clean() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ok.bock");
fs::write(&path, "fn add(a: Int, b: Int) -> Int { a + b }\n").unwrap();
let options = CheckOptions {
aspects: AspectSelection::All,
brief: true,
strict: false,
};
let outcome = run(vec![path], &options).unwrap();
assert_eq!(outcome, CheckOutcome::Clean);
}
#[test]
fn check_options_strictness_maps_strict_flag() {
let dev = CheckOptions::default();
assert!(!dev.strict);
assert_eq!(dev.strictness(), Strictness::Development);
let prod = CheckOptions {
aspects: AspectSelection::All,
brief: false,
strict: true,
};
assert_eq!(prod.strictness(), Strictness::Production);
}
#[test]
fn context_strictness_level_maps_profiles() {
assert_eq!(
context_strictness_level(Strictness::Sketch),
StrictnessLevel::Lax
);
assert_eq!(
context_strictness_level(Strictness::Development),
StrictnessLevel::Standard
);
assert_eq!(
context_strictness_level(Strictness::Production),
StrictnessLevel::Strict
);
}
const PUBLIC_ITEM_NO_CONTEXT: &str = "module Lib
public fn add(a: Int, b: Int) -> Int { a + b }
";
#[test]
fn default_check_treats_missing_context_as_warning_clean_exit() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lib.bock");
fs::write(&path, PUBLIC_ITEM_NO_CONTEXT).unwrap();
let outcome = run(vec![path], &CheckOptions::default()).unwrap();
assert_eq!(
outcome,
CheckOutcome::Clean,
"missing @context must be a warning (exit clean) at development strictness"
);
}
#[test]
fn strict_check_treats_missing_context_as_error_failed_exit() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lib.bock");
fs::write(&path, PUBLIC_ITEM_NO_CONTEXT).unwrap();
let options = CheckOptions {
aspects: AspectSelection::All,
brief: false,
strict: true,
};
let outcome = run(vec![path], &options).unwrap();
assert_eq!(
outcome,
CheckOutcome::Failed,
"missing @context must be an error (exit failed) under --strict / production"
);
}
#[test]
fn only_context_runs_validate_context_completeness_gate() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lib.bock");
fs::write(&path, PUBLIC_ITEM_NO_CONTEXT).unwrap();
let dev = CheckOptions {
aspects: AspectSelection::Only([Aspect::Context].into_iter().collect()),
brief: false,
strict: false,
};
assert_eq!(
run(vec![path.clone()], &dev).unwrap(),
CheckOutcome::Clean,
"--only=context at development strictness must surface completeness as a warning"
);
let strict = CheckOptions {
aspects: AspectSelection::Only([Aspect::Context].into_iter().collect()),
brief: false,
strict: true,
};
assert_eq!(
run(vec![path], &strict).unwrap(),
CheckOutcome::Failed,
"--only=context --strict must flag missing @context as an error"
);
}
#[test]
fn only_types_does_not_run_context_validation() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("lib.bock");
fs::write(&path, PUBLIC_ITEM_NO_CONTEXT).unwrap();
let options = CheckOptions {
aspects: AspectSelection::Only([Aspect::Types].into_iter().collect()),
brief: false,
strict: true,
};
assert_eq!(
run(vec![path], &options).unwrap(),
CheckOutcome::Clean,
"--only=types must not run context completeness validation even under --strict"
);
}
}