-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathquery.rs
1266 lines (1138 loc) · 47.3 KB
/
query.rs
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::BTreeMap;
use ron::extensions::Extensions;
use serde::{Deserialize, Serialize};
use trustfall::TransparentValue;
use crate::ReleaseType;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum RequiredSemverUpdate {
#[serde(alias = "minor")]
Minor,
#[serde(alias = "major")]
Major,
}
impl RequiredSemverUpdate {
pub fn as_str(&self) -> &'static str {
match self {
Self::Major => "major",
Self::Minor => "minor",
}
}
}
impl From<RequiredSemverUpdate> for ReleaseType {
fn from(value: RequiredSemverUpdate) -> Self {
match value {
RequiredSemverUpdate::Major => Self::Major,
RequiredSemverUpdate::Minor => Self::Minor,
}
}
}
/// The level of intensity of the error when a lint occurs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum LintLevel {
/// If this lint occurs, do nothing.
#[serde(alias = "allow")]
Allow,
/// If this lint occurs, print a warning.
#[serde(alias = "warn")]
Warn,
/// If this lint occurs, raise an error.
#[serde(alias = "deny")]
Deny,
}
impl LintLevel {
pub fn as_str(self) -> &'static str {
match self {
LintLevel::Allow => "allow",
LintLevel::Warn => "warn",
LintLevel::Deny => "deny",
}
}
}
/// Kind of semver update.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActualSemverUpdate {
Major,
Minor,
Patch,
NotChanged,
}
impl ActualSemverUpdate {
pub(crate) fn supports_requirement(&self, required: RequiredSemverUpdate) -> bool {
match (*self, required) {
(ActualSemverUpdate::Major, _) => true,
(ActualSemverUpdate::Minor, RequiredSemverUpdate::Major) => false,
(ActualSemverUpdate::Minor, _) => true,
(_, _) => false,
}
}
}
impl From<ReleaseType> for ActualSemverUpdate {
fn from(value: ReleaseType) -> Self {
match value {
ReleaseType::Major => Self::Major,
ReleaseType::Minor => Self::Minor,
ReleaseType::Patch => Self::Patch,
}
}
}
/// A query that can be executed on a pair of rustdoc output files,
/// returning instances of a particular kind of semver violation.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemverQuery {
pub id: String,
pub(crate) human_readable_name: String,
pub description: String,
pub required_update: RequiredSemverUpdate,
/// The default lint level for when this lint occurs.
pub lint_level: LintLevel,
#[serde(default)]
pub reference: Option<String>,
#[serde(default)]
pub reference_link: Option<String>,
pub(crate) query: String,
#[serde(default)]
pub(crate) arguments: BTreeMap<String, TransparentValue>,
/// The top-level error describing the semver violation that was detected.
/// Even if multiple instances of this semver issue are found, this error
/// message is displayed only at most once.
pub(crate) error_message: String,
/// Optional template that can be combined with each query output to produce
/// a human-readable description of the specific semver violation that was discovered.
#[serde(default)]
pub(crate) per_result_error_template: Option<String>,
/// Optional data to create witness code for query output. See the [`Witness`] struct for
/// more information.
#[serde(default)]
pub witness: Option<Witness>,
}
impl SemverQuery {
/// Deserializes a [`SemverQuery`] from a [`ron`]-encoded string slice.
///
/// Returns an `Err` if the deserialization fails.
pub fn from_ron_str(query_text: &str) -> ron::Result<Self> {
let mut deserializer = ron::Deserializer::from_str_with_options(
query_text,
ron::Options::default().with_default_extension(Extensions::IMPLICIT_SOME),
)?;
Self::deserialize(&mut deserializer)
}
pub fn all_queries() -> BTreeMap<String, SemverQuery> {
let mut queries = BTreeMap::default();
for (id, query_text) in get_queries() {
let query = Self::from_ron_str(query_text).unwrap_or_else(|e| {
panic!(
"\
Failed to parse a query: {e}
```ron
{query_text}
```"
);
});
assert_eq!(id, query.id, "Query id must match file name");
let id_conflict = queries.insert(query.id.clone(), query);
assert!(id_conflict.is_none(), "{id_conflict:?}");
}
queries
}
}
/// Configured values for a [`SemverQuery`] that differ from the lint's defaults.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct QueryOverride {
/// The required version bump for this lint; see [`SemverQuery`].`required_update`.
///
/// If this is `None`, use the query's default `required_update` when calculating
/// the effective required version bump.
#[serde(default)]
pub required_update: Option<RequiredSemverUpdate>,
/// The lint level for this lint; see [`SemverQuery`].`lint_level`.
///
/// If this is `None`, use the query's default `lint_level` when calculating
/// the effective lint level.
#[serde(default)]
pub lint_level: Option<LintLevel>,
}
/// A mapping of lint ids to configured values that override that lint's defaults.
pub type OverrideMap = BTreeMap<String, QueryOverride>;
/// A stack of [`OverrideMap`] values capturing our precedence rules.
///
/// Items toward the top of the stack (later in the backing `Vec`) have *higher* precedence
/// and override items lower in the stack. If an override is set and not `None` for a given lint
/// in multiple maps in the stack, the value at the top of the stack will be used
/// to calculate the effective lint level or required version update.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OverrideStack(Vec<OverrideMap>);
impl OverrideStack {
/// Creates a new, empty [`OverrideStack`] instance.
#[must_use]
pub fn new() -> Self {
Self(Vec::new())
}
/// Inserts the given map at the top of the stack.
///
/// The inserted overrides will take precedence over any lower item in the stack,
/// if both maps have a not-`None` entry for a given lint.
pub fn push(&mut self, item: &OverrideMap) {
self.0.push(item.clone());
}
/// Calculates the *effective* lint level of this query, by searching for an override
/// mapped to this query's id from the top of the stack first, returning the query's default
/// lint level if not overridden.
#[must_use]
pub fn effective_lint_level(&self, query: &SemverQuery) -> LintLevel {
self.0
.iter()
.rev()
.find_map(|x| x.get(&query.id).and_then(|y| y.lint_level))
.unwrap_or(query.lint_level)
}
/// Calculates the *effective* required version bump of this query, by searching for an override
/// mapped to this query's id from the top of the stack first, returning the query's default
/// required version bump if not overridden.
#[must_use]
pub fn effective_required_update(&self, query: &SemverQuery) -> RequiredSemverUpdate {
self.0
.iter()
.rev()
.find_map(|x| x.get(&query.id).and_then(|y| y.required_update))
.unwrap_or(query.required_update)
}
}
/// Data for generating a **witness** from the results of a [`SemverQuery`].
///
/// A witness is a minimal compilable example of how downstream code would
/// break given this change. See field documentation for more information
/// on each member.
///
/// Fields besides [`hint_template`](Self::hint_template) are optional, as it is not
/// always necessary to use an additional query [`witness_query`](Self::witness_query)
/// or possible to build a compilable witness from [`witness_template`](Self::witness_template)
/// for a given `SemverQuery`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Witness {
/// A [`handlebars`] template that renders a user-facing hint to give a quick
/// explanation of breakage. This may not be a buildable example, but it should
/// show the idea of why downstream code could break. It will be provided all
/// `@output` data from the [`SemverQuery`] query that contains this [`Witness`].
///
/// Example for the `function_missing` lint, where `name` is the (re)moved function's
/// name and `path` is the importable path:
///
/// ```no_run
/// # let _ = r#"
/// use {{join "::" path}};
/// {{name}}(...);
/// # "#;
/// ```
///
/// Notice how this is not a compilable example, but it provides a distilled hint to the user
/// of how downstream code would break with this change.
pub hint_template: String,
/// A [`handlebars`] template that renders the compilable witness example of how
/// downstream code would break.
///
/// This template will be provided any fields with `@output` directives in the
/// original [`SemverQuery`]. If [`witness_query`](Self::witness_query) is `Some`,
/// it will also be provided the `@output`s of that query. (The additional query's
/// outputs will take precedence over the original query if they share the same name.)
///
/// Example for the `enum_variant_missing` lint, where `path` is the importable path of the enum,
/// `name` is the name of the enum, and `variant_name` is the name of the removed/renamed variant:
///
/// ```no_run
/// # let _ = r#"
/// fn witness(item: {{path}}) {
/// if let {{path}}::{{variant_name}} {..} = item {
///
/// }
/// }
/// # "#;
/// ```
#[serde(default)]
pub witness_template: Option<String>,
/// An optional query to collect more information that is necessary to render
/// the [`witness_template`](Self::witness_template).
///
/// If `None`, no additional query will be run.
#[serde(default)]
pub witness_query: Option<WitnessQuery>,
}
/// A [`trustfall`] query, for [`Witness`] generation, containing the query
/// string itself and a mapping of argument names to value types which are
/// provided to the query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WitnessQuery {
/// The string containing the Trustfall query.
pub query: String,
/// The mapping of argument names to values provided to the query.
///
/// These can be inherited from a previous query ([`InheritedValue::Inherited`]) or
/// specified as [`InheritedValue::Constant`]s.
#[serde(default)]
pub arguments: BTreeMap<String, InheritedValue>,
}
/// Represents either a value inherited from a previous query, or a
/// provided constant value.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum InheritedValue {
/// Inherit the value from the previous output whose name is the given `String`.
Inherited { inherit: String },
/// Provide the constant value specified here.
Constant(TransparentValue),
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::{collections::BTreeMap, path::Path};
use anyhow::Context;
use rayon::prelude::*;
use semver::Version;
use serde::{Deserialize, Serialize};
use trustfall::{FieldValue, TransparentValue};
use trustfall_rustdoc::{
load_rustdoc, VersionedIndex, VersionedRustdocAdapter, VersionedStorage,
};
use crate::query::{
InheritedValue, LintLevel, OverrideMap, OverrideStack, QueryOverride, RequiredSemverUpdate,
SemverQuery,
};
use crate::templating::make_handlebars_registry;
static TEST_CRATE_NAMES: OnceLock<Vec<String>> = OnceLock::new();
/// Mapping test crate (pair) name -> (old rustdoc, new rustdoc).
static TEST_CRATE_RUSTDOCS: OnceLock<BTreeMap<String, (VersionedStorage, VersionedStorage)>> =
OnceLock::new();
/// Mapping test crate (pair) name -> (old index, new index).
static TEST_CRATE_INDEXES: OnceLock<
BTreeMap<String, (VersionedIndex<'static>, VersionedIndex<'static>)>,
> = OnceLock::new();
fn get_test_crate_names() -> &'static [String] {
TEST_CRATE_NAMES.get_or_init(initialize_test_crate_names)
}
fn get_all_test_crates() -> &'static BTreeMap<String, (VersionedStorage, VersionedStorage)> {
TEST_CRATE_RUSTDOCS.get_or_init(initialize_test_crate_rustdocs)
}
fn get_all_test_crate_indexes(
) -> &'static BTreeMap<String, (VersionedIndex<'static>, VersionedIndex<'static>)> {
TEST_CRATE_INDEXES.get_or_init(initialize_test_crate_indexes)
}
fn get_test_crate_indexes(
test_crate: &str,
) -> &'static (VersionedIndex<'static>, VersionedIndex<'static>) {
&get_all_test_crate_indexes()[test_crate]
}
fn initialize_test_crate_names() -> Vec<String> {
std::fs::read_dir("./test_crates/")
.expect("directory test_crates/ not found")
.map(|dir_entry| dir_entry.expect("failed to list test_crates/"))
.filter(|dir_entry| {
// Only return directories inside `test_crates/` that contain
// an `old/Cargo.toml` file. This works around finicky git + cargo behavior:
// - Create a git branch, commit a new test case, and generate its rustdoc.
// - Cargo will then create `Cargo.lock` files for the crate,
// which are ignored by git.
// - Check out another branch, and git won't delete the `Cargo.lock` files
// since they aren't tracked. But we don't want to run tests on those crates!
if !dir_entry
.metadata()
.expect("failed to retrieve test_crates/* metadata")
.is_dir()
{
return false;
}
let mut test_crate_cargo_toml = dir_entry.path();
test_crate_cargo_toml.extend(["old", "Cargo.toml"]);
test_crate_cargo_toml.as_path().is_file()
})
.map(|dir_entry| {
String::from(
String::from(
dir_entry
.path()
.to_str()
.expect("failed to convert dir_entry to String"),
)
.strip_prefix("./test_crates/")
.expect(
"the dir_entry doesn't start with './test_crates/', which is unexpected",
),
)
})
.collect()
}
fn initialize_test_crate_rustdocs() -> BTreeMap<String, (VersionedStorage, VersionedStorage)> {
get_test_crate_names()
.par_iter()
.map(|crate_pair| {
let old_rustdoc = load_pregenerated_rustdoc(crate_pair.as_str(), "old");
let new_rustdoc = load_pregenerated_rustdoc(crate_pair, "new");
(crate_pair.clone(), (old_rustdoc, new_rustdoc))
})
.collect()
}
fn initialize_test_crate_indexes(
) -> BTreeMap<String, (VersionedIndex<'static>, VersionedIndex<'static>)> {
get_all_test_crates()
.par_iter()
.map(|(key, (old_crate, new_crate))| {
let old_index = VersionedIndex::from_storage(old_crate);
let new_index = VersionedIndex::from_storage(new_crate);
(key.clone(), (old_index, new_index))
})
.collect()
}
fn load_pregenerated_rustdoc(crate_pair: &str, crate_version: &str) -> VersionedStorage {
let rustdoc_path =
format!("./localdata/test_data/{crate_pair}/{crate_version}/rustdoc.json");
let metadata_path =
format!("./localdata/test_data/{crate_pair}/{crate_version}/metadata.json");
let metadata_text = std::fs::read_to_string(&metadata_path).map_err(|e| anyhow::anyhow!(e).context(
format!("Could not load {metadata_path} file. These files are newly required as of PR#1007. Please re-run ./scripts/regenerate_test_rustdocs.sh"))).expect("failed to load metadata");
let metadata = serde_json::from_str(&metadata_text).expect("failed to parse metadata file");
load_rustdoc(Path::new(&rustdoc_path), Some(metadata))
.with_context(|| format!("Could not load {rustdoc_path} file, did you forget to run ./scripts/regenerate_test_rustdocs.sh ?"))
.expect("failed to load rustdoc")
}
#[test]
fn all_queries_are_valid() {
let (_baseline, current) = get_test_crate_indexes("template");
let adapter =
VersionedRustdocAdapter::new(current, Some(current)).expect("failed to create adapter");
for semver_query in SemverQuery::all_queries().into_values() {
let _ = adapter
.run_query(&semver_query.query, semver_query.arguments)
.expect("not a valid query");
}
}
#[test]
fn pub_use_handling() {
let (_baseline, current) = get_test_crate_indexes("pub_use_handling");
let query = r#"
{
Crate {
item {
... on Struct {
name @filter(op: "=", value: ["$struct"])
canonical_path {
canonical_path: path @output
}
importable_path @fold {
path @output
}
}
}
}
}"#;
let mut arguments = BTreeMap::new();
arguments.insert("struct", "CheckPubUseHandling");
let adapter =
VersionedRustdocAdapter::new(current, None).expect("could not create adapter");
let results_iter = adapter
.run_query(query, arguments)
.expect("failed to run query");
let actual_results: Vec<BTreeMap<_, _>> = results_iter
.map(|res| res.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
.collect();
let expected_result: FieldValue =
vec!["pub_use_handling", "inner", "CheckPubUseHandling"].into();
assert_eq!(1, actual_results.len(), "{actual_results:?}");
assert_eq!(
expected_result, actual_results[0]["canonical_path"],
"{actual_results:?}"
);
let mut actual_paths = actual_results[0]["path"]
.as_vec_with(|val| val.as_vec_with(FieldValue::as_str))
.expect("not a Vec<Vec<&str>>");
actual_paths.sort_unstable();
let expected_paths = vec![
vec!["pub_use_handling", "CheckPubUseHandling"],
vec!["pub_use_handling", "inner", "CheckPubUseHandling"],
];
assert_eq!(expected_paths, actual_paths);
}
type TestOutput = BTreeMap<String, Vec<BTreeMap<String, FieldValue>>>;
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
struct WitnessOutput {
filename: String,
begin_line: usize,
hint: String,
}
impl PartialOrd for WitnessOutput {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
/// Sorts by span (filename, begin_line)
impl Ord for WitnessOutput {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(&self.filename, self.begin_line).cmp(&(&other.filename, other.begin_line))
}
}
fn pretty_format_output_difference(
query_name: &str,
output_name1: &'static str,
output1: TestOutput,
output_name2: &'static str,
output2: TestOutput,
) -> String {
let output_ron1 =
ron::ser::to_string_pretty(&output1, ron::ser::PrettyConfig::default()).unwrap();
let output_ron2 =
ron::ser::to_string_pretty(&output2, ron::ser::PrettyConfig::default()).unwrap();
let diff = similar_asserts::SimpleDiff::from_str(
&output_ron1,
&output_ron2,
output_name1,
output_name2,
);
[
format!("Query {query_name} produced incorrect output (./src/lints/{query_name}.ron)."),
diff.to_string(),
"Remember that result output order matters, and remember to re-run \
./scripts/regenerate_test_rustdocs.sh when needed."
.to_string(),
]
.join("\n\n")
}
fn run_query_on_crate_pair(
semver_query: &SemverQuery,
crate_pair_name: &String,
indexed_crate_new: &VersionedIndex<'_>,
indexed_crate_old: &VersionedIndex<'_>,
) -> (String, Vec<BTreeMap<String, FieldValue>>) {
let adapter = VersionedRustdocAdapter::new(indexed_crate_new, Some(indexed_crate_old))
.expect("could not create adapter");
let results_iter = adapter
.run_query(&semver_query.query, semver_query.arguments.clone())
.unwrap();
// Ensure span data inside `@fold` blocks is deterministically ordered,
// since the underlying adapter is non-deterministic due to its iteration over hashtables.
// Our heuristic for detecting spans inside `@fold` is to look for:
// - list-typed outputs
// - with names ending in `_begin_line`
// - located inside *one* `@fold` level (i.e. their component is directly under the root).
let parsed_query = trustfall_core::frontend::parse(adapter.schema(), &semver_query.query)
.expect("not a valid query");
let fold_keys_and_targets: BTreeMap<&str, Vec<Arc<str>>> = parsed_query
.outputs
.iter()
.filter_map(|(name, output)| {
if name.as_ref().ends_with("_begin_line") && output.value_type.is_list() {
if let Some(fold) = parsed_query
.ir_query
.root_component
.folds
.values()
.find(|fold| fold.component.root == parsed_query.vids[&output.vid].root)
{
let targets = parsed_query
.outputs
.values()
.filter_map(|o| {
fold.component
.vertices
.contains_key(&o.vid)
.then_some(Arc::clone(&o.name))
})
.collect();
Some((name.as_ref(), targets))
} else {
None
}
} else {
None
}
})
.collect();
let results = results_iter
.map(move |mut res| {
// Reorder `@fold`-ed span data in increasing `begin_line` order.
for (fold_key, targets) in &fold_keys_and_targets {
let mut data: Vec<(u64, usize)> = res[*fold_key]
.as_vec_with(FieldValue::as_u64)
.expect("fold key was not a list of u64")
.into_iter()
.enumerate()
.map(|(idx, val)| (val, idx))
.collect();
data.sort_unstable();
for target in targets {
res.entry(Arc::clone(target)).and_modify(|value| {
// The output of a `@fold @transform(op: "count")` might not be a list here,
// so ignore such outputs. They don't need reordering anyway.
if let Some(slice) = value.as_slice() {
let new_order = data
.iter()
.map(|(_, idx)| slice[*idx].clone())
.collect::<Vec<_>>()
.into();
*value = new_order;
}
});
}
}
// Turn the output keys into regular strings.
res.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
})
.collect::<Vec<BTreeMap<_, _>>>();
(format!("./test_crates/{crate_pair_name}/"), results)
}
fn assert_no_false_positives_in_nonchanged_crate(
query_name: &str,
semver_query: &SemverQuery,
indexed_crate: &VersionedIndex<'_>,
crate_pair_name: &String,
crate_version: &str,
) {
let (crate_pair_path, output) =
run_query_on_crate_pair(semver_query, crate_pair_name, indexed_crate, indexed_crate);
if !output.is_empty() {
// This `if` statement means that a false positive happened.
// The query was ran on two identical crates (with the same rustdoc)
// and it produced a non-empty output, which means that it found issues
// in a crate pair that definitely has no semver breaks.
let actual_output_name = Box::leak(Box::new(format!(
"actual ({crate_pair_name}/{crate_version})"
)));
let output_difference = pretty_format_output_difference(
query_name,
"expected (empty)",
BTreeMap::new(),
actual_output_name,
BTreeMap::from([(crate_pair_path, output)]),
);
panic!("The query produced a non-empty output when it compared two crates with the same rustdoc.\n{output_difference}\n");
}
}
pub(in crate::query) fn check_query_execution(query_name: &str) {
let query_text = std::fs::read_to_string(format!("./src/lints/{query_name}.ron")).unwrap();
let semver_query = SemverQuery::from_ron_str(&query_text).unwrap();
let mut query_execution_results: TestOutput = get_test_crate_names()
.iter()
.map(|crate_pair_name| {
let (baseline, current) = get_test_crate_indexes(crate_pair_name);
assert_no_false_positives_in_nonchanged_crate(
query_name,
&semver_query,
current,
crate_pair_name,
"new",
);
assert_no_false_positives_in_nonchanged_crate(
query_name,
&semver_query,
baseline,
crate_pair_name,
"old",
);
run_query_on_crate_pair(&semver_query, crate_pair_name, current, baseline)
})
.filter(|(_crate_pair_name, output)| !output.is_empty())
.collect();
// Reorder vector of results into a deterministic order that will compensate for
// nondeterminism in how the results are ordered.
let key_func = |elem: &BTreeMap<String, FieldValue>| {
// Queries should either:
// - define an explicit `ordering_key` string value sufficient to establish
// a total order of results for each crate, or
// - define `span_filename` and `span_begin_line` values where the lint is being raised,
// which will then define a total order of results for that query on that crate.
let ordering_key = elem
.get("ordering_key")
.and_then(|value| value.as_arc_str());
if let Some(key) = ordering_key {
(Arc::clone(key), 0)
} else {
let filename = elem.get("span_filename").map(|value| {
value
.as_arc_str()
.expect("`span_filename` was not a string")
});
let line = elem
.get("span_begin_line")
.map(|value: &FieldValue| value.as_usize().expect("begin line was not an int"));
match (filename, line) {
(Some(filename), Some(line)) => (Arc::clone(filename), line),
(Some(_filename), None) => panic!("No `span_begin_line` was returned by the query, even though `span_filename` was present. A valid query must either output an explicit `ordering_key`, or output both `span_filename` and `span_begin_line`. See https://github.com/obi1kenobi/cargo-semver-checks/blob/main/CONTRIBUTING.md for details."),
(None, Some(_line)) => panic!("No `span_filename` was returned by the query, even though `span_begin_line` was present. A valid query must either output an explicit `ordering_key`, or output both `span_filename` and `span_begin_line`. See https://github.com/obi1kenobi/cargo-semver-checks/blob/main/CONTRIBUTING.md for details."),
(None, None) => panic!("A valid query must either output an explicit `ordering_key`, or output both `span_filename` and `span_begin_line`. See https://github.com/obi1kenobi/cargo-semver-checks/blob/main/CONTRIBUTING.md for details."),
}
}
};
for value in query_execution_results.values_mut() {
value.sort_unstable_by_key(key_func);
}
// TODO: Remove this once Rust 1.85 is the oldest Rust supported by cargo-semver-checks.
if query_name == "static_became_unsafe"
&& rustc_version::version().is_ok_and(|version| version < Version::new(1, 85, 0))
{
eprintln!("skipping query execution test for lint `static_became_unsafe` since data for it isn't available in Rust prior to 1.85");
return;
}
insta::with_settings!(
{
prepend_module_to_snapshot => false,
snapshot_path => "../test_outputs/query_execution",
},
{
insta::assert_ron_snapshot!(query_name, &query_execution_results);
}
);
let transparent_results: BTreeMap<_, Vec<BTreeMap<_, TransparentValue>>> =
query_execution_results
.into_iter()
.map(|(k, v)| {
(
k,
v.into_iter()
.map(|x| x.into_iter().map(|(k, v)| (k, v.into())).collect())
.collect(),
)
})
.collect();
let registry = make_handlebars_registry();
if let Some(template) = semver_query.per_result_error_template {
assert!(!transparent_results.is_empty());
let flattened_actual_results: Vec<_> = transparent_results
.iter()
.flat_map(|(_key, value)| value)
.collect();
for semver_violation_result in flattened_actual_results {
registry
.render_template(&template, semver_violation_result)
.with_context(|| "Error instantiating semver query template.")
.expect("could not materialize template");
}
}
if let Some(witness) = semver_query.witness {
let actual_witnesses: BTreeMap<_, BTreeSet<_>> = transparent_results
.iter()
.map(|(k, v)| {
(
Cow::Borrowed(k.as_str()),
v.iter()
.map(|values| {
let Some(TransparentValue::String(filename)) = values.get("span_filename") else {
unreachable!("Missing span_filename String, this should be validated above")
};
let begin_line = match values.get("span_begin_line") {
Some(TransparentValue::Int64(i)) => *i as usize,
Some(TransparentValue::Uint64(n)) => *n as usize,
_ => unreachable!("Missing span_begin_line Int, this should be validated above"),
};
// TODO: Run witness queries and generate full witness here.
WitnessOutput {
filename: filename.to_string(),
begin_line,
hint: registry
.render_template(&witness.hint_template, values)
.expect("error rendering hint template"),
}
})
.collect(),
)
})
.collect();
insta::with_settings!(
{
prepend_module_to_snapshot => false,
snapshot_path => "../test_outputs/witnesses",
description => format!(
"Lint `{query_name}` did not have the expected witness output.\n\
See https://github.com/obi1kenobi/cargo-semver-checks/blob/main/CONTRIBUTING.md#testing-witnesses\n\
for more information."
),
},
{
insta::assert_toml_snapshot!(query_name, &actual_witnesses);
}
);
}
}
/// Helper function to construct a blank query with a given id, lint level, and required
/// version bump.
#[must_use]
fn make_blank_query(
id: String,
lint_level: LintLevel,
required_update: RequiredSemverUpdate,
) -> SemverQuery {
SemverQuery {
id,
lint_level,
required_update,
human_readable_name: String::new(),
description: String::new(),
reference: None,
reference_link: None,
query: String::new(),
arguments: BTreeMap::new(),
error_message: String::new(),
per_result_error_template: None,
witness: None,
}
}
#[test]
fn test_overrides() {
let mut stack = OverrideStack::new();
stack.push(&OverrideMap::from_iter([
(
"query1".into(),
QueryOverride {
lint_level: Some(LintLevel::Allow),
required_update: Some(RequiredSemverUpdate::Minor),
},
),
(
"query2".into(),
QueryOverride {
lint_level: None,
required_update: Some(RequiredSemverUpdate::Minor),
},
),
]));
let q1 = make_blank_query(
"query1".into(),
LintLevel::Deny,
RequiredSemverUpdate::Major,
);
let q2 = make_blank_query(
"query2".into(),
LintLevel::Warn,
RequiredSemverUpdate::Major,
);
// Should pick overridden values.
assert_eq!(stack.effective_lint_level(&q1), LintLevel::Allow);
assert_eq!(
stack.effective_required_update(&q1),
RequiredSemverUpdate::Minor
);
// Should pick overridden value for semver and fall back to default lint level
// which is not overridden
assert_eq!(stack.effective_lint_level(&q2), LintLevel::Warn);
assert_eq!(
stack.effective_required_update(&q2),
RequiredSemverUpdate::Minor
);
}
#[test]
fn test_override_precedence() {
let mut stack = OverrideStack::new();
stack.push(&OverrideMap::from_iter([
(
"query1".into(),
QueryOverride {
lint_level: Some(LintLevel::Allow),
required_update: Some(RequiredSemverUpdate::Minor),
},
),
(
("query2".into()),
QueryOverride {
lint_level: None,
required_update: Some(RequiredSemverUpdate::Minor),
},
),
]));
stack.push(&OverrideMap::from_iter([(
"query1".into(),
QueryOverride {
required_update: None,
lint_level: Some(LintLevel::Warn),
},
)]));
let q1 = make_blank_query(
"query1".into(),
LintLevel::Deny,
RequiredSemverUpdate::Major,
);
let q2 = make_blank_query(
"query2".into(),
LintLevel::Warn,
RequiredSemverUpdate::Major,
);
// Should choose overridden value at the top of the stack
assert_eq!(stack.effective_lint_level(&q1), LintLevel::Warn);
// Should fall back to a configured value lower in the stack because
// top is not set.
assert_eq!(
stack.effective_required_update(&q1),
RequiredSemverUpdate::Minor
);
// Should pick overridden value for semver and fall back to default lint level
// which is not overridden
assert_eq!(stack.effective_lint_level(&q2), LintLevel::Warn);
assert_eq!(
stack.effective_required_update(&q2),
RequiredSemverUpdate::Minor
);
}
/// Makes sure we can specify [`InheritedValue`]s with `Inherited(...)`
/// and untagged variants as [`TransparentValue`]s.
#[test]
fn test_inherited_value_deserialization() {
let my_map: BTreeMap<String, InheritedValue> = ron::from_str(
r#"{
"abc": (inherit: "abc"),
"string": "literal_string",
"int": -30,
"int_list": [-30, -2],
"string_list": ["abc", "123"],
}"#,
)
.expect("deserialization failed");
let Some(InheritedValue::Inherited { inherit: abc }) = my_map.get("abc") else {
panic!("Expected Inherited, got {:?}", my_map.get("abc"));
};
assert_eq!(abc, "abc");
let Some(InheritedValue::Constant(TransparentValue::String(string))) = my_map.get("string")
else {