cargo-playdate 0.2.4

Build tool for neat yellow console.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fmt::Debug;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;

use anyhow::Context;
use anyhow::anyhow;
use anyhow::ensure;
use cargo::CargoResult;
use cargo::core::Package;
use cargo::core::Target;
use cargo::core::Verbosity;
use cargo::core::compiler::CompileKind;
use cargo::core::compiler::CrateType;
use cargo::util::command_prelude::CompileMode;
use playdate::compile::dylib_suffix_for_host_opt;
use playdate::compile::static_lib_suffix;
use playdate::io::soft_link_checked;
use playdate::toolchain::gcc::ArmToolchain;
use playdate::toolchain::sdk::Sdk;
use termcolor::Color;

use crate::cli::cmd::Cmd;
use crate::config::Config;
use crate::layout::CargoLayout;
use crate::layout::Layout;
use crate::layout::LayoutLockable;
use crate::layout::ForTargetLayout;
use crate::logger::LogErr;
use crate::proc::args_line_for_proc;
use crate::proc::cargo_proxy_cmd;
use crate::proc::reader::CargoJsonReader;
use crate::proc::reader::format::ArtifactProfile;
use crate::utils::cargo::CompileKindExt;
use crate::utils::path::AsRelativeTo;
use crate::utils::workspace::PossibleTargets;


pub mod plan;
pub mod rustflags;


pub fn build<'cfg>(config: &'cfg Config<'cfg>) -> CargoResult<Vec<BuildProduct<'cfg>>> {
	if config.dry_run {
		return Ok(Default::default());
	}

	// get plan _before_ cargo invocation:
	let plan = config.build_plan()?;

	// call cargo:
	let mut cargo = cargo_proxy_cmd(&config, &Cmd::Build)?;

	// add build-std:
	// https://github.com/rust-lang/cargo/issues/8733
	// https://stackoverflow.com/a/76614919/829264
	// We cannot specify build-std for one target, so for all if needed for one:
	if !has_only_nopd_targets(config)? {
		cargo.args(["-Zbuild-std=core,alloc", "-Zunstable-options"]);
	}
	config.log().verbose(|mut log| {
		            log.status("Cargo", args_line_for_proc(&cargo));
	            });


	// read cargo output:
	let artifacts = read_cargo_output(config, cargo)?;

	let mut products = Vec::new();

	for (package, target, art) in artifacts {
		log::debug!(
		            "cargo: rustc: artifact: {}:{} ({:?}) {:#?}",
		            art.package_id.name(),
		            art.target.name,
		            art.target.kind(),
		            art.filenames.iter().map(|p| p.as_relative_to_root(config))
		);

		// That's easier and faster then build bcx and inspecting unit-graph
		let invocations = plan.build_package_invocations(&package.package_id())
		                      .collect::<Vec<_>>();

		let mapping = art.filenames
		                 .iter()
		                 .flat_map(|path| {
			                 let invocation =
				                 invocations.iter()
				                            .find(|inv| inv.links.contains_key(path) || inv.outputs.contains(path));
			                 debug_assert!(invocation.is_some());
			                 log::trace!("{:?} <== {}", invocation.map(|i| i.kind), path.display());
			                 invocation.map(|i| (path, i))
		                 })
		                 .map(|(p, i)| {
			                 let ct = if art.executable.as_deref() == Some(p.as_path()) {
				                 CrateType::Bin
			                 } else {
				                 let ct = config.rustc_outputs(CompileMode::Build, &art.target.kind(), &i.kind)
				                                .log_err_cargo(config)
				                                .into_iter()
				                                .flat_map(|out| out.0.into_iter())
				                                .find(|ft| {
					                                // compare with final filename that should be:
					                                let name = ft.uplift_filename(target);
					                                p.file_name() == Some(OsStr::new(&name))
				                                })
				                                .map(|fty| fty.crate_type)
				                                .flatten()
				                                .unwrap_or_else(|| {
					                                // We're probably never goes to this fallback, but it should be there anyway:
					                                guess_crate_type(config, &p, art.target.kind(), i.kind)
				                                });
				                 log::debug!(
				                             "crate type: {ct} - {:?}",
				                             p.file_name().map(|s| s.to_string_lossy())
				);
				                 ct
			                 };
			                 (p, ct, i)
		                 });


		for (path, ct, inv) in mapping {
			let layout = config.layout_for(inv.kind)?.lock(config.workspace.config())?;
			let artifact = CargoArtifact { package,
			                               path,
			                               name: art.target.name,
			                               ct: ct.clone(),
			                               ck: inv.kind,
			                               profile: art.profile.to_owned(),
			                               example: target.is_example() };
			let product = match ct {
				CrateType::Bin if artifact.ck.is_playdate() => build_binary(config, layout, artifact),
				CrateType::Dylib | CrateType::Cdylib if artifact.ck.is_simulator() => {
					build_library(config, layout, artifact)
				},
				CrateType::Staticlib if artifact.ck.is_playdate() => build_library(config, layout, artifact),
				_ => {
					let name = if package.name() == art.target.name {
						Cow::Borrowed(art.target.name.as_str())
					} else {
						format!("{}, crate {}", package.name(), art.target.name).into()
					};
					let target = if artifact.ck.is_playdate() {
						"playdate"
					} else {
						"simulator"
					};
					config.log().status_with_color(
					                               "Skip",
					                               format!(
						"drop {name}, can't build {} targeting {target}",
						artifact.ct
					),
					                               Color::Yellow,
					);
					continue;
				},
			};


			if !config.compile_options.build_config.keep_going {
				products.push(product?);
			} else {
				if let Ok(product) = product.log_err_cargo(config) {
					products.push(product);
				}
			}

			config.log()
			      .status("Finished", format!("{} of {}", ct, inv.package_name));
		}
	}


	config.log().verbose(|mut log| {
		            log.status("Finished", "cargo execution, got products:");
		            for (i, p) in products.iter().enumerate() {
			            let (head, msg) = match p {
				            BuildProduct::Success { name, src_ct, dst_ct, .. } => {
				               let ct = if dst_ct == src_ct {
					               format!("{dst_ct}")
				               } else {
					               format!("{src_ct} -> {dst_ct}")
				               };
				               ("Build", format!("[{i}] {name} ({ct})"))
			               },
			               BuildProduct::Skip { reason, ct, .. } => {
				               ("Skip", format!("[{i}] ({ct}) with reason: {reason}"))
			               },
			            };
			            log.status_with_color(head, msg, Color::White);
		            }
	            });
	Ok(products)
}


fn read_cargo_output<'cc>(
	config: &'cc Config,
	cargo: Command)
	-> CargoResult<Vec<(&'cc Package, &'cc Target, crate::proc::reader::format::Artifact)>> {
	use crate::proc::reader::format::CargoMessage;

	let mut reader = CargoJsonReader::new(cargo)?;
	let mut build_finished_success = None;

	let artifacts = {
		let mut_ref = &mut build_finished_success;
		reader.read()?.filter_map(|m| {
			              // don't print BuildFinished(true) yet:
			              if !matches!(m, CargoMessage::BuildFinished { success: true }) {
				              config.log().print_cargo_message(&m);
			              }
			              match m {
				              CargoMessage::CompilerArtifact(art) => Some(art),
			                 CargoMessage::BuildFinished { success } => {
				                 *mut_ref = Some(success);
				                 None
			                 },

			                 CargoMessage::CompilerMessage { message } => {
				                 if !config.compile_options.build_config.emit_json() {
					                 match message.level.as_str() {
						                 level if level == "warning" || "error" == level => {
						                    let message = message.rendered
						                                         .trim()
						                                         .strip_prefix(&format!("{level}: "))
						                                         .map(Cow::Borrowed)
						                                         .unwrap_or(message.rendered.as_str().into());

						                    if level == "warning" {
							                    config.log().warn(message);
						                    } else {
							                    config.log().error(message);
						                    }
					                    },
					                    _ => (),
					                 }
				                 }
				                 None
			                 },
			                 _ => None,
			              }
		              })
	};


	let possible_targets = config.possible_targets()?;

	// Add completion to iterator with asking & logging process status.
	// It's looks a little bit ugly with map to `Option` then `flat_map`, but
	// after optimization there is no these perturbations.
	// Also we don't need to fail entire process if one target fails and so status will not ok.
	let artifacts =
		map_artifacts(possible_targets, artifacts).map(|v| Some(v))
		                                          .chain([reader].into_iter()
		                                                         .flat_map(|mut r| {
			                                                         r.status()
			                                                          .log_err_cargo(config)
			                                                          .ok()
			                                                          .map(|status| {
				                                                          status.exit_ok().log_err_cargo(config).ok()
			                                                          })
			                                                          .flatten()
		                                                         })
		                                                         .map(|_| None))
		                                          .flatten()
		                                          .collect::<Vec<_>>();
	let success = build_finished_success.filter(|v| *v)
	                                    .ok_or_else(|| anyhow!("build not successful"));
	if !config.compile_options.build_config.keep_going {
		success?;
	} else {
		success.log_err_cargo(config).ok();
	}

	Ok(artifacts)
}


fn map_artifacts<'cargo, 'cc>(
	targets: impl Iterator<Item = PossibleTargets<'cc>>,
	artifacts: impl Iterator<Item = crate::proc::reader::format::Artifact> + 'cargo)
	-> impl Iterator<Item = (&'cc Package, &'cc Target, crate::proc::reader::format::Artifact)> {
	let targets = targets.collect::<Vec<_>>();
	artifacts.filter_map(move |art| {
		         targets.iter()
		                .find(|(p, ..)| p.package_id() == art.package_id)
		                .and_then(|(package, targets, ..)| {
			                targets.into_iter()
			                       .find(|t| t.name() == art.target.name.as_str() && t.kind() == &art.target.kind())
			                       .map(|target| (*package, *target, art))
		                })
	         })
}


#[derive(Debug)]
struct CargoArtifact<'cfg, 'cr, Name: AsRef<str> + Debug> {
	package: &'cfg Package,
	path: &'cr Path,
	/// Crate name
	name: Name,

	ct: CrateType,
	ck: CompileKind,
	profile: ArtifactProfile,

	#[allow(dead_code)]
	example: bool,
}


#[derive(Debug)]
pub enum BuildProduct<'cfg> {
	Success {
		package: &'cfg Package,

		/// Crate-target ID
		name: String,

		src_ct: CrateType,
		dst_ct: CrateType,
		ck: CompileKind,
		profile: ArtifactProfile,

		path: PathBuf,
		layout: ForTargetLayout<PathBuf>,
	},
	Skip {
		reason: String,

		package: &'cfg Package,
		ct: CrateType,
		ck: CompileKind,
	},
}

impl<'cfg> BuildProduct<'cfg> {
	fn skip_as_unsupported<S: AsRef<str> + Debug>(artifact: CargoArtifact<'cfg, '_, S>) -> Self {
		let reason = format!(
		                     "{} ({}) {:?} unsupported target {:?}",
		                     artifact.package.name(),
		                     artifact.name.as_ref(),
		                     artifact.ct,
		                     artifact.ck
		);
		Self::Skip { reason,
		             ct: artifact.ct,
		             ck: artifact.ck,
		             package: artifact.package }
	}
}


impl<'t> Config<'t> {
	fn get_sdk_for(&self, ct: &CrateType, ck: &CompileKind) -> anyhow::Result<&Sdk> {
		let msg = format!("Linking without SDK is not supported yet (target: {ct}, compile-kind: {ck:?})");
		self.sdk().with_context(|| msg).log_err()
	}

	fn get_gcc_for(&self, ct: &CrateType, ck: &CompileKind) -> anyhow::Result<&ArmToolchain> {
		let msg =
			format!("Linking without ARM GNU toolchain is not supported yet (target: {ct}, compile-kind: {ck:?})");
		self.gcc().with_context(|| msg).log_err()
	}
}


fn build_binary<'cfg, Layout, S>(config: &'cfg Config,
                                 layout: Layout,
                                 artifact: CargoArtifact<'cfg, '_, S>)
                                 -> anyhow::Result<BuildProduct<'cfg>>
	where Layout: AsRef<CargoLayout>,
	      S: AsRef<str> + Debug
{
	ensure!(
	        matches!(artifact.path.try_exists(), Ok(true)),
	        "artifact {} not found at {}",
	        artifact.name.as_ref(),
	        artifact.path.display()
	);

	let mut pdl = ForTargetLayout::new(
	                                   layout.as_ref(),
	                                   artifact.package.name().as_str(),
	                                   Some(artifact.name.as_ref()),
	).lock(config.workspace.config())?;
	pdl.as_mut().prepare()?;

	let product = if artifact.ck.is_playdate() {
		ensure!(artifact.ct == CrateType::Bin, "executable binary expected");

		// product should be in pd-layout:
		let pdl_ref = pdl.as_inner();
		let product = {
			use playdate::layout::Layout as _;
			pdl_ref.binary()
		};
		let linked = soft_link_checked(&artifact.path, &product, true, pdl_ref.dest())?;
		log::debug!(
		            "{} linked (overwritten: {linked}) {}",
		            artifact.ct,
		            product.as_relative_to_root(config).display()
		);

		BuildProduct::Success { ck: artifact.ck,
		                        src_ct: artifact.ct,
		                        dst_ct: CrateType::Bin,
		                        profile: artifact.profile,
		                        layout: pdl_ref.to_owned(),
		                        path: product.to_path_buf().into(),
		                        package: artifact.package,
		                        name: artifact.name.as_ref().to_owned() }
	} else {
		// Currently this case is usually unreachable, but who knows future…
		BuildProduct::skip_as_unsupported(artifact)
	};

	Ok(product)
}


fn build_library<'cfg, Layout, S>(config: &'cfg Config,
                                  layout: Layout,
                                  artifact: CargoArtifact<'cfg, '_, S>)
                                  -> anyhow::Result<BuildProduct<'cfg>>
	where Layout: AsRef<CargoLayout>,
	      S: AsRef<str> + Debug
{
	config.log().status(
	                    "Compiling",
	                    format!(
		"{} of {}{}",
		artifact.ct,
		artifact.package,
		if config.workspace.config().extra_verbose() {
			format!(" from {}", artifact.path.as_relative_to_root(config).display())
		} else {
			Default::default()
		}
	),
	);
	ensure!(
	        matches!(artifact.path.try_exists(), Ok(true)),
	        "artifact {} not found at {}",
	        artifact.name.as_ref(),
	        artifact.path.display()
	);

	let mut pdl = ForTargetLayout::new(
	                                   layout.as_ref(),
	                                   artifact.package.name().as_str(),
	                                   Some(artifact.name.as_ref()),
	).lock(config.workspace.config())?;
	pdl.as_mut().prepare()?;

	let product = if artifact.ck.is_playdate() {
		ensure!(artifact.ct == CrateType::Staticlib, "static lib expected");

		let sdk = config.get_sdk_for(&artifact.ct, &artifact.ck)?;
		let arm = config.get_gcc_for(&artifact.ct, &artifact.ck)?;
		let gcc = arm.gcc();

		// product should be in pd-layout:
		let pdl_ref = pdl.as_inner();
		let product = {
			use playdate::layout::Layout as _;
			pdl_ref.binary()
		};
		let link_map = format!("-T{}", sdk.build_support().link_map().display());
		let d = None::<&Path>;

		let mut gcc = Command::new(gcc.path());
		gcc.arg(artifact.path);
		// TODO: #feature=compat & --with-setup => gcc.arg(setup.c) and -l artifact.path
		// TODO: use const `GCC_ARGS_LIB` from support::compile
		gcc.args([
			"-nostartfiles",
			"-mthumb",
			"-mcpu=cortex-m7",
			"-mfloat-abi=hard",
			"-mfpu=fpv5-sp-d16",
			"-D__FPU_USED=1",
			"-Wl,--cref,--gc-sections,--no-warn-mismatch,--emit-relocs",
			"-fno-exceptions",
			"-mword-relocations",
			"-fno-common",
		]);
		gcc.arg(&link_map);
		if let Some(d) = d {
			gcc.arg(format!("-MF{}", d.display()));
		}
		gcc.args([OsStr::new("-o"), product.as_os_str()]);
		gcc.args(["--entry", "eventHandlerShim"]);

		config.log().verbose(|mut log| {
			            log.status("Gcc", args_line_for_proc(&gcc));
		            });

		// Print gcc's output in verbose mode only!
		let quiet = config.workspace.config().shell().verbosity() == Verbosity::Quiet;
		let extra_verbose = config.workspace.config().extra_verbose();
		gcc.stderr(if quiet { Stdio::null() } else { Stdio::inherit() });
		gcc.stdout(if extra_verbose {
			   Stdio::inherit()
		   } else {
			   Stdio::null()
		   });
		gcc.status()?.exit_ok()?;
		BuildProduct::Success { ck: artifact.ck,
		                        src_ct: artifact.ct,
		                        dst_ct: CrateType::Bin,
		                        profile: artifact.profile,
		                        layout: pdl_ref.to_owned(),
		                        path: product.to_path_buf().into(),
		                        package: artifact.package,
		                        name: artifact.name.as_ref().to_owned() }
	} else if artifact.ck.is_simulator() {
		ensure!(artifact.ct.is_dynamic(), "dynamic lib expected");
		let pdl = pdl.as_ref();
		let product = {
			use playdate::layout::Layout as _;
			pdl.library()
			   .with_extension(artifact.path.extension().unwrap_or_default())
		};
		let linked = soft_link_checked(&artifact.path, &product, true, pdl.dest())?;
		log::debug!(
		            "{} linked (overwritten: {linked}) {}",
		            artifact.ct,
		            product.as_relative_to_root(config).display()
		);
		BuildProduct::Success { ck: artifact.ck,
		                        src_ct: artifact.ct.to_owned(),
		                        dst_ct: artifact.ct,
		                        profile: artifact.profile,
		                        layout: pdl.to_owned(),
		                        path: product,
		                        package: artifact.package,
		                        name: artifact.name.as_ref().to_owned() }
	} else {
		// Currently this case is usually unreachable, but who knows future…
		BuildProduct::skip_as_unsupported(artifact)
	};

	Ok(product)
}


/// Guesses a `CrateType` by `path`.ext and artifact crate types (target kind).
///
/// `crate_types` should not be empty, otherwise `None` will be returned.
fn guess_crate_type(config: &Config, path: &Path, tk: cargo::core::TargetKind, ck: CompileKind) -> CrateType {
	let mut crate_types = tk.rustc_crate_types();
	let unknown = || CrateType::Other("UNKNOWN".into());

	if crate_types.len() == 1 {
		return crate_types.pop().unwrap_or_else(unknown);
	}

	let ext = path.extension();
	if ext.is_none() && crate_types.contains(&CrateType::Bin) {
		return CrateType::Bin;
	}

	if let Some(ext) = ext {
		if ext == static_lib_suffix() && crate_types.contains(&CrateType::Staticlib) {
			CrateType::Staticlib
		} else {
			let dylib_suffix = dylib_suffix_for_target(config, ck);
			if Some(ext) == dylib_suffix.as_deref().map(|s| OsStr::new(s)) &&
			   (crate_types.contains(&CrateType::Dylib) || crate_types.contains(&CrateType::Cdylib))
			{
				// For us it doesn't matter if it's dylib or cdylib
				CrateType::Dylib
			} else if ext == OsStr::new("rlib") {
				CrateType::Rlib
			} else {
				unknown()
			}
		}
	} else {
		unknown()
	}
}


pub fn dylib_suffix_for_target<'c>(config: &'c Config, kind: CompileKind) -> Option<Cow<'c, str>> {
	use crate::utils::rustc::TargetSpec;

	let for_target = |kind| {
		config.rustc
		      .target_spec(kind)
		      .log_err_cargo(config)
		      .ok()
		      .map(|spec| spec.dll_suffix)
		      .flatten()
	};
	let for_host = || for_target(&CompileKind::Host);

	match kind {
		CompileKind::Host => {
			for_host().map(Cow::from)
			          .or_else(|| dylib_suffix_for_host_opt().map(Into::into))
		},
		CompileKind::Target(target) if target == config.host_target => {
			for_host().map(Cow::from)
			          .or_else(|| dylib_suffix_for_host_opt().map(Into::into))
		},
		CompileKind::Target(_) => for_target(&kind).map(Into::into),
	}
}


fn has_only_nopd_targets(config: &Config) -> CargoResult<bool> {
	let pd = CompileKind::playdate();
	let kinds = &config.compile_options.build_config.requested_kinds[..];
	let contains_nopd = kinds.iter().find(|kind| *kind != &pd).is_some();
	let contains_pd = kinds.contains(&pd);
	if !contains_pd && contains_nopd {
		return Ok(true);
	}

	// kinds of interest:
	let mut kinds: Vec<CompileKind> = Vec::new();
	kinds.extend(&config.compile_options.build_config.requested_kinds);

	let specs = config.compile_options
	                  .spec
	                  .to_package_id_specs(&config.workspace)?;
	let cli_features = &config.compile_options.cli_features;
	let members = config.workspace.members_with_features(&specs, cli_features)?;

	for (package, ..) in members {
		if contains_nopd {
			kinds.extend(package.manifest().default_kind());
		}
		kinds.extend(package.manifest().forced_kind());
	}

	let contains_nopd = kinds.iter().find(|kind| *kind != &pd).is_some();
	let contains_pd = kinds.contains(&pd);

	Ok(!contains_pd && contains_nopd)
}