Debian Codegraph @

Xtree-house/skidder/src/build.rs

raw symbols SCIP
1 use std::fs::{self, File};
2 use std::io;
3 use std::path::Path;
4 use std::process::Command;
5 use std::sync::OnceLock;
6
7 use anyhow::{bail, ensure, Context, Result};
8 use sha1::{Digest, Sha1};
9 use tempfile::TempDir;
10 use walkdir::WalkDir;
11
12 use crate::{decompress, Metadata, LIB_EXTENSION};
13
14 type Checksum = [u8; 20];
15 fn is_fresh(grammar_dir: &Path, force: bool) -> Result<(Checksum, bool)> {
16 let src_dir = grammar_dir.join("src");
17 let cookie = grammar_dir.join(".BUILD_COOKIE");
18 let mut hasher = Sha1::new();
19 for file in WalkDir::new(src_dir) {
20 let file = file?;
21 let file_type = file.file_type();
22 // Hash any .c, .cc or .h file
23 if !file_type.is_file() {
24 continue;
25 }
26 let file_name = file.file_name();
27 let Some(file_name) = file_name.to_str() else {
28 continue;
29 };
30 let Some((_, extension)) = file_name.rsplit_once('.') else {
31 continue;
32 };
33 if !matches!(extension, "h" | "c" | "cc") {
34 continue;
35 }
36 let path = file.path();
37
38 hasher.update(file_name.as_bytes());
39 hasher.update([0, 0, 0, 0]);
40 File::open(path)
41 .and_then(|mut file| io::copy(&mut file, &mut hasher))
42 .with_context(|| format!("failed to read {}", path.display()))?;
43 hasher.update([0, 0, 0, 0]);
44 }
45
46 let checksum = hasher.finalize();
47 if force {
48 return Ok((checksum.into(), false));
49 }
50 let Ok(prev_checksum) = fs::read(cookie) else {
51 return Ok((checksum.into(), false));
52 };
53 Ok((checksum.into(), prev_checksum == checksum[..]))
54 }
55
56 #[cfg(not(windows))]
57 const SCANNER_OBJECT: &str = "scanner.o";
58 #[cfg(windows)]
59 const SCANNER_OBJECT: &str = "scanner.obj";
60 const BUILD_TARGET: &str = env!("BUILD_TARGET");
61 static CPP_COMPILER: OnceLock<cc::Tool> = OnceLock::new();
62 static C_COMPILER: OnceLock<cc::Tool> = OnceLock::new();
63
64 enum CompilerCommand {
65 Build,
66 BuildAndLink { obj_files: Vec<&'static str> },
67 }
68 impl CompilerCommand {
69 pub fn setup(self, build_dir: &Path, src_dir: &Path, file: &Path, out_file: &str) -> Command {
70 let cpp = file.extension().is_some_and(|ext| ext == "cc");
71 let compiler = if cpp {
72 CPP_COMPILER.get_or_init(|| {
73 cc::Build::new()
74 .cpp(true)
75 .opt_level(3)
76 .std("c++14")
77 .debug(false)
78 .cargo_metadata(false)
79 .host(BUILD_TARGET)
80 .target(BUILD_TARGET)
81 .get_compiler()
82 })
83 } else {
84 C_COMPILER.get_or_init(|| {
85 cc::Build::new()
86 // Note that we use a C++ compiler but force C mode below
87 // with "-xc". This is important for compilation of grammars
88 // that have C++ scanners. If we used `cpp(false)` then the
89 // scanner might miss symbols from the C++ standard library.
90 .cpp(true)
91 .debug(false)
92 .opt_level(3)
93 .std("c11")
94 .cargo_metadata(false)
95 .host(BUILD_TARGET)
96 .target(BUILD_TARGET)
97 .get_compiler()
98 })
99 };
100 let mut cmd = compiler.to_command();
101 cmd.current_dir(build_dir);
102 if compiler.is_like_msvc() {
103 cmd.args(["/nologo", "/LD", "/utf-8", "/I"]).arg(src_dir);
104 match self {
105 CompilerCommand::Build => {
106 cmd.arg(format!("/Fo{out_file}")).arg("/c").arg(file);
107 }
108 CompilerCommand::BuildAndLink { obj_files } => {
109 cmd.args(obj_files)
110 .arg(file)
111 .arg("/link")
112 .arg(format!("/out:{out_file}"));
113 }
114 }
115 } else {
116 #[cfg(not(windows))]
117 cmd.arg("-fPIC");
118 cmd.args(["-shared", "-fno-exceptions", "-o", out_file, "-I"])
119 .arg(src_dir);
120 if cfg!(all(
121 unix,
122 not(any(target_os = "macos", target_os = "illumos"))
123 )) {
124 cmd.arg("-Wl,-z,relro,-z,now");
125 }
126 match self {
127 CompilerCommand::Build => {
128 cmd.arg("-c");
129 }
130 CompilerCommand::BuildAndLink { obj_files } => {
131 cmd.args(obj_files);
132 }
133 }
134 if !cpp {
135 cmd.arg("-xc");
136 }
137 cmd.arg(file);
138 };
139 cmd
140 }
141 }
142
143 pub fn build_grammar(grammar_name: &str, grammar_dir: &Path, force: bool) -> Result<()> {
144 let src_dir = grammar_dir.join("src");
145 let mut parser = src_dir.join("parser.c");
146 ensure!(
147 parser.exists(),
148 "failed to compile {grammar_name}: {} not found!",
149 parser.display()
150 );
151 let (hash, fresh) = is_fresh(grammar_dir, force)?;
152 if fresh {
153 return Ok(());
154 }
155 let build_dir = TempDir::new().context("failed to create temporary build directory")?;
156 let metadata = Metadata::read(&grammar_dir.join("metadata.json"))
157 .with_context(|| format!("failed to read metadata for {grammar_name}"))?;
158 let Some(parser_definition) = metadata.parser_definition() else {
159 bail!("source directories with parser.c files must have parser definition metadata");
160 };
161 if parser_definition.compressed {
162 let decompressed_parser = build_dir.path().join(format!("{grammar_name}.c"));
163 let mut dst = File::create(&decompressed_parser).with_context(|| {
164 format!(
165 "failed to create parser.c file in temporary build directory {}",
166 build_dir.path().display()
167 )
168 })?;
169 File::open(&parser)
170 .map_err(anyhow::Error::from)
171 .and_then(|mut reader| decompress(&mut reader, &mut dst))
172 .with_context(|| {
173 format!("failed to decompress parser {}", build_dir.path().display())
174 })?;
175 parser = decompressed_parser;
176 }
177 let mut commands = Vec::new();
178 let mut obj_files = Vec::new();
179 if src_dir.join("scanner.c").exists() {
180 let scanner_cmd = CompilerCommand::Build.setup(
181 build_dir.path(),
182 &src_dir,
183 &src_dir.join("scanner.c"),
184 SCANNER_OBJECT,
185 );
186 obj_files.push(SCANNER_OBJECT);
187 commands.push(scanner_cmd)
188 } else if src_dir.join("scanner.cc").exists() {
189 let scanner_cmd = CompilerCommand::Build.setup(
190 build_dir.path(),
191 &src_dir,
192 &src_dir.join("scanner.cc"),
193 SCANNER_OBJECT,
194 );
195 obj_files.push(SCANNER_OBJECT);
196 commands.push(scanner_cmd)
197 }
198 let lib_name = format!("{grammar_name}.{LIB_EXTENSION}");
199 let parser_cmd = CompilerCommand::BuildAndLink { obj_files }.setup(
200 build_dir.path(),
201 &src_dir,
202 &parser,
203 &lib_name,
204 );
205 commands.push(parser_cmd);
206
207 for mut cmd in commands {
208 let output = cmd.output().context("Failed to execute compiler")?;
209 if !output.status.success() {
210 bail!(
211 "Parser compilation failed.\nStdout: {}\nStderr: {}",
212 String::from_utf8_lossy(&output.stdout),
213 String::from_utf8_lossy(&output.stderr)
214 );
215 }
216 }
217 let from = build_dir.path().join(lib_name);
218 let to = grammar_dir.join(grammar_name).with_extension(LIB_EXTENSION);
219 fs::copy(&from, &to).with_context(|| {
220 format!(
221 "failed to copy compiled library from {} to {}",
222 from.display(),
223 to.display()
224 )
225 })?;
226 let _ = fs::write(grammar_dir.join(".BUILD_COOKIE"), hash);
227 Ok(())
228 }