use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process;
use std::time::Instant;
use bock_air::{
lower_module, resolve_names_with_registry, Binding, ModuleRegistry, NameKind, NodeIdGen,
ResolvedName, SymbolTable,
};
use bock_ast::Visibility;
use bock_build::dep_graph::{self, DepGraph};
use bock_build::toolchain::ToolchainRegistry;
use bock_codegen::{
run_scaffolder, CodeGenerator, GoGenerator, JsGenerator, PyGenerator, RsGenerator,
ScaffoldConfig, SourceInfo, TsGenerator,
};
use bock_errors::{Diagnostic, DiagnosticBag, FileId, Severity, Span};
use bock_lexer::Lexer;
use bock_parser::Parser;
use bock_source::SourceMap;
use bock_types::{collect_exports, seed_imports, seed_prelude, Strictness, TypeChecker};
const KNOWN_TARGETS: &[&str] = &["js", "ts", "python", "rust", "go"];
pub struct BuildOptions {
pub targets: Vec<String>,
pub release: bool,
pub source_only: bool,
#[allow(dead_code)]
pub deterministic: bool,
pub strict: bool,
pub pin_all: bool,
pub source_map: bool,
}
pub fn run(options: &BuildOptions) -> anyhow::Result<()> {
let total_start = Instant::now();
let files = discover_bock_files_recursive(".")?;
if files.is_empty() {
eprintln!("error: no .bock files found");
process::exit(1);
}
println!(
"build: compiling {} source file{}",
files.len(),
if files.len() == 1 { "" } else { "s" }
);
let strictness = if options.strict || options.release {
Strictness::Production
} else {
Strictness::Development
};
let (scaffold_config, project_name) = read_scaffold_config()?;
if matches!(strictness, Strictness::Production) {
let project_root = std::env::current_dir()
.map_err(|e| anyhow::anyhow!("could not read current directory: {e}"))?;
run_production_gate(&project_root)?;
}
let frontend_start = Instant::now();
let mut source_map = SourceMap::new();
let mut parsed_files: Vec<ParsedFile> = Vec::new();
let mut found_errors = false;
for src in crate::stdlib::core_sources() {
match parse_stdlib_source(&src, &mut source_map) {
Ok(pf) => parsed_files.push(pf),
Err(()) => found_errors = true,
}
}
for file_path in &files {
match parse_file(file_path, &mut source_map) {
Ok(pf) => parsed_files.push(pf),
Err(()) => found_errors = true,
}
}
if found_errors {
eprintln!("build: aborting due to parse errors");
process::exit(1);
}
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 => {
eprintln!("error: circular module dependency detected");
process::exit(1);
}
};
let mut registry = ModuleRegistry::new();
let mut air_modules = Vec::new();
let mut source_infos = Vec::new();
let mut module_source_paths: Vec<PathBuf> = Vec::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);
match compile_frontend_with_registry(
&pf.module,
&pf.filename,
source_file,
®istry,
strictness,
pf.is_stdlib,
) {
Ok((air_module, checker)) => {
let exports = collect_exports(module_id, &pf.path, &checker, &air_module);
registry.register(exports);
air_modules.push(air_module);
source_infos.push(pf.filename.clone());
module_source_paths.push(pf.path.clone());
}
Err(()) => found_errors = true,
}
}
if found_errors {
eprintln!("build: aborting due to errors");
process::exit(1);
}
let frontend_ms = frontend_start.elapsed().as_millis();
println!(
" frontend: {frontend_ms}ms ({} modules)",
air_modules.len()
);
let toolchain_registry = ToolchainRegistry::with_builtins();
for target in &options.targets {
let target_start = Instant::now();
let output_dir = if options.release {
PathBuf::from(format!("build/release/{target}"))
} else {
PathBuf::from(format!("build/{target}"))
};
std::fs::create_dir_all(&output_dir).map_err(|e| {
anyhow::anyhow!(
"failed to create output directory {}: {e}",
output_dir.display()
)
})?;
let generator: Box<dyn CodeGenerator> = create_generator(target)?;
println!(" target: {target}");
let mut total_files_written = 0;
let module_inputs: Vec<(&bock_types::AIRModule, &Path)> = air_modules
.iter()
.zip(module_source_paths.iter())
.map(|(m, p)| (m, p.as_path()))
.collect();
let mut emitted_files: Vec<bock_codegen::OutputFile> = Vec::new();
match generator.generate_project(&module_inputs) {
Ok(mut generated) => {
let emit_url_comment = matches!(target.as_str(), "js" | "ts");
for output_file in &mut generated.files {
if options.source_map {
if let Some(sm) = output_file.source_map.as_mut() {
populate_source_map(sm, &parsed_files, &source_map);
}
}
let dest = output_dir.join(&output_file.path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
if options.source_map {
if let Some(sm) = &output_file.source_map {
let map_name = format!(
"{}.map",
output_file
.path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("output")
);
let map_path = dest.with_file_name(&map_name);
std::fs::write(&map_path, sm.to_source_map_v3_json())?;
if emit_url_comment {
if !output_file.content.is_empty()
&& !output_file.content.ends_with('\n')
{
output_file.content.push('\n');
}
output_file
.content
.push_str(&format!("//# sourceMappingURL={map_name}\n"));
}
total_files_written += 1;
}
}
std::fs::write(&dest, &output_file.content)?;
total_files_written += 1;
emitted_files.push(output_file.clone());
}
}
Err(e) => {
eprintln!("error: codegen failed for target {target}: {e}");
found_errors = true;
}
}
if found_errors {
eprintln!("build: aborting due to codegen errors");
process::exit(1);
}
if !options.source_only {
let target_config = scaffold_config.target(target).cloned().unwrap_or_default();
match run_scaffolder(
target,
&target_config,
&emitted_files,
project_name.as_deref(),
) {
Ok(scaffold_files) => {
for sf in &scaffold_files {
let dest = output_dir.join(&sf.path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&dest, &sf.content)?;
total_files_written += 1;
}
}
Err(e) => {
eprintln!("error: scaffolding failed for target {target}: {e}");
found_errors = true;
}
}
}
if found_errors {
eprintln!("build: aborting due to scaffolding errors");
process::exit(1);
}
if !options.source_only {
let target_config = scaffold_config.target(target).cloned().unwrap_or_default();
let framework = bock_codegen::effective_test_framework(target, &target_config);
match generator.generate_tests(&module_inputs, &framework) {
Ok(artifacts) => {
for tf in &artifacts.files {
let dest = output_dir.join(&tf.path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&dest, &tf.content)?;
total_files_written += 1;
}
if let Some(append) = &artifacts.entry_append {
if let Some(entry_rel) = entry_file_rel(target) {
let entry_path = output_dir.join(entry_rel);
if entry_path.exists() {
let mut content = std::fs::read_to_string(&entry_path)?;
content.push_str(append);
std::fs::write(&entry_path, content)?;
}
}
}
}
Err(e) => {
eprintln!("error: test transpilation failed for target {target}: {e}");
found_errors = true;
}
}
}
if found_errors {
eprintln!("build: aborting due to test-transpilation errors");
process::exit(1);
}
if !options.source_only {
if let Err(e) = format_output_tree(target, &output_dir) {
eprintln!(" warning: post-emit formatting skipped for {target}: {e}");
}
}
if !options.source_only {
if toolchain_registry.validates_per_project(target) {
match toolchain_registry.invoke_project(target, &output_dir, false) {
Ok(_result) => {}
Err(bock_build::toolchain::ToolchainError::NotFound {
install_hint, ..
}) => {
eprintln!(
" warning: {target} toolchain not found, skipping compilation.\n \
hint: {install_hint}"
);
}
Err(e) => {
eprintln!("error: target compilation failed: {e}");
found_errors = true;
}
}
} else {
let ext = target_file_extension(target);
let generated_files = find_files_with_extension(&output_dir, &ext)?;
for gen_file in &generated_files {
if is_transpiled_test_file(gen_file) {
continue;
}
match toolchain_registry.invoke(target, gen_file, false) {
Ok(_result) => {}
Err(bock_build::toolchain::ToolchainError::NotFound {
install_hint,
..
}) => {
eprintln!(
" warning: {target} toolchain not found, skipping compilation.\n \
hint: {install_hint}"
);
break;
}
Err(e) => {
eprintln!("error: target compilation failed: {e}");
found_errors = true;
}
}
}
}
}
let target_ms = target_start.elapsed().as_millis();
println!(
" wrote {total_files_written} file{} to {} ({target_ms}ms)",
if total_files_written == 1 { "" } else { "s" },
output_dir.display()
);
}
if found_errors {
eprintln!("build: completed with errors");
process::exit(1);
}
if options.pin_all {
let project_root = std::env::current_dir()
.map_err(|e| anyhow::anyhow!("could not read current directory: {e}"))?;
let pinned = pin_all_build_decisions(&project_root)?;
println!("build: pin-all pinned {pinned} decision(s)");
}
let total_ms = total_start.elapsed().as_millis();
println!("build: done ({total_ms}ms)");
Ok(())
}
fn entry_file_rel(target: &str) -> Option<&'static str> {
match target {
"rust" | "rs" => Some("src/main.rs"),
_ => None,
}
}
fn format_output_tree(target: &str, output_dir: &Path) -> anyhow::Result<()> {
match target {
"go" => {
let status = process::Command::new("gofmt")
.arg("-w")
.arg(output_dir)
.status()
.map_err(|e| anyhow::anyhow!("gofmt not available: {e}"))?;
if !status.success() {
anyhow::bail!("gofmt -w exited with status {status}");
}
Ok(())
}
"rust" | "rs" => {
let rs_files = find_files_with_extension(output_dir, "rs")?;
if rs_files.is_empty() {
return Ok(());
}
let status = process::Command::new("rustfmt")
.args(["--edition", "2021"])
.args(&rs_files)
.status()
.map_err(|e| anyhow::anyhow!("rustfmt not available: {e}"))?;
if !status.success() {
anyhow::bail!("rustfmt exited with status {status}");
}
Ok(())
}
_ => Ok(()),
}
}
fn read_scaffold_config() -> anyhow::Result<(ScaffoldConfig, Option<String>)> {
let path = Path::new("bock.project");
if !path.is_file() {
return Ok((ScaffoldConfig::default(), None));
}
let source = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("could not read bock.project: {e}"))?;
ScaffoldConfig::from_project_toml_with_name(&source)
.map_err(|e| anyhow::anyhow!("invalid project-mode configuration: {e}"))
}
fn run_production_gate(project_root: &Path) -> anyhow::Result<()> {
let writer = bock_ai::ManifestWriter::new(project_root);
let decisions = writer
.read_build()
.map_err(|e| anyhow::anyhow!("could not read build manifest: {e}"))?;
let report = bock_ai::validate_production(&decisions);
if !report.is_empty() {
eprint!("{}", report.render_error());
process::exit(1);
}
Ok(())
}
fn pin_all_build_decisions(project_root: &Path) -> anyhow::Result<usize> {
let build_root = project_root.join(".bock").join("decisions").join("build");
if !build_root.exists() {
return Ok(0);
}
let mut files: Vec<PathBuf> = Vec::new();
collect_json_files(&build_root, &mut files)?;
let who = pinned_by();
let now = chrono::Utc::now();
let mut total_pinned = 0usize;
for file in files {
let bytes = std::fs::read(&file)
.map_err(|e| anyhow::anyhow!("could not read {}: {e}", file.display()))?;
let mut entries: Vec<bock_ai::Decision> = serde_json::from_slice(&bytes)
.map_err(|e| anyhow::anyhow!("could not parse {}: {e}", file.display()))?;
let mut changed = false;
for entry in entries.iter_mut() {
if entry.pinned {
continue;
}
entry.pinned = true;
entry.pin_reason = Some(format!("bulk-pinned via `bock build --pin-all` by {who}"));
entry.pinned_at = Some(now);
entry.pinned_by = Some(who.clone());
changed = true;
total_pinned += 1;
}
if changed {
let pretty = serde_json::to_vec_pretty(&entries)
.map_err(|e| anyhow::anyhow!("could not serialize {}: {e}", file.display()))?;
std::fs::write(&file, pretty)
.map_err(|e| anyhow::anyhow!("could not write {}: {e}", file.display()))?;
}
}
Ok(total_pinned)
}
fn collect_json_files(root: &Path, out: &mut Vec<PathBuf>) -> anyhow::Result<()> {
for entry in std::fs::read_dir(root)? {
let entry = entry?;
let path = entry.path();
let file_type = entry.file_type()?;
if file_type.is_dir() {
collect_json_files(&path, out)?;
} else if path.extension().and_then(|e| e.to_str()) == Some("json") {
out.push(path);
}
}
Ok(())
}
fn pinned_by() -> String {
std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.unwrap_or_else(|_| "unknown".into())
}
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) -> 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);
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);
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,
) -> 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);
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);
return Err(());
}
Ok(ParsedFile {
path: src.logical_path.clone(),
filename,
file_id,
module,
is_stdlib: true,
})
}
fn compile_frontend_with_registry(
module: &bock_ast::Module,
filename: &str,
source_file: &bock_source::SourceFile,
registry: &ModuleRegistry,
strictness: Strictness,
is_stdlib: bool,
) -> Result<(bock_types::AIRModule, TypeChecker), ()> {
let strictness = if is_stdlib {
Strictness::Development
} else {
strictness
};
let mut all_diagnostics: Vec<Diagnostic> = Vec::new();
let mut symbols = SymbolTable::new();
register_builtins(&mut symbols);
let resolve_diags = resolve_names_with_registry(module, &mut symbols, registry);
collect_diagnostics(&mut all_diagnostics, &resolve_diags);
if has_errors(&all_diagnostics) {
print_diagnostics(&all_diagnostics, filename, &source_file.content);
return Err(());
}
let id_gen = NodeIdGen::new();
let mut air_module = lower_module(module, &id_gen, &symbols);
let mut checker = TypeChecker::new();
register_type_builtins(&mut checker);
seed_prelude(&mut checker, registry);
seed_imports(&mut checker, &module.imports, registry);
checker.check_module(&mut air_module);
collect_diagnostics(&mut all_diagnostics, &checker.diags);
if has_errors(&all_diagnostics) {
print_diagnostics(&all_diagnostics, filename, &source_file.content);
return Err(());
}
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);
let capability_diags = bock_types::verify_capabilities(&air_module, strictness);
collect_diagnostics(&mut all_diagnostics, &capability_diags);
if has_errors(&all_diagnostics) {
print_diagnostics(&all_diagnostics, filename, &source_file.content);
return Err(());
}
if !is_stdlib {
let warnings: Vec<&Diagnostic> = all_diagnostics
.iter()
.filter(|d| d.severity != Severity::Error)
.collect();
if !warnings.is_empty() {
let to_render: Vec<Diagnostic> = warnings.into_iter().cloned().collect();
print_diagnostics(&to_render, filename, &source_file.content);
}
}
Ok((air_module, checker))
}
fn populate_source_map(
sm: &mut bock_codegen::SourceMap,
parsed: &[ParsedFile],
source_map: &SourceMap,
) {
let max_file_id = sm.mappings.iter().map(|m| m.src_file_id).max().unwrap_or(0);
let mut contents: Vec<Option<(String, String)>> =
vec![None; (max_file_id as usize).saturating_add(1)];
for pf in parsed {
let file = source_map.get_file(pf.file_id);
let idx = pf.file_id.0 as usize;
if idx < contents.len() {
contents[idx] = Some((file.path.display().to_string(), file.content.clone()));
}
}
sm.sources = contents
.iter()
.enumerate()
.map(|(i, opt)| match opt {
Some((path, content)) => SourceInfo {
path: path.clone(),
content: Some(content.clone()),
},
None => SourceInfo {
path: format!("<unknown-{i}>"),
content: None,
},
})
.collect();
let content_refs: Vec<&str> = contents
.iter()
.map(|o| o.as_ref().map(|(_, c)| c.as_str()).unwrap_or(""))
.collect();
sm.resolve_positions(&content_refs);
}
fn create_generator(target: &str) -> anyhow::Result<Box<dyn CodeGenerator>> {
match target {
"js" => Ok(Box::new(JsGenerator::new())),
"ts" => Ok(Box::new(TsGenerator::new())),
"python" => Ok(Box::new(PyGenerator::new())),
"rust" => Ok(Box::new(RsGenerator::new())),
"go" => Ok(Box::new(GoGenerator::new())),
_ => {
anyhow::bail!(
"unknown target '{target}'. Valid targets: {}",
KNOWN_TARGETS.join(", ")
);
}
}
}
fn is_transpiled_test_file(path: &Path) -> bool {
matches!(
path.file_name().and_then(|s| s.to_str()),
Some("bock.test.js" | "bock.test.ts" | "test_bock.py")
)
}
fn target_file_extension(target: &str) -> String {
bock_codegen::TargetProfile::from_id(target)
.map(|p| p.conventions.file_extension)
.unwrap_or_else(|| "txt".to_string())
}
fn find_files_with_extension(dir: &Path, ext: &str) -> anyhow::Result<Vec<PathBuf>> {
let mut result = Vec::new();
if !dir.is_dir() {
return Ok(result);
}
let entries = std::fs::read_dir(dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
result.extend(find_files_with_extension(&path, ext)?);
} else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
result.push(path);
}
}
result.sort();
Ok(result)
}
fn discover_bock_files_recursive(dir: &str) -> anyhow::Result<Vec<PathBuf>> {
let mut files = Vec::new();
walk_dir_recursive(Path::new(dir), &mut files)?;
files.sort();
Ok(files)
}
fn walk_dir_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() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with('.')
|| name == "build"
|| name == "target"
|| name == "node_modules"
|| name == "test"
|| name == "tests"
{
continue;
}
}
walk_dir_recursive(&path, files)?;
} else if path.is_file() {
if let Some(ext) = path.extension() {
if ext == "bock" {
files.push(path);
}
}
}
}
Ok(())
}
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 print_diagnostics(diagnostics: &[Diagnostic], filename: &str, source: &str) {
let rendered = bock_errors::render(diagnostics, filename, source);
eprint!("{rendered}");
}
fn register_type_builtins(checker: &mut TypeChecker) {
use bock_types::{FnType, PrimitiveType, Type};
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);
checker.env.define("None", Type::Error);
}
fn register_builtins(symbols: &mut SymbolTable) {
let builtin_span = Span {
file: FileId(0),
start: 0,
end: 0,
};
let builtins = [
("print", u32::MAX - 1),
("println", u32::MAX - 2),
("debug", u32::MAX - 3),
("Ok", u32::MAX - 10),
("Err", u32::MAX - 11),
("Some", u32::MAX - 12),
("None", u32::MAX - 13),
];
for (name, def_id) in builtins {
symbols.define(
name.to_string(),
Binding {
name: name.to_string(),
resolved: ResolvedName {
def_id,
kind: NameKind::Function,
},
visibility: Visibility::Public,
span: builtin_span,
used: true,
is_import: false,
},
);
}
}
pub fn parse_targets(target: Option<String>, all_targets: bool) -> anyhow::Result<Vec<String>> {
if all_targets {
return Ok(KNOWN_TARGETS.iter().map(|s| (*s).to_string()).collect());
}
match target {
Some(t) => {
if !KNOWN_TARGETS.contains(&t.as_str()) {
anyhow::bail!(
"unknown target '{t}'. Valid targets: {}",
KNOWN_TARGETS.join(", ")
);
}
Ok(vec![t])
}
None => {
Ok(vec!["js".to_string()])
}
}
}