-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathtranslate.rs
2532 lines (2341 loc) · 87.7 KB
/
translate.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 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Defines a translator that converts an `Ast` to an `Hir`.
*/
use std::cell::{Cell, RefCell};
use std::result;
use ast::{self, Ast, Span, Visitor};
use hir::{self, Error, ErrorKind, Hir};
use unicode::{self, ClassQuery};
type Result<T> = result::Result<T, Error>;
/// A builder for constructing an AST->HIR translator.
#[derive(Clone, Debug)]
pub struct TranslatorBuilder {
allow_invalid_utf8: bool,
flags: Flags,
}
impl Default for TranslatorBuilder {
fn default() -> TranslatorBuilder {
TranslatorBuilder::new()
}
}
impl TranslatorBuilder {
/// Create a new translator builder with a default c onfiguration.
pub fn new() -> TranslatorBuilder {
TranslatorBuilder {
allow_invalid_utf8: false,
flags: Flags::default(),
}
}
/// Build a translator using the current configuration.
pub fn build(&self) -> Translator {
Translator {
stack: RefCell::new(vec![]),
flags: Cell::new(self.flags),
allow_invalid_utf8: self.allow_invalid_utf8,
}
}
/// When enabled, translation will permit the construction of a regular
/// expression that may match invalid UTF-8.
///
/// When disabled (the default), the translator is guaranteed to produce
/// an expression that will only ever match valid UTF-8 (otherwise, the
/// translator will return an error).
///
/// Perhaps surprisingly, when invalid UTF-8 isn't allowed, a negated ASCII
/// word boundary (uttered as `(?-u:\B)` in the concrete syntax) will cause
/// the parser to return an error. Namely, a negated ASCII word boundary
/// can result in matching positions that aren't valid UTF-8 boundaries.
pub fn allow_invalid_utf8(
&mut self,
yes: bool,
) -> &mut TranslatorBuilder {
self.allow_invalid_utf8 = yes;
self
}
/// Enable or disable the case insensitive flag (`i`) by default.
pub fn case_insensitive(&mut self, yes: bool) -> &mut TranslatorBuilder {
self.flags.case_insensitive = if yes { Some(true) } else { None };
self
}
/// Enable or disable the multi-line matching flag (`m`) by default.
pub fn multi_line(&mut self, yes: bool) -> &mut TranslatorBuilder {
self.flags.multi_line = if yes { Some(true) } else { None };
self
}
/// Enable or disable the "dot matches any character" flag (`s`) by
/// default.
pub fn dot_matches_new_line(
&mut self,
yes: bool,
) -> &mut TranslatorBuilder {
self.flags.dot_matches_new_line = if yes { Some(true) } else { None };
self
}
/// Enable or disable the "swap greed" flag (`U`) by default.
pub fn swap_greed(&mut self, yes: bool) -> &mut TranslatorBuilder {
self.flags.swap_greed = if yes { Some(true) } else { None };
self
}
/// Enable or disable the Unicode flag (`u`) by default.
pub fn unicode(&mut self, yes: bool) -> &mut TranslatorBuilder {
self.flags.unicode = if yes { None } else { Some(false) };
self
}
}
/// A translator maps abstract syntax to a high level intermediate
/// representation.
///
/// A translator may be benefit from reuse. That is, a translator can translate
/// many abstract syntax trees.
///
/// A `Translator` can be configured in more detail via a
/// [`TranslatorBuilder`](struct.TranslatorBuilder.html).
#[derive(Clone, Debug)]
pub struct Translator {
/// Our call stack, but on the heap.
stack: RefCell<Vec<HirFrame>>,
/// The current flag settings.
flags: Cell<Flags>,
/// Whether we're allowed to produce HIR that can match arbitrary bytes.
allow_invalid_utf8: bool,
}
impl Translator {
/// Create a new translator using the default configuration.
pub fn new() -> Translator {
TranslatorBuilder::new().build()
}
/// Translate the given abstract syntax tree (AST) into a high level
/// intermediate representation (HIR).
///
/// If there was a problem doing the translation, then an HIR-specific
/// error is returned.
///
/// The original pattern string used to produce the `Ast` *must* also be
/// provided. The translator does not use the pattern string during any
/// correct translation, but is used for error reporting.
pub fn translate(&mut self, pattern: &str, ast: &Ast) -> Result<Hir> {
ast::visit(ast, TranslatorI::new(self, pattern))
}
}
/// An HirFrame is a single stack frame, represented explicitly, which is
/// created for each item in the Ast that we traverse.
///
/// Note that technically, this type doesn't represent our entire stack
/// frame. In particular, the Ast visitor represents any state associated with
/// traversing the Ast itself.
#[derive(Clone, Debug)]
enum HirFrame {
/// An arbitrary HIR expression. These get pushed whenever we hit a base
/// case in the Ast. They get popped after an inductive (i.e., recursive)
/// step is complete.
Expr(Hir),
/// A Unicode character class. This frame is mutated as we descend into
/// the Ast of a character class (which is itself its own mini recursive
/// structure).
ClassUnicode(hir::ClassUnicode),
/// A byte-oriented character class. This frame is mutated as we descend
/// into the Ast of a character class (which is itself its own mini
/// recursive structure).
///
/// Byte character classes are created when Unicode mode (`u`) is disabled.
/// If `allow_invalid_utf8` is disabled (the default), then a byte
/// character is only permitted to match ASCII text.
ClassBytes(hir::ClassBytes),
/// This is pushed on to the stack upon first seeing any kind of group,
/// indicated by parentheses (including non-capturing groups). It is popped
/// upon leaving a group.
Group {
/// The old active flags, if any, when this group was opened.
///
/// If this group sets flags, then the new active flags are set to the
/// result of merging the old flags with the flags introduced by this
/// group.
///
/// When this group is popped, the active flags should be restored to
/// the flags set here.
///
/// The "active" flags correspond to whatever flags are set in the
/// Translator.
old_flags: Option<Flags>,
},
/// This is pushed whenever a concatenation is observed. After visiting
/// every sub-expression in the concatenation, the translator's stack is
/// popped until it sees a Concat frame.
Concat,
/// This is pushed whenever an alternation is observed. After visiting
/// every sub-expression in the alternation, the translator's stack is
/// popped until it sees an Alternation frame.
Alternation,
}
impl HirFrame {
/// Assert that the current stack frame is an Hir expression and return it.
fn unwrap_expr(self) -> Hir {
match self {
HirFrame::Expr(expr) => expr,
_ => panic!("tried to unwrap expr from HirFrame, got: {:?}", self)
}
}
/// Assert that the current stack frame is a Unicode class expression and
/// return it.
fn unwrap_class_unicode(self) -> hir::ClassUnicode {
match self {
HirFrame::ClassUnicode(cls) => cls,
_ => panic!("tried to unwrap Unicode class \
from HirFrame, got: {:?}", self)
}
}
/// Assert that the current stack frame is a byte class expression and
/// return it.
fn unwrap_class_bytes(self) -> hir::ClassBytes {
match self {
HirFrame::ClassBytes(cls) => cls,
_ => panic!("tried to unwrap byte class \
from HirFrame, got: {:?}", self)
}
}
/// Assert that the current stack frame is a group indicator and return
/// its corresponding flags (the flags that were active at the time the
/// group was entered) if they exist.
fn unwrap_group(self) -> Option<Flags> {
match self {
HirFrame::Group { old_flags } => old_flags,
_ => panic!("tried to unwrap group from HirFrame, got: {:?}", self)
}
}
}
impl<'t, 'p> Visitor for TranslatorI<'t, 'p> {
type Output = Hir;
type Err = Error;
fn finish(self) -> Result<Hir> {
if self.trans().stack.borrow().is_empty() {
// This can happen if the Ast given consists of a single set of
// flags. e.g., `(?i)`. /shrug
return Ok(Hir::empty());
}
// ... otherwise, we should have exactly one HIR on the stack.
assert_eq!(self.trans().stack.borrow().len(), 1);
Ok(self.pop().unwrap().unwrap_expr())
}
fn visit_pre(&mut self, ast: &Ast) -> Result<()> {
match *ast {
Ast::Class(ast::Class::Bracketed(_)) => {
if self.flags().unicode() {
let cls = hir::ClassUnicode::empty();
self.push(HirFrame::ClassUnicode(cls));
} else {
let cls = hir::ClassBytes::empty();
self.push(HirFrame::ClassBytes(cls));
}
}
Ast::Group(ref x) => {
let old_flags = x.flags().map(|ast| self.set_flags(ast));
self.push(HirFrame::Group {
old_flags: old_flags,
});
}
Ast::Concat(ref x) if x.asts.is_empty() => {}
Ast::Concat(_) => {
self.push(HirFrame::Concat);
}
Ast::Alternation(ref x) if x.asts.is_empty() => {}
Ast::Alternation(_) => {
self.push(HirFrame::Alternation);
}
_ => {}
}
Ok(())
}
fn visit_post(&mut self, ast: &Ast) -> Result<()> {
match *ast {
Ast::Empty(_) => {
self.push(HirFrame::Expr(Hir::empty()));
}
Ast::Flags(ref x) => {
self.set_flags(&x.flags);
}
Ast::Literal(ref x) => {
self.push(HirFrame::Expr(self.hir_literal(x)?));
}
Ast::Dot(span) => {
self.push(HirFrame::Expr(self.hir_dot(span)?));
}
Ast::Assertion(ref x) => {
self.push(HirFrame::Expr(self.hir_assertion(x)?));
}
Ast::Class(ast::Class::Perl(ref x)) => {
if self.flags().unicode() {
let cls = self.hir_perl_unicode_class(x);
let hcls = hir::Class::Unicode(cls);
self.push(HirFrame::Expr(Hir::class(hcls)));
} else {
let cls = self.hir_perl_byte_class(x);
let hcls = hir::Class::Bytes(cls);
self.push(HirFrame::Expr(Hir::class(hcls)));
}
}
Ast::Class(ast::Class::Unicode(ref x)) => {
let cls = hir::Class::Unicode(self.hir_unicode_class(x)?);
self.push(HirFrame::Expr(Hir::class(cls)));
}
Ast::Class(ast::Class::Bracketed(ref ast)) => {
if self.flags().unicode() {
let mut cls = self.pop().unwrap().unwrap_class_unicode();
self.unicode_fold_and_negate(ast.negated, &mut cls);
if cls.iter().next().is_none() {
return Err(self.error(
ast.span, ErrorKind::EmptyClassNotAllowed));
}
let expr = Hir::class(hir::Class::Unicode(cls));
self.push(HirFrame::Expr(expr));
} else {
let mut cls = self.pop().unwrap().unwrap_class_bytes();
self.bytes_fold_and_negate(
&ast.span, ast.negated, &mut cls)?;
if cls.iter().next().is_none() {
return Err(self.error(
ast.span, ErrorKind::EmptyClassNotAllowed));
}
let expr = Hir::class(hir::Class::Bytes(cls));
self.push(HirFrame::Expr(expr));
}
}
Ast::Repetition(ref x) => {
let expr = self.pop().unwrap().unwrap_expr();
self.push(HirFrame::Expr(self.hir_repetition(x, expr)));
}
Ast::Group(ref x) => {
let expr = self.pop().unwrap().unwrap_expr();
if let Some(flags) = self.pop().unwrap().unwrap_group() {
self.trans().flags.set(flags);
}
self.push(HirFrame::Expr(self.hir_group(x, expr)));
}
Ast::Concat(_) => {
let mut exprs = vec![];
while let Some(HirFrame::Expr(expr)) = self.pop() {
if !expr.kind().is_empty() {
exprs.push(expr);
}
}
exprs.reverse();
self.push(HirFrame::Expr(Hir::concat(exprs)));
}
Ast::Alternation(_) => {
let mut exprs = vec![];
while let Some(HirFrame::Expr(expr)) = self.pop() {
exprs.push(expr);
}
exprs.reverse();
self.push(HirFrame::Expr(Hir::alternation(exprs)));
}
}
Ok(())
}
fn visit_class_set_item_pre(
&mut self,
ast: &ast::ClassSetItem,
) -> Result<()> {
match *ast {
ast::ClassSetItem::Bracketed(_) => {
if self.flags().unicode() {
let cls = hir::ClassUnicode::empty();
self.push(HirFrame::ClassUnicode(cls));
} else {
let cls = hir::ClassBytes::empty();
self.push(HirFrame::ClassBytes(cls));
}
}
// We needn't handle the Union case here since the visitor will
// do it for us.
_ => {}
}
Ok(())
}
fn visit_class_set_item_post(
&mut self,
ast: &ast::ClassSetItem,
) -> Result<()> {
match *ast {
ast::ClassSetItem::Empty(_) => {}
ast::ClassSetItem::Literal(ref x) => {
if self.flags().unicode() {
let mut cls = self.pop().unwrap().unwrap_class_unicode();
cls.push(hir::ClassUnicodeRange::new(x.c, x.c));
self.push(HirFrame::ClassUnicode(cls));
} else {
let mut cls = self.pop().unwrap().unwrap_class_bytes();
let byte = self.class_literal_byte(x)?;
cls.push(hir::ClassBytesRange::new(byte, byte));
self.push(HirFrame::ClassBytes(cls));
}
}
ast::ClassSetItem::Range(ref x) => {
if self.flags().unicode() {
let mut cls = self.pop().unwrap().unwrap_class_unicode();
cls.push(hir::ClassUnicodeRange::new(x.start.c, x.end.c));
self.push(HirFrame::ClassUnicode(cls));
} else {
let mut cls = self.pop().unwrap().unwrap_class_bytes();
let start = self.class_literal_byte(&x.start)?;
let end = self.class_literal_byte(&x.end)?;
cls.push(hir::ClassBytesRange::new(start, end));
self.push(HirFrame::ClassBytes(cls));
}
}
ast::ClassSetItem::Ascii(ref x) => {
if self.flags().unicode() {
let mut cls = self.pop().unwrap().unwrap_class_unicode();
for &(s, e) in ascii_class(&x.kind) {
cls.push(hir::ClassUnicodeRange::new(s, e));
}
self.unicode_fold_and_negate(x.negated, &mut cls);
self.push(HirFrame::ClassUnicode(cls));
} else {
let mut cls = self.pop().unwrap().unwrap_class_bytes();
for &(s, e) in ascii_class(&x.kind) {
cls.push(hir::ClassBytesRange::new(s as u8, e as u8));
}
self.bytes_fold_and_negate(
&x.span, x.negated, &mut cls)?;
self.push(HirFrame::ClassBytes(cls));
}
}
ast::ClassSetItem::Unicode(ref x) => {
let xcls = self.hir_unicode_class(x)?;
let mut cls = self.pop().unwrap().unwrap_class_unicode();
cls.union(&xcls);
self.push(HirFrame::ClassUnicode(cls));
}
ast::ClassSetItem::Perl(ref x) => {
if self.flags().unicode() {
let xcls = self.hir_perl_unicode_class(x);
let mut cls = self.pop().unwrap().unwrap_class_unicode();
cls.union(&xcls);
self.push(HirFrame::ClassUnicode(cls));
} else {
let xcls = self.hir_perl_byte_class(x);
let mut cls = self.pop().unwrap().unwrap_class_bytes();
cls.union(&xcls);
self.push(HirFrame::ClassBytes(cls));
}
}
ast::ClassSetItem::Bracketed(ref ast) => {
if self.flags().unicode() {
let mut cls1 = self.pop().unwrap().unwrap_class_unicode();
self.unicode_fold_and_negate(ast.negated, &mut cls1);
let mut cls2 = self.pop().unwrap().unwrap_class_unicode();
cls2.union(&cls1);
self.push(HirFrame::ClassUnicode(cls2));
} else {
let mut cls1 = self.pop().unwrap().unwrap_class_bytes();
self.bytes_fold_and_negate(
&ast.span, ast.negated, &mut cls1)?;
let mut cls2 = self.pop().unwrap().unwrap_class_bytes();
cls2.union(&cls1);
self.push(HirFrame::ClassBytes(cls2));
}
}
// This is handled automatically by the visitor.
ast::ClassSetItem::Union(_) => {}
}
Ok(())
}
fn visit_class_set_binary_op_pre(
&mut self,
_op: &ast::ClassSetBinaryOp,
) -> Result<()> {
if self.flags().unicode() {
let cls = hir::ClassUnicode::empty();
self.push(HirFrame::ClassUnicode(cls));
} else {
let cls = hir::ClassBytes::empty();
self.push(HirFrame::ClassBytes(cls));
}
Ok(())
}
fn visit_class_set_binary_op_in(
&mut self,
_op: &ast::ClassSetBinaryOp,
) -> Result<()> {
if self.flags().unicode() {
let cls = hir::ClassUnicode::empty();
self.push(HirFrame::ClassUnicode(cls));
} else {
let cls = hir::ClassBytes::empty();
self.push(HirFrame::ClassBytes(cls));
}
Ok(())
}
fn visit_class_set_binary_op_post(
&mut self,
op: &ast::ClassSetBinaryOp,
) -> Result<()> {
use ast::ClassSetBinaryOpKind::*;
if self.flags().unicode() {
let mut rhs = self.pop().unwrap().unwrap_class_unicode();
let mut lhs = self.pop().unwrap().unwrap_class_unicode();
let mut cls = self.pop().unwrap().unwrap_class_unicode();
if self.flags().case_insensitive() {
rhs.case_fold_simple();
lhs.case_fold_simple();
}
match op.kind {
Intersection => lhs.intersect(&rhs),
Difference => lhs.difference(&rhs),
SymmetricDifference => lhs.symmetric_difference(&rhs),
}
cls.union(&lhs);
self.push(HirFrame::ClassUnicode(cls));
} else {
let mut rhs = self.pop().unwrap().unwrap_class_bytes();
let mut lhs = self.pop().unwrap().unwrap_class_bytes();
let mut cls = self.pop().unwrap().unwrap_class_bytes();
if self.flags().case_insensitive() {
rhs.case_fold_simple();
lhs.case_fold_simple();
}
match op.kind {
Intersection => lhs.intersect(&rhs),
Difference => lhs.difference(&rhs),
SymmetricDifference => lhs.symmetric_difference(&rhs),
}
cls.union(&lhs);
self.push(HirFrame::ClassBytes(cls));
}
Ok(())
}
}
/// The internal implementation of a translator.
///
/// This type is responsible for carrying around the original pattern string,
/// which is not tied to the internal state of a translator.
///
/// A TranslatorI exists for the time it takes to translate a single Ast.
#[derive(Clone, Debug)]
struct TranslatorI<'t, 'p> {
trans: &'t Translator,
pattern: &'p str,
}
impl<'t, 'p> TranslatorI<'t, 'p> {
/// Build a new internal translator.
fn new(trans: &'t Translator, pattern: &'p str) -> TranslatorI<'t, 'p> {
TranslatorI { trans: trans, pattern: pattern }
}
/// Return a reference to the underlying translator.
fn trans(&self) -> &Translator {
&self.trans
}
/// Push the given frame on to the call stack.
fn push(&self, frame: HirFrame) {
self.trans().stack.borrow_mut().push(frame);
}
/// Pop the top of the call stack. If the call stack is empty, return None.
fn pop(&self) -> Option<HirFrame> {
self.trans().stack.borrow_mut().pop()
}
/// Create a new error with the given span and error type.
fn error(&self, span: Span, kind: ErrorKind) -> Error {
Error { kind: kind, pattern: self.pattern.to_string(), span: span }
}
/// Return a copy of the active flags.
fn flags(&self) -> Flags {
self.trans().flags.get()
}
/// Set the flags of this translator from the flags set in the given AST.
/// Then, return the old flags.
fn set_flags(&self, ast_flags: &ast::Flags) -> Flags {
let old_flags = self.flags();
let mut new_flags = Flags::from_ast(ast_flags);
new_flags.merge(&old_flags);
self.trans().flags.set(new_flags);
old_flags
}
fn hir_literal(&self, lit: &ast::Literal) -> Result<Hir> {
let ch = match self.literal_to_char(lit)? {
byte @ hir::Literal::Byte(_) => return Ok(Hir::literal(byte)),
hir::Literal::Unicode(ch) => ch,
};
if self.flags().case_insensitive() {
self.hir_from_char_case_insensitive(lit.span, ch)
} else {
self.hir_from_char(lit.span, ch)
}
}
/// Convert an Ast literal to its scalar representation.
///
/// When Unicode mode is enabled, then this always succeeds and returns a
/// `char` (Unicode scalar value).
///
/// When Unicode mode is disabled, then a raw byte is returned. If that
/// byte is not ASCII and invalid UTF-8 is not allowed, then this returns
/// an error.
fn literal_to_char(&self, lit: &ast::Literal) -> Result<hir::Literal> {
if self.flags().unicode() {
return Ok(hir::Literal::Unicode(lit.c));
}
let byte = match lit.byte() {
None => return Ok(hir::Literal::Unicode(lit.c)),
Some(byte) => byte,
};
if byte <= 0x7F {
return Ok(hir::Literal::Unicode(byte as char));
}
if !self.trans().allow_invalid_utf8 {
return Err(self.error(lit.span, ErrorKind::InvalidUtf8));
}
Ok(hir::Literal::Byte(byte))
}
fn hir_from_char(&self, span: Span, c: char) -> Result<Hir> {
if !self.flags().unicode() && c.len_utf8() > 1 {
return Err(self.error(span, ErrorKind::UnicodeNotAllowed));
}
Ok(Hir::literal(hir::Literal::Unicode(c)))
}
fn hir_from_char_case_insensitive(
&self,
span: Span,
c: char,
) -> Result<Hir> {
// If case folding won't do anything, then don't bother trying.
if !unicode::contains_simple_case_mapping(c, c) {
return self.hir_from_char(span, c);
}
if self.flags().unicode() {
let mut cls = hir::ClassUnicode::new(vec![
hir::ClassUnicodeRange::new(c, c),
]);
cls.case_fold_simple();
Ok(Hir::class(hir::Class::Unicode(cls)))
} else {
if c.len_utf8() > 1 {
return Err(self.error(span, ErrorKind::UnicodeNotAllowed));
}
let mut cls = hir::ClassBytes::new(vec![
hir::ClassBytesRange::new(c as u8, c as u8),
]);
cls.case_fold_simple();
Ok(Hir::class(hir::Class::Bytes(cls)))
}
}
fn hir_dot(&self, span: Span) -> Result<Hir> {
let unicode = self.flags().unicode();
if !unicode && !self.trans().allow_invalid_utf8 {
return Err(self.error(span, ErrorKind::InvalidUtf8));
}
Ok(if self.flags().dot_matches_new_line() {
Hir::any(!unicode)
} else {
Hir::dot(!unicode)
})
}
fn hir_assertion(&self, asst: &ast::Assertion) -> Result<Hir> {
let unicode = self.flags().unicode();
let multi_line = self.flags().multi_line();
Ok(match asst.kind {
ast::AssertionKind::StartLine => {
Hir::anchor(if multi_line {
hir::Anchor::StartLine
} else {
hir::Anchor::StartText
})
}
ast::AssertionKind::EndLine => {
Hir::anchor(if multi_line {
hir::Anchor::EndLine
} else {
hir::Anchor::EndText
})
}
ast::AssertionKind::StartText => {
Hir::anchor(hir::Anchor::StartText)
}
ast::AssertionKind::EndText => {
Hir::anchor(hir::Anchor::EndText)
}
ast::AssertionKind::WordBoundary => {
Hir::word_boundary(if unicode {
hir::WordBoundary::Unicode
} else {
hir::WordBoundary::Ascii
})
}
ast::AssertionKind::NotWordBoundary => {
Hir::word_boundary(if unicode {
hir::WordBoundary::UnicodeNegate
} else {
// It is possible for negated ASCII word boundaries to
// match at invalid UTF-8 boundaries, even when searching
// valid UTF-8.
if !self.trans().allow_invalid_utf8 {
return Err(self.error(
asst.span, ErrorKind::InvalidUtf8));
}
hir::WordBoundary::AsciiNegate
})
}
})
}
fn hir_group(&self, group: &ast::Group, expr: Hir) -> Hir {
let kind = match group.kind {
ast::GroupKind::CaptureIndex(idx) => {
hir::GroupKind::CaptureIndex(idx)
}
ast::GroupKind::CaptureName(ref capname) => {
hir::GroupKind::CaptureName {
name: capname.name.clone(),
index: capname.index,
}
}
ast::GroupKind::NonCapturing(_) => hir::GroupKind::NonCapturing,
};
Hir::group(hir::Group {
kind: kind,
hir: Box::new(expr),
})
}
fn hir_repetition(&self, rep: &ast::Repetition, expr: Hir) -> Hir {
let kind = match rep.op.kind {
ast::RepetitionKind::ZeroOrOne => hir::RepetitionKind::ZeroOrOne,
ast::RepetitionKind::ZeroOrMore => hir::RepetitionKind::ZeroOrMore,
ast::RepetitionKind::OneOrMore => hir::RepetitionKind::OneOrMore,
ast::RepetitionKind::Range(ast::RepetitionRange::Exactly(m)) => {
hir::RepetitionKind::Range(hir::RepetitionRange::Exactly(m))
}
ast::RepetitionKind::Range(ast::RepetitionRange::AtLeast(m)) => {
hir::RepetitionKind::Range(hir::RepetitionRange::AtLeast(m))
}
ast::RepetitionKind::Range(ast::RepetitionRange::Bounded(m,n)) => {
hir::RepetitionKind::Range(hir::RepetitionRange::Bounded(m, n))
}
};
let greedy =
if self.flags().swap_greed() {
!rep.greedy
} else {
rep.greedy
};
Hir::repetition(hir::Repetition {
kind: kind,
greedy: greedy,
hir: Box::new(expr),
})
}
fn hir_unicode_class(
&self,
ast_class: &ast::ClassUnicode,
) -> Result<hir::ClassUnicode> {
use ast::ClassUnicodeKind::*;
if !self.flags().unicode() {
return Err(self.error(
ast_class.span,
ErrorKind::UnicodeNotAllowed,
));
}
let query = match ast_class.kind {
OneLetter(name) => ClassQuery::OneLetter(name),
Named(ref name) => ClassQuery::Binary(name),
NamedValue { ref name, ref value, .. } => {
ClassQuery::ByValue {
property_name: name,
property_value: value,
}
}
};
match unicode::class(query) {
Ok(mut class) => {
self.unicode_fold_and_negate(ast_class.negated, &mut class);
Ok(class)
}
Err(unicode::Error::PropertyNotFound) => {
Err(self.error(
ast_class.span,
ErrorKind::UnicodePropertyNotFound,
))
}
Err(unicode::Error::PropertyValueNotFound) => {
Err(self.error(
ast_class.span,
ErrorKind::UnicodePropertyValueNotFound,
))
}
}
}
fn hir_perl_unicode_class(
&self,
ast_class: &ast::ClassPerl,
) -> hir::ClassUnicode {
use ast::ClassPerlKind::*;
use unicode_tables::perl_word::PERL_WORD;
assert!(self.flags().unicode());
let mut class = match ast_class.kind {
Digit => {
let query = ClassQuery::Binary("Decimal_Number");
unicode::class(query).unwrap()
}
Space => {
let query = ClassQuery::Binary("Whitespace");
unicode::class(query).unwrap()
}
Word => unicode::hir_class(PERL_WORD),
};
// We needn't apply case folding here because the Perl Unicode classes
// are already closed under Unicode simple case folding.
if ast_class.negated {
class.negate();
}
class
}
fn hir_perl_byte_class(
&self,
ast_class: &ast::ClassPerl,
) -> hir::ClassBytes {
use ast::ClassPerlKind::*;
assert!(!self.flags().unicode());
let mut class = match ast_class.kind {
Digit => hir_ascii_class_bytes(&ast::ClassAsciiKind::Digit),
Space => hir_ascii_class_bytes(&ast::ClassAsciiKind::Space),
Word => hir_ascii_class_bytes(&ast::ClassAsciiKind::Word),
};
// We needn't apply case folding here because the Perl ASCII classes
// are already closed (under ASCII case folding).
if ast_class.negated {
class.negate();
}
class
}
fn unicode_fold_and_negate(
&self,
negated: bool,
class: &mut hir::ClassUnicode,
) {
// Note that we must apply case folding before negation!
// Consider `(?i)[^x]`. If we applied negation field, then
// the result would be the character class that matched any
// Unicode scalar value.
if self.flags().case_insensitive() {
class.case_fold_simple();
}
if negated {
class.negate();
}
}
fn bytes_fold_and_negate(
&self,
span: &Span,
negated: bool,
class: &mut hir::ClassBytes,
) -> Result<()> {
// Note that we must apply case folding before negation!
// Consider `(?i)[^x]`. If we applied negation field, then
// the result would be the character class that matched any
// Unicode scalar value.
if self.flags().case_insensitive() {
class.case_fold_simple();
}
if negated {
class.negate();
}
if !self.trans().allow_invalid_utf8 && !class.is_all_ascii() {
return Err(self.error(span.clone(), ErrorKind::InvalidUtf8));
}
Ok(())
}
/// Return a scalar byte value suitable for use as a literal in a byte
/// character class.
fn class_literal_byte(&self, ast: &ast::Literal) -> Result<u8> {
match self.literal_to_char(ast)? {
hir::Literal::Byte(byte) => Ok(byte),
hir::Literal::Unicode(ch) => {
if ch <= 0x7F as char {
Ok(ch as u8)
} else {
// We can't feasibly support Unicode in
// byte oriented classes. Byte classes don't
// do Unicode case folding.
Err(self.error(ast.span, ErrorKind::UnicodeNotAllowed))
}
}
}
}
}
/// A translator's representation of a regular expression's flags at any given
/// moment in time.
///
/// Each flag can be in one of three states: absent, present but disabled or
/// present but enabled.
#[derive(Clone, Copy, Debug, Default)]
struct Flags {
case_insensitive: Option<bool>,
multi_line: Option<bool>,
dot_matches_new_line: Option<bool>,
swap_greed: Option<bool>,
unicode: Option<bool>,
// Note that `ignore_whitespace` is omitted here because it is handled
// entirely in the parser.
}
impl Flags {
fn from_ast(ast: &ast::Flags) -> Flags {
let mut flags = Flags::default();
let mut enable = true;
for item in &ast.items {
match item.kind {
ast::FlagsItemKind::Negation => {
enable = false;
}
ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive) => {
flags.case_insensitive = Some(enable);
}
ast::FlagsItemKind::Flag(ast::Flag::MultiLine) => {
flags.multi_line = Some(enable);
}
ast::FlagsItemKind::Flag(ast::Flag::DotMatchesNewLine) => {
flags.dot_matches_new_line = Some(enable);
}
ast::FlagsItemKind::Flag(ast::Flag::SwapGreed) => {
flags.swap_greed = Some(enable);
}
ast::FlagsItemKind::Flag(ast::Flag::Unicode) => {
flags.unicode = Some(enable);
}
ast::FlagsItemKind::Flag(ast::Flag::IgnoreWhitespace) => {}
}
}
flags
}
fn merge(&mut self, previous: &Flags) {
if self.case_insensitive.is_none() {
self.case_insensitive = previous.case_insensitive;
}
if self.multi_line.is_none() {
self.multi_line = previous.multi_line;
}
if self.dot_matches_new_line.is_none() {
self.dot_matches_new_line = previous.dot_matches_new_line;
}
if self.swap_greed.is_none() {
self.swap_greed = previous.swap_greed;
}
if self.unicode.is_none() {
self.unicode = previous.unicode;
}
}
fn case_insensitive(&self) -> bool {
self.case_insensitive.unwrap_or(false)
}
fn multi_line(&self) -> bool {
self.multi_line.unwrap_or(false)