This repository was archived by the owner on Sep 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathpartial.rs
More file actions
2634 lines (2404 loc) · 99.9 KB
/
partial.rs
File metadata and controls
2634 lines (2404 loc) · 99.9 KB
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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, stack-graphs authors.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------
//! Partial paths are "snippets" of paths that we can precalculate for each file that we analyze.
//!
//! Stack graphs are _incremental_, since we can produce a subgraph for each file without having
//! to look at the contents of any other file in the repo, or in any upstream or downstream
//! dependencies.
//!
//! This is great, because it means that when we receive a new commit for a repository, we only
//! have to examine, and generate new stack subgraphs for, the files that are changed as part of
//! that commit.
//!
//! Having done that, one possible way to find name binding paths would be to load in all of the
//! subgraphs for the files that belong to the current commit, union them together into the
//! combined graph for that commit, and run the [path-finding algorithm][] on that combined graph.
//! However, we think that this will require too much computation at query time.
//!
//! [path-finding algorithm]: ../paths/index.html
//!
//! Instead, we want to precompute parts of the path-finding algorithm, by calculating _partial
//! paths_ for each file. Because stack graphs have limited places where a path can cross from one
//! file into another, we can calculate all of the possible partial paths that reach those
//! “import/export” points.
//!
//! At query time, we can then load in the _partial paths_ for each file, instead of the files'
//! full stack graph structure. We can efficiently [concatenate][] partial paths together,
//! producing the original "full" path that represents a name binding.
//!
//! [concatenate]: struct.PartialPath.html#method.concatenate
use std::convert::TryFrom;
use std::fmt::Display;
use std::num::NonZeroU32;
use controlled_option::ControlledOption;
use controlled_option::Niche;
use enumset::EnumSetType;
use smallvec::SmallVec;
use crate::arena::Deque;
use crate::arena::DequeArena;
use crate::arena::Handle;
use crate::graph::Edge;
use crate::graph::Node;
use crate::graph::NodeID;
use crate::graph::StackGraph;
use crate::graph::Symbol;
use crate::paths::PathResolutionError;
use crate::utils::cmp_option;
use crate::utils::equals_option;
//-------------------------------------------------------------------------------------------------
// Displaying stuff
/// This trait only exists because:
///
/// - we need `Display` implementations that dereference arena handles from our `StackGraph` and
/// `PartialPaths` bags o' crap,
/// - many of our arena-managed types can handles to _other_ arena-managed data, which we need to
/// recursively display as part of displaying the "outer" instance, and
/// - in particular, we sometimes need `&mut` access to the `PartialPaths` arenas.
///
/// The borrow checker is not very happy with us having all of these constraints at the same time —
/// in particular, the last one.
///
/// This trait gets around the problem by breaking up the display operation into two steps:
///
/// - First, each data instance has a chance to "prepare" itself with `&mut` access to whatever
/// arenas it needs. (Anything containing a `Deque`, for instance, uses this step to ensure
/// that our copy of the deque is pointed in the right direction, since reversing requires
/// `&mut` access to the arena.)
///
/// - Once everything has been prepared, we return a value that implements `Display`, and
/// contains _non-mutable_ references to the arena. Because our arena references are
/// non-mutable, we don't run into any problems with the borrow checker while recursively
/// displaying the contents of the data instance.
trait DisplayWithPartialPaths {
fn prepare(&mut self, _graph: &StackGraph, _partials: &mut PartialPaths) {}
fn display_with(
&self,
graph: &StackGraph,
partials: &PartialPaths,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result;
}
/// Prepares and returns a `Display` implementation for a type `D` that implements
/// `DisplayWithPartialPaths`. We only require `&mut` access to the `PartialPath` arenas while
/// creating the `Display` instance; the `Display` instance itself will only retain shared access
/// to the arenas.
fn display_with<'a, D>(
mut value: D,
graph: &'a StackGraph,
partials: &'a mut PartialPaths,
) -> impl Display + 'a
where
D: DisplayWithPartialPaths + 'a,
{
value.prepare(graph, partials);
DisplayWithPartialPathsWrapper {
value,
graph,
partials,
}
}
/// Returns a `Display` implementation that you can use inside of your `display_with` method to
/// display any recursive fields. This assumes that the recursive fields have already been
/// prepared.
fn display_prepared<'a, D>(
value: D,
graph: &'a StackGraph,
partials: &'a PartialPaths,
) -> impl Display + 'a
where
D: DisplayWithPartialPaths + 'a,
{
DisplayWithPartialPathsWrapper {
value,
graph,
partials,
}
}
#[doc(hidden)]
struct DisplayWithPartialPathsWrapper<'a, D> {
value: D,
graph: &'a StackGraph,
partials: &'a PartialPaths,
}
impl<'a, D> Display for DisplayWithPartialPathsWrapper<'a, D>
where
D: DisplayWithPartialPaths,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.value.display_with(self.graph, self.partials, f)
}
}
//-------------------------------------------------------------------------------------------------
// Symbol stack variables
/// Represents an unknown list of scoped symbols.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, Hash, Niche, Ord, PartialEq, PartialOrd)]
pub struct SymbolStackVariable(#[niche] NonZeroU32);
impl SymbolStackVariable {
pub fn new(variable: u32) -> Option<SymbolStackVariable> {
NonZeroU32::new(variable).map(SymbolStackVariable)
}
/// Creates a new symbol stack variable. This constructor is used when creating a new, empty
/// partial path, since there aren't any other variables that we need to be fresher than.
pub(crate) fn initial() -> SymbolStackVariable {
SymbolStackVariable(unsafe { NonZeroU32::new_unchecked(1) })
}
/// Applies an offset to this variable.
///
/// When concatenating partial paths, we have to ensure that the left- and right-hand sides
/// have non-overlapping sets of variables. To do this, we find the maximum value of any
/// variable on the left-hand side, and add this “offset” to the values of all of the variables
/// on the right-hand side.
pub fn with_offset(self, symbol_variable_offset: u32) -> SymbolStackVariable {
let offset_value = self.0.get() + symbol_variable_offset;
SymbolStackVariable(unsafe { NonZeroU32::new_unchecked(offset_value) })
}
pub(crate) fn as_u32(self) -> u32 {
self.0.get()
}
fn as_usize(self) -> usize {
self.0.get() as usize
}
}
impl Display for SymbolStackVariable {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "%{}", self.0.get())
}
}
impl From<NonZeroU32> for SymbolStackVariable {
fn from(value: NonZeroU32) -> SymbolStackVariable {
SymbolStackVariable(value)
}
}
impl Into<u32> for SymbolStackVariable {
fn into(self) -> u32 {
self.0.get()
}
}
impl TryFrom<u32> for SymbolStackVariable {
type Error = ();
fn try_from(value: u32) -> Result<SymbolStackVariable, ()> {
let value = NonZeroU32::new(value).ok_or(())?;
Ok(SymbolStackVariable(value))
}
}
//-------------------------------------------------------------------------------------------------
// Scope stack variables
/// Represents an unknown list of exported scopes.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, Hash, Niche, Ord, PartialEq, PartialOrd)]
pub struct ScopeStackVariable(#[niche] NonZeroU32);
impl ScopeStackVariable {
pub fn new(variable: u32) -> Option<ScopeStackVariable> {
NonZeroU32::new(variable).map(ScopeStackVariable)
}
/// Creates a new scope stack variable. This constructor is used when creating a new, empty
/// partial path, since there aren't any other variables that we need to be fresher than.
fn initial() -> ScopeStackVariable {
ScopeStackVariable(unsafe { NonZeroU32::new_unchecked(1) })
}
/// Creates a new scope stack variable that is fresher than all other variables in a partial
/// path. (You must calculate the maximum variable number already in use.)
fn fresher_than(max_used: u32) -> ScopeStackVariable {
ScopeStackVariable(unsafe { NonZeroU32::new_unchecked(max_used + 1) })
}
/// Applies an offset to this variable.
///
/// When concatenating partial paths, we have to ensure that the left- and right-hand sides
/// have non-overlapping sets of variables. To do this, we find the maximum value of any
/// variable on the left-hand side, and add this “offset” to the values of all of the variables
/// on the right-hand side.
pub fn with_offset(self, scope_variable_offset: u32) -> ScopeStackVariable {
let offset_value = self.0.get() + scope_variable_offset;
ScopeStackVariable(unsafe { NonZeroU32::new_unchecked(offset_value) })
}
pub(crate) fn as_u32(self) -> u32 {
self.0.get()
}
fn as_usize(self) -> usize {
self.0.get() as usize
}
}
impl Display for ScopeStackVariable {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "${}", self.0.get())
}
}
impl From<NonZeroU32> for ScopeStackVariable {
fn from(value: NonZeroU32) -> ScopeStackVariable {
ScopeStackVariable(value)
}
}
impl Into<u32> for ScopeStackVariable {
fn into(self) -> u32 {
self.0.get()
}
}
impl TryFrom<u32> for ScopeStackVariable {
type Error = ();
fn try_from(value: u32) -> Result<ScopeStackVariable, ()> {
let value = NonZeroU32::new(value).ok_or(())?;
Ok(ScopeStackVariable(value))
}
}
//-------------------------------------------------------------------------------------------------
// Partial symbol stacks
/// A symbol with an unknown, but possibly empty, list of exported scopes attached to it.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct PartialScopedSymbol {
pub symbol: Handle<Symbol>,
// Note that not having an attached scope list is _different_ than having an empty attached
// scope list.
pub scopes: ControlledOption<PartialScopeStack>,
}
impl PartialScopedSymbol {
/// Applies an offset to this scoped symbol.
///
/// When concatenating partial paths, we have to ensure that the left- and right-hand sides
/// have non-overlapping sets of variables. To do this, we find the maximum value of any
/// variable on the left-hand side, and add this “offset” to the values of all of the variables
/// on the right-hand side.
pub fn with_offset(mut self, scope_variable_offset: u32) -> PartialScopedSymbol {
let scopes = self
.scopes
.into_option()
.map(|stack| stack.with_offset(scope_variable_offset));
self.scopes = ControlledOption::from_option(scopes);
self
}
/// Matches this precondition symbol against another, unifying its contents with an existing
/// set of bindings.
pub fn unify(
&mut self,
partials: &mut PartialPaths,
rhs: PartialScopedSymbol,
scope_bindings: &mut PartialScopeStackBindings,
) -> Result<(), PathResolutionError> {
if self.symbol != rhs.symbol {
return Err(PathResolutionError::SymbolStackUnsatisfied);
}
match (self.scopes.into_option(), rhs.scopes.into_option()) {
(Some(lhs), Some(rhs)) => {
let unified = lhs.unify(partials, rhs, scope_bindings)?;
self.scopes = ControlledOption::some(unified);
}
(None, None) => {}
_ => return Err(PathResolutionError::SymbolStackUnsatisfied),
}
Ok(())
}
/// Returns whether two partial scoped symbols "match". The symbols must be identical, and any
/// attached scopes must also match.
pub fn matches(self, partials: &mut PartialPaths, postcondition: PartialScopedSymbol) -> bool {
if self.symbol != postcondition.symbol {
return false;
}
// If one side has an attached scope but the other doesn't, then the scoped symbols don't
// match.
if self.scopes.is_none() != postcondition.scopes.is_none() {
return false;
}
// Otherwise, if both sides have an attached scope, they have to be compatible.
if let Some(precondition_scopes) = self.scopes.into_option() {
if let Some(postcondition_scopes) = postcondition.scopes.into_option() {
return precondition_scopes.matches(partials, postcondition_scopes);
}
}
true
}
/// Applies a set of bindings to this partial scoped symbol, producing a new scoped symbol.
pub fn apply_partial_bindings(
mut self,
partials: &mut PartialPaths,
scope_bindings: &PartialScopeStackBindings,
) -> Result<PartialScopedSymbol, PathResolutionError> {
let scopes = match self.scopes.into_option() {
Some(scopes) => Some(scopes.apply_partial_bindings(partials, scope_bindings)?),
None => None,
};
self.scopes = scopes.into();
Ok(self)
}
pub fn equals(&self, partials: &mut PartialPaths, other: &PartialScopedSymbol) -> bool {
self.symbol == other.symbol
&& equals_option(
self.scopes.into_option(),
other.scopes.into_option(),
|a, b| a.equals(partials, b),
)
}
pub fn cmp(
&self,
graph: &StackGraph,
partials: &mut PartialPaths,
other: &PartialScopedSymbol,
) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
.then_with(|| graph[self.symbol].cmp(&graph[other.symbol]))
.then_with(|| {
cmp_option(
self.scopes.into_option(),
other.scopes.into_option(),
|a, b| a.cmp(partials, b),
)
})
}
pub fn display<'a>(
self,
graph: &'a StackGraph,
partials: &'a mut PartialPaths,
) -> impl Display + 'a {
display_with(self, graph, partials)
}
}
impl DisplayWithPartialPaths for PartialScopedSymbol {
fn prepare(&mut self, graph: &StackGraph, partials: &mut PartialPaths) {
if let Some(mut scopes) = self.scopes.into_option() {
scopes.prepare(graph, partials);
self.scopes = scopes.into();
}
}
fn display_with(
&self,
graph: &StackGraph,
partials: &PartialPaths,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
if let Some(scopes) = self.scopes.into_option() {
write!(
f,
"{}/({})",
self.symbol.display(graph),
display_prepared(scopes, graph, partials)
)
} else {
write!(f, "{}", self.symbol.display(graph))
}
}
}
/// A pattern that might match against a symbol stack. Consists of a (possibly empty) list of
/// partial scoped symbols, along with an optional symbol stack variable.
#[repr(C)]
#[derive(Clone, Copy, Niche)]
pub struct PartialSymbolStack {
#[niche]
symbols: Deque<PartialScopedSymbol>,
length: u32,
variable: ControlledOption<SymbolStackVariable>,
}
impl PartialSymbolStack {
/// Returns whether this partial symbol stack can match the empty symbol stack.
#[inline(always)]
pub fn can_match_empty(&self) -> bool {
self.symbols.is_empty()
}
/// Returns whether this partial symbol stack can _only_ match the empty symbol stack.
#[inline(always)]
pub fn can_only_match_empty(&self) -> bool {
self.symbols.is_empty() && self.variable.is_none()
}
/// Returns whether this partial symbol stack contains any symbols.
#[inline(always)]
pub fn contains_symbols(&self) -> bool {
!self.symbols.is_empty()
}
/// Returns whether this partial symbol stack has a symbol stack variable.
#[inline(always)]
pub fn has_variable(&self) -> bool {
self.variable.is_some()
}
#[inline(always)]
pub fn len(&self) -> usize {
self.length as usize
}
/// Returns an empty partial symbol stack.
pub fn empty() -> PartialSymbolStack {
PartialSymbolStack {
symbols: Deque::empty(),
length: 0,
variable: ControlledOption::none(),
}
}
/// Returns a partial symbol stack containing only a symbol stack variable.
pub fn from_variable(variable: SymbolStackVariable) -> PartialSymbolStack {
PartialSymbolStack {
symbols: Deque::empty(),
length: 0,
variable: ControlledOption::some(variable),
}
}
/// Returns whether this partial symbol stack is iterable in both directions without needing
/// mutable access to the arena.
pub fn have_reversal(&self, partials: &PartialPaths) -> bool {
self.symbols.have_reversal(&partials.partial_symbol_stacks)
}
/// Applies an offset to this partial symbol stack.
///
/// When concatenating partial paths, we have to ensure that the left- and right-hand sides
/// have non-overlapping sets of variables. To do this, we find the maximum value of any
/// variable on the left-hand side, and add this “offset” to the values of all of the variables
/// on the right-hand side.
pub fn with_offset(
mut self,
partials: &mut PartialPaths,
symbol_variable_offset: u32,
scope_variable_offset: u32,
) -> PartialSymbolStack {
let mut result = match self.variable.into_option() {
Some(variable) => Self::from_variable(variable.with_offset(symbol_variable_offset)),
None => Self::empty(),
};
while let Some(symbol) = self.pop_front(partials) {
result.push_back(partials, symbol.with_offset(scope_variable_offset));
}
result
}
fn prepend(&mut self, partials: &mut PartialPaths, mut head: Deque<PartialScopedSymbol>) {
while let Some(head) = head.pop_back(&mut partials.partial_symbol_stacks).copied() {
self.push_front(partials, head);
}
}
/// Pushes a new [`PartialScopedSymbol`][] onto the front of this partial symbol stack.
pub fn push_front(&mut self, partials: &mut PartialPaths, symbol: PartialScopedSymbol) {
self.length += 1;
self.symbols
.push_front(&mut partials.partial_symbol_stacks, symbol);
}
/// Pushes a new [`PartialScopedSymbol`][] onto the back of this partial symbol stack.
pub fn push_back(&mut self, partials: &mut PartialPaths, symbol: PartialScopedSymbol) {
self.length += 1;
self.symbols
.push_back(&mut partials.partial_symbol_stacks, symbol);
}
/// Removes and returns the [`PartialScopedSymbol`][] at the front of this partial symbol
/// stack. If the stack is empty, returns `None`.
pub fn pop_front(&mut self, partials: &mut PartialPaths) -> Option<PartialScopedSymbol> {
let result = self
.symbols
.pop_front(&mut partials.partial_symbol_stacks)
.copied();
if result.is_some() {
self.length -= 1;
}
result
}
/// Removes and returns the [`PartialScopedSymbol`][] at the back of this partial symbol stack.
/// If the stack is empty, returns `None`.
pub fn pop_back(&mut self, partials: &mut PartialPaths) -> Option<PartialScopedSymbol> {
let result = self
.symbols
.pop_back(&mut partials.partial_symbol_stacks)
.copied();
if result.is_some() {
self.length -= 1;
}
result
}
pub fn display<'a>(
self,
graph: &'a StackGraph,
partials: &'a mut PartialPaths,
) -> impl Display + 'a {
display_with(self, graph, partials)
}
/// Returns whether two partial symbol stacks "match". They must be the same length, and each
/// respective partial scoped symbol must match.
pub fn matches(mut self, partials: &mut PartialPaths, mut other: PartialSymbolStack) -> bool {
while let Some(self_element) = self.pop_front(partials) {
if let Some(other_element) = other.pop_front(partials) {
if !self_element.matches(partials, other_element) {
return false;
}
} else {
// Stacks aren't the same length.
return false;
}
}
if other.contains_symbols() {
// Stacks aren't the same length.
return false;
}
self.variable.into_option() == other.variable.into_option()
}
/// Applies a set of bindings to this partial symbol stack, producing a new partial symbol
/// stack.
pub fn apply_partial_bindings(
mut self,
partials: &mut PartialPaths,
symbol_bindings: &PartialSymbolStackBindings,
scope_bindings: &PartialScopeStackBindings,
) -> Result<PartialSymbolStack, PathResolutionError> {
// If this partial symbol stack ends in a variable, see if we have a binding for it. If
// so, substitute that binding in. If not, leave the variable as-is.
let mut result = match self.variable.into_option() {
Some(variable) => match symbol_bindings.get(variable) {
Some(bound) => bound,
None => PartialSymbolStack::from_variable(variable),
},
None => PartialSymbolStack::empty(),
};
// Then prepend all of the scoped symbols that appear at the beginning of this stack,
// applying the bindings to any attached scopes as well.
while let Some(partial_symbol) = self.pop_back(partials) {
let partial_symbol = partial_symbol.apply_partial_bindings(partials, scope_bindings)?;
result.push_front(partials, partial_symbol);
}
Ok(result)
}
/// Given two partial symbol stacks, returns the largest possible partial symbol stack such that
/// any symbol stack that satisfies the result also satisfies both inputs. This takes into
/// account any existing variable assignments, and updates those variable assignments with
/// whatever constraints are necessary to produce a correct result.
///
/// Note that this operation is commutative. (Concatenating partial paths, defined in
/// [`PartialPath::concatenate`][], is not.)
pub fn unify(
self,
partials: &mut PartialPaths,
mut rhs: PartialSymbolStack,
symbol_bindings: &mut PartialSymbolStackBindings,
scope_bindings: &mut PartialScopeStackBindings,
) -> Result<PartialSymbolStack, PathResolutionError> {
let mut lhs = self;
// First, look at the shortest common prefix of lhs and rhs, and verify that they match.
let mut head = Deque::empty();
while lhs.contains_symbols() && rhs.contains_symbols() {
let mut lhs_front = lhs.pop_front(partials).unwrap();
let rhs_front = rhs.pop_front(partials).unwrap();
lhs_front.unify(partials, rhs_front, scope_bindings)?;
head.push_back(&mut partials.partial_symbol_stacks, lhs_front);
}
// Now at most one stack still has symbols. Zero, one, or both of them have variables.
// Let's do a case analysis on all of those possibilities.
// CASE 1:
// Both lhs and rhs have no more symbols. The answer is always yes, and any variables that
// are present get bound. (If both sides have variables, then one variable gets bound to
// the other, since both lhs and rhs will match _any other symbol stack_ at this point. If
// only one side has a variable, then the variable gets bound to the empty stack.)
//
// lhs rhs
// ============ ============
// () () => yes either
// () () $2 => yes rhs, $2 => ()
// () $1 () => yes lhs, $1 => ()
// () $1 () $2 => yes lhs, $2 => $1
if !lhs.contains_symbols() && !rhs.contains_symbols() {
match (lhs.variable.into_option(), rhs.variable.into_option()) {
(None, None) => {
lhs.prepend(partials, head);
return Ok(lhs);
}
(None, Some(var)) => {
symbol_bindings.add(
partials,
var,
PartialSymbolStack::empty(),
scope_bindings,
)?;
rhs.prepend(partials, head);
return Ok(rhs);
}
(Some(var), None) => {
symbol_bindings.add(
partials,
var,
PartialSymbolStack::empty(),
scope_bindings,
)?;
lhs.prepend(partials, head);
return Ok(lhs);
}
(Some(lhs_var), Some(rhs_var)) => {
symbol_bindings.add(
partials,
rhs_var,
PartialSymbolStack::from_variable(lhs_var),
scope_bindings,
)?;
lhs.prepend(partials, head);
return Ok(lhs);
}
}
}
// CASE 2:
// One of the stacks contains symbols and the other doesn't, and the “empty” stack doesn't
// have a variable. Since there's no variable on the empty side to capture the remaining
// content on the non-empty side, the answer is always no.
//
// lhs rhs
// ============ ============
// () (stuff) => NO
// () (stuff) $2 => NO
// (stuff) () => NO
// (stuff) $1 () => NO
if !lhs.contains_symbols() && lhs.variable.is_none() {
return Err(PathResolutionError::SymbolStackUnsatisfied);
}
if !rhs.contains_symbols() && rhs.variable.is_none() {
return Err(PathResolutionError::SymbolStackUnsatisfied);
}
// CASE 3:
// One of the stacks contains symbols and the other doesn't, and the “empty” stack _does_
// have a variable. If both sides have the same variable, the answer is NO. Otherwise,
// the answer is YES, and the “empty” side's variable needs to capture the entirety of the
// non-empty side.
//
// lhs rhs
// ============ ============
// (...) $1 (...) $1 => no
// () $1 (stuff) => yes rhs, $1 => rhs
// () $1 (stuff) $2 => yes rhs, $1 => rhs
// (stuff) () $2 => yes lhs, $2 => lhs
// (stuff) $1 () $2 => yes lhs, $2 => lhs
match (lhs.variable.into_option(), rhs.variable.into_option()) {
(Some(v1), Some(v2)) if v1 == v2 => {
return Err(PathResolutionError::ScopeStackUnsatisfied)
}
_ => {}
}
if lhs.contains_symbols() {
let rhs_variable = rhs.variable.into_option().unwrap();
symbol_bindings.add(partials, rhs_variable, lhs, scope_bindings)?;
lhs.prepend(partials, head);
return Ok(lhs);
}
if rhs.contains_symbols() {
let lhs_variable = lhs.variable.into_option().unwrap();
symbol_bindings.add(partials, lhs_variable, rhs, scope_bindings)?;
rhs.prepend(partials, head);
return Ok(rhs);
}
unreachable!();
}
pub fn equals(mut self, partials: &mut PartialPaths, mut other: PartialSymbolStack) -> bool {
while let Some(self_symbol) = self.pop_front(partials) {
if let Some(other_symbol) = other.pop_front(partials) {
if !self_symbol.equals(partials, &other_symbol) {
return false;
}
} else {
return false;
}
}
if !other.symbols.is_empty() {
return false;
}
equals_option(
self.variable.into_option(),
other.variable.into_option(),
|a, b| a == b,
)
}
pub fn cmp(
mut self,
graph: &StackGraph,
partials: &mut PartialPaths,
mut other: PartialSymbolStack,
) -> std::cmp::Ordering {
use std::cmp::Ordering;
while let Some(self_symbol) = self.pop_front(partials) {
if let Some(other_symbol) = other.pop_front(partials) {
match self_symbol.cmp(graph, partials, &other_symbol) {
Ordering::Equal => continue,
result @ _ => return result,
}
} else {
return Ordering::Greater;
}
}
if !other.symbols.is_empty() {
return Ordering::Less;
}
cmp_option(
self.variable.into_option(),
other.variable.into_option(),
|a, b| a.cmp(&b),
)
}
/// Returns an iterator over the contents of this partial symbol stack.
pub fn iter<'a>(
&self,
partials: &'a mut PartialPaths,
) -> impl Iterator<Item = PartialScopedSymbol> + 'a {
self.symbols
.iter(&mut partials.partial_symbol_stacks)
.copied()
}
/// Returns an iterator over the contents of this partial symbol stack, with no guarantee
/// about the ordering of the elements.
pub fn iter_unordered<'a>(
&self,
partials: &'a PartialPaths,
) -> impl Iterator<Item = PartialScopedSymbol> + 'a {
self.symbols
.iter_unordered(&partials.partial_symbol_stacks)
.copied()
}
pub fn variable(&self) -> Option<SymbolStackVariable> {
self.variable.clone().into_option()
}
fn ensure_both_directions(&mut self, partials: &mut PartialPaths) {
self.symbols
.ensure_backwards(&mut partials.partial_symbol_stacks);
self.symbols
.ensure_forwards(&mut partials.partial_symbol_stacks);
}
fn ensure_forwards(&mut self, partials: &mut PartialPaths) {
self.symbols
.ensure_forwards(&mut partials.partial_symbol_stacks);
}
/// Returns the largest value of any symbol stack variable in this partial symbol stack.
pub fn largest_symbol_stack_variable(&self) -> u32 {
self.variable
.into_option()
.map(SymbolStackVariable::as_u32)
.unwrap_or(0)
}
/// Returns the largest value of any scope stack variable in this partial symbol stack.
pub fn largest_scope_stack_variable(&self, partials: &PartialPaths) -> u32 {
// We don't have to check the postconditions, because it's not valid for a postcondition to
// refer to a variable that doesn't exist in the precondition.
self.iter_unordered(partials)
.filter_map(|symbol| symbol.scopes.into_option())
.filter_map(|scopes| scopes.variable.into_option())
.map(ScopeStackVariable::as_u32)
.max()
.unwrap_or(0)
}
}
impl DisplayWithPartialPaths for PartialSymbolStack {
fn prepare(&mut self, graph: &StackGraph, partials: &mut PartialPaths) {
// Ensure that our deque is pointed forwards while we still have a mutable reference to the
// arena.
self.symbols
.ensure_forwards(&mut partials.partial_symbol_stacks);
// And then prepare each symbol in the stack.
let mut symbols = self.symbols;
while let Some(mut symbol) = symbols
.pop_front(&mut partials.partial_symbol_stacks)
.copied()
{
symbol.prepare(graph, partials);
}
}
fn display_with(
&self,
graph: &StackGraph,
partials: &PartialPaths,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
for symbol in self.symbols.iter_reused(&partials.partial_symbol_stacks) {
symbol.display_with(graph, partials, f)?;
}
if let Some(variable) = self.variable.into_option() {
if self.symbols.is_empty() {
write!(f, "{}", variable)?;
} else {
write!(f, ",{}", variable)?;
}
}
Ok(())
}
}
//-------------------------------------------------------------------------------------------------
// Partial scope stacks
/// A pattern that might match against a scope stack. Consists of a (possibly empty) list of
/// exported scopes, along with an optional scope stack variable.
#[repr(C)]
#[derive(Clone, Copy, Niche)]
pub struct PartialScopeStack {
#[niche]
scopes: Deque<Handle<Node>>,
length: u32,
variable: ControlledOption<ScopeStackVariable>,
}
impl PartialScopeStack {
/// Returns whether this partial scope stack can match the empty scope stack.
#[inline(always)]
pub fn can_match_empty(&self) -> bool {
self.scopes.is_empty()
}
/// Returns whether this partial scope stack can _only_ match the empty scope stack.
#[inline(always)]
pub fn can_only_match_empty(&self) -> bool {
self.scopes.is_empty() && self.variable.is_none()
}
/// Returns whether this partial scope stack contains any scopes.
#[inline(always)]
pub fn contains_scopes(&self) -> bool {
!self.scopes.is_empty()
}
/// Returns whether this partial scope stack has a scope stack variable.
#[inline(always)]
pub fn has_variable(&self) -> bool {
self.variable.is_some()
}
#[inline(always)]
pub fn len(&self) -> usize {
self.length as usize
}
/// Returns an empty partial scope stack.
pub fn empty() -> PartialScopeStack {
PartialScopeStack {
scopes: Deque::empty(),
length: 0,
variable: ControlledOption::none(),
}
}
/// Returns a partial scope stack containing only a scope stack variable.
pub fn from_variable(variable: ScopeStackVariable) -> PartialScopeStack {
PartialScopeStack {
scopes: Deque::empty(),
length: 0,
variable: ControlledOption::some(variable),
}
}
/// Returns whether this partial scope stack is iterable in both directions without needing
/// mutable access to the arena.
pub fn have_reversal(&self, partials: &PartialPaths) -> bool {
self.scopes.have_reversal(&partials.partial_scope_stacks)
}
/// Applies an offset to this partial scope stack.
///
/// When concatenating partial paths, we have to ensure that the left- and right-hand sides
/// have non-overlapping sets of variables. To do this, we find the maximum value of any
/// variable on the left-hand side, and add this “offset” to the values of all of the variables
/// on the right-hand side.
pub fn with_offset(mut self, scope_variable_offset: u32) -> PartialScopeStack {
match self.variable.into_option() {
Some(variable) => {
self.variable = ControlledOption::some(variable.with_offset(scope_variable_offset));
}
None => {}
};
self
}
/// Returns whether two partial scope stacks match exactly the same set of scope stacks.
pub fn matches(mut self, partials: &mut PartialPaths, mut other: PartialScopeStack) -> bool {
while let Some(self_element) = self.pop_front(partials) {
if let Some(other_element) = other.pop_front(partials) {
if self_element != other_element {
return false;
}
} else {
// Stacks aren't the same length.
return false;
}
}
if other.contains_scopes() {
// Stacks aren't the same length.
return false;
}
self.variable.into_option() == other.variable.into_option()
}
/// Applies a set of partial scope stack bindings to this partial scope stack, producing a new
/// partial scope stack.
pub fn apply_partial_bindings(
mut self,