forked from jj-vcs/jj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrevset.rs
2255 lines (2101 loc) · 80.3 KB
/
revset.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::Borrow;
use std::cmp::{Ordering, Reverse};
use std::collections::HashSet;
use std::iter::Peekable;
use std::ops::Range;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::{error, fmt};
use itertools::Itertools;
use once_cell::sync::Lazy;
use pest::iterators::{Pair, Pairs};
use pest::pratt_parser::{Assoc, Op, PrattParser};
use pest::Parser;
use pest_derive::Parser;
use thiserror::Error;
use crate::backend::{BackendError, BackendResult, CommitId};
use crate::commit::Commit;
use crate::index::{HexPrefix, IndexEntry, IndexPosition, PrefixResolution, RevWalk};
use crate::matchers::{EverythingMatcher, Matcher, PrefixMatcher};
use crate::op_store::WorkspaceId;
use crate::repo::RepoRef;
use crate::repo_path::{FsPathParseError, RepoPath};
use crate::revset_graph_iterator::RevsetGraphIterator;
use crate::rewrite;
use crate::store::Store;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RevsetError {
#[error("Revision \"{0}\" doesn't exist")]
NoSuchRevision(String),
#[error("Commit id prefix \"{0}\" is ambiguous")]
AmbiguousCommitIdPrefix(String),
#[error("Change id prefix \"{0}\" is ambiguous")]
AmbiguousChangeIdPrefix(String),
#[error("Unexpected error from store: {0}")]
StoreError(#[from] BackendError),
}
fn resolve_git_ref(repo: RepoRef, symbol: &str) -> Result<Vec<CommitId>, RevsetError> {
let view = repo.view();
for git_ref_prefix in &["", "refs/", "refs/heads/", "refs/tags/", "refs/remotes/"] {
if let Some(ref_target) = view.git_refs().get(&(git_ref_prefix.to_string() + symbol)) {
return Ok(ref_target.adds());
}
}
Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
fn resolve_branch(repo: RepoRef, symbol: &str) -> Result<Vec<CommitId>, RevsetError> {
if let Some(branch_target) = repo.view().branches().get(symbol) {
return Ok(branch_target
.local_target
.as_ref()
.map(|target| target.adds())
.unwrap_or_default());
}
if let Some((name, remote_name)) = symbol.split_once('@') {
if let Some(branch_target) = repo.view().branches().get(name) {
if let Some(target) = branch_target.remote_targets.get(remote_name) {
return Ok(target.adds());
}
}
}
Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
fn resolve_commit_id(repo: RepoRef, symbol: &str) -> Result<Vec<CommitId>, RevsetError> {
// First check if it's a full commit id.
if let Ok(binary_commit_id) = hex::decode(symbol) {
let commit_id = CommitId::new(binary_commit_id);
match repo.store().get_commit(&commit_id) {
Ok(_) => return Ok(vec![commit_id]),
Err(BackendError::NotFound) => {} // fall through
Err(err) => return Err(RevsetError::StoreError(err)),
}
}
if let Some(prefix) = HexPrefix::new(symbol.to_owned()) {
match repo.index().resolve_prefix(&prefix) {
PrefixResolution::NoMatch => {
return Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
PrefixResolution::AmbiguousMatch => {
return Err(RevsetError::AmbiguousCommitIdPrefix(symbol.to_owned()))
}
PrefixResolution::SingleMatch(commit_id) => return Ok(vec![commit_id]),
}
}
Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
fn resolve_change_id(repo: RepoRef, change_id_prefix: &str) -> Result<Vec<CommitId>, RevsetError> {
if let Some(hex_prefix) = HexPrefix::new(change_id_prefix.to_owned()) {
let mut found_change_id = None;
let mut commit_ids = vec![];
// TODO: Create a persistent lookup from change id to (visible?) commit ids.
for index_entry in RevsetExpression::all().evaluate(repo, None).unwrap().iter() {
let change_id = index_entry.change_id();
if change_id.hex().starts_with(hex_prefix.hex()) {
if let Some(previous_change_id) = found_change_id.replace(change_id.clone()) {
if previous_change_id != change_id {
return Err(RevsetError::AmbiguousChangeIdPrefix(
change_id_prefix.to_owned(),
));
}
}
commit_ids.push(index_entry.commit_id());
}
}
if found_change_id.is_none() {
return Err(RevsetError::NoSuchRevision(change_id_prefix.to_owned()));
}
Ok(commit_ids)
} else {
Err(RevsetError::NoSuchRevision(change_id_prefix.to_owned()))
}
}
pub fn resolve_symbol(
repo: RepoRef,
symbol: &str,
workspace_id: Option<&WorkspaceId>,
) -> Result<Vec<CommitId>, RevsetError> {
if symbol.ends_with('@') {
let target_workspace = if symbol == "@" {
if let Some(workspace_id) = workspace_id {
workspace_id.clone()
} else {
return Err(RevsetError::NoSuchRevision(symbol.to_owned()));
}
} else {
WorkspaceId::new(symbol.strip_suffix('@').unwrap().to_string())
};
if let Some(commit_id) = repo.view().get_wc_commit_id(&target_workspace) {
Ok(vec![commit_id.clone()])
} else {
Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
} else if symbol == "root" {
Ok(vec![repo.store().root_commit_id().clone()])
} else {
// Try to resolve as a tag
if let Some(target) = repo.view().tags().get(symbol) {
return Ok(target.adds());
}
// Try to resolve as a branch
let branch_result = resolve_branch(repo, symbol);
if !matches!(branch_result, Err(RevsetError::NoSuchRevision(_))) {
return branch_result;
}
// Try to resolve as a git ref
let git_ref_result = resolve_git_ref(repo, symbol);
if !matches!(git_ref_result, Err(RevsetError::NoSuchRevision(_))) {
return git_ref_result;
}
// Try to resolve as a commit id.
let commit_id_result = resolve_commit_id(repo, symbol);
if !matches!(commit_id_result, Err(RevsetError::NoSuchRevision(_))) {
return commit_id_result;
}
// Try to resolve as a change id.
let change_id_result = resolve_change_id(repo, symbol);
if !matches!(change_id_result, Err(RevsetError::NoSuchRevision(_))) {
return change_id_result;
}
Err(RevsetError::NoSuchRevision(symbol.to_owned()))
}
}
#[derive(Parser)]
#[grammar = "revset.pest"]
pub struct RevsetParser;
#[derive(Debug)]
pub struct RevsetParseError {
kind: RevsetParseErrorKind,
pest_error: Option<Box<pest::error::Error<Rule>>>,
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RevsetParseErrorKind {
#[error("Syntax error")]
SyntaxError,
#[error("Revset function \"{0}\" doesn't exist")]
NoSuchFunction(String),
#[error("Invalid arguments to revset function \"{name}\": {message}")]
InvalidFunctionArguments { name: String, message: String },
#[error("Invalid file pattern: {0}")]
FsPathParseError(#[source] FsPathParseError),
#[error("Cannot resolve file pattern without workspace")]
FsPathWithoutWorkspace,
}
impl RevsetParseError {
fn new(kind: RevsetParseErrorKind) -> Self {
RevsetParseError {
kind,
pest_error: None,
}
}
fn with_span(kind: RevsetParseErrorKind, span: pest::Span<'_>) -> Self {
let err = pest::error::Error::new_from_span(
pest::error::ErrorVariant::CustomError {
message: kind.to_string(),
},
span,
);
RevsetParseError {
kind,
pest_error: Some(Box::new(err)),
}
}
pub fn kind(&self) -> &RevsetParseErrorKind {
&self.kind
}
}
impl From<pest::error::Error<Rule>> for RevsetParseError {
fn from(err: pest::error::Error<Rule>) -> Self {
RevsetParseError {
kind: RevsetParseErrorKind::SyntaxError,
pest_error: Some(Box::new(err)),
}
}
}
impl fmt::Display for RevsetParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(err) = &self.pest_error {
err.fmt(f)
} else {
self.kind.fmt(f)
}
}
}
impl error::Error for RevsetParseError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.kind {
// SyntaxError is a wrapper for pest::error::Error.
RevsetParseErrorKind::SyntaxError => {
self.pest_error.as_ref().map(|e| e as &dyn error::Error)
}
// Otherwise the kind represents this error.
e => e.source(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RevsetFilterPredicate {
/// Commits with number of parents in the range.
ParentCount(Range<u32>),
/// Commits with description containing the needle.
Description(String),
/// Commits with author's name or email containing the needle.
Author(String),
/// Commits with committer's name or email containing the needle.
Committer(String),
/// Commits modifying no files. Equivalent to `Not(File(["."]))`.
Empty,
/// Commits modifying the paths specified by the pattern.
File(Vec<RepoPath>),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RevsetExpression {
None,
All,
Commits(Vec<CommitId>),
Symbol(String),
Parents(Rc<RevsetExpression>),
Children(Rc<RevsetExpression>),
Ancestors(Rc<RevsetExpression>),
// Commits that are ancestors of "heads" but not ancestors of "roots"
Range {
roots: Rc<RevsetExpression>,
heads: Rc<RevsetExpression>,
},
// Commits that are descendants of "roots" and ancestors of "heads"
DagRange {
roots: Rc<RevsetExpression>,
heads: Rc<RevsetExpression>,
},
Heads(Rc<RevsetExpression>),
Roots(Rc<RevsetExpression>),
VisibleHeads,
PublicHeads,
Branches,
RemoteBranches,
Tags,
GitRefs,
GitHead,
Filter {
candidates: Rc<RevsetExpression>,
predicate: RevsetFilterPredicate,
},
Present(Rc<RevsetExpression>),
Union(Rc<RevsetExpression>, Rc<RevsetExpression>),
Intersection(Rc<RevsetExpression>, Rc<RevsetExpression>),
Difference(Rc<RevsetExpression>, Rc<RevsetExpression>),
}
impl RevsetExpression {
pub fn none() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::None)
}
pub fn all() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::All)
}
pub fn symbol(value: String) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Symbol(value))
}
pub fn commit(commit_id: CommitId) -> Rc<RevsetExpression> {
RevsetExpression::commits(vec![commit_id])
}
pub fn commits(commit_ids: Vec<CommitId>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Commits(commit_ids))
}
pub fn visible_heads() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::VisibleHeads)
}
pub fn public_heads() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::PublicHeads)
}
pub fn branches() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Branches)
}
pub fn remote_branches() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::RemoteBranches)
}
pub fn tags() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Tags)
}
pub fn git_refs() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::GitRefs)
}
pub fn git_head() -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::GitHead)
}
pub fn filter(predicate: RevsetFilterPredicate) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Filter {
candidates: RevsetExpression::all(),
predicate,
})
}
/// Commits in `self` that don't have descendants in `self`.
pub fn heads(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Heads(self.clone()))
}
/// Commits in `self` that don't have ancestors in `self`.
pub fn roots(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Roots(self.clone()))
}
/// Parents of `self`.
pub fn parents(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Parents(self.clone()))
}
/// Ancestors of `self`, including `self`.
pub fn ancestors(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Ancestors(self.clone()))
}
/// Children of `self`.
pub fn children(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Children(self.clone()))
}
/// Descendants of `self`, including `self`.
pub fn descendants(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
self.dag_range_to(&RevsetExpression::visible_heads())
}
/// Commits that are descendants of `self` and ancestors of `heads`, both
/// inclusive.
pub fn dag_range_to(
self: &Rc<RevsetExpression>,
heads: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::DagRange {
roots: self.clone(),
heads: heads.clone(),
})
}
/// Connects any ancestors and descendants in the set by adding the commits
/// between them.
pub fn connected(self: &Rc<RevsetExpression>) -> Rc<RevsetExpression> {
self.dag_range_to(self)
}
/// Commits reachable from `heads` but not from `self`.
pub fn range(
self: &Rc<RevsetExpression>,
heads: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Range {
roots: self.clone(),
heads: heads.clone(),
})
}
/// Commits that are in `self` or in `other` (or both).
pub fn union(
self: &Rc<RevsetExpression>,
other: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Union(self.clone(), other.clone()))
}
/// Commits that are in `self` and in `other`.
pub fn intersection(
self: &Rc<RevsetExpression>,
other: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Intersection(self.clone(), other.clone()))
}
/// Commits that are in `self` but not in `other`.
pub fn minus(
self: &Rc<RevsetExpression>,
other: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
Rc::new(RevsetExpression::Difference(self.clone(), other.clone()))
}
pub fn evaluate<'repo>(
&self,
repo: RepoRef<'repo>,
workspace_ctx: Option<&RevsetWorkspaceContext>,
) -> Result<Box<dyn Revset<'repo> + 'repo>, RevsetError> {
evaluate_expression(repo, self, workspace_ctx)
}
}
fn parse_expression_rule(
pairs: Pairs<Rule>,
workspace_ctx: Option<&RevsetWorkspaceContext>,
) -> Result<Rc<RevsetExpression>, RevsetParseError> {
static PRATT: Lazy<PrattParser<Rule>> = Lazy::new(|| {
PrattParser::new()
.op(Op::infix(Rule::union_op, Assoc::Left))
.op(Op::infix(Rule::intersection_op, Assoc::Left)
| Op::infix(Rule::difference_op, Assoc::Left))
// Ranges can't be nested without parentheses. Associativity doesn't matter.
.op(Op::infix(Rule::dag_range_op, Assoc::Left) | Op::infix(Rule::range_op, Assoc::Left))
.op(Op::prefix(Rule::dag_range_pre_op) | Op::prefix(Rule::range_pre_op))
.op(Op::postfix(Rule::dag_range_post_op) | Op::postfix(Rule::range_post_op))
// Neighbors
.op(Op::postfix(Rule::parents_op) | Op::postfix(Rule::children_op))
});
PRATT
.map_primary(|primary| parse_primary_rule(primary.into_inner(), workspace_ctx))
.map_prefix(|op, rhs| match op.as_rule() {
Rule::dag_range_pre_op | Rule::range_pre_op => Ok(rhs?.ancestors()),
r => panic!("unexpected prefix operator rule {r:?}"),
})
.map_postfix(|lhs, op| match op.as_rule() {
Rule::dag_range_post_op => Ok(lhs?.descendants()),
Rule::range_post_op => Ok(lhs?.range(&RevsetExpression::visible_heads())),
Rule::parents_op => Ok(lhs?.parents()),
Rule::children_op => Ok(lhs?.children()),
r => panic!("unexpected postfix operator rule {r:?}"),
})
.map_infix(|lhs, op, rhs| match op.as_rule() {
Rule::union_op => Ok(lhs?.union(&rhs?)),
Rule::intersection_op => Ok(lhs?.intersection(&rhs?)),
Rule::difference_op => Ok(lhs?.minus(&rhs?)),
Rule::dag_range_op => Ok(lhs?.dag_range_to(&rhs?)),
Rule::range_op => Ok(lhs?.range(&rhs?)),
r => panic!("unexpected infix operator rule {r:?}"),
})
.parse(pairs)
}
fn parse_primary_rule(
mut pairs: Pairs<Rule>,
workspace_ctx: Option<&RevsetWorkspaceContext>,
) -> Result<Rc<RevsetExpression>, RevsetParseError> {
let first = pairs.next().unwrap();
match first.as_rule() {
Rule::expression => parse_expression_rule(first.into_inner(), workspace_ctx),
Rule::function_name => {
let arguments_pair = pairs.next().unwrap();
parse_function_expression(first, arguments_pair, workspace_ctx)
}
Rule::symbol => parse_symbol_rule(first.into_inner()),
_ => {
panic!("unxpected revset parse rule: {:?}", first.as_str());
}
}
}
fn parse_symbol_rule(mut pairs: Pairs<Rule>) -> Result<Rc<RevsetExpression>, RevsetParseError> {
let first = pairs.next().unwrap();
match first.as_rule() {
Rule::identifier => Ok(RevsetExpression::symbol(first.as_str().to_owned())),
Rule::literal_string => {
return Ok(RevsetExpression::symbol(
first
.as_str()
.strip_prefix('"')
.unwrap()
.strip_suffix('"')
.unwrap()
.to_owned(),
));
}
_ => {
panic!("unxpected symbol parse rule: {:?}", first.as_str());
}
}
}
fn parse_function_expression(
name_pair: Pair<Rule>,
arguments_pair: Pair<Rule>,
workspace_ctx: Option<&RevsetWorkspaceContext>,
) -> Result<Rc<RevsetExpression>, RevsetParseError> {
let name = name_pair.as_str();
match name {
"parents" => {
let arg = expect_one_argument(name, arguments_pair)?;
let expression = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(expression.parents())
}
"children" => {
let arg = expect_one_argument(name, arguments_pair)?;
let expression = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(expression.children())
}
"ancestors" => {
let arg = expect_one_argument(name, arguments_pair)?;
let expression = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(expression.ancestors())
}
"descendants" => {
let arg = expect_one_argument(name, arguments_pair)?;
let expression = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(expression.descendants())
}
"connected" => {
let arg = expect_one_argument(name, arguments_pair)?;
let candidates = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(candidates.connected())
}
"none" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::none())
}
"all" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::all())
}
"heads" => {
if let Some(arg) = expect_one_optional_argument(name, arguments_pair)? {
let candidates = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(candidates.heads())
} else {
Ok(RevsetExpression::visible_heads())
}
}
"roots" => {
let arg = expect_one_argument(name, arguments_pair)?;
let candidates = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(candidates.roots())
}
"public_heads" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::public_heads())
}
"branches" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::branches())
}
"remote_branches" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::remote_branches())
}
"tags" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::tags())
}
"git_refs" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::git_refs())
}
"git_head" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::git_head())
}
"merges" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::filter(
RevsetFilterPredicate::ParentCount(2..u32::MAX),
))
}
"description" => {
let arg = expect_one_argument(name, arguments_pair)?;
let needle = parse_function_argument_to_string(name, arg)?;
Ok(RevsetExpression::filter(
RevsetFilterPredicate::Description(needle),
))
}
"author" => {
let arg = expect_one_argument(name, arguments_pair)?;
let needle = parse_function_argument_to_string(name, arg)?;
Ok(RevsetExpression::filter(RevsetFilterPredicate::Author(
needle,
)))
}
"committer" => {
let arg = expect_one_argument(name, arguments_pair)?;
let needle = parse_function_argument_to_string(name, arg)?;
Ok(RevsetExpression::filter(RevsetFilterPredicate::Committer(
needle,
)))
}
"empty" => {
expect_no_arguments(name, arguments_pair)?;
Ok(RevsetExpression::filter(RevsetFilterPredicate::Empty))
}
"file" => {
if let Some(ctx) = workspace_ctx {
let arguments_span = arguments_pair.as_span();
let paths = arguments_pair
.into_inner()
.map(|arg| {
let span = arg.as_span();
let needle = parse_function_argument_to_string(name, arg)?;
let path = RepoPath::parse_fs_path(ctx.cwd, ctx.workspace_root, &needle)
.map_err(|e| {
RevsetParseError::with_span(
RevsetParseErrorKind::FsPathParseError(e),
span,
)
})?;
Ok(path)
})
.collect::<Result<Vec<_>, RevsetParseError>>()?;
if paths.is_empty() {
Err(RevsetParseError::with_span(
RevsetParseErrorKind::InvalidFunctionArguments {
name: name.to_owned(),
message: "Expected at least 1 argument".to_string(),
},
arguments_span,
))
} else {
Ok(RevsetExpression::filter(RevsetFilterPredicate::File(paths)))
}
} else {
Err(RevsetParseError::new(
RevsetParseErrorKind::FsPathWithoutWorkspace,
))
}
}
"present" => {
let arg = expect_one_argument(name, arguments_pair)?;
let expression = parse_expression_rule(arg.into_inner(), workspace_ctx)?;
Ok(Rc::new(RevsetExpression::Present(expression)))
}
_ => Err(RevsetParseError::with_span(
RevsetParseErrorKind::NoSuchFunction(name.to_owned()),
name_pair.as_span(),
)),
}
}
fn expect_no_arguments(name: &str, arguments_pair: Pair<Rule>) -> Result<(), RevsetParseError> {
let span = arguments_pair.as_span();
let mut argument_pairs = arguments_pair.into_inner();
if argument_pairs.next().is_none() {
Ok(())
} else {
Err(RevsetParseError::with_span(
RevsetParseErrorKind::InvalidFunctionArguments {
name: name.to_owned(),
message: "Expected 0 arguments".to_string(),
},
span,
))
}
}
fn expect_one_argument<'i>(
name: &str,
arguments_pair: Pair<'i, Rule>,
) -> Result<Pair<'i, Rule>, RevsetParseError> {
let span = arguments_pair.as_span();
let mut argument_pairs = arguments_pair.into_inner().fuse();
if let (Some(arg), None) = (argument_pairs.next(), argument_pairs.next()) {
Ok(arg)
} else {
Err(RevsetParseError::with_span(
RevsetParseErrorKind::InvalidFunctionArguments {
name: name.to_owned(),
message: "Expected 1 argument".to_string(),
},
span,
))
}
}
fn expect_one_optional_argument<'i>(
name: &str,
arguments_pair: Pair<'i, Rule>,
) -> Result<Option<Pair<'i, Rule>>, RevsetParseError> {
let span = arguments_pair.as_span();
let mut argument_pairs = arguments_pair.into_inner().fuse();
if let (opt_arg, None) = (argument_pairs.next(), argument_pairs.next()) {
Ok(opt_arg)
} else {
Err(RevsetParseError::with_span(
RevsetParseErrorKind::InvalidFunctionArguments {
name: name.to_owned(),
message: "Expected 0 or 1 arguments".to_string(),
},
span,
))
}
}
fn parse_function_argument_to_string(
name: &str,
pair: Pair<Rule>,
) -> Result<String, RevsetParseError> {
let span = pair.as_span();
let workspace_ctx = None; // string literal shouldn't depend on workspace information
let expression = parse_expression_rule(pair.into_inner(), workspace_ctx)?;
match expression.as_ref() {
RevsetExpression::Symbol(symbol) => Ok(symbol.clone()),
_ => Err(RevsetParseError::with_span(
RevsetParseErrorKind::InvalidFunctionArguments {
name: name.to_string(),
message: "Expected function argument of type string".to_owned(),
},
span,
)),
}
}
pub fn parse(
revset_str: &str,
workspace_ctx: Option<&RevsetWorkspaceContext>,
) -> Result<Rc<RevsetExpression>, RevsetParseError> {
let mut pairs = RevsetParser::parse(Rule::program, revset_str)?;
let first = pairs.next().unwrap();
parse_expression_rule(first.into_inner(), workspace_ctx)
}
/// Walks `expression` tree and applies `f` recursively from leaf nodes.
///
/// If `f` returns `None`, the original expression node is reused. If no nodes
/// rewritten, returns `None`. `std::iter::successors()` could be used if
/// the transformation needs to be applied repeatedly until converged.
fn transform_expression_bottom_up(
expression: &Rc<RevsetExpression>,
mut f: impl FnMut(&Rc<RevsetExpression>) -> Option<Rc<RevsetExpression>>,
) -> Option<Rc<RevsetExpression>> {
fn transform_child_rec(
expression: &Rc<RevsetExpression>,
f: &mut impl FnMut(&Rc<RevsetExpression>) -> Option<Rc<RevsetExpression>>,
) -> Option<Rc<RevsetExpression>> {
match expression.as_ref() {
RevsetExpression::None => None,
RevsetExpression::All => None,
RevsetExpression::Commits(_) => None,
RevsetExpression::Symbol(_) => None,
RevsetExpression::Parents(base) => {
transform_rec(base, f).map(RevsetExpression::Parents)
}
RevsetExpression::Children(roots) => {
transform_rec(roots, f).map(RevsetExpression::Children)
}
RevsetExpression::Ancestors(base) => {
transform_rec(base, f).map(RevsetExpression::Ancestors)
}
RevsetExpression::Range { roots, heads } => transform_rec_pair((roots, heads), f)
.map(|(roots, heads)| RevsetExpression::Range { roots, heads }),
RevsetExpression::DagRange { roots, heads } => transform_rec_pair((roots, heads), f)
.map(|(roots, heads)| RevsetExpression::DagRange { roots, heads }),
RevsetExpression::VisibleHeads => None,
RevsetExpression::Heads(candidates) => {
transform_rec(candidates, f).map(RevsetExpression::Heads)
}
RevsetExpression::Roots(candidates) => {
transform_rec(candidates, f).map(RevsetExpression::Roots)
}
RevsetExpression::PublicHeads => None,
RevsetExpression::Branches => None,
RevsetExpression::RemoteBranches => None,
RevsetExpression::Tags => None,
RevsetExpression::GitRefs => None,
RevsetExpression::GitHead => None,
RevsetExpression::Filter {
candidates,
predicate,
} => transform_rec(candidates, f).map(|candidates| RevsetExpression::Filter {
candidates,
predicate: predicate.clone(),
}),
RevsetExpression::Present(candidates) => {
transform_rec(candidates, f).map(RevsetExpression::Present)
}
RevsetExpression::Union(expression1, expression2) => {
transform_rec_pair((expression1, expression2), f).map(
|(expression1, expression2)| RevsetExpression::Union(expression1, expression2),
)
}
RevsetExpression::Intersection(expression1, expression2) => {
transform_rec_pair((expression1, expression2), f).map(
|(expression1, expression2)| {
RevsetExpression::Intersection(expression1, expression2)
},
)
}
RevsetExpression::Difference(expression1, expression2) => {
transform_rec_pair((expression1, expression2), f).map(
|(expression1, expression2)| {
RevsetExpression::Difference(expression1, expression2)
},
)
}
}
.map(Rc::new)
}
fn transform_rec_pair(
(expression1, expression2): (&Rc<RevsetExpression>, &Rc<RevsetExpression>),
f: &mut impl FnMut(&Rc<RevsetExpression>) -> Option<Rc<RevsetExpression>>,
) -> Option<(Rc<RevsetExpression>, Rc<RevsetExpression>)> {
match (transform_rec(expression1, f), transform_rec(expression2, f)) {
(Some(new_expression1), Some(new_expression2)) => {
Some((new_expression1, new_expression2))
}
(Some(new_expression1), None) => Some((new_expression1, expression2.clone())),
(None, Some(new_expression2)) => Some((expression1.clone(), new_expression2)),
(None, None) => None,
}
}
fn transform_rec(
expression: &Rc<RevsetExpression>,
f: &mut impl FnMut(&Rc<RevsetExpression>) -> Option<Rc<RevsetExpression>>,
) -> Option<Rc<RevsetExpression>> {
if let Some(new_expression) = transform_child_rec(expression, f) {
// must propagate new expression tree
Some(f(&new_expression).unwrap_or(new_expression))
} else {
f(expression)
}
}
transform_rec(expression, &mut f)
}
/// Transforms intersection of filter expressions. The resulting tree may
/// contain redundant intersections like `all() & e`.
fn internalize_filter_intersection(
expression: &Rc<RevsetExpression>,
) -> Option<Rc<RevsetExpression>> {
// Since both sides must have already been "internalize"d, we don't need to
// apply the whole bottom-up pass to new intersection node. Instead, just push
// new 'c & g(d)' down to 'g(c & d)' while either side is a filter node.
fn intersect_down(
expression1: &Rc<RevsetExpression>,
expression2: &Rc<RevsetExpression>,
) -> Rc<RevsetExpression> {
if let RevsetExpression::Filter {
candidates,
predicate,
} = expression2.as_ref()
{
// e1 & f2(c2) -> f2(e1 & c2)
// f1(c1) & f2(c2) -> f2(f1(c1) & c2) -> f2(f1(c1 & c2))
Rc::new(RevsetExpression::Filter {
candidates: intersect_down(expression1, candidates),
predicate: predicate.clone(),
})
} else if let RevsetExpression::Filter {
candidates,
predicate,
} = expression1.as_ref()
{
// f1(c1) & e2 -> f1(c1 & e2)
// g1(f1(c1)) & e2 -> g1(f1(c1) & e2) -> g1(f1(c1 & e2))
Rc::new(RevsetExpression::Filter {
candidates: intersect_down(candidates, expression2),
predicate: predicate.clone(),
})
} else {
expression1.intersection(expression2)
}
}
// Bottom-up pass pulls up filter node from leaf 'f(c) & e' -> 'f(c & e)',
// so that a filter node can be found as a direct child of an intersection node.
// However, the rewritten intersection node 'c & e' can also be a rewrite target
// if 'e' is a filter node. That's why intersect_down() is also recursive.
transform_expression_bottom_up(expression, |expression| {
if let RevsetExpression::Intersection(expression1, expression2) = expression.as_ref() {
match (expression1.as_ref(), expression2.as_ref()) {
(_, RevsetExpression::Filter { .. }) | (RevsetExpression::Filter { .. }, _) => {
Some(intersect_down(expression1, expression2))
}
_ => None, // don't recreate identical node
}
} else {
None
}
})
}
/// Eliminates redundant intersection with `all()`.
fn fold_intersection_with_all(expression: &Rc<RevsetExpression>) -> Option<Rc<RevsetExpression>> {
transform_expression_bottom_up(expression, |expression| {
if let RevsetExpression::Intersection(expression1, expression2) = expression.as_ref() {
match (expression1.as_ref(), expression2.as_ref()) {
(_, RevsetExpression::All) => Some(expression1.clone()),
(RevsetExpression::All, _) => Some(expression2.clone()),
_ => None,
}
} else {
None
}
})
}
/// Rewrites the given `expression` tree to reduce evaluation cost. Returns new
/// tree.
pub fn optimize(expression: Rc<RevsetExpression>) -> Rc<RevsetExpression> {
let expression = internalize_filter_intersection(&expression).unwrap_or(expression);
fold_intersection_with_all(&expression).unwrap_or(expression)
}
pub trait Revset<'repo> {
// All revsets currently iterate in order of descending index position
fn iter<'revset>(&'revset self) -> RevsetIterator<'revset, 'repo>;
fn is_empty(&self) -> bool {
self.iter().next().is_none()
}
}
pub struct RevsetIterator<'revset, 'repo: 'revset> {
inner: Box<dyn Iterator<Item = IndexEntry<'repo>> + 'revset>,
}
impl<'revset, 'repo> RevsetIterator<'revset, 'repo> {
fn new(inner: Box<dyn Iterator<Item = IndexEntry<'repo>> + 'revset>) -> Self {
Self { inner }
}
pub fn commit_ids(self) -> RevsetCommitIdIterator<'revset, 'repo> {
RevsetCommitIdIterator(self.inner)
}
pub fn commits(self, store: &Arc<Store>) -> RevsetCommitIterator<'revset, 'repo> {