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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
|
//! ref: composer/src/Composer/DependencyResolver/Rule.php
use std::any::Any;
use anyhow::Result;
use indexmap::IndexMap;
use shirabe_php_shim::{
LogicException, PhpMixed, abs, array_filter, array_keys, array_shift, array_values, implode,
is_object,
};
use shirabe_semver::constraint::Constraint;
use shirabe_semver::constraint::ConstraintInterface;
use crate::dependency_resolver::Pool;
use crate::dependency_resolver::Problem;
use crate::dependency_resolver::Request;
use crate::dependency_resolver::RuleSet;
use crate::package::AliasPackage;
use crate::package::BasePackage;
use crate::package::Link;
use crate::package::PackageInterface;
use crate::package::version::VersionParser;
use crate::repository::PlatformRepository;
use crate::repository::RepositorySet;
/// PHP: @phpstan-type ReasonData = Link|BasePackage|string|int|array{...}|array{...}
/// We model this as an enum.
#[derive(Debug)]
pub enum ReasonData {
Link(Link),
BasePackage(Box<dyn BasePackage>),
String(String),
Int(i64),
RootRequire {
package_name: String,
constraint: Box<dyn ConstraintInterface>,
},
Fixed {
package: Box<dyn BasePackage>,
},
/// Phase B placeholder for an arbitrary PHP-side value not yet mapped to a real variant.
Mixed(PhpMixed),
}
impl From<PhpMixed> for ReasonData {
fn from(value: PhpMixed) -> Self {
// TODO(phase-b): callers should construct the appropriate variant directly;
// this catch-all keeps the rule constructors building while reason_data threading
// through PhpMixed in the resolver is still in transition.
match value {
PhpMixed::String(s) => ReasonData::String(s),
PhpMixed::Int(i) => ReasonData::Int(i),
other => ReasonData::Mixed(other),
}
}
}
// reason constants and // their reason data contents
pub const RULE_ROOT_REQUIRE: i64 = 2;
pub const RULE_FIXED: i64 = 3;
pub const RULE_PACKAGE_CONFLICT: i64 = 6;
pub const RULE_PACKAGE_REQUIRES: i64 = 7;
pub const RULE_PACKAGE_SAME_NAME: i64 = 10;
pub const RULE_LEARNED: i64 = 12;
pub const RULE_PACKAGE_ALIAS: i64 = 13;
pub const RULE_PACKAGE_INVERSE_ALIAS: i64 = 14;
// bitfield defs
pub const BITFIELD_TYPE: i64 = 0;
pub const BITFIELD_REASON: i64 = 8;
pub const BITFIELD_DISABLED: i64 = 16;
pub trait Rule: std::fmt::Display + std::fmt::Debug {
fn bitfield(&self) -> i64;
fn bitfield_mut(&mut self) -> &mut i64;
fn request(&self) -> Option<&Request>;
fn request_mut(&mut self) -> Option<&mut Request>;
fn reason_data(&self) -> Option<&ReasonData>;
fn reason_data_mut(&mut self) -> Option<&mut ReasonData>;
fn get_literals(&self) -> Vec<i64>;
fn get_hash(&self) -> PhpMixed;
fn equals(&self, rule: &dyn Rule) -> bool;
fn is_assertion(&self) -> bool;
fn clone_box(&self) -> Box<dyn Rule> {
todo!()
}
/// PHP: `$rule instanceof MultiConflictRule`. Returns a borrow of the
/// underlying `MultiConflictRule` when this rule is one, otherwise `None`.
fn as_multi_conflict(&self) -> Option<&crate::dependency_resolver::MultiConflictRule> {
None
}
/// @return self::RULE_*
fn get_reason(&self) -> i64 {
(self.bitfield() & (255 << BITFIELD_REASON)) >> BITFIELD_REASON
}
/// @phpstan-return ReasonData
fn get_reason_data(&self) -> &ReasonData {
// TODO(phase-b): reason_data() returns Option; PHP getReasonData unconditional
self.reason_data().unwrap()
}
fn get_required_package(&self) -> Option<String> {
match self.get_reason() {
r if r == RULE_ROOT_REQUIRE => match self.get_reason_data() {
ReasonData::RootRequire { package_name, .. } => Some(package_name.clone()),
_ => None,
},
r if r == RULE_FIXED => match self.get_reason_data() {
ReasonData::Fixed { package } => Some(package.get_name().to_string()),
_ => None,
},
r if r == RULE_PACKAGE_REQUIRES => match self.get_reason_data() {
ReasonData::Link(link) => Some(link.get_target().to_string()),
_ => None,
},
_ => None,
}
}
/// @param RuleSet::TYPE_* $type
fn set_type(&mut self, r#type: i64) {
*self.bitfield_mut() =
(self.bitfield() & !(255i64 << BITFIELD_TYPE)) | ((255 & r#type) << BITFIELD_TYPE);
}
fn get_type(&self) -> i64 {
(self.bitfield() & (255 << BITFIELD_TYPE)) >> BITFIELD_TYPE
}
fn disable(&mut self) {
*self.bitfield_mut() =
(self.bitfield() & !(255i64 << BITFIELD_DISABLED)) | (1i64 << BITFIELD_DISABLED);
}
fn enable(&mut self) {
*self.bitfield_mut() &= !(255i64 << BITFIELD_DISABLED);
}
fn is_disabled(&self) -> bool {
0 != ((self.bitfield() & (255 << BITFIELD_DISABLED)) >> BITFIELD_DISABLED)
}
fn is_enabled(&self) -> bool {
0 == ((self.bitfield() & (255 << BITFIELD_DISABLED)) >> BITFIELD_DISABLED)
}
fn is_caused_by_lock(
&self,
_repository_set: &RepositorySet,
request: &Request,
pool: &Pool,
) -> bool {
if self.get_reason() == RULE_PACKAGE_REQUIRES {
if let ReasonData::Link(link) = self.get_reason_data() {
if PlatformRepository::is_platform_package(link.get_target()) {
return false;
}
// TODO(phase-b): Request::get_locked_repository() signature
let locked_repo: Option<()> = todo!("request.get_locked_repository()");
if let Some(_locked_repo) = locked_repo {
let packages: Vec<Box<dyn BasePackage>> = todo!("locked_repo.get_packages()");
for package in packages {
let p: &dyn BasePackage = todo!("package as BasePackage reference");
if p.get_name() == link.get_target() {
if pool.is_unacceptable_fixed_or_locked_package(p) {
return true;
}
if !link
.get_constraint()
.matches(&Constraint::new("=", p.get_version()))
{
return true;
}
// required package was locked but has been unlocked and still matches
if !request.is_locked_package(todo!("package as &dyn PackageInterface"))
{
return true;
}
break;
}
}
}
}
}
if self.get_reason() == RULE_ROOT_REQUIRE {
if let ReasonData::RootRequire {
package_name,
constraint,
} = self.get_reason_data()
{
if PlatformRepository::is_platform_package(package_name) {
return false;
}
// TODO(phase-b): Request::get_locked_repository() signature
let locked_repo: Option<()> = todo!("request.get_locked_repository()");
if let Some(_locked_repo) = locked_repo {
let packages: Vec<Box<dyn BasePackage>> = todo!("locked_repo.get_packages()");
for package in packages {
let p: &dyn BasePackage = todo!("package as BasePackage reference");
if p.get_name() == package_name {
if pool.is_unacceptable_fixed_or_locked_package(p) {
return true;
}
if !constraint.matches(&Constraint::new("=", p.get_version())) {
return true;
}
break;
}
}
}
}
}
false
}
/// @internal
fn get_source_package(&self, pool: &Pool) -> Result<Box<dyn BasePackage>> {
let literals = self.get_literals();
match self.get_reason() {
r if r == RULE_PACKAGE_CONFLICT => {
let mut package1 = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[0]).clone_box(),
);
let mut package2 = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[1]).clone_box(),
);
let reason_data = self.get_reason_data();
// swap literals if they are not in the right order with package2 being the conflicter
if let ReasonData::Link(link) = reason_data {
if link.get_source() == package1.get_name() {
std::mem::swap(&mut package1, &mut package2);
}
}
Ok(package2)
}
r if r == RULE_PACKAGE_REQUIRES => {
let source_literal = literals[0];
let source_package = self.deduplicate_default_branch_alias(
pool.literal_to_package(source_literal).clone_box(),
);
Ok(source_package)
}
_ => Err(LogicException {
message: "Not implemented".to_string(),
code: 0,
}
.into()),
}
}
/// @param BasePackage[] $installedMap
/// @param array<Rule[]> $learnedPool
fn get_pretty_string(
&self,
repository_set: &RepositorySet,
request: &Request,
pool: &mut Pool,
is_verbose: bool,
installed_map: &IndexMap<String, Box<dyn BasePackage>>,
_learned_pool: &Vec<Vec<Box<dyn Rule>>>,
) -> String {
let mut literals = self.get_literals();
match self.get_reason() {
r if r == RULE_ROOT_REQUIRE => {
let reason_data = self.get_reason_data();
let (package_name, constraint): (&str, &dyn ConstraintInterface) = match reason_data
{
ReasonData::RootRequire {
package_name,
constraint,
} => (package_name.as_str(), constraint.as_ref()),
_ => return String::new(),
};
let packages = pool.what_provides(package_name, Some(constraint));
if 0 == packages.len() {
return format!(
"No package found to satisfy root composer.json require {} {}",
package_name,
constraint.get_pretty_string(),
);
}
// PHP: array_values(array_filter($packages, fn ($p) => !($p instanceof AliasPackage)))
let packages_non_alias: Vec<Box<dyn BasePackage>> = packages
.iter()
.filter(|p| p.as_any().downcast_ref::<AliasPackage>().is_none())
.map(|p| p.clone_box())
.collect();
if packages_non_alias.len() == 1 {
let package = &packages_non_alias[0];
// TODO(phase-b): request.is_locked_package signature
if request.is_locked_package(todo!("package as &dyn PackageInterface")) {
return format!(
"{} is locked to version {} and an update of this package was not requested.",
package.get_pretty_name(),
package.get_pretty_version(),
);
}
}
format!(
"Root composer.json requires {} {} -> satisfiable by {}.",
package_name,
constraint.get_pretty_string(),
self.format_packages_unique(
pool,
packages,
is_verbose,
Some(constraint),
false
),
)
}
r if r == RULE_FIXED => {
let package_in = match self.get_reason_data() {
ReasonData::Fixed { package } => package.clone_box(),
_ => return String::new(),
};
let package = self.deduplicate_default_branch_alias(package_in);
if request.is_locked_package(todo!("package as &dyn PackageInterface")) {
return format!(
"{} is locked to version {} and an update of this package was not requested.",
package.get_pretty_name(),
package.get_pretty_version(),
);
}
format!(
"{} is present at version {} and cannot be modified by Composer",
package.get_pretty_name(),
package.get_pretty_version(),
)
}
r if r == RULE_PACKAGE_CONFLICT => {
let mut package1 = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[0]).clone_box(),
);
let mut package2 = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[1]).clone_box(),
);
let mut conflict_target = package1.get_pretty_string();
let reason_data = self.get_reason_data();
let link = match reason_data {
ReasonData::Link(l) => l,
_ => return String::new(),
};
// swap literals if they are not in the right order with package2 being the conflicter
if link.get_source() == package1.get_name() {
std::mem::swap(&mut package1, &mut package2);
conflict_target = format!(
"{} {}",
package1.get_pretty_name(),
link.get_pretty_constraint().unwrap_or("")
);
}
// if the conflict is not directly against the package but something it provides/replaces,
// we try to find that link to display a better message
if link.get_target() != package1.get_name() {
let mut provide_type: Option<&str> = None;
let mut provided: Option<String> = None;
for provide in package1.get_provides().values() {
if provide.get_target() == link.get_target() {
provide_type = Some("provides");
provided =
Some(provide.get_pretty_constraint().unwrap_or("").to_string());
break;
}
}
for replace in package1.get_replaces().values() {
if replace.get_target() == link.get_target() {
provide_type = Some("replaces");
provided =
Some(replace.get_pretty_constraint().unwrap_or("").to_string());
break;
}
}
if let Some(pt) = provide_type {
conflict_target = format!(
"{} {} ({} {} {} {})",
link.get_target(),
link.get_pretty_constraint().unwrap_or(""),
package1.get_pretty_string(),
pt,
link.get_target(),
provided.unwrap_or_default(),
);
}
}
format!(
"{} conflicts with {}.",
package2.get_pretty_string(),
conflict_target
)
}
r if r == RULE_PACKAGE_REQUIRES => {
assert!(literals.len() > 0);
let source_literal = array_shift(&mut literals).unwrap();
let source_package = self.deduplicate_default_branch_alias(
pool.literal_to_package(source_literal).clone_box(),
);
let reason_data = self.get_reason_data();
let link = match reason_data {
ReasonData::Link(l) => l,
_ => return String::new(),
};
let mut requires: Vec<Box<dyn BasePackage>> = vec![];
for literal in &literals {
requires.push(pool.literal_to_package(*literal).clone_box());
}
let text = link.get_pretty_string(&*source_package);
if requires.len() > 0 {
format!(
"{} -> satisfiable by {}.",
text,
self.format_packages_unique(
pool,
requires,
is_verbose,
Some(link.get_constraint()),
false,
),
)
} else {
let target_name = link.get_target();
let reason = Problem::get_missing_package_reason(
repository_set,
request,
pool,
is_verbose,
target_name,
Some(link.get_constraint()),
);
return format!("{} -> {}", text, reason.1);
}
}
r if r == RULE_PACKAGE_SAME_NAME => {
let mut package_names: IndexMap<String, bool> = IndexMap::new();
for literal in &literals {
let package = pool.literal_to_package(*literal);
package_names.insert(package.get_name().to_string(), true);
}
// PHP: unset($literal);
let replaced_name = match self.get_reason_data() {
ReasonData::String(s) => s.clone(),
_ => String::new(),
};
if package_names.len() > 1 {
let reason = if !package_names.contains_key(&replaced_name) {
format!(
"They {} replace {} and thus cannot coexist.",
if literals.len() == 2 { "both" } else { "all" },
replaced_name,
)
} else {
let mut replacer_names = package_names.clone();
replacer_names.shift_remove(&replaced_name);
let replacer_names = array_keys(&replacer_names);
let mut reason_str = if replacer_names.len() == 1 {
format!("{} replaces ", replacer_names[0])
} else {
format!("[{}] replace ", implode(", ", &replacer_names))
};
reason_str.push_str(&format!(
"{} and thus cannot coexist with it.",
replaced_name,
));
reason_str
};
let mut installed_packages: Vec<Box<dyn BasePackage>> = vec![];
let mut removable_packages: Vec<Box<dyn BasePackage>> = vec![];
for literal in &literals {
if installed_map.contains_key(&abs(*literal).to_string()) {
installed_packages.push(pool.literal_to_package(*literal).clone_box());
} else {
removable_packages.push(pool.literal_to_package(*literal).clone_box());
}
}
if installed_packages.len() > 0 && removable_packages.len() > 0 {
return format!(
"{} cannot be installed as that would require removing {}. {}",
self.format_packages_unique(
pool,
removable_packages,
is_verbose,
None,
true,
),
self.format_packages_unique(
pool,
installed_packages,
is_verbose,
None,
true,
),
reason,
);
}
return format!(
"Only one of these can be installed: {}. {}",
self.format_packages_unique_from_literals(
pool, &literals, is_verbose, None, true
),
reason,
);
}
format!(
"You can only install one version of a package, so only one of these can be installed: {}.",
self.format_packages_unique_from_literals(
pool, &literals, is_verbose, None, true
),
)
}
r if r == RULE_LEARNED => {
/// @TODO currently still generates way too much output to be helpful, and in some cases can even lead to endless recursion
// (PHP commented-out alternative code preserved)
let learned_string = " (conflict analysis result)";
let rule_text = if literals.len() == 1 {
pool.literal_to_pretty_string(literals[0], &installed_map)
} else {
let mut groups: IndexMap<String, Vec<Box<dyn BasePackage>>> = IndexMap::new();
for literal in &literals {
let package = pool.literal_to_package(*literal);
let group = if installed_map.contains_key(&package.id().to_string()) {
if *literal > 0 { "keep" } else { "remove" }
} else {
if *literal > 0 {
"install"
} else {
"don't install"
}
};
groups
.entry(group.to_string())
.or_insert_with(Vec::new)
.push(self.deduplicate_default_branch_alias(package.clone_box()));
}
let mut rule_texts: Vec<String> = vec![];
for (group, packages) in &groups {
rule_texts.push(format!(
"{}{} {}",
group,
if packages.len() > 1 { " one of" } else { "" },
self.format_packages_unique(
pool,
packages.iter().map(|p| p.clone_box()).collect(),
is_verbose,
None,
false,
),
));
}
implode(" | ", &rule_texts)
};
format!("Conclusion: {}{}", rule_text, learned_string)
}
r if r == RULE_PACKAGE_ALIAS => {
let alias_package = pool.literal_to_package(literals[0]);
// avoid returning content like "9999999-dev is an alias of dev-master" as it is useless
if alias_package.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS {
return String::new();
}
let package = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[1]).clone_box(),
);
format!(
"{} is an alias of {} and thus requires it to be installed too.",
alias_package.get_pretty_string(),
package.get_pretty_string(),
)
}
r if r == RULE_PACKAGE_INVERSE_ALIAS => {
// inverse alias rules work the other way around than above
let alias_package = pool.literal_to_package(literals[1]);
// avoid returning content like "9999999-dev is an alias of dev-master" as it is useless
if alias_package.get_version() == VersionParser::DEFAULT_BRANCH_ALIAS {
return String::new();
}
let package = self.deduplicate_default_branch_alias(
pool.literal_to_package(literals[0]).clone_box(),
);
format!(
"{} is an alias of {} and must be installed with it.",
alias_package.get_pretty_string(),
package.get_pretty_string(),
)
}
_ => {
let mut rule_text = String::new();
for (i, literal) in literals.iter().enumerate() {
if i != 0 {
rule_text.push('|');
}
rule_text.push_str(&pool.literal_to_pretty_string(*literal, &installed_map));
}
format!("({})", rule_text)
}
}
}
/// @param array<int|BasePackage> $literalsOrPackages An array containing packages or literals
fn format_packages_unique(
&self,
pool: &Pool,
literals_or_packages: Vec<Box<dyn BasePackage>>,
is_verbose: bool,
constraint: Option<&dyn ConstraintInterface>,
use_removed_version_group: bool,
) -> String {
let mut packages: Vec<Box<dyn BasePackage>> = vec![];
for package in literals_or_packages {
// PHP: \is_object($package) ? $package : $pool->literalToPackage($package);
// In Rust we already have BasePackage, so no conversion needed.
packages.push(package);
}
Problem::get_package_list(
&packages,
is_verbose,
Some(pool),
constraint,
use_removed_version_group,
)
}
/// Helper for cases where literals come as int IDs (PHP supports both via union).
fn format_packages_unique_from_literals(
&self,
pool: &Pool,
literals: &[i64],
is_verbose: bool,
constraint: Option<&dyn ConstraintInterface>,
use_removed_version_group: bool,
) -> String {
let mut packages: Vec<Box<dyn BasePackage>> = vec![];
for literal in literals {
packages.push(pool.literal_to_package(*literal).clone_box());
}
Problem::get_package_list(
&packages,
is_verbose,
Some(pool),
constraint,
use_removed_version_group,
)
}
fn deduplicate_default_branch_alias(
&self,
package: Box<dyn BasePackage>,
) -> Box<dyn BasePackage> {
if let Some(alias_pkg) = package.as_any().downcast_ref::<AliasPackage>() {
if alias_pkg.get_pretty_version() == VersionParser::DEFAULT_BRANCH_ALIAS {
return alias_pkg.get_alias_of().clone_box();
}
}
package
}
}
#[derive(Debug)]
pub struct RuleBase {
pub(crate) bitfield: i64,
pub(crate) request: Option<Request>,
pub(crate) reason_data: Option<ReasonData>,
}
impl RuleBase {
pub const BITFIELD_DISABLED: i64 = BITFIELD_DISABLED;
pub const BITFIELD_REASON: i64 = BITFIELD_REASON;
pub const BITFIELD_TYPE: i64 = BITFIELD_TYPE;
pub fn new(reason: i64, reason_data: ReasonData) -> Self {
let bitfield =
(0i64 << BITFIELD_DISABLED) | (reason << BITFIELD_REASON) | (255i64 << BITFIELD_TYPE);
Self {
bitfield,
request: None,
reason_data: Some(reason_data),
}
}
pub fn is_disabled(&self) -> bool {
0 != ((self.bitfield & (255 << BITFIELD_DISABLED)) >> BITFIELD_DISABLED)
}
}
|