Skip to content

Commit 85674b2

Browse files
committed
fix(build): require fresh single-file destinations
Fixes #37
1 parent 808cc6a commit 85674b2

6 files changed

Lines changed: 310 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ format: `Unreleased` then release buckets, grouped by impact.
2121
canonical decimal spelling across the interpreter, native C11, and Core
2222
Wasm lanes, allowing computed integers to be printed without handwritten
2323
digit tables.
24+
- Single-file native and Web/Wasm builds now require fresh destinations.
25+
Native output is reserved before compiler invocation and Web output uses an
26+
atomic create-new directory, so existing sources/artifacts and concurrent
27+
winners are never overwritten or merged; invalid parents report `SPX-I301`
28+
and existing destinations report `SPX-I307`.
2429
- Native contract-failure stderr now includes the canonical clause, persistent
2530
function identity, and declaration-ordered observed arguments, matching the
2631
interpreter's human repair detail while preserving the normalized status

‎docs/CLI-GUIDE.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,14 @@ available build targets differ between the standalone and full toolchains.
117117
Commands that list `--json` in scoped help provide their structured form for
118118
automation.
119119

120+
Every explicit single-file build output is create-new. Native builds reserve
121+
the exact destination before invoking the compiler and publish through that
122+
retained file; Web/Wasm builds atomically create a fresh package directory.
123+
An existing file, directory, symlink, or concurrent winner is rejected with
124+
`SPX-I307` and left unchanged. An invalid or unavailable parent is rejected as
125+
`SPX-I301`; builds never merge into an existing directory or overwrite their
126+
own `.spx` input.
127+
120128
## Diagnose command-line errors
121129

122130
Command-line grammar errors exit without compiling the input. Start with

‎src/cli/build.rs‎

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use std::fs;
1+
use std::fs::{self, File, OpenOptions};
2+
use std::io::{self, Write as _};
23
use std::path::{Component, Path, PathBuf};
34

45
use same_file::Handle;
@@ -38,6 +39,139 @@ pub(crate) struct ProjectOutputParent {
3839
retain: bool,
3940
}
4041

42+
/// Create-new reservation for one single-file native artifact.
43+
///
44+
/// Holding the exact destination file from before compilation through final
45+
/// publication prevents both accidental overwrite and two concurrent builds
46+
/// from claiming the same spelling.
47+
pub(crate) struct SourceNativeOutput {
48+
parent: PathBuf,
49+
parent_identity: Handle,
50+
path: PathBuf,
51+
identity: Option<Handle>,
52+
file: Option<File>,
53+
retained: bool,
54+
}
55+
56+
impl SourceNativeOutput {
57+
pub(crate) fn prepare(path: &Path) -> Result<Self, Diagnostic> {
58+
path.file_name().ok_or_else(|| {
59+
parent_error("single-file native output must name one destination file")
60+
})?;
61+
let parent = path
62+
.parent()
63+
.filter(|parent| !parent.as_os_str().is_empty())
64+
.unwrap_or_else(|| Path::new("."));
65+
let parent_metadata = fs::symlink_metadata(parent).map_err(|error| {
66+
parent_error(format!(
67+
"cannot inspect single-file native output parent {}: {error}",
68+
parent.display()
69+
))
70+
})?;
71+
if !is_plain_directory(&parent_metadata) {
72+
return Err(parent_error(
73+
"single-file native output parent must be a real non-reparse directory",
74+
));
75+
}
76+
let parent_identity = Handle::from_path(parent).map_err(|error| {
77+
parent_error(format!(
78+
"cannot identify single-file native output parent: {error}"
79+
))
80+
})?;
81+
let file = OpenOptions::new()
82+
.read(true)
83+
.write(true)
84+
.create_new(true)
85+
.open(path)
86+
.map_err(|error| {
87+
let code = if error.kind() == io::ErrorKind::AlreadyExists {
88+
"SPX-I307"
89+
} else {
90+
"SPX-I301"
91+
};
92+
Diagnostic::io(
93+
code,
94+
format!(
95+
"cannot reserve fresh single-file native destination {}: {error}",
96+
path.display()
97+
),
98+
)
99+
})?;
100+
let identity = Handle::from_file(file).map_err(|error| {
101+
parent_error(format!(
102+
"cannot identify reserved single-file native destination: {error}"
103+
))
104+
})?;
105+
let file = identity.as_file().try_clone().map_err(|error| {
106+
parent_error(format!("cannot retain native destination handle: {error}"))
107+
})?;
108+
Ok(Self {
109+
parent: parent.to_path_buf(),
110+
parent_identity,
111+
path: path.to_path_buf(),
112+
identity: Some(identity),
113+
file: Some(file),
114+
retained: false,
115+
})
116+
}
117+
118+
pub(crate) fn publish(&mut self, compiled: &Path) -> Result<(), Diagnostic> {
119+
if !same_plain_directory(&self.parent, &self.parent_identity)
120+
|| Handle::from_path(&self.path).ok().as_ref() != self.identity.as_ref()
121+
{
122+
return Err(parent_error(
123+
"single-file native destination changed during compilation",
124+
));
125+
}
126+
let mut compiled_file = File::open(compiled).map_err(|error| {
127+
parent_error(format!("cannot open compiled native artifact: {error}"))
128+
})?;
129+
let metadata = compiled_file.metadata().map_err(|error| {
130+
parent_error(format!("cannot inspect compiled native artifact: {error}"))
131+
})?;
132+
if !metadata.is_file() {
133+
return Err(parent_error("compiled native artifact is not a plain file"));
134+
}
135+
let file = self
136+
.file
137+
.as_mut()
138+
.ok_or_else(|| parent_error("single-file native destination handle is unavailable"))?;
139+
io::copy(&mut compiled_file, file).map_err(|error| {
140+
parent_error(format!("cannot publish native artifact bytes: {error}"))
141+
})?;
142+
file.set_permissions(metadata.permissions())
143+
.map_err(|error| {
144+
parent_error(format!(
145+
"cannot publish native artifact permissions: {error}"
146+
))
147+
})?;
148+
file.flush().map_err(|error| {
149+
parent_error(format!("cannot flush native artifact publication: {error}"))
150+
})?;
151+
if Handle::from_path(&self.path).ok().as_ref() != self.identity.as_ref() {
152+
return Err(parent_error(
153+
"single-file native destination changed during publication",
154+
));
155+
}
156+
self.retained = true;
157+
Ok(())
158+
}
159+
}
160+
161+
impl Drop for SourceNativeOutput {
162+
fn drop(&mut self) {
163+
if self.retained
164+
|| !same_plain_directory(&self.parent, &self.parent_identity)
165+
|| Handle::from_path(&self.path).ok().as_ref() != self.identity.as_ref()
166+
{
167+
return;
168+
}
169+
drop(self.file.take());
170+
drop(self.identity.take());
171+
let _ = fs::remove_file(&self.path);
172+
}
173+
}
174+
41175
struct CreatedProjectOutputParent {
42176
grandparent: PathBuf,
43177
grandparent_identity: Handle,

‎src/cli_driver.rs‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2555,7 +2555,34 @@ fn build_source(options: &cli::build::BuildOptions, input: &Path) -> Result<(),
25552555
.expect("source build options always have an output");
25562556
match options.target.as_str() {
25572557
"native" => {
2558-
codegen::build(&program, output).map_err(|error| report(&[error], false))?;
2558+
let mut destination = cli::build::SourceNativeOutput::prepare(output)
2559+
.map_err(|error| report(&[error], false))?;
2560+
let c_source = codegen::emit_c(&program).map_err(|error| report(&[error], false))?;
2561+
let leaf = format!("program{}", std::env::consts::EXE_SUFFIX);
2562+
let mut scratch = native_scratch::Scratch::create(&leaf, None).map_err(|error| {
2563+
report(
2564+
&[Diagnostic::io(
2565+
"SPX-I301",
2566+
format!("cannot create native build scratch: {error}"),
2567+
)],
2568+
false,
2569+
)
2570+
})?;
2571+
codegen::compile_native_executable(&c_source, scratch.path())
2572+
.map_err(|error| report(&[error], false))?;
2573+
scratch.seal().map_err(|error| {
2574+
report(
2575+
&[Diagnostic::io(
2576+
"SPX-I301",
2577+
format!("cannot seal native build scratch: {error}"),
2578+
)],
2579+
false,
2580+
)
2581+
})?;
2582+
destination
2583+
.publish(scratch.path())
2584+
.map_err(|error| report(&[error], false))?;
2585+
let _ = scratch.cleanup();
25592586
println!("built native executable {}", output.display());
25602587
}
25612588
"web" | "wasm" => {

‎src/wasm.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1735,10 +1735,18 @@ pub fn build_web(program: &Program, output: &Path) -> Result<(), Diagnostic> {
17351735
"for admitted scalar exports, use --target web --profile internal-strings-v1 --export <stable-id>; generics, resources and public String signatures remain outside that profile",
17361736
));
17371737
}
1738-
std::fs::create_dir_all(output).map_err(|error| {
1738+
std::fs::create_dir(output).map_err(|error| {
1739+
let code = if error.kind() == std::io::ErrorKind::AlreadyExists {
1740+
"SPX-I307"
1741+
} else {
1742+
"SPX-I301"
1743+
};
17391744
Diagnostic::io(
1740-
"SPX-I301",
1741-
format!("cannot create web output {}: {error}", output.display()),
1745+
code,
1746+
format!(
1747+
"cannot create fresh web output {}: {error}",
1748+
output.display()
1749+
),
17421750
)
17431751
})?;
17441752
let wasm_bytes = emit_resolved_module(&resolved)?;

‎tests/compiler.rs‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,3 +474,126 @@ fn human_diagnostics_include_terminal_safe_source_locations() {
474474
"{\"code\":\"SPX-T001\",\"severity\":\"error\",\"message\":\"invalid source\",\"path\":\"src/main.spx\",\"location\":{\"line\":2,\"column\":3,\"start\":4,\"end\":9},\"help\":\"replace it\"}"
475475
);
476476
}
477+
478+
#[test]
479+
fn single_file_build_refuses_existing_and_invalid_destinations_without_clobbering() {
480+
let root = std::env::temp_dir().join(format!(
481+
"semaprax-source-build-freshness-{}-{}",
482+
std::process::id(),
483+
std::time::SystemTime::now()
484+
.duration_since(std::time::UNIX_EPOCH)
485+
.unwrap()
486+
.as_nanos()
487+
));
488+
std::fs::create_dir(&root).unwrap();
489+
let source = root.join("input.spx");
490+
std::fs::write(&source, VALID).unwrap();
491+
let source_bytes = std::fs::read(&source).unwrap();
492+
493+
let run = |target: &str, output: &Path| {
494+
Command::new(env!("CARGO_BIN_EXE_semaprax"))
495+
.arg("build")
496+
.arg(&source)
497+
.args(["--target", target, "-o"])
498+
.arg(output)
499+
.output()
500+
.unwrap()
501+
};
502+
503+
let victim = root.join("victim");
504+
std::fs::write(&victim, b"precious\n").unwrap();
505+
let result = run("native", &victim);
506+
assert_eq!(result.status.code(), Some(1));
507+
assert!(String::from_utf8_lossy(&result.stderr).contains("SPX-I307"));
508+
assert_eq!(std::fs::read(&victim).unwrap(), b"precious\n");
509+
510+
let result = run("native", &source);
511+
assert_eq!(result.status.code(), Some(1));
512+
assert!(String::from_utf8_lossy(&result.stderr).contains("SPX-I307"));
513+
assert_eq!(std::fs::read(&source).unwrap(), source_bytes);
514+
515+
let web = root.join("web");
516+
std::fs::create_dir(&web).unwrap();
517+
std::fs::write(web.join("index.html"), b"mine\n").unwrap();
518+
std::fs::write(web.join("keep.txt"), b"keep\n").unwrap();
519+
let result = run("web", &web);
520+
assert_eq!(result.status.code(), Some(1));
521+
assert!(String::from_utf8_lossy(&result.stderr).contains("SPX-I307"));
522+
assert_eq!(std::fs::read(web.join("index.html")).unwrap(), b"mine\n");
523+
assert_eq!(std::fs::read(web.join("keep.txt")).unwrap(), b"keep\n");
524+
525+
let missing = root.join("missing").join("artifact");
526+
let result = run("native", &missing);
527+
assert_eq!(result.status.code(), Some(1));
528+
assert!(String::from_utf8_lossy(&result.stderr).contains("SPX-I301"));
529+
assert!(!root.join("missing").exists());
530+
531+
#[cfg(unix)]
532+
{
533+
use std::os::unix::fs::PermissionsExt as _;
534+
let read_only = root.join("read-only");
535+
std::fs::create_dir(&read_only).unwrap();
536+
std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o555)).unwrap();
537+
let output = read_only.join("artifact");
538+
let result = run("native", &output);
539+
std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o755)).unwrap();
540+
assert_eq!(result.status.code(), Some(1));
541+
assert!(String::from_utf8_lossy(&result.stderr).contains("SPX-I301"));
542+
assert!(!output.exists());
543+
std::fs::remove_dir(read_only).unwrap();
544+
}
545+
546+
if Command::new("clang").arg("--version").output().is_ok() {
547+
let fresh = root.join(format!("fresh{}", std::env::consts::EXE_SUFFIX));
548+
let result = run("native", &fresh);
549+
assert!(
550+
result.status.success(),
551+
"{}",
552+
String::from_utf8_lossy(&result.stderr)
553+
);
554+
let executed = Command::new(&fresh).output().unwrap();
555+
assert!(executed.status.success());
556+
assert_eq!(executed.stdout, b"42\n");
557+
std::fs::remove_file(fresh).unwrap();
558+
}
559+
560+
let concurrent = root.join("concurrent-web");
561+
let command = || {
562+
let mut child = Command::new(env!("CARGO_BIN_EXE_semaprax"));
563+
child
564+
.arg("build")
565+
.arg(&source)
566+
.args(["--target", "web", "-o"])
567+
.arg(&concurrent)
568+
.stdout(std::process::Stdio::piped())
569+
.stderr(std::process::Stdio::piped());
570+
child.spawn().unwrap()
571+
};
572+
let first = command();
573+
let second = command();
574+
let results = [
575+
first.wait_with_output().unwrap(),
576+
second.wait_with_output().unwrap(),
577+
];
578+
assert_eq!(
579+
results
580+
.iter()
581+
.filter(|result| result.status.success())
582+
.count(),
583+
1
584+
);
585+
let loser = results
586+
.iter()
587+
.find(|result| !result.status.success())
588+
.unwrap();
589+
assert_eq!(loser.status.code(), Some(1));
590+
assert!(String::from_utf8_lossy(&loser.stderr).contains("SPX-I307"));
591+
std::fs::remove_dir_all(concurrent).unwrap();
592+
593+
std::fs::remove_file(web.join("index.html")).unwrap();
594+
std::fs::remove_file(web.join("keep.txt")).unwrap();
595+
std::fs::remove_dir(web).unwrap();
596+
std::fs::remove_file(victim).unwrap();
597+
std::fs::remove_file(source).unwrap();
598+
std::fs::remove_dir(root).unwrap();
599+
}

0 commit comments

Comments
 (0)