1mod features;
7mod syntax;
8use crate::cfg::CfgExpr;
9use crate::meter::{ItemAdmission, Meter};
10use crate::{DependencyDeclaration, LoadError, LoadErrorKind, RelPath, TargetKind};
11pub(crate) use features::destination;
12use purrdf_lex::allocation::Memory;
13use purrdf_lex::walk::{WorkList, try_equal_range_by, try_sort_unstable_by};
14use std::collections::BTreeMap;
15use syn::ext::IdentExt as _;
16use syn::parse::Parser as _;
17pub(crate) use syntax::filter;
18pub(crate) use syntax::predicate;
19
20#[derive(Debug, Clone, Copy)]
22pub enum CfgAtom<'a> {
23 Name(&'a str),
25 Value(&'a str, &'a str),
27}
28#[derive(Debug, Clone, Copy)]
34pub struct DeclaredCfg<'a> {
35 triple: &'a str,
36 atoms: &'a [CfgAtom<'a>],
37}
38impl<'a> DeclaredCfg<'a> {
39 #[must_use]
41 pub const fn complete(triple: &'a str, atoms: &'a [CfgAtom<'a>]) -> Self {
42 Self { triple, atoms }
43 }
44}
45#[derive(Debug, Clone, Copy)]
52pub struct DeclaredConfiguration<'a> {
53 target: DeclaredCfg<'a>,
54 host: Option<DeclaredCfg<'a>>,
55 features: &'a [&'a str],
56 kind: TargetKind,
57 name: &'a str,
58}
59impl<'a> DeclaredConfiguration<'a> {
60 #[must_use]
62 pub const fn new(
63 target: DeclaredCfg<'a>,
64 features: &'a [&'a str],
65 kind: TargetKind,
66 name: &'a str,
67 ) -> Self {
68 Self {
69 target,
70 host: None,
71 features,
72 kind,
73 name,
74 }
75 }
76 #[must_use]
78 pub const fn with_host(mut self, host: DeclaredCfg<'a>) -> Self {
79 self.host = Some(host);
80 self
81 }
82}
83#[derive(Debug, PartialEq, Eq)]
85pub struct CfgSelection {
86 triple: String,
87 predicates: Vec<String>,
88}
89impl CfgSelection {
90 #[must_use]
92 pub fn triple(&self) -> &str {
93 &self.triple
94 }
95 #[must_use]
97 pub fn predicates(&self) -> &[String] {
98 &self.predicates
99 }
100}
101#[derive(Debug, PartialEq, Eq)]
109pub struct ActiveConfiguration {
110 target: CfgSelection,
111 host: Option<CfgSelection>,
112 pub(crate) features: Vec<String>,
113 pub(crate) optional: Vec<String>,
114 kind: TargetKind,
115 name: String,
116}
117impl ActiveConfiguration {
118 #[must_use]
120 pub const fn target(&self) -> &CfgSelection {
121 &self.target
122 }
123 #[must_use]
125 pub const fn host(&self) -> Option<&CfgSelection> {
126 self.host.as_ref()
127 }
128 #[must_use]
130 pub fn features(&self) -> &[String] {
131 &self.features
132 }
133 #[must_use]
135 pub fn optional_dependencies(&self) -> &[String] {
136 &self.optional
137 }
138 #[must_use]
140 pub const fn target_kind(&self) -> TargetKind {
141 self.kind
142 }
143 #[must_use]
145 pub fn target_name(&self) -> &str {
146 &self.name
147 }
148 pub(crate) fn selected(&self) -> Option<&CfgSelection> {
149 if self.kind == TargetKind::BuildScript {
150 self.host.as_ref()
151 } else {
152 Some(&self.target)
153 }
154 }
155 pub(crate) fn same_features_under(
156 &self,
157 other: &Self,
158 meter: &Meter,
159 path: &RelPath,
160 ) -> Result<bool, LoadError> {
161 comparison_work(&self.features, meter, path)?;
162 comparison_work(&other.features, meter, path)?;
163 Ok(self.features == other.features)
164 }
165 pub(crate) fn same_syntax_under(
166 &self,
167 other: &Self,
168 meter: &Meter,
169 path: &RelPath,
170 ) -> Result<bool, LoadError> {
171 for cfg in [self.selected(), other.selected()].into_iter().flatten() {
172 meter.work(cfg.triple.len().saturating_add(1), path, None)?;
173 comparison_work(&cfg.predicates, meter, path)?;
174 }
175 let features_agree = self.same_features_under(other, meter, path)?;
176 Ok(self.selected() == other.selected() && features_agree)
177 }
178}
179
180fn comparison_work(values: &[String], meter: &Meter, path: &RelPath) -> Result<(), LoadError> {
181 meter.work(values.len(), path, None)?;
182 for value in values {
183 meter.work(value.len().saturating_add(1), path, None)?;
184 }
185 Ok(())
186}
187pub(crate) fn admit(
188 input: DeclaredConfiguration<'_>,
189 graph: &BTreeMap<String, Vec<String>>,
190 deps: &[DependencyDeclaration],
191 meter: &Meter,
192 path: &RelPath,
193) -> Result<ActiveConfiguration, LoadError> {
194 let before = meter.usage();
195 let options = meter.options().clone();
196 let ((result, after), _) =
197 crate::parse::parse_counted(path, "", options.max_file_tokens, |_tree| {
198 let local = Meter::resume(&options, before);
199 let result = admit_inner(input, graph, deps, &local, path);
200 (result, local.configuration_usage())
201 })?;
202 meter.configuration_spent(before, after, path)?;
203 result
204}
205fn admit_inner(
206 input: DeclaredConfiguration<'_>,
207 graph: &BTreeMap<String, Vec<String>>,
208 deps: &[DependencyDeclaration],
209 meter: &Meter,
210 path: &RelPath,
211) -> Result<ActiveConfiguration, LoadError> {
212 let mut admission = ItemAdmission::new(meter, path);
213 let mut memory = Memory::new(&mut admission);
214 let result = (|| {
215 let target = cfg_set(input.target, meter, path, &mut memory)?;
216 let host = input
217 .host
218 .map(|cfg| cfg_set(cfg, meter, path, &mut memory))
219 .transpose()?;
220 if input.kind == TargetKind::BuildScript && host.is_none() {
221 return Err(failure(
222 path,
223 "a build-script context needs an explicit host cfg",
224 ));
225 }
226 let name = memory.string(input.name).map_err(native)?;
227 let (features, optional) =
228 features::admit(input.features, graph, deps, meter, path, &mut memory)?;
229 Ok(ActiveConfiguration {
230 target,
231 host,
232 features,
233 optional,
234 kind: input.kind,
235 name,
236 })
237 })();
238 result.map_err(|error| recover(error, &mut admission))
239}
240fn cfg_set<S: purrdf_lex::allocation::Admission + ?Sized>(
241 input: DeclaredCfg<'_>,
242 meter: &Meter,
243 path: &RelPath,
244 memory: &mut Memory<'_, S>,
245) -> Result<CfgSelection, LoadError> {
246 if input.triple.is_empty() || input.triple.chars().any(char::is_whitespace) {
247 return Err(failure(path, "supply an explicit nonempty target triple"));
248 }
249 let triple = memory.string(input.triple).map_err(native)?;
250 let mut predicates = Vec::new();
251 for atom in input.atoms {
252 let (key, value) = match atom {
253 CfgAtom::Name(key) => (*key, None),
254 CfgAtom::Value(key, value) => (*key, Some(*value)),
255 };
256 meter.work(
257 key.len()
258 .saturating_add(value.map_or(0, str::len))
259 .saturating_add(1),
260 path,
261 None,
262 )?;
263 if u64::try_from(key.len()).unwrap_or(u64::MAX) > meter.options().max_file_bytes {
264 return Err(failure(
265 path,
266 "cfg name exceeds the original file-byte bound",
267 ));
268 }
269 let identifier = syn::Ident::parse_any
270 .parse_str(key)
271 .map_err(|_| failure(path, "cfg names must be Rust identifiers"))?;
272 let key = memory
273 .format(&format_args!("{}", identifier.unraw()))
274 .map_err(native)?;
275 if key == "feature" {
276 return Err(failure(
277 path,
278 "cfg names must be Rust identifiers; feature values belong in the package feature selection",
279 ));
280 }
281 let value = match value {
282 None => memory.string(&key),
283 Some(value) => memory.format(&format_args!("{key} = {value:?}")),
284 }
285 .map_err(native)?;
286 memory.push(&mut predicates, value).map_err(native)?;
287 }
288 sort_unique(&mut predicates, meter, path)?;
289 Ok(CfgSelection { triple, predicates })
290}
291pub(crate) fn sort_unique(
292 values: &mut [String],
293 meter: &Meter,
294 path: &RelPath,
295) -> Result<(), LoadError> {
296 try_sort_unstable_by(values, |a, b| {
297 meter.work(
298 a.len().saturating_add(b.len()).saturating_add(1),
299 path,
300 None,
301 )?;
302 Ok::<_, LoadError>(a.cmp(b))
303 })?;
304 for pair in values.windows(2) {
305 meter.work(1, path, None)?;
306 if pair[0] == pair[1] {
307 return Err(failure(path, "duplicate declared configuration value"));
308 }
309 }
310 Ok(())
311}
312pub(crate) fn contains(
313 values: &[String],
314 value: &str,
315 meter: &Meter,
316 path: &RelPath,
317) -> Result<bool, LoadError> {
318 let found = try_equal_range_by(values, |known| {
319 meter.work(
320 known.len().saturating_add(value.len()).saturating_add(1),
321 path,
322 None,
323 )?;
324 Ok::<_, LoadError>(known.as_str().cmp(value))
325 })?;
326 Ok(!found.is_empty())
327}
328pub(crate) fn evaluate(
329 expr: &CfgExpr,
330 cfg: &ActiveConfiguration,
331 dependency: bool,
332 meter: &Meter,
333 path: &RelPath,
334) -> Result<bool, LoadError> {
335 #[derive(Clone, Copy)]
336 enum Frame<'a> {
337 Node(&'a CfgExpr),
338 Not,
339 Fold(bool, usize),
340 }
341 let selected = cfg
342 .selected()
343 .ok_or_else(|| failure(path, "configured target lost its required host cfg"))?;
344 let mut admission = ItemAdmission::new(meter, path);
345 let mut memory = Memory::new(&mut admission);
346 let result = (|| {
347 let mut pending = WorkList::<_, 16>::new();
348 let mut values = WorkList::<bool, 16>::new();
349 pending
350 .try_push_admitted(Frame::Node(expr), &mut memory)
351 .map_err(native)?;
352 while let Some(frame) = pending.pop() {
353 meter.work(1, path, None)?;
354 let value = match frame {
355 Frame::Node(CfgExpr::Boolean(value)) => Some(*value),
356 Frame::Node(CfgExpr::Test) => {
357 if dependency {
358 return Err(failure(
359 path,
360 "Cargo target dependency predicates cannot select test",
361 ));
362 }
363 Some(contains(&selected.predicates, "test", meter, path)?)
364 }
365 Frame::Node(CfgExpr::Other(text)) => Some(atom(
366 text,
367 cfg,
368 selected,
369 dependency,
370 meter,
371 path,
372 &mut memory,
373 )?),
374 Frame::Node(CfgExpr::Not(inner)) => {
375 pending
376 .try_push_admitted(Frame::Not, &mut memory)
377 .map_err(native)?;
378 pending
379 .try_push_admitted(Frame::Node(inner), &mut memory)
380 .map_err(native)?;
381 None
382 }
383 Frame::Node(CfgExpr::All(children) | CfgExpr::Any(children)) => {
384 let all = matches!(frame, Frame::Node(CfgExpr::All(_)));
385 pending
386 .try_push_admitted(Frame::Fold(all, children.len()), &mut memory)
387 .map_err(native)?;
388 for child in children.iter().rev() {
389 pending
390 .try_push_admitted(Frame::Node(child), &mut memory)
391 .map_err(native)?;
392 }
393 None
394 }
395 Frame::Not => Some(
396 !values
397 .pop()
398 .ok_or_else(|| failure(path, "cfg evaluation lost an operand"))?,
399 ),
400 Frame::Fold(all, count) => {
401 let mut result = all;
402 for _ in 0..count {
403 meter.work(1, path, None)?;
404 let value = values
405 .pop()
406 .ok_or_else(|| failure(path, "cfg evaluation lost an operand"))?;
407 if all {
408 result &= value;
409 } else {
410 result |= value;
411 }
412 }
413 Some(result)
414 }
415 };
416 if let Some(value) = value {
417 values
418 .try_push_admitted(value, &mut memory)
419 .map_err(native)?;
420 }
421 }
422 let value = values
423 .pop()
424 .ok_or_else(|| failure(path, "cfg evaluation produced no decision"))?;
425 if !values.is_empty() {
426 return Err(failure(path, "cfg evaluation left extra decisions"));
427 }
428 Ok(value)
429 })();
430 result.map_err(|error| recover(error, &mut admission))
431}
432fn atom<S: purrdf_lex::allocation::Admission + ?Sized>(
433 text: &str,
434 cfg: &ActiveConfiguration,
435 selected: &CfgSelection,
436 dependency: bool,
437 meter: &Meter,
438 path: &RelPath,
439 memory: &mut Memory<'_, S>,
440) -> Result<bool, LoadError> {
441 let key = text.split_once(" = ").map_or(text, |(key, _)| key);
442 if key.contains("::") {
443 return Err(failure(
444 path,
445 "qualified cfg predicate names are unsupported",
446 ));
447 }
448 if dependency && ["test", "feature", "debug_assertions", "proc_macro"].contains(&key) {
449 return Err(failure(
450 path,
451 "Cargo target dependency predicates cannot select test, feature, debug_assertions or proc_macro",
452 ));
453 }
454 let mut found = contains(&selected.predicates, text, meter, path)?;
455 for feature in &cfg.features {
456 let predicate = memory
457 .format(&format_args!("feature = {feature:?}"))
458 .map_err(native)?;
459 meter.work(
460 predicate.len().saturating_add(text.len()).saturating_add(1),
461 path,
462 None,
463 )?;
464 found |= predicate == text;
465 }
466 Ok(found)
467}
468pub(crate) fn failure(path: &RelPath, message: &str) -> LoadError {
469 LoadError::new(
470 path,
471 None,
472 LoadErrorKind::Locked {
473 field: "configuration",
474 message: message.to_owned(),
475 source: None,
476 },
477 )
478}
479pub(crate) fn condition(
480 condition: &str,
481 cfg: &ActiveConfiguration,
482 meter: &Meter,
483 path: &RelPath,
484) -> Result<bool, LoadError> {
485 let selected = cfg
486 .selected()
487 .ok_or_else(|| failure(path, "target condition needs an explicit host cfg"))?;
488 meter.work(
489 condition
490 .len()
491 .saturating_add(selected.triple.len())
492 .saturating_add(1),
493 path,
494 None,
495 )?;
496 if !condition.trim_start().starts_with("cfg(") {
497 return Ok(condition == selected.triple);
498 }
499 let mut admission = ItemAdmission::new(meter, path);
500 let text = Memory::new(&mut admission)
501 .format(&format_args!("#![{condition}]\n"))
502 .map_err(|source| admission.error(source))?;
503 if u64::try_from(text.len()).unwrap_or(u64::MAX) > meter.options().max_file_bytes {
504 return Err(failure(
505 path,
506 "target predicate exceeds the original file-byte bound",
507 ));
508 }
509 let before = meter.usage();
510 let options = meter.options().clone();
511 let ((result, after), scan) =
512 crate::parse::parse_counted(path, &text, options.max_file_tokens, |tree| {
513 let local = Meter::resume(&options, before);
514 let result = (|| {
515 if tree.attrs.len() != 1
516 || !tree.items.is_empty()
517 || !tree.attrs[0].path().is_ident("cfg")
518 {
519 return Err(failure(
520 path,
521 "target table must contain exactly one cfg predicate",
522 ));
523 }
524 let meta = tree.attrs[0]
525 .parse_args_with(crate::cfg::parse_meta)
526 .map_err(|error| failure(path, &error.to_string()))?;
527 predicate(&meta, cfg, true, &local, path)
528 })();
529 (result, local.configuration_usage())
530 })?;
531 meter.configuration_spent(before, after, path)?;
532 meter.scanned(scan);
533 result
534}
535fn native(source: purrdf_lex::allocation::StorageError) -> LoadError {
536 LoadError::new(&RelPath::root(), None, LoadErrorKind::Storage(source))
537}
538fn recover(error: LoadError, admission: &mut ItemAdmission<'_>) -> LoadError {
539 match error.kind {
540 LoadErrorKind::Storage(source) => admission.error(source),
541 _ => error,
542 }
543}