| 1 |
use anyhow::{anyhow, bail, Context, Result}; |
| 2 |
use serde::{Deserialize, Serialize}; |
| 3 |
use std::fs; |
| 4 |
use std::sync::atomic::{AtomicUsize, Ordering}; |
| 5 |
use std::sync::Arc; |
| 6 |
use std::time::SystemTime; |
| 7 |
use std::{ |
| 8 |
collections::HashSet, |
| 9 |
path::{Path, PathBuf}, |
| 10 |
process::Command, |
| 11 |
sync::mpsc::channel, |
| 12 |
}; |
| 13 |
use tempfile::TempPath; |
| 14 |
use tree_house::tree_sitter::Grammar; |
| 15 |
|
| 16 |
#[cfg(target_os = "macos")] |
| 17 |
const DYLIB_EXTENSION: &str = "dylib"; |
| 18 |
|
| 19 |
#[cfg(all(unix, not(target_os = "macos")))] |
| 20 |
const DYLIB_EXTENSION: &str = "so"; |
| 21 |
|
| 22 |
#[cfg(windows)] |
| 23 |
const DYLIB_EXTENSION: &str = "dll"; |
| 24 |
|
| 25 |
#[cfg(target_arch = "wasm32")] |
| 26 |
const DYLIB_EXTENSION: &str = "wasm"; |
| 27 |
|
| 28 |
#[derive(Debug, Serialize, Deserialize)] |
| 29 |
struct Configuration { |
| 30 |
#[serde(rename = "use-grammars")] |
| 31 |
pub grammar_selection: Option<GrammarSelection>, |
| 32 |
pub grammar: Vec<GrammarConfiguration>, |
| 33 |
} |
| 34 |
|
| 35 |
#[derive(Debug, Serialize, Deserialize)] |
| 36 |
#[serde(rename_all = "lowercase", untagged)] |
| 37 |
pub enum GrammarSelection { |
| 38 |
Only { only: HashSet<String> }, |
| 39 |
Except { except: HashSet<String> }, |
| 40 |
} |
| 41 |
|
| 42 |
#[derive(Debug, Serialize, Deserialize)] |
| 43 |
#[serde(deny_unknown_fields)] |
| 44 |
pub struct GrammarConfiguration { |
| 45 |
#[serde(rename = "name")] |
| 46 |
pub grammar_id: String, |
| 47 |
pub source: GrammarSource, |
| 48 |
} |
| 49 |
|
| 50 |
#[derive(Debug, Serialize, Deserialize)] |
| 51 |
#[serde(rename_all = "lowercase", untagged)] |
| 52 |
pub enum GrammarSource { |
| 53 |
Local { |
| 54 |
path: String, |
| 55 |
}, |
| 56 |
Git { |
| 57 |
#[serde(rename = "git")] |
| 58 |
remote: String, |
| 59 |
#[serde(rename = "rev")] |
| 60 |
revision: String, |
| 61 |
subpath: Option<String>, |
| 62 |
}, |
| 63 |
} |
| 64 |
|
| 65 |
const BUILD_TARGET: &str = env!("BUILD_TARGET"); |
| 66 |
const REMOTE_NAME: &str = "origin"; |
| 67 |
|
| 68 |
#[cfg(target_arch = "wasm32")] |
| 69 |
pub fn get_language(name: &str) -> Result<Option<Grammar>> { |
| 70 |
unimplemented!() |
| 71 |
} |
| 72 |
|
| 73 |
#[cfg(not(target_arch = "wasm32"))] |
| 74 |
pub fn get_language(name: &str) -> Result<Option<Grammar>> { |
| 75 |
let mut rel_library_path = PathBuf::new().join("grammars").join(name); |
| 76 |
rel_library_path.set_extension(DYLIB_EXTENSION); |
| 77 |
let library_path = crate::runtime_file(&rel_library_path); |
| 78 |
if !library_path.exists() { |
| 79 |
return Ok(None); |
| 80 |
} |
| 81 |
|
| 82 |
let grammar = unsafe { Grammar::new(name, &library_path) }?; |
| 83 |
Ok(Some(grammar)) |
| 84 |
} |
| 85 |
|
| 86 |
fn ensure_git_is_available() -> Result<()> { |
| 87 |
helix_stdx::env::which("git")?; |
| 88 |
Ok(()) |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
fn warn_if_workspace_languages_skipped(trust: &crate::workspace_trust::WorkspaceTrust) { |
| 94 |
let workspace_languages = crate::workspace_lang_config_file(); |
| 95 |
if !workspace_languages.exists() { |
| 96 |
return; |
| 97 |
} |
| 98 |
if trust |
| 99 |
.query_current(crate::workspace_trust::TrustQuery::LocalConfig) |
| 100 |
.is_trusted() |
| 101 |
{ |
| 102 |
return; |
| 103 |
} |
| 104 |
println!( |
| 105 |
"Note: workspace `{}` was skipped because the workspace is not trusted. Run \ |
| 106 |
`:workspace-trust` from an interactive helix session in this workspace to opt in.", |
| 107 |
workspace_languages.display(), |
| 108 |
); |
| 109 |
} |
| 110 |
|
| 111 |
pub fn fetch_grammars(strict: bool) -> Result<()> { |
| 112 |
ensure_git_is_available()?; |
| 113 |
|
| 114 |
|
| 115 |
let mut grammars = get_grammar_configs()?; |
| 116 |
grammars.retain(|grammar| !matches!(grammar.source, GrammarSource::Local { .. })); |
| 117 |
|
| 118 |
let total = grammars.len(); |
| 119 |
let counter = Arc::new(AtomicUsize::new(0)); |
| 120 |
|
| 121 |
println!("Fetching {} grammars", total); |
| 122 |
let counter = Arc::clone(&counter); |
| 123 |
|
| 124 |
let results = run_parallel(grammars, move |grammar| { |
| 125 |
let current = counter.fetch_add(1, Ordering::Relaxed) + 1; |
| 126 |
|
| 127 |
println!( |
| 128 |
"Fetching grammars ({}/{}): {}", |
| 129 |
current, total, grammar.grammar_id |
| 130 |
); |
| 131 |
fetch_grammar(grammar) |
| 132 |
}); |
| 133 |
|
| 134 |
let mut errors = Vec::new(); |
| 135 |
let mut git_updated = Vec::new(); |
| 136 |
let mut git_up_to_date = 0; |
| 137 |
let mut non_git = Vec::new(); |
| 138 |
|
| 139 |
for (grammar_id, res) in results { |
| 140 |
match res { |
| 141 |
Ok(FetchStatus::GitUpToDate) => git_up_to_date += 1, |
| 142 |
Ok(FetchStatus::GitUpdated { revision }) => git_updated.push((grammar_id, revision)), |
| 143 |
Ok(FetchStatus::NonGit) => non_git.push(grammar_id), |
| 144 |
Err(e) => errors.push((grammar_id, e)), |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
non_git.sort_unstable(); |
| 149 |
git_updated.sort_unstable_by(|a, b| a.0.cmp(&b.0)); |
| 150 |
|
| 151 |
if git_up_to_date != 0 { |
| 152 |
println!("{} up to date git grammars", git_up_to_date); |
| 153 |
} |
| 154 |
|
| 155 |
if !non_git.is_empty() { |
| 156 |
println!("{} non git grammars", non_git.len()); |
| 157 |
println!("\t{:?}", non_git); |
| 158 |
} |
| 159 |
|
| 160 |
if !git_updated.is_empty() { |
| 161 |
println!("{} updated grammars", git_updated.len()); |
| 162 |
|
| 163 |
let longest_id = git_updated.iter().map(|x| x.0.len()).max().unwrap(); |
| 164 |
for (id, rev) in git_updated { |
| 165 |
println!( |
| 166 |
"\t{id:width$} now on {rev}", |
| 167 |
id = id, |
| 168 |
width = longest_id, |
| 169 |
rev = rev |
| 170 |
); |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
if !errors.is_empty() { |
| 175 |
let len = errors.len(); |
| 176 |
for (i, (grammar, error)) in errors.into_iter().enumerate() { |
| 177 |
println!("Failure {}/{len}: {grammar} {error}", i + 1); |
| 178 |
} |
| 179 |
if strict { |
| 180 |
bail!("{len} grammars failed to fetch"); |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
Ok(()) |
| 185 |
} |
| 186 |
|
| 187 |
pub fn build_grammars(target: Option<String>, strict: bool) -> Result<()> { |
| 188 |
ensure_git_is_available()?; |
| 189 |
|
| 190 |
let grammars = get_grammar_configs()?; |
| 191 |
|
| 192 |
let total = grammars.len(); |
| 193 |
let counter = Arc::new(AtomicUsize::new(0)); |
| 194 |
|
| 195 |
println!("Building {} grammars", grammars.len()); |
| 196 |
|
| 197 |
let counter = Arc::clone(&counter); |
| 198 |
let results = run_parallel(grammars, move |grammar| { |
| 199 |
let current = counter.fetch_add(1, Ordering::Relaxed) + 1; |
| 200 |
|
| 201 |
println!( |
| 202 |
"Building grammars ({}/{}): {}", |
| 203 |
current, total, grammar.grammar_id |
| 204 |
); |
| 205 |
build_grammar(grammar, target.as_deref()) |
| 206 |
}); |
| 207 |
|
| 208 |
let mut errors = Vec::new(); |
| 209 |
let mut already_built = 0; |
| 210 |
let mut built = Vec::new(); |
| 211 |
|
| 212 |
for (grammar_id, res) in results { |
| 213 |
match res { |
| 214 |
Ok(BuildStatus::AlreadyBuilt) => already_built += 1, |
| 215 |
Ok(BuildStatus::Built) => built.push(grammar_id), |
| 216 |
Err(e) => errors.push((grammar_id, e)), |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
built.sort_unstable(); |
| 221 |
|
| 222 |
if already_built != 0 { |
| 223 |
println!("{} grammars already built", already_built); |
| 224 |
} |
| 225 |
|
| 226 |
if !built.is_empty() { |
| 227 |
println!("{} grammars built now", built.len()); |
| 228 |
println!("\t{:?}", built); |
| 229 |
} |
| 230 |
|
| 231 |
if !errors.is_empty() { |
| 232 |
let len = errors.len(); |
| 233 |
for (i, (grammar_id, error)) in errors.into_iter().enumerate() { |
| 234 |
println!("Failure {}/{len}: {grammar_id} {error}", i + 1); |
| 235 |
} |
| 236 |
if strict { |
| 237 |
bail!("{len} grammars failed to build"); |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
Ok(()) |
| 242 |
} |
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
fn get_grammar_configs() -> Result<Vec<GrammarConfiguration>> { |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
at |
| 253 |
|
| 254 |
let trust = crate::workspace_trust::WorkspaceTrust::new(Default::default()); |
| 255 |
warn_if_workspace_languages_skipped(&trust); |
| 256 |
let config: Configuration = crate::config::user_lang_config(&trust) |
| 257 |
.context("Could not parse languages.toml")? |
| 258 |
.try_into()?; |
| 259 |
|
| 260 |
let grammars = match config.grammar_selection { |
| 261 |
Some(GrammarSelection::Only { only: selections }) => config |
| 262 |
.grammar |
| 263 |
.into_iter() |
| 264 |
.filter(|grammar| selections.contains(&grammar.grammar_id)) |
| 265 |
.collect(), |
| 266 |
Some(GrammarSelection::Except { except: rejections }) => config |
| 267 |
.grammar |
| 268 |
.into_iter() |
| 269 |
.filter(|grammar| !rejections.contains(&grammar.grammar_id)) |
| 270 |
.collect(), |
| 271 |
None => config.grammar, |
| 272 |
}; |
| 273 |
|
| 274 |
Ok(grammars) |
| 275 |
} |
| 276 |
|
| 277 |
pub fn get_grammar_names() -> Result<Option<HashSet<String>>> { |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
let trust = crate::workspace_trust::WorkspaceTrust::new(Default::default()); |
| 282 |
warn_if_workspace_languages_skipped(&trust); |
| 283 |
let config: Configuration = crate::config::user_lang_config(&trust) |
| 284 |
.context("Could not parse languages.toml")? |
| 285 |
.try_into()?; |
| 286 |
|
| 287 |
let grammars = match config.grammar_selection { |
| 288 |
Some(GrammarSelection::Only { only: selections }) => Some(selections), |
| 289 |
Some(GrammarSelection::Except { except: rejections }) => Some( |
| 290 |
config |
| 291 |
.grammar |
| 292 |
.into_iter() |
| 293 |
.map(|grammar| grammar.grammar_id) |
| 294 |
.filter(|id| !rejections.contains(id)) |
| 295 |
.collect(), |
| 296 |
), |
| 297 |
None => None, |
| 298 |
}; |
| 299 |
|
| 300 |
Ok(grammars) |
| 301 |
} |
| 302 |
|
| 303 |
fn run_parallel<F, Res>(grammars: Vec<GrammarConfiguration>, job: F) -> Vec<(String, Result<Res>)> |
| 304 |
where |
| 305 |
F: Fn(GrammarConfiguration) -> Result<Res> + Send + 'static + Clone, |
| 306 |
Res: Send + 'static, |
| 307 |
{ |
| 308 |
let pool = threadpool::Builder::new().build(); |
| 309 |
let (tx, rx) = channel(); |
| 310 |
|
| 311 |
for grammar in grammars { |
| 312 |
let tx = tx.clone(); |
| 313 |
let job = job.clone(); |
| 314 |
|
| 315 |
pool.execute(move || { |
| 316 |
|
| 317 |
|
| 318 |
let _ = tx.send((grammar.grammar_id.clone(), job(grammar))); |
| 319 |
}); |
| 320 |
} |
| 321 |
|
| 322 |
drop(tx); |
| 323 |
|
| 324 |
rx.iter().collect() |
| 325 |
} |
| 326 |
|
| 327 |
enum FetchStatus { |
| 328 |
GitUpToDate, |
| 329 |
GitUpdated { revision: String }, |
| 330 |
NonGit, |
| 331 |
} |
| 332 |
|
| 333 |
#[derive(Copy, Clone)] |
| 334 |
enum GitObjectFormat { |
| 335 |
Sha1, |
| 336 |
Sha256, |
| 337 |
} |
| 338 |
|
| 339 |
impl GitObjectFormat { |
| 340 |
fn as_str(&self) -> &'static str { |
| 341 |
match self { |
| 342 |
Self::Sha1 => "sha1", |
| 343 |
Self::Sha256 => "sha256", |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
fn extract_object_format_from_revision(rev: &str) -> (GitObjectFormat, &str) { |
| 349 |
if let Some(stripped) = rev.strip_prefix("sha1:") { |
| 350 |
return (GitObjectFormat::Sha1, stripped); |
| 351 |
} |
| 352 |
|
| 353 |
if let Some(stripped) = rev.strip_prefix("sha256:") { |
| 354 |
return (GitObjectFormat::Sha256, stripped); |
| 355 |
} |
| 356 |
|
| 357 |
if rev.len() == 64 && rev.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 358 |
return (GitObjectFormat::Sha256, rev); |
| 359 |
} |
| 360 |
|
| 361 |
(GitObjectFormat::Sha1, rev) |
| 362 |
} |
| 363 |
|
| 364 |
struct VendoredGrammar { |
| 365 |
dir: PathBuf, |
| 366 |
} |
| 367 |
|
| 368 |
impl VendoredGrammar { |
| 369 |
fn new(grammar: &str) -> Self { |
| 370 |
let dir = crate::runtime_dirs() |
| 371 |
.first() |
| 372 |
.expect("No runtime directories provided") |
| 373 |
.join("grammars") |
| 374 |
.join("sources") |
| 375 |
.join(grammar); |
| 376 |
|
| 377 |
Self { dir } |
| 378 |
} |
| 379 |
|
| 380 |
|
| 381 |
fn revision(&self) -> Option<String> { |
| 382 |
git(&self.dir, ["rev-parse", "HEAD"]).ok() |
| 383 |
} |
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
fn fetch(&self, remote: &str, rev: &str, object_format: GitObjectFormat) -> Result<()> { |
| 390 |
self.reinit(remote, object_format)?; |
| 391 |
|
| 392 |
git(&self.dir, ["fetch", "--depth", "1", REMOTE_NAME, rev])?; |
| 393 |
git(&self.dir, ["checkout", rev])?; |
| 394 |
|
| 395 |
Ok(()) |
| 396 |
} |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
fn init(&self, remote: &str, object_format: GitObjectFormat) -> Result<()> { |
| 402 |
|
| 403 |
fs::create_dir_all(&self.dir).context(format!( |
| 404 |
"Could not create grammar directory {:?}", |
| 405 |
&self.dir |
| 406 |
))?; |
| 407 |
|
| 408 |
|
| 409 |
if !self.dir.join(".git").exists() { |
| 410 |
git( |
| 411 |
&self.dir, |
| 412 |
["init", "--object-format", object_format.as_str()], |
| 413 |
)?; |
| 414 |
} |
| 415 |
|
| 416 |
|
| 417 |
if self.remote().as_deref() != Some(remote) { |
| 418 |
self.set_remote(remote)?; |
| 419 |
} |
| 420 |
|
| 421 |
Ok(()) |
| 422 |
} |
| 423 |
|
| 424 |
|
| 425 |
fn reinit(&self, remote: &str, object_format: GitObjectFormat) -> Result<()> { |
| 426 |
fs::remove_dir_all(&self.dir)?; |
| 427 |
self.init(remote, object_format)?; |
| 428 |
Ok(()) |
| 429 |
} |
| 430 |
|
| 431 |
|
| 432 |
fn remote(&self) -> Option<String> { |
| 433 |
git(&self.dir, ["remote", "get-url", REMOTE_NAME]).ok() |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
fn set_remote(&self, remote: &str) -> Result<()> { |
| 438 |
git(&self.dir, ["remote", "set-url", REMOTE_NAME, remote]) |
| 439 |
.or_else(|_| git(&self.dir, ["remote", "add", REMOTE_NAME, remote]))?; |
| 440 |
Ok(()) |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> { |
| 445 |
let GrammarSource::Git { |
| 446 |
remote, revision, .. |
| 447 |
} = grammar.source |
| 448 |
else { |
| 449 |
return Ok(FetchStatus::NonGit); |
| 450 |
}; |
| 451 |
|
| 452 |
let repo = VendoredGrammar::new(&grammar.grammar_id); |
| 453 |
|
| 454 |
let (object_format, revision) = extract_object_format_from_revision(&revision); |
| 455 |
|
| 456 |
|
| 457 |
repo.init(&remote, object_format)?; |
| 458 |
|
| 459 |
if repo.revision().is_some_and(|rev| rev == revision) { |
| 460 |
return Ok(FetchStatus::GitUpToDate); |
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
repo.fetch(&remote, revision, object_format)?; |
| 465 |
|
| 466 |
Ok(FetchStatus::GitUpdated { |
| 467 |
revision: revision.to_string(), |
| 468 |
}) |
| 469 |
} |
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
fn git<I, S>(repository_dir: &Path, args: I) -> Result<String> |
| 474 |
where |
| 475 |
I: IntoIterator<Item = S>, |
| 476 |
S: AsRef<std::ffi::OsStr>, |
| 477 |
{ |
| 478 |
let output = Command::new("git") |
| 479 |
.args(args) |
| 480 |
.current_dir(repository_dir) |
| 481 |
.output()?; |
| 482 |
|
| 483 |
if output.status.success() { |
| 484 |
Ok(String::from_utf8_lossy(&output.stdout) |
| 485 |
.trim_end() |
| 486 |
.to_owned()) |
| 487 |
} else { |
| 488 |
|
| 489 |
Err(anyhow!( |
| 490 |
"Git command failed.\nStdout: {}\nStderr: {}", |
| 491 |
String::from_utf8_lossy(&output.stdout), |
| 492 |
String::from_utf8_lossy(&output.stderr), |
| 493 |
)) |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
enum BuildStatus { |
| 498 |
AlreadyBuilt, |
| 499 |
Built, |
| 500 |
} |
| 501 |
|
| 502 |
fn build_grammar(grammar: GrammarConfiguration, target: Option<&str>) -> Result<BuildStatus> { |
| 503 |
let grammar_dir = if let GrammarSource::Local { path } = &grammar.source { |
| 504 |
PathBuf::from(&path) |
| 505 |
} else { |
| 506 |
crate::runtime_dirs() |
| 507 |
.first() |
| 508 |
.expect("No runtime directories provided") |
| 509 |
.join("grammars") |
| 510 |
.join("sources") |
| 511 |
.join(&grammar.grammar_id) |
| 512 |
}; |
| 513 |
|
| 514 |
let grammar_dir_entries = grammar_dir.read_dir().with_context(|| { |
| 515 |
format!( |
| 516 |
"Failed to read directory {:?}. Did you use 'hx --grammar fetch'?", |
| 517 |
grammar_dir |
| 518 |
) |
| 519 |
})?; |
| 520 |
|
| 521 |
if grammar_dir_entries.count() == 0 { |
| 522 |
return Err(anyhow!( |
| 523 |
"Directory {:?} is empty. Did you use 'hx --grammar fetch'?", |
| 524 |
grammar_dir |
| 525 |
)); |
| 526 |
}; |
| 527 |
|
| 528 |
let path = match &grammar.source { |
| 529 |
GrammarSource::Git { |
| 530 |
subpath: Some(subpath), |
| 531 |
.. |
| 532 |
} => grammar_dir.join(subpath), |
| 533 |
_ => grammar_dir, |
| 534 |
} |
| 535 |
.join("src"); |
| 536 |
|
| 537 |
build_tree_sitter_library(&path, grammar, target) |
| 538 |
} |
| 539 |
|
| 540 |
fn build_tree_sitter_library( |
| 541 |
src_path: &Path, |
| 542 |
grammar: GrammarConfiguration, |
| 543 |
target: Option<&str>, |
| 544 |
) -> Result<BuildStatus> { |
| 545 |
let header_path = src_path; |
| 546 |
let parser_path = src_path.join("parser.c"); |
| 547 |
let mut scanner_path = src_path.join("scanner.c"); |
| 548 |
|
| 549 |
let scanner_path = if scanner_path.exists() { |
| 550 |
Some(scanner_path) |
| 551 |
} else { |
| 552 |
scanner_path.set_extension("cc"); |
| 553 |
if scanner_path.exists() { |
| 554 |
Some(scanner_path) |
| 555 |
} else { |
| 556 |
None |
| 557 |
} |
| 558 |
}; |
| 559 |
let parser_lib_path = crate::runtime_dirs() |
| 560 |
.first() |
| 561 |
.expect("No runtime directories provided") |
| 562 |
.join("grammars"); |
| 563 |
let mut library_path = parser_lib_path.join(&grammar.grammar_id); |
| 564 |
library_path.set_extension(DYLIB_EXTENSION); |
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
if std::env::var("OUT_DIR").is_ok() && std::env::var("CARGO").is_ok() { |
| 570 |
if let Some(scanner_path) = scanner_path.as_ref().and_then(|path| path.to_str()) { |
| 571 |
println!("cargo:rerun-if-changed={scanner_path}"); |
| 572 |
} |
| 573 |
if let Some(parser_path) = parser_path.to_str() { |
| 574 |
println!("cargo:rerun-if-changed={parser_path}"); |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
let recompile = needs_recompile(&library_path, &parser_path, scanner_path.as_ref()) |
| 579 |
.context("Failed to compare source and binary timestamps")?; |
| 580 |
|
| 581 |
if !recompile { |
| 582 |
return Ok(BuildStatus::AlreadyBuilt); |
| 583 |
} |
| 584 |
|
| 585 |
let mut config = cc::Build::new(); |
| 586 |
config |
| 587 |
.cpp(true) |
| 588 |
.opt_level(3) |
| 589 |
.cargo_metadata(false) |
| 590 |
.host(BUILD_TARGET) |
| 591 |
.target(target.unwrap_or(BUILD_TARGET)); |
| 592 |
let compiler = config.get_compiler(); |
| 593 |
let mut command = Command::new(compiler.path()); |
| 594 |
command.current_dir(src_path); |
| 595 |
for (key, value) in compiler.env() { |
| 596 |
command.env(key, value); |
| 597 |
} |
| 598 |
|
| 599 |
command.args(compiler.args()); |
| 600 |
|
| 601 |
let _path_guard; |
| 602 |
|
| 603 |
if compiler.is_like_msvc() { |
| 604 |
command |
| 605 |
.args(["/nologo", "/LD", "/I"]) |
| 606 |
.arg(header_path) |
| 607 |
.arg("/utf-8") |
| 608 |
.arg("/std:c11"); |
| 609 |
if let Some(scanner_path) = scanner_path.as_ref() { |
| 610 |
if scanner_path.extension() == Some("c".as_ref()) { |
| 611 |
command.arg(scanner_path); |
| 612 |
} else { |
| 613 |
let mut cpp_command = Command::new(compiler.path()); |
| 614 |
cpp_command.current_dir(src_path); |
| 615 |
for (key, value) in compiler.env() { |
| 616 |
cpp_command.env(key, value); |
| 617 |
} |
| 618 |
cpp_command.args(compiler.args()); |
| 619 |
let object_file = |
| 620 |
library_path.with_file_name(format!("{}_scanner.obj", &grammar.grammar_id)); |
| 621 |
cpp_command |
| 622 |
.args(["/nologo", "/LD", "/I"]) |
| 623 |
.arg(header_path) |
| 624 |
.arg("/utf-8") |
| 625 |
.arg("/std:c++14") |
| 626 |
.arg(format!("/Fo{}", object_file.display())) |
| 627 |
.arg("/c") |
| 628 |
.arg(scanner_path); |
| 629 |
let output = cpp_command |
| 630 |
.output() |
| 631 |
.context("Failed to execute C++ compiler")?; |
| 632 |
|
| 633 |
if !output.status.success() { |
| 634 |
return Err(anyhow!( |
| 635 |
"Parser compilation failed.\nStdout: {}\nStderr: {}", |
| 636 |
String::from_utf8_lossy(&output.stdout), |
| 637 |
String::from_utf8_lossy(&output.stderr) |
| 638 |
)); |
| 639 |
} |
| 640 |
command.arg(&object_file); |
| 641 |
_path_guard = TempPath::try_from_path(object_file).unwrap(); |
| 642 |
} |
| 643 |
} |
| 644 |
|
| 645 |
command |
| 646 |
.arg(parser_path) |
| 647 |
.arg("/link") |
| 648 |
.arg(format!("/out:{}", library_path.to_str().unwrap())); |
| 649 |
} else { |
| 650 |
#[cfg(not(windows))] |
| 651 |
command.arg("-fPIC"); |
| 652 |
|
| 653 |
command |
| 654 |
.arg("-shared") |
| 655 |
.arg("-fno-exceptions") |
| 656 |
.arg("-I") |
| 657 |
.arg(header_path) |
| 658 |
.arg("-o") |
| 659 |
.arg(&library_path); |
| 660 |
|
| 661 |
if let Some(scanner_path) = scanner_path.as_ref() { |
| 662 |
if scanner_path.extension() == Some("c".as_ref()) { |
| 663 |
command.arg("-xc").arg("-std=c11").arg(scanner_path); |
| 664 |
} else { |
| 665 |
let mut cpp_command = Command::new(compiler.path()); |
| 666 |
cpp_command.current_dir(src_path); |
| 667 |
for (key, value) in compiler.env() { |
| 668 |
cpp_command.env(key, value); |
| 669 |
} |
| 670 |
cpp_command.args(compiler.args()); |
| 671 |
let object_file = |
| 672 |
library_path.with_file_name(format!("{}_scanner.o", &grammar.grammar_id)); |
| 673 |
|
| 674 |
#[cfg(not(windows))] |
| 675 |
cpp_command.arg("-fPIC"); |
| 676 |
|
| 677 |
cpp_command |
| 678 |
.arg("-fno-exceptions") |
| 679 |
.arg("-I") |
| 680 |
.arg(header_path) |
| 681 |
.arg("-o") |
| 682 |
.arg(&object_file) |
| 683 |
.arg("-std=c++14") |
| 684 |
.arg("-c") |
| 685 |
.arg(scanner_path); |
| 686 |
let output = cpp_command |
| 687 |
.output() |
| 688 |
.context("Failed to execute C++ compiler")?; |
| 689 |
if !output.status.success() { |
| 690 |
return Err(anyhow!( |
| 691 |
"Parser compilation failed.\nStdout: {}\nStderr: {}", |
| 692 |
String::from_utf8_lossy(&output.stdout), |
| 693 |
String::from_utf8_lossy(&output.stderr) |
| 694 |
)); |
| 695 |
} |
| 696 |
|
| 697 |
command.arg(&object_file); |
| 698 |
_path_guard = TempPath::try_from_path(object_file).unwrap(); |
| 699 |
} |
| 700 |
} |
| 701 |
command.arg("-xc").arg("-std=c11").arg(parser_path); |
| 702 |
if cfg!(all( |
| 703 |
unix, |
| 704 |
not(any(target_os = "macos", target_os = "illumos")) |
| 705 |
)) { |
| 706 |
command.arg("-Wl,-z,relro,-z,now"); |
| 707 |
} |
| 708 |
} |
| 709 |
|
| 710 |
let output = command |
| 711 |
.output() |
| 712 |
.context("Failed to execute C/C++ compiler")?; |
| 713 |
if !output.status.success() { |
| 714 |
return Err(anyhow!( |
| 715 |
"Parser compilation failed.\nStdout: {}\nStderr: {}", |
| 716 |
String::from_utf8_lossy(&output.stdout), |
| 717 |
String::from_utf8_lossy(&output.stderr) |
| 718 |
)); |
| 719 |
} |
| 720 |
|
| 721 |
Ok(BuildStatus::Built) |
| 722 |
} |
| 723 |
|
| 724 |
fn needs_recompile( |
| 725 |
lib_path: &Path, |
| 726 |
parser_c_path: &Path, |
| 727 |
scanner_path: Option<&PathBuf>, |
| 728 |
) -> Result<bool> { |
| 729 |
if !lib_path.exists() { |
| 730 |
return Ok(true); |
| 731 |
} |
| 732 |
let lib_mtime = mtime(lib_path)?; |
| 733 |
if mtime(parser_c_path)? > lib_mtime { |
| 734 |
return Ok(true); |
| 735 |
} |
| 736 |
if let Some(scanner_path) = scanner_path { |
| 737 |
if mtime(scanner_path)? > lib_mtime { |
| 738 |
return Ok(true); |
| 739 |
} |
| 740 |
} |
| 741 |
Ok(false) |
| 742 |
} |
| 743 |
|
| 744 |
fn mtime(path: &Path) -> Result<SystemTime> { |
| 745 |
Ok(fs::metadata(path)?.modified()?) |
| 746 |
} |
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
pub fn load_runtime_file(language: &str, filename: &str) -> Result<String, std::io::Error> { |
| 751 |
let path = crate::runtime_file(PathBuf::new().join("queries").join(language).join(filename)); |
| 752 |
std::fs::read_to_string(path) |
| 753 |
} |