ripbi-core 0.2.0

Static analysis engine for Power BI semantic models: TMDL and PBIR ingestion, DAX reference extraction, dependency graph, and reachability
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Format-agnostic report AST: the normalized shape every report source format
//! (PBIR `definition/` folders, PBIR-Legacy `report.json` Layout) is parsed into.
//!
//! The types here are plain data with no parsing or I/O behaviour. Their only logic
//! is the enumeration at the bottom of this module ([`ReportModel::bindings`] and
//! [`ReportModel::dax_expressions`]), which is the single place that knows where
//! report-side reachability roots and report-owned DAX live. The graph layer
//! consumes those two functions instead of walking the AST itself, so a new
//! binding-bearing field cannot be silently omitted from reachability analysis.
//!
//! Bindings hold references *as written* — structured entity trees in PBIR,
//! written names in legacy Layout — never resolved model objects. Resolution
//! against the semantic model is the graph layer's job, via
//! [`ModelIndex`](crate::ModelIndex); keeping the written form is what lets both
//! source formats populate the same structures.

use std::fmt;

use crate::identity::{FieldRef, NameKey, Quoted};
use crate::model::{DaxExpressionKind, DaxExpressionRef, ExpressionOwner};

/// Normalized report definition, regardless of source format (PBIR, PBIR-Legacy
/// Layout). One instance per report: an analysis runs one
/// [`TabularDatabase`](crate::TabularDatabase) against the reports that share it,
/// and each report's `name` completes its bindings' provenance.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ReportModel {
    /// Report identity for provenance: the `.platform` display name, or the report
    /// folder's name when the source records none.
    pub name: Option<String>,
    /// The semantic model this report connects to (PBIR `datasetReference`).
    pub dataset: DatasetReference,
    /// Report-level filters (PBIR `report.json` filterConfig).
    pub filters: Vec<Filter>,
    /// Pages in source order.
    pub pages: Vec<Page>,
    /// Bookmarks in source order.
    pub bookmarks: Vec<Bookmark>,
    /// Report-level measures (PBIR `reportExtensions.json`): DAX that lives in the
    /// report, not the model.
    pub measures: Vec<ReportMeasure>,
}

/// How a report reaches its semantic model (PBIR `datasetReference`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatasetReference {
    /// Relative path to a sibling semantic-model folder (`byPath`). Forward
    /// slashes are the Power BI-written form; hand-edited files may carry
    /// backslashes, so the CLI accepts both when resolving.
    ByPath {
        /// Path as written, e.g. `../Sales.SemanticModel`.
        path: String,
    },
    /// Live connection to a remote semantic model (`byConnection`).
    ByConnection {
        /// Connection string as written.
        connection_string: String,
    },
    /// Absent, unrecognized, or not yet parsed.
    Unresolved,
}

impl Default for DatasetReference {
    /// An unparsed reference is `Unresolved`, never a path or a connection,
    /// mirroring [`PartitionSource::Other`](crate::PartitionSource): schema drift
    /// must never fabricate a report↔model pairing.
    fn default() -> Self {
        Self::Unresolved
    }
}

/// One page of a report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Page {
    /// Page object name, e.g. `ReportSectionacd41c847407a998c130`. PBIR keys its
    /// folders and files by it, and bookmarks reference pages by it.
    pub name: NameKey,
    /// Author-facing name, e.g. `Overview`.
    pub display_name: Option<String>,
    /// Hidden pages still bind fields — their visuals render on demand — so this
    /// flag is display-only, never liveness.
    pub is_hidden: bool,
    /// Filters applied to the whole page.
    pub filters: Vec<Filter>,
    /// The page's drillthrough/tooltip role, if it has one.
    pub binding: Option<PageBinding>,
    /// Visuals on the page, in source order.
    pub visuals: Vec<Visual>,
}

/// The role a page plays in drillthrough and tooltips (PBIR `pageBinding.type`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum PageBindingKind {
    /// An ordinary page. The default.
    #[default]
    Default,
    /// Reached via drillthrough; its parameters bind fields.
    Drillthrough,
    /// Rendered as a tooltip for other visuals.
    Tooltip,
}

/// A page's drillthrough/tooltip configuration (PBIR `pageBinding`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PageBinding {
    /// What kind of page binding this is.
    pub kind: PageBindingKind,
    /// Fields a drillthrough caller must supply, in source order.
    pub parameters: Vec<DrillthroughParameter>,
}

/// One drillthrough field (PBIR `pageBinding.parameters[]`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DrillthroughParameter {
    /// Parameter name as written, e.g. `Param_Filter5`.
    pub name: Option<NameKey>,
    /// The bound field (PBIR `fieldExpr`).
    pub target: FieldTarget,
}

/// One visual on a page.
///
/// Slicers are not a separate kind: a slicer is a visual with `visual_type`
/// `"slicer"`, and its field wells carry the binding. Saved slicer *selections*
/// are literal values, not references, and are not modeled.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Visual {
    /// Visual object name — the PBIR folder name and bookmarks' key.
    pub name: NameKey,
    /// Visual type as written, e.g. `"donutChart"`, `"slicer"`, `"card"`.
    pub visual_type: String,
    /// Field wells (PBIR `query.queryState`): role → projections.
    pub wells: Vec<FieldWell>,
    /// Filters applied to this visual only.
    pub filters: Vec<Filter>,
    /// Sort-by fields (PBIR `sortDefinition`), in sort order.
    pub sorts: Vec<FieldTarget>,
    /// Fields driving conditional-formatting rules.
    pub conditional_formatting: Vec<FieldTarget>,
    /// Fields referenced by the visual's accessibility alt text
    /// (`visualContainerObjects.general.altText`): a screen reader reads it,
    /// so dropping the field breaks the visual.
    pub alt_text: Vec<FieldTarget>,
    /// Page used as this visual's tooltip, by page object name. A report-internal
    /// reference: it keeps the page reachable, not a model object.
    pub tooltip_page: Option<NameKey>,
}

/// One field well of a visual: everything projected into a single role.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct FieldWell {
    /// Role name as written, e.g. `"Category"`, `"Y"`, `"Tooltips"`, `"Values"`.
    pub role: String,
    /// Projections in the well, in source order.
    pub projections: Vec<Projection>,
}

/// One field projected into a well.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Projection {
    /// The projected field.
    pub target: FieldTarget,
    /// Written display form as it appears in the file (PBIR `queryRef`), e.g.
    /// `Sales.Customers % of Total`. Diagnostics only — `target` is authoritative.
    pub query_ref: Option<String>,
    /// Whether the projection is active. Inactive projections still bind: they are
    /// one toggle away from live, and dropping them would under-count roots.
    pub active: bool,
}

/// A filter at report, page, visual, or bookmark level.
///
/// The filtered *values* (the condition tree's literals) are data, not references,
/// and are not modeled — only the fields a filter touches can keep objects alive.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Filter {
    /// Filter name within its scope, e.g. `Filter5`. Drillthrough parameters bind
    /// to filters by this name (PBIR `boundFilter`).
    pub name: Option<NameKey>,
    /// The filtered field itself (PBIR `filterConfig.filters[].field`).
    pub target: Option<FieldTarget>,
    /// Further fields referenced by the filter's condition tree, with query aliases
    /// (`SourceRef.Source`) already resolved to entities by the parser.
    pub references: Vec<FieldTarget>,
}

/// A saved exploration state, restorable by a reader.
///
/// Bookmark bindings are enumerated like any other: applying a bookmark re-applies
/// its saved filters and projections, so a field kept alive only by a bookmark is
/// still alive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bookmark {
    /// Bookmark object name — the PBIR file name, and the provenance key.
    pub name: NameKey,
    /// Author-facing name.
    pub display_name: Option<String>,
    /// Filters saved at report level (`explorationState.filters`).
    pub filters: Vec<Filter>,
    /// Captured state, per page it spans (usually one).
    pub sections: Vec<BookmarkSection>,
}

/// The slice of a bookmark's state belonging to one page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BookmarkSection {
    /// The captured page, by object name.
    pub page: NameKey,
    /// Saved filters (`byName` and `byExpr`).
    pub filters: Vec<Filter>,
    /// Saved per-visual state, in source order.
    pub visuals: Vec<BookmarkVisual>,
}

/// A bookmark's saved state for one visual.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BookmarkVisual {
    /// The visual, by object name.
    pub visual: NameKey,
    /// Fields active when the bookmark was captured, as wells by role.
    pub wells: Vec<FieldWell>,
    /// Filters saved for this visual (`visualContainers.<id>.filters`).
    pub filters: Vec<Filter>,
}

/// A DAX measure defined in the report (PBIR `reportExtensions.json`), not the
/// model.
///
/// A report measure bridges usage in both directions: its body references model
/// objects (so it is an expression source the graph must consume), and visuals
/// reference it by name (so it is a reachability root of its own). Name lookup
/// should try report measures before model measures — within its report, a report
/// measure shadows a model measure of the same name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReportMeasure {
    /// Measure name, unique within its report.
    pub name: NameKey,
    /// The measure's DAX expression.
    pub expression: String,
    /// Dynamic format string (DAX).
    pub format_string: Option<String>,
}

/// A model-object reference as written in a report binding, before resolution.
///
/// PBIR bindings are structured JSON entity trees (`Column`, `Measure`,
/// `HierarchyLevel`, `Aggregation`); legacy Layout binds written names. Both
/// normalize here, so downstream code never branches on source format.
///
/// The column/measure discrimination is kept rather than collapsed into
/// [`FieldRef`], because the binding states it outright and resolution would
/// otherwise be guessing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FieldTarget {
    /// A column, by its table (`SourceRef.Entity`) and name (`Property`).
    Column {
        /// Owning table as written.
        table: NameKey,
        /// Column name as written.
        column: NameKey,
    },
    /// A measure, by name. Measures are model-global; the entity PBIR writes
    /// alongside them is the home table as displayed, carried for provenance only.
    Measure {
        /// Home table as written, if any.
        home_table: Option<NameKey>,
        /// Measure name as written.
        measure: NameKey,
    },
    /// A hierarchy level: the level a visual drills to, which keeps the whole
    /// hierarchy (and its level columns) alive.
    HierarchyLevel {
        /// Owning table as written. For a hierarchy reached over a column
        /// variation this is the *varied* (base) table; the hierarchy itself
        /// lives on the variation's target table.
        table: NameKey,
        /// Hierarchy name as written.
        hierarchy: NameKey,
        /// Level name as written.
        level: NameKey,
        /// The varied column (PBIR `PropertyVariationSource.Property`), when
        /// the hierarchy is reached over a column variation — the key that
        /// joins this binding to the model-side
        /// [`crate::model::Column::variations`] declaration.
        via_column: Option<NameKey>,
        /// The variation's name (PBIR `PropertyVariationSource.Name`), which
        /// picks between a column's variations when there are several.
        via_variation: Option<NameKey>,
    },
    /// An aggregation over an inner reference, e.g. Sum of `'Sales'[Units]`.
    /// The inner target is what stays alive; the function is diagnostics.
    Aggregation {
        /// Aggregation function as written, e.g. `"Sum"`.
        function: Option<String>,
        /// The aggregated field.
        inner: Box<FieldTarget>,
    },
    /// A written name the parser could not structure — legacy Layout strings,
    /// unresolved query aliases. Kept anyway: a binding we cannot read is still a
    /// binding, and dropping it would under-count roots.
    Written(FieldRef),
}

impl fmt::Display for FieldTarget {
    /// Human-readable form for diagnostics, quoting names the way [`FieldRef`]
    /// does. The hierarchy-level and aggregation forms are illustrative, not valid
    /// DAX — level references have no DAX syntax.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FieldTarget::Column { table, column } => {
                write!(f, "{}[{}]", Quoted(table.as_str()), column.as_str())
            }
            FieldTarget::Measure {
                home_table,
                measure,
            } => match home_table {
                Some(table) => write!(f, "{}[{}]", Quoted(table.as_str()), measure.as_str()),
                None => write!(f, "[{}]", measure.as_str()),
            },
            FieldTarget::HierarchyLevel {
                table,
                hierarchy,
                level,
                ..
            } => write!(
                f,
                "hierarchy {}[{}] level {}",
                Quoted(table.as_str()),
                hierarchy.as_str(),
                Quoted(level.as_str())
            ),
            FieldTarget::Aggregation { function, inner } => match function {
                Some(function) => write!(f, "{function}({inner})"),
                None => write!(f, "Aggregation({inner})"),
            },
            FieldTarget::Written(reference) => write!(f, "{reference}"),
        }
    }
}

/// What kind of report-side usage a binding represents.
///
/// The kind powers "used by" explanations (`'Sales'[Amount]` ← filter on
/// *Overview* ← page 2) and groups bindings for reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BindingKind<'a> {
    /// A field projected into a visual's field well, with the well's role.
    FieldWell {
        /// Role name as written, e.g. `"Category"`, `"Y"`, `"Tooltips"`.
        role: &'a str,
    },
    /// A filter at report, page, visual, or bookmark level.
    Filter,
    /// A visual's sort-by field.
    Sort,
    /// A drillthrough parameter's bound field.
    Drillthrough,
    /// A field driving a conditional-formatting rule.
    ConditionalFormatting,
    /// A visual's accessibility alt text (`general.altText`).
    AltText,
}

/// Borrowed view of one report binding, with its provenance.
///
/// The page/visual/bookmark fields answer *where* the binding lives — the `None`s
/// narrow it: a report-level filter has neither page nor visual, a page filter has
/// no visual. Which *report* a binding came from is answered by the
/// [`ReportModel`] it was enumerated from, so the report name is not repeated here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BindingRef<'a> {
    /// Page the binding lives on; `None` for report-level bindings.
    pub page: Option<&'a NameKey>,
    /// Visual the binding lives in; `None` outside a visual.
    pub visual: Option<&'a NameKey>,
    /// Bookmark whose saved state carries the binding; `None` for live bindings.
    pub bookmark: Option<&'a NameKey>,
    /// What kind of binding this is.
    pub kind: BindingKind<'a>,
    /// The model object referenced, as written.
    pub target: &'a FieldTarget,
}

impl ReportModel {
    /// Every model-object reference the report makes, with its provenance — the
    /// reachability roots the graph's BFS starts from.
    ///
    /// Order follows report order (report filters, then per page: drillthrough
    /// parameters, page filters, and each visual's wells, filters, sorts, and
    /// conditional formatting; then per bookmark: report-level filters, and per
    /// section: section filters and each visual's wells and filters), so the
    /// result is deterministic for a given report and diffable across runs.
    ///
    /// Everything borrows from the report, so this allocates only the returned
    /// `Vec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ripbi_core::report::{BindingKind, FieldTarget, Filter, ReportModel};
    /// use ripbi_core::NameKey;
    ///
    /// let report = ReportModel {
    ///     filters: vec![Filter {
    ///         target: Some(FieldTarget::Column {
    ///             table: NameKey::new("Product"),
    ///             column: NameKey::new("Category"),
    ///         }),
    ///         ..Default::default()
    ///     }],
    ///     ..Default::default()
    /// };
    ///
    /// let bindings = report.bindings();
    /// assert_eq!(bindings.len(), 1);
    /// assert_eq!(bindings[0].kind, BindingKind::Filter);
    /// // A report-level filter belongs to no page and no visual.
    /// assert_eq!(bindings[0].page, None);
    /// assert_eq!(bindings[0].visual, None);
    /// ```
    #[must_use]
    pub fn bindings(&self) -> Vec<BindingRef<'_>> {
        let mut out = Vec::new();

        for filter in &self.filters {
            extend_with_filter(&mut out, None, None, None, filter);
        }

        for page in &self.pages {
            let page_id = Some(&page.name);

            if let Some(binding) = &page.binding {
                for parameter in &binding.parameters {
                    out.push(BindingRef {
                        page: page_id,
                        visual: None,
                        bookmark: None,
                        kind: BindingKind::Drillthrough,
                        target: &parameter.target,
                    });
                }
            }

            for filter in &page.filters {
                extend_with_filter(&mut out, page_id, None, None, filter);
            }

            for visual in &page.visuals {
                let visual_id = Some(&visual.name);
                extend_with_wells(&mut out, page_id, visual_id, None, &visual.wells);

                for filter in &visual.filters {
                    extend_with_filter(&mut out, page_id, visual_id, None, filter);
                }

                for target in &visual.sorts {
                    out.push(BindingRef {
                        page: page_id,
                        visual: visual_id,
                        bookmark: None,
                        kind: BindingKind::Sort,
                        target,
                    });
                }

                for target in &visual.conditional_formatting {
                    out.push(BindingRef {
                        page: page_id,
                        visual: visual_id,
                        bookmark: None,
                        kind: BindingKind::ConditionalFormatting,
                        target,
                    });
                }

                for target in &visual.alt_text {
                    out.push(BindingRef {
                        page: page_id,
                        visual: visual_id,
                        bookmark: None,
                        kind: BindingKind::AltText,
                        target,
                    });
                }
            }
        }

        for bookmark in &self.bookmarks {
            let bookmark_id = Some(&bookmark.name);

            for filter in &bookmark.filters {
                extend_with_filter(&mut out, None, None, bookmark_id, filter);
            }

            for section in &bookmark.sections {
                let page_id = Some(&section.page);

                for filter in &section.filters {
                    extend_with_filter(&mut out, page_id, None, bookmark_id, filter);
                }

                for visual in &section.visuals {
                    let visual_id = Some(&visual.visual);
                    extend_with_wells(&mut out, page_id, visual_id, bookmark_id, &visual.wells);

                    for filter in &visual.filters {
                        extend_with_filter(&mut out, page_id, visual_id, bookmark_id, filter);
                    }
                }
            }
        }

        out
    }

    /// Every DAX expression defined report-side — report-level measures — on top of
    /// [`TabularDatabase::dax_expressions`](crate::TabularDatabase::dax_expressions),
    /// which covers the model side.
    ///
    /// A report measure has no home table, so `home_table` is always `None`:
    /// unqualified `[Name]` references in its body can only be measures — of the
    /// report first, then the model.
    ///
    /// Owners borrow their names, so this allocates only the returned `Vec`.
    #[must_use]
    pub fn dax_expressions(&self) -> Vec<DaxExpressionRef<'_>> {
        let mut out = Vec::new();

        for measure in &self.measures {
            let owner = ExpressionOwner::ReportMeasure {
                measure: measure.name.as_str(),
            };
            out.push(DaxExpressionRef {
                owner,
                kind: DaxExpressionKind::ReportMeasure,
                home_table: None,
                text: &measure.expression,
            });
            if let Some(text) = &measure.format_string {
                out.push(DaxExpressionRef {
                    owner,
                    kind: DaxExpressionKind::ReportMeasureFormatString,
                    home_table: None,
                    text,
                });
            }
        }

        out
    }
}

/// Appends one [`BindingRef`] per field a filter carries, all tagged
/// [`BindingKind::Filter`]: the declared `target` first, then the condition tree's
/// `references`, preserving file order for stable diffs.
fn extend_with_filter<'a>(
    out: &mut Vec<BindingRef<'a>>,
    page: Option<&'a NameKey>,
    visual: Option<&'a NameKey>,
    bookmark: Option<&'a NameKey>,
    filter: &'a Filter,
) {
    for target in filter.target.iter().chain(&filter.references) {
        out.push(BindingRef {
            page,
            visual,
            bookmark,
            kind: BindingKind::Filter,
            target,
        });
    }
}

/// Appends one [`BindingRef`] per projection in the wells, tagged with its well's
/// role. Inactive projections bind too: they are one toggle away from live.
fn extend_with_wells<'a>(
    out: &mut Vec<BindingRef<'a>>,
    page: Option<&'a NameKey>,
    visual: Option<&'a NameKey>,
    bookmark: Option<&'a NameKey>,
    wells: &'a [FieldWell],
) {
    for well in wells {
        for projection in &well.projections {
            out.push(BindingRef {
                page,
                visual,
                bookmark,
                kind: BindingKind::FieldWell {
                    role: well.role.as_str(),
                },
                target: &projection.target,
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    fn column_target(table: &str, column: &str) -> FieldTarget {
        FieldTarget::Column {
            table: NameKey::new(table),
            column: NameKey::new(column),
        }
    }

    fn measure_target(home_table: Option<&str>, measure: &str) -> FieldTarget {
        FieldTarget::Measure {
            home_table: home_table.map(NameKey::new),
            measure: NameKey::new(measure),
        }
    }

    fn filter_on(target: FieldTarget) -> Filter {
        Filter {
            target: Some(target),
            ..Default::default()
        }
    }

    fn page(name: &str) -> Page {
        Page {
            name: NameKey::new(name),
            display_name: None,
            is_hidden: false,
            filters: Vec::new(),
            binding: None,
            visuals: Vec::new(),
        }
    }

    fn visual(name: &str, visual_type: &str) -> Visual {
        Visual {
            name: NameKey::new(name),
            visual_type: visual_type.to_string(),
            wells: Vec::new(),
            filters: Vec::new(),
            sorts: Vec::new(),
            conditional_formatting: Vec::new(),
            alt_text: Vec::new(),
            tooltip_page: None,
        }
    }

    fn well(role: &str, targets: &[FieldTarget]) -> FieldWell {
        FieldWell {
            role: role.to_string(),
            projections: targets
                .iter()
                .cloned()
                .map(|target| Projection {
                    target,
                    query_ref: None,
                    active: true,
                })
                .collect(),
        }
    }

    mod field_target {
        use super::*;

        #[rstest]
        #[case::column(column_target("Product", "Category"), "'Product'[Category]")]
        #[case::measure_with_home_table(measure_target(Some("Sales"), "Cost"), "'Sales'[Cost]")]
        #[case::measure_without_home_table(measure_target(None, "Cost"), "[Cost]")]
        #[case::hierarchy_level(
            FieldTarget::HierarchyLevel {
                table: NameKey::new("Accounts"),
                hierarchy: NameKey::new("Street Hierarchy"),
                level: NameKey::new("State or Province"),
                via_column: None,
                via_variation: None,
            },
            "hierarchy 'Accounts'[Street Hierarchy] level 'State or Province'"
        )]
        #[case::aggregation(
            FieldTarget::Aggregation {
                function: Some("Sum".to_string()),
                inner: Box::new(column_target("Sales", "Units")),
            },
            "Sum('Sales'[Units])"
        )]
        #[case::aggregation_without_function(
            FieldTarget::Aggregation {
                function: None,
                inner: Box::new(column_target("Sales", "Units")),
            },
            "Aggregation('Sales'[Units])"
        )]
        #[case::written(
            FieldTarget::Written(FieldRef {
                table: Some(NameKey::new("Sales")),
                name: NameKey::new("Amount"),
            }),
            "'Sales'[Amount]"
        )]
        fn displays_for_diagnostics(#[case] target: FieldTarget, #[case] expected: &str) {
            assert_eq!(target.to_string(), expected);
        }

        #[test]
        fn compares_equal_ignoring_case() {
            assert_eq!(
                column_target("Product", "Category"),
                column_target("PRODUCT", "CATEGORY")
            );
            assert_eq!(
                measure_target(Some("Sales"), "Cost"),
                measure_target(Some("sales"), "COST")
            );
        }

        /// The binding states column-or-measure outright; losing it would make
        /// resolution guess where it currently knows.
        #[test]
        fn distinguishes_a_column_from_a_measure_with_the_same_names() {
            assert_ne!(
                column_target("Sales", "Cost"),
                measure_target(Some("Sales"), "Cost")
            );
        }
    }

    mod bindings {
        use super::*;

        /// The common report identity; each test adds the binding site it checks.
        fn sample() -> ReportModel {
            ReportModel {
                name: Some("Sales overview".to_string()),
                dataset: DatasetReference::ByPath {
                    path: "../Sales.SemanticModel".to_string(),
                },
                ..Default::default()
            }
        }

        fn sample_with_page(page: Page) -> ReportModel {
            ReportModel {
                pages: vec![page],
                ..sample()
            }
        }

        /// One binding's full provenance: page, visual, bookmark, kind, and the
        /// target as `Display` — what resolution consumes.
        type Provenance<'a> = (
            Option<&'a str>,
            Option<&'a str>,
            Option<&'a str>,
            BindingKind<'a>,
            String,
        );

        /// `Provenance` per binding, in enumeration order — the full
        /// specification `bindings()` must satisfy.
        fn provenance(report: &ReportModel) -> Vec<Provenance<'_>> {
            report
                .bindings()
                .into_iter()
                .map(|binding| {
                    (
                        binding.page.map(NameKey::as_str),
                        binding.visual.map(NameKey::as_str),
                        binding.bookmark.map(NameKey::as_str),
                        binding.kind,
                        binding.target.to_string(),
                    )
                })
                .collect()
        }

        #[test]
        fn a_report_filter_has_no_page_visual_or_bookmark() {
            let report = ReportModel {
                filters: vec![filter_on(column_target("Product", "Category"))],
                ..sample()
            };
            let bindings = report.bindings();

            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page, None);
            assert_eq!(bindings[0].visual, None);
            assert_eq!(bindings[0].bookmark, None);
            assert_eq!(bindings[0].kind, BindingKind::Filter);
        }

        #[test]
        fn a_drillthrough_parameter_is_tagged_on_its_page() {
            let report = sample_with_page(Page {
                binding: Some(PageBinding {
                    kind: PageBindingKind::Drillthrough,
                    parameters: vec![DrillthroughParameter {
                        name: Some(NameKey::new("Param_Filter5")),
                        target: column_target("Industries", "Industry"),
                    }],
                }),
                ..page("ReportSection1")
            });

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].visual, None);
            assert_eq!(bindings[0].kind, BindingKind::Drillthrough);
        }

        #[test]
        fn a_page_filter_carries_its_page_but_no_visual() {
            let report = sample_with_page(Page {
                filters: vec![filter_on(column_target("Owners", "Sales owner"))],
                ..page("ReportSection1")
            });

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].visual, None);
            assert_eq!(bindings[0].kind, BindingKind::Filter);
        }

        #[test]
        fn a_visual_well_carries_role_page_and_visual() {
            let report = sample_with_page(Page {
                visuals: vec![Visual {
                    wells: vec![well("Category", &[column_target("Product", "Category")])],
                    ..visual("visual1", "donutChart")
                }],
                ..page("ReportSection1")
            });

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].visual.unwrap().as_str(), "visual1");
            assert_eq!(bindings[0].bookmark, None);
            assert_eq!(
                bindings[0].kind,
                BindingKind::FieldWell { role: "Category" }
            );
        }

        #[test]
        fn sorts_and_conditional_formatting_are_tagged_as_such() {
            let report = sample_with_page(Page {
                visuals: vec![Visual {
                    sorts: vec![column_target("Product", "Category")],
                    conditional_formatting: vec![measure_target(Some("Sales"), "Margin")],
                    ..visual("visual1", "tableEx")
                }],
                ..page("ReportSection1")
            });

            let bindings = report.bindings();
            assert_eq!(
                bindings.iter().map(|b| b.kind).collect::<Vec<_>>(),
                vec![BindingKind::Sort, BindingKind::ConditionalFormatting]
            );
            // Both bindings belong to their visual, at page level.
            for binding in &bindings {
                assert_eq!(binding.page.unwrap().as_str(), "ReportSection1");
                assert_eq!(binding.visual.unwrap().as_str(), "visual1");
            }
        }

        #[test]
        fn a_bookmark_filter_carries_bookmark_and_page() {
            let report = ReportModel {
                bookmarks: vec![Bookmark {
                    name: NameKey::new("Bookmark1"),
                    display_name: Some("FY24".to_string()),
                    filters: Vec::new(),
                    sections: vec![BookmarkSection {
                        page: NameKey::new("ReportSection1"),
                        filters: vec![filter_on(column_target("Products", "Product category"))],
                        visuals: Vec::new(),
                    }],
                }],
                ..sample()
            };

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].visual, None);
            assert_eq!(bindings[0].bookmark.unwrap().as_str(), "Bookmark1");
            assert_eq!(bindings[0].kind, BindingKind::Filter);
        }

        #[test]
        fn bookmark_wells_carry_bookmark_page_and_visual() {
            let report = ReportModel {
                bookmarks: vec![Bookmark {
                    name: NameKey::new("Bookmark1"),
                    display_name: None,
                    filters: Vec::new(),
                    sections: vec![BookmarkSection {
                        page: NameKey::new("ReportSection1"),
                        filters: Vec::new(),
                        visuals: vec![BookmarkVisual {
                            visual: NameKey::new("visual1"),
                            wells: vec![well("Rows", &[column_target("Product", "Subcategory")])],
                            filters: Vec::new(),
                        }],
                    }],
                }],
                ..sample()
            };

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].visual.unwrap().as_str(), "visual1");
            assert_eq!(bindings[0].bookmark.unwrap().as_str(), "Bookmark1");
            assert_eq!(bindings[0].kind, BindingKind::FieldWell { role: "Rows" });
        }

        /// The declared target comes first, then the condition tree's references,
        /// in file order.
        #[test]
        fn a_filter_yields_target_then_references_in_order() {
            let report = sample_with_page(Page {
                visuals: vec![Visual {
                    filters: vec![Filter {
                        name: Some(NameKey::new("Filter5")),
                        target: Some(column_target("Product", "Category")),
                        references: vec![
                            column_target("Product", "Subcategory"),
                            measure_target(None, "Units"),
                        ],
                    }],
                    ..visual("visual1", "donutChart")
                }],
                ..page("ReportSection1")
            });

            let targets: Vec<&FieldTarget> =
                report.bindings().into_iter().map(|b| b.target).collect();
            assert_eq!(
                targets,
                vec![
                    &column_target("Product", "Category"),
                    &column_target("Product", "Subcategory"),
                    &measure_target(None, "Units"),
                ]
            );
        }

        /// A filter the parser could not give a structured target still binds:
        /// its references are roots even when `target` is `None`.
        #[test]
        fn a_filter_without_a_target_still_binds_its_references() {
            let report = sample_with_page(Page {
                visuals: vec![Visual {
                    filters: vec![Filter {
                        name: Some(NameKey::new("Filter5")),
                        target: None,
                        references: vec![
                            column_target("Product", "Subcategory"),
                            measure_target(None, "Units"),
                        ],
                    }],
                    ..visual("visual1", "donutChart")
                }],
                ..page("ReportSection1")
            });

            let targets: Vec<&FieldTarget> =
                report.bindings().into_iter().map(|b| b.target).collect();
            assert_eq!(
                targets,
                vec![
                    &column_target("Product", "Subcategory"),
                    &measure_target(None, "Units"),
                ]
            );
        }

        /// An inactive projection is one toggle away from live; dropping it would
        /// under-count roots and report live code as unused.
        #[test]
        fn an_inactive_projection_still_binds() {
            let report = sample_with_page(Page {
                visuals: vec![Visual {
                    wells: vec![FieldWell {
                        role: "Y".to_string(),
                        projections: vec![Projection {
                            target: column_target("Sales", "Units"),
                            query_ref: None,
                            active: false,
                        }],
                    }],
                    ..visual("visual1", "lineChart")
                }],
                ..page("ReportSection1")
            });

            assert_eq!(report.bindings().len(), 1);
        }

        /// Hidden is not dead: a hidden page's visuals render on demand, so their
        /// wells bind like any other page's. Skipping hidden pages would
        /// under-count roots and report live code as unused.
        #[test]
        fn a_hidden_pages_visuals_still_bind() {
            let report = sample_with_page(Page {
                is_hidden: true,
                visuals: vec![Visual {
                    wells: vec![well("Values", &[column_target("Sales", "Units")])],
                    ..visual("visual1", "card")
                }],
                ..page("ReportSection1")
            });

            let bindings = report.bindings();
            assert_eq!(bindings.len(), 1);
            assert_eq!(bindings[0].page.unwrap().as_str(), "ReportSection1");
            assert_eq!(bindings[0].kind, BindingKind::FieldWell { role: "Values" });
        }

        /// Enumeration walks report order — report filters, page (parameters,
        /// filters, visuals: wells, filters, sorts, conditional formatting), then
        /// bookmarks — so runs are diffable. Every binding's full provenance is
        /// pinned, not just its kind: a slipped page, visual, or bookmark on any
        /// site must fail here.
        #[test]
        fn order_follows_report_structure() {
            let report = ReportModel {
                filters: vec![filter_on(column_target("Product", "Category"))],
                pages: vec![
                    Page {
                        binding: Some(PageBinding {
                            kind: PageBindingKind::Drillthrough,
                            parameters: vec![DrillthroughParameter {
                                name: None,
                                target: column_target("Industries", "Industry"),
                            }],
                        }),
                        filters: vec![filter_on(column_target("Owners", "Sales owner"))],
                        visuals: vec![Visual {
                            wells: vec![well("Category", &[column_target("Product", "Category")])],
                            filters: vec![filter_on(column_target("Region", "Country"))],
                            sorts: vec![measure_target(Some("Sales"), "Sales")],
                            conditional_formatting: vec![measure_target(Some("Sales"), "Margin")],
                            ..visual("visual1", "donutChart")
                        }],
                        ..page("ReportSection1")
                    },
                    Page {
                        visuals: vec![Visual {
                            wells: vec![well(
                                "Tooltips",
                                &[measure_target(Some("Sales"), "Customers %")],
                            )],
                            ..visual("visual2", "slicer")
                        }],
                        ..page("ReportSection2")
                    },
                ],
                bookmarks: vec![Bookmark {
                    name: NameKey::new("Bookmark1"),
                    display_name: None,
                    filters: vec![filter_on(measure_target(None, "Total Units"))],
                    sections: vec![BookmarkSection {
                        page: NameKey::new("ReportSection1"),
                        filters: vec![filter_on(column_target("Products", "Product category"))],
                        visuals: vec![BookmarkVisual {
                            visual: NameKey::new("visual1"),
                            wells: vec![well("Rows", &[column_target("Product", "Subcategory")])],
                            filters: vec![filter_on(column_target("Product", "Color"))],
                        }],
                    }],
                }],
                measures: Vec::new(),
                ..sample()
            };

            assert_eq!(
                provenance(&report),
                vec![
                    // Report filter.
                    (
                        None,
                        None,
                        None,
                        BindingKind::Filter,
                        "'Product'[Category]".to_string(),
                    ),
                    // Page 1 drillthrough parameter.
                    (
                        Some("ReportSection1"),
                        None,
                        None,
                        BindingKind::Drillthrough,
                        "'Industries'[Industry]".to_string(),
                    ),
                    // Page 1 filter.
                    (
                        Some("ReportSection1"),
                        None,
                        None,
                        BindingKind::Filter,
                        "'Owners'[Sales owner]".to_string(),
                    ),
                    // Visual 1 well.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        None,
                        BindingKind::FieldWell { role: "Category" },
                        "'Product'[Category]".to_string(),
                    ),
                    // Visual 1 filter.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        None,
                        BindingKind::Filter,
                        "'Region'[Country]".to_string(),
                    ),
                    // Visual 1 sort.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        None,
                        BindingKind::Sort,
                        "'Sales'[Sales]".to_string(),
                    ),
                    // Visual 1 conditional formatting.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        None,
                        BindingKind::ConditionalFormatting,
                        "'Sales'[Margin]".to_string(),
                    ),
                    // Visual 2 well.
                    (
                        Some("ReportSection2"),
                        Some("visual2"),
                        None,
                        BindingKind::FieldWell { role: "Tooltips" },
                        "'Sales'[Customers %]".to_string(),
                    ),
                    // Bookmark report-level filter: no page, no visual.
                    (
                        None,
                        None,
                        Some("Bookmark1"),
                        BindingKind::Filter,
                        "[Total Units]".to_string(),
                    ),
                    // Bookmark section filter.
                    (
                        Some("ReportSection1"),
                        None,
                        Some("Bookmark1"),
                        BindingKind::Filter,
                        "'Products'[Product category]".to_string(),
                    ),
                    // Bookmark well.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        Some("Bookmark1"),
                        BindingKind::FieldWell { role: "Rows" },
                        "'Product'[Subcategory]".to_string(),
                    ),
                    // Bookmark visual filter.
                    (
                        Some("ReportSection1"),
                        Some("visual1"),
                        Some("Bookmark1"),
                        BindingKind::Filter,
                        "'Product'[Color]".to_string(),
                    ),
                ]
            );
        }
    }

    /// The same field, bound through PBIR's structured entities and through legacy
    /// Layout's written names, must enumerate to the same provenance: this
    /// equivalence is the AST's whole reason to exist.
    mod format_agnostic {
        use super::*;

        fn report_with(well_target: FieldTarget) -> ReportModel {
            ReportModel {
                pages: vec![Page {
                    visuals: vec![Visual {
                        wells: vec![well("Y", &[well_target])],
                        ..visual("visual1", "clusteredColumnChart")
                    }],
                    ..page("ReportSection1")
                }],
                ..Default::default()
            }
        }

        #[test]
        fn structured_and_written_targets_bind_alike() {
            let pbir = report_with(FieldTarget::Measure {
                home_table: Some(NameKey::new("Sales")),
                measure: NameKey::new("Cost"),
            });
            let legacy = report_with(FieldTarget::Written(FieldRef {
                table: Some(NameKey::new("Sales")),
                name: NameKey::new("Cost"),
            }));

            let pbir_bindings = pbir.bindings();
            let legacy_bindings = legacy.bindings();
            assert_eq!(pbir_bindings.len(), 1);
            assert_eq!(legacy_bindings.len(), 1);

            // Provenance and kind are identical; only the target's variant differs.
            assert_eq!(pbir_bindings[0].page, legacy_bindings[0].page);
            assert_eq!(pbir_bindings[0].visual, legacy_bindings[0].visual);
            assert_eq!(pbir_bindings[0].bookmark, legacy_bindings[0].bookmark);
            assert_eq!(pbir_bindings[0].kind, legacy_bindings[0].kind);
        }
    }

    mod dax_expressions {
        use super::*;

        #[test]
        fn enumerates_a_report_measures_body_and_format_string() {
            let report = ReportModel {
                measures: vec![ReportMeasure {
                    name: NameKey::new("Growth %"),
                    expression: "DIVIDE([Sales] - [Prior Sales], [Prior Sales])".to_string(),
                    format_string: Some("0.0%;-0.0%;0.0%".to_string()),
                }],
                ..Default::default()
            };

            let expressions = report.dax_expressions();
            assert_eq!(expressions.len(), 2);

            assert_eq!(
                expressions[0],
                DaxExpressionRef {
                    owner: ExpressionOwner::ReportMeasure {
                        measure: "Growth %"
                    },
                    kind: DaxExpressionKind::ReportMeasure,
                    home_table: None,
                    text: "DIVIDE([Sales] - [Prior Sales], [Prior Sales])",
                }
            );
            assert_eq!(
                expressions[1],
                DaxExpressionRef {
                    owner: ExpressionOwner::ReportMeasure {
                        measure: "Growth %"
                    },
                    kind: DaxExpressionKind::ReportMeasureFormatString,
                    home_table: None,
                    text: "0.0%;-0.0%;0.0%",
                }
            );
        }

        /// Most report measures carry no dynamic format string; only the body is
        /// then an expression source.
        #[test]
        fn a_measure_without_a_format_string_enumerates_only_its_body() {
            let report = ReportModel {
                measures: vec![ReportMeasure {
                    name: NameKey::new("Total Units"),
                    expression: "SUM('Sales'[Units])".to_string(),
                    format_string: None,
                }],
                ..Default::default()
            };

            let expressions = report.dax_expressions();
            assert_eq!(expressions.len(), 1);
            assert_eq!(expressions[0].kind, DaxExpressionKind::ReportMeasure);
        }

        #[test]
        fn a_report_without_measures_has_none() {
            assert!(ReportModel::default().dax_expressions().is_empty());
        }

        /// The owner is the measure's reachability identity: visuals reference it,
        /// its body references model objects, and the graph node must match both.
        /// Compared through `Display`: `ObjectId` equality ignores case, so it
        /// could never catch a lowercased or rewritten name.
        #[test]
        fn owner_materializes_a_report_measure_object_id() {
            let owner = ExpressionOwner::ReportMeasure {
                measure: "Growth %",
            };
            assert_eq!(
                owner.to_object_id().to_string(),
                "report measure 'Growth %'"
            );
        }
    }

    mod expression_views {
        use super::*;

        /// Mirrors the model-side guarantee: bindings enumerate without allocating
        /// beyond the returned `Vec`, which holds only while every field borrows.
        #[test]
        fn are_copy_so_enumeration_borrows_everything() {
            fn assert_copy<T: Copy>() {}
            assert_copy::<BindingRef<'_>>();
            assert_copy::<BindingKind<'_>>();
        }
    }

    mod defaults {
        use super::*;

        /// An unparsed dataset reference must never masquerade as a path or a
        /// connection, or a wrong report↔model pairing would reach the graph.
        #[test]
        fn a_dataset_reference_is_unresolved() {
            assert_eq!(DatasetReference::default(), DatasetReference::Unresolved);
            assert_eq!(ReportModel::default().dataset, DatasetReference::Unresolved);
        }

        /// Most pages are plain pages; PBIR omits the binding for them entirely.
        #[test]
        fn a_page_binding_kind_is_default() {
            assert_eq!(PageBindingKind::default(), PageBindingKind::Default);
            assert_eq!(PageBinding::default().kind, PageBindingKind::Default);
        }
    }
}