-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathast.rs
1610 lines (1493 loc) · 48.2 KB
/
ast.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 2017 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.
use std::error;
use std::fmt;
/// An error that occurred while parsing a regular expression into an abstract
/// syntax tree.
///
/// Note that note all ASTs represents a valid regular expression. For example,
/// an AST is constructed without error for `\p{Quux}`, but `Quux` is not a
/// valid Unicode property name. That particular error is reported when
/// translating an AST to the high-level intermediate representation (`HIR`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Error {
/// The span of this error.
pub span: Span,
/// The kind of error.
pub kind: ErrorKind,
}
/// The type of an error that occurred while building an AST.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
/// An invalid escape sequence was found in a character class set.
ClassIllegal,
/// An opening `[` was found with no corresponding closing `]`.
ClassUnclosed,
/// An opening `{` was found with no corresponding closing `}`.
CountedRepetitionUnclosed,
/// An empty decimal number was given where one was expected.
DecimalEmpty,
/// An invalid decimal number was given where one was expected.
DecimalInvalid,
/// A bracketed hex literal was empty.
EscapeHexEmpty,
/// A bracketed hex literal did not correspond to a Unicode scalar value.
EscapeHexInvalid,
/// An invalid hexadecimal digit was found.
EscapeHexInvalidDigit {
/// The invalid digit (i.e., not [0-9a-zA-Z]).
c: char,
},
/// EOF was found before an escape sequence was completed.
EscapeUnexpectedEof,
/// An unrecognized escape sequence.
EscapeUnrecognized {
/// The unrecognized escape.
c: char,
},
/// A flag was used twice, e.g., `i-i`.
FlagDuplicate {
/// The duplicate flag.
flag: char,
/// The position of the original flag. The error position
/// points to the duplicate flag.
original: Span,
},
/// The negation operator was used twice, e.g., `-i-s`.
FlagRepeatedNegation {
/// The position of the original negation operator. The error position
/// points to the duplicate negation operator.
original: Span,
},
/// Expected a flag but got EOF, e.g., `(?`.
FlagUnexpectedEof,
/// Unrecognized flag, e.g., `a`.
FlagUnrecognized {
/// The unrecognized flag.
flag: char,
},
/// An empty group, e.g., `()`.
GroupEmpty,
/// A capture group name is empty, e.g., `(?P<>abc)`.
GroupNameEmpty,
/// An invalid character was seen for a capture group name. This includes
/// errors where the first character is a digit (even though subsequent
/// characters are allowed to be digits).
GroupNameInvalid {
/// The invalid character. This may be a digit if it's the first
/// character in the name.
c: char,
},
/// A closing `>` could not be found for a capture group name.
GroupNameUnexpectedEof,
/// An unclosed group, e.g., `(ab`.
///
/// The span of this error corresponds to the unclosed parenthesis.
GroupUnclosed,
/// An unopened group, e.g., `ab)`.
GroupUnopened,
/// The nest limit was exceeded. The limit stored here is the limit
/// configured in the parser.
NestLimitExceeded(u32),
/// When octal support is disabled, this error is produced when an octal
/// escape is used. The octal escape is assumed to be an invocation of
/// a backreference, which is the common case.
UnsupportedBackreference,
/// When syntax similar to PCRE's look-around is used, this error is
/// returned. Some example syntaxes that are rejected include, but are
/// not necessarily limited to, `(?=re)`, `(?!re)`, `(?<=re)` and
/// `(?<!re)`. Note that all of these syntaxes are otherwise invalid; this
/// error is used to improve the user experience.
UnsupportedLookAround,
}
impl error::Error for Error {
fn description(&self) -> &str {
use self::ErrorKind::*;
match self.kind {
ClassIllegal => "illegal item found in character class",
ClassUnclosed => "unclosed character class",
CountedRepetitionUnclosed => "unclosed counted repetition",
DecimalEmpty => "empty decimal literal",
DecimalInvalid => "invalid decimal literal",
EscapeHexEmpty => "empty hexadecimal literal",
EscapeHexInvalid => "invalid hexadecimal literal",
EscapeHexInvalidDigit{..} => "invalid hexadecimal digit",
EscapeUnexpectedEof => "unexpected eof (escape sequence)",
EscapeUnrecognized{..} => "unrecognized escape sequence",
FlagDuplicate{..} => "duplicate flag",
FlagRepeatedNegation{..} => "repeated negation",
FlagUnexpectedEof => "unexpected eof (flag)",
FlagUnrecognized{..} => "unrecognized flag",
GroupEmpty => "empty group",
GroupNameEmpty => "empty capture group name",
GroupNameInvalid{..} => "invalid capture group name",
GroupNameUnexpectedEof => "unclosed capture group name",
GroupUnclosed => "unclosed group",
GroupUnopened => "unopened group",
NestLimitExceeded(_) => "nest limit exceeded",
UnsupportedBackreference => "backreferences are not supported",
UnsupportedLookAround => "look-around is not supported",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ErrorKind::*;
match self.kind {
ClassIllegal => {
write!(f, "illegal item found in character class")
}
ClassUnclosed => {
write!(f, "unclosed character class")
}
CountedRepetitionUnclosed => {
write!(f, "unclosed counted repetition")
}
DecimalEmpty => {
write!(f, "decimal literal empty")
}
DecimalInvalid => {
write!(f, "decimal literal invalid")
}
EscapeHexEmpty => {
write!(f, "hexadecimal literal empty")
}
EscapeHexInvalid => {
write!(f, "hexadecimal literal is not a Unicode scalar value")
}
EscapeHexInvalidDigit { c } => {
write!(f, "invalid hexadecimal digit '{}'", c)
}
EscapeUnexpectedEof => {
write!(f, "incomplete escape sequence, \
reached end of pattern prematurely")
}
EscapeUnrecognized { c } => {
write!(f, "unrecognized escape sequence '\\{}'", c)
}
FlagDuplicate { flag, .. } => {
write!(f, "duplicate flag '{}'", flag)
}
FlagRepeatedNegation{..} => {
write!(f, "flag negation operator repeated")
}
FlagUnexpectedEof => {
write!(f, "expected flag but got end of regex")
}
FlagUnrecognized { flag } => {
write!(f, "unrecognized flag '{}'", flag)
}
GroupEmpty => {
write!(f, "empty group")
}
GroupNameEmpty => {
write!(f, "empty capture group name")
}
GroupNameInvalid{ c } => {
write!(f, "invalid capture group character '{}'", c)
}
GroupNameUnexpectedEof => {
write!(f, "unclosed capture group name")
}
GroupUnclosed => {
write!(f, "unclosed group")
}
GroupUnopened => {
write!(f, "unopened group")
}
NestLimitExceeded(limit) => {
write!(f, "exceed the maximum number of \
nested parentheses/brackets ({})", limit)
}
UnsupportedBackreference => {
write!(f, "backreferences are not supported")
}
UnsupportedLookAround => {
write!(f, "look-around (including look-ahead and look-behind) \
is not supported")
}
}
}
}
/// Span represents the position information of a single AST item.
///
/// All span positions are absolute byte offsets that can be used on the
/// original regular expression that was parsed.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Span {
/// The start byte offset.
pub start: Position,
/// The end byte offset.
pub end: Position,
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Span({:?}, {:?})", self.start, self.end)
}
}
/// A single position in a regular expression.
///
/// A position encodes one half of a span, and include the byte offset, line
/// number and column number.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Position {
/// The absolute offset of this position, starting at `0` from the
/// beginning of the regular expression pattern string.
pub offset: usize,
/// The line number, starting at `1`.
pub line: usize,
/// The approximate column number, starting at `1`.
pub column: usize,
}
impl fmt::Debug for Position {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Position(o: {:?}, l: {:?}, c: {:?})",
self.offset, self.line, self.column)
}
}
impl Span {
/// Create a new span with the given positions.
pub fn new(start: Position, end: Position) -> Span {
Span { start: start, end: end }
}
/// Create a new span using the given position as the start and end.
pub fn splat(pos: Position) -> Span {
Span::new(pos, pos)
}
/// Create a new span by replacing the starting the position with the one
/// given.
pub fn with_start(self, pos: Position) -> Span {
Span { start: pos, ..self }
}
/// Create a new span by replacing the ending the position with the one
/// given.
pub fn with_end(self, pos: Position) -> Span {
Span { end: pos, ..self }
}
}
impl Position {
/// Create a new position with the given information.
///
/// `offset` is the absolute offset of the position, starting at `0` from
/// the beginning of the regular expression pattern string.
///
/// `line` is the line number, starting at `1`.
///
/// `column` is the approximate column number, starting at `1`.
pub fn new(offset: usize, line: usize, column: usize) -> Position {
Position { offset: offset, line: line, column: column }
}
}
/// An abstract syntax tree for a singular expression along with comments
/// found.
///
/// Comments are not stored in the tree itself to avoid complexity. Each
/// comment contains a span of precisely where it occurred in the original
/// regular expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WithComments {
/// The actual ast.
pub ast: Ast,
/// All comments found in the original regular expression.
pub comments: Vec<Comment>,
}
/// A comment from a regular expression with an associated span.
///
/// A regular expression can only contain comments when the `x` flag is
/// enabled.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Comment {
/// The span of this comment, including the beginning `#` and ending `\n`.
pub span: Span,
/// The comment text, starting with the first character following the `#`
/// and ending with the last character preceding the `\n`.
pub comment: String,
}
/// An abstract syntax tree for a single regular expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Ast {
/// An empty regex that matches everything.
Empty(Span),
/// A set of flags, e.g., `(?is)`.
Flags(SetFlags),
/// A single character literal, which includes escape sequences.
Literal(Literal),
/// The "any character" class.
Dot(Span),
/// A single zero-width assertion.
Assertion(Assertion),
/// A single character class. This includes all forms of character classes
/// except for `.`. e.g., `\d`, `\pN`, `[a-z]` and `[[:alpha:]]`.
Class(Class),
/// A repetition operator applied to an arbitrary regular expression.
Repetition(Repetition),
/// A grouped regular expression.
Group(Group),
/// An alternation of regular expressions.
Alternation(Alternation),
/// A concatenation of regular expressions.
Concat(Concat),
}
impl Ast {
/// Return the span of this abstract syntax tree.
pub fn span(&self) -> &Span {
match *self {
Ast::Empty(ref span) => span,
Ast::Literal(ref x) => &x.span,
Ast::Dot(ref span) => span,
Ast::Class(ref x) => x.span(),
Ast::Assertion(ref x) => &x.span,
Ast::Repetition(ref x) => &x.span,
Ast::Group(ref x) => &x.span,
Ast::Flags(ref x) => &x.span,
Ast::Alternation(ref x) => &x.span,
Ast::Concat(ref x) => &x.span,
}
}
}
impl fmt::Display for Ast {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Ast::Empty(_) => Ok(()),
Ast::Flags(ref x) => x.fmt(f),
Ast::Literal(ref x) => x.fmt(f),
Ast::Dot(_) => '.'.fmt(f),
Ast::Assertion(ref x) => x.fmt(f),
Ast::Class(ref x) => x.fmt(f),
Ast::Repetition(ref x) => x.fmt(f),
Ast::Group(ref x) => x.fmt(f),
Ast::Alternation(ref x) => x.fmt(f),
Ast::Concat(ref x) => x.fmt(f),
}
}
}
/// An alternation of regular expressions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Alternation {
/// The span of this alternation.
pub span: Span,
/// The alternate regular expressions.
pub asts: Vec<Ast>,
}
impl Alternation {
/// Return this alternation as an AST.
///
/// If this alternation contains zero ASTs, then Ast::Empty is
/// returned. If this alternation contains exactly 1 AST, then the
/// corresponding AST is returned. Otherwise, Ast::Alternation is returned.
pub fn into_ast(mut self) -> Ast {
match self.asts.len() {
0 => Ast::Empty(self.span),
1 => self.asts.pop().unwrap(),
_ => Ast::Alternation(self),
}
}
}
impl fmt::Display for Alternation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for x in &self.asts {
if !first {
try!('|'.fmt(f));
}
first = false;
try!(x.fmt(f));
}
Ok(())
}
}
/// A concatenation of regular expressions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Concat {
/// The span of this concatenation.
pub span: Span,
/// The concatenation regular expressions.
pub asts: Vec<Ast>,
}
impl Concat {
/// Return this concatenation as an AST.
///
/// If this concatenation contains zero ASTs, then Ast::Empty is
/// returned. If this concatenation contains exactly 1 AST, then the
/// corresponding AST is returned. Otherwise, Ast::Concat is returned.
pub fn into_ast(mut self) -> Ast {
match self.asts.len() {
0 => Ast::Empty(self.span),
1 => self.asts.pop().unwrap(),
_ => Ast::Concat(self),
}
}
}
impl fmt::Display for Concat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for x in &self.asts {
try!(x.fmt(f));
}
Ok(())
}
}
/// A single literal expression.
///
/// A literal corresponds to a single Unicode scalar value. Literals may be
/// represented in their literal form, e.g., `a` or in their escaped form,
/// e.g., `\x61`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Literal {
/// The span of this literal.
pub span: Span,
/// The kind of this literal.
pub kind: LiteralKind,
/// The Unicode scalar value corresponding to this literal.
pub c: char,
}
impl fmt::Display for Literal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::LiteralKind::*;
match self.kind {
Verbatim => self.c.fmt(f),
Special(ref x) => x.fmt(f),
Punctuation => write!(f, r"\{}", self.c),
Octal => write!(f, r"\{:o}", self.c as u32),
HexFixed(HexLiteralKind::X) => {
write!(f, r"\x{:02X}", self.c as u32)
}
HexFixed(HexLiteralKind::UnicodeShort) => {
write!(f, r"\u{:04X}", self.c as u32)
}
HexFixed(HexLiteralKind::UnicodeLong) => {
write!(f, r"\U{:08X}", self.c as u32)
}
HexBrace(HexLiteralKind::X) => {
write!(f, r"\x{{{:X}}}", self.c as u32)
}
HexBrace(HexLiteralKind::UnicodeShort) => {
write!(f, r"\u{{{:X}}}", self.c as u32)
}
HexBrace(HexLiteralKind::UnicodeLong) => {
write!(f, r"\U{{{:X}}}", self.c as u32)
}
}
}
}
/// The kind of a single literal expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LiteralKind {
/// The literal is written verbatim, e.g., `a` or `☃`.
Verbatim,
/// The literal is written as a specially recognized escape, e.g., `\f`
/// or `\n`.
Special(SpecialLiteralKind),
/// The literal is written as an escape because it is punctuation, e.g.,
/// `\*` or `\[`.
Punctuation,
/// The literal is written as an octal escape, e.g., `\141`.
Octal,
/// The literal is written as a hex code with a fixed number of digits
/// depending on the type of the escape, e.g., `\x61` or or `\u0061` or
/// `\U00000061`.
HexFixed(HexLiteralKind),
/// The literal is written as a hex code with a bracketed number of
/// digits. The only restriction is that the bracketed hex code must refer
/// to a valid Unicode scalar value.
HexBrace(HexLiteralKind),
}
/// The type of a special literal.
///
/// A special literal is a special escape sequence recognized by the regex
/// parser, e.g., `\f` or `\n`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SpecialLiteralKind {
/// Bell, spelled `\a` (`\x07`).
Bell,
/// Form feed, spelled `\f` (`\x0C`).
FormFeed,
/// Tab, spelled `\t` (`\x09`).
Tab,
/// Line feed, spelled `\n` (`\x0A`).
LineFeed,
/// Carriage return, spelled `\r` (`\x0D`).
CarriageReturn,
/// Vertical tab, spelled `\v` (`\x0B`).
VerticalTab,
/// Space, spelled `\ ` (`\x20`). Note that this can only appear when
/// parsing in verbose mode.
Space,
}
impl fmt::Display for SpecialLiteralKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::SpecialLiteralKind::*;
match *self {
Bell => r"\a".fmt(f),
FormFeed => r"\f".fmt(f),
Tab => r"\t".fmt(f),
LineFeed => r"\n".fmt(f),
CarriageReturn => r"\r".fmt(f),
VerticalTab => r"\v".fmt(f),
Space => r"\ ".fmt(f),
}
}
}
/// The type of a Unicode hex literal.
///
/// Note that all variants behave the same when used with brackets. They only
/// differ when used without brackets in the number of hex digits that must
/// follow.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HexLiteralKind {
/// A `\x` prefix. When used without brackets, this form is limited to
/// two digits.
X,
/// A `\u` prefix. When used without brackets, this form is limited to
/// four digits.
UnicodeShort,
/// A `\U` prefix. When used without brackets, this form is limited to
/// eight digits.
UnicodeLong,
}
impl HexLiteralKind {
/// The number of digits that must be used with this literal form when
/// used without brackets. When used with brackets, there is no
/// restriction on the number of digits.
pub fn digits(&self) -> u32 {
match *self {
HexLiteralKind::X => 2,
HexLiteralKind::UnicodeShort => 4,
HexLiteralKind::UnicodeLong => 8,
}
}
}
/// A single character class expression.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Class {
/// A perl character class, e.g., `\d` or `\W`.
Perl(ClassPerl),
/// A Unicode character class, e.g., `\pL` or `\p{Greek}`.
Unicode(ClassUnicode),
/// A character class set, which may contain zero or more character ranges
/// and/or zero or more nested classes. e.g., `[a-zA-Z\pL]`.
Set(ClassSet),
}
impl Class {
/// Return the span of this character class.
pub fn span(&self) -> &Span {
match *self {
Class::Perl(ref x) => &x.span,
Class::Unicode(ref x) => &x.span,
Class::Set(ref x) => &x.span,
}
}
}
impl fmt::Display for Class {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Class::Perl(ref x) => x.fmt(f),
Class::Unicode(ref x) => x.fmt(f),
Class::Set(ref x) => x.fmt(f),
}
}
}
/// A Perl character class.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassPerl {
/// The span of this class.
pub span: Span,
/// The kind of Perl class.
pub kind: ClassPerlKind,
/// Whether the class is negated or not. e.g., `\d` is not negated but
/// `\D` is.
pub negated: bool,
}
impl fmt::Display for ClassPerl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ClassPerlKind::Digit if self.negated => r"\D".fmt(f),
ClassPerlKind::Digit => r"\d".fmt(f),
ClassPerlKind::Space if self.negated => r"\S".fmt(f),
ClassPerlKind::Space => r"\s".fmt(f),
ClassPerlKind::Word if self.negated => r"\W".fmt(f),
ClassPerlKind::Word => r"\w".fmt(f),
}
}
}
/// The available Perl character classes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassPerlKind {
/// Decimal numbers.
Digit,
/// Whitespace.
Space,
/// Word characters.
Word,
}
/// An ASCII character class.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassAscii {
/// The span of this class.
pub span: Span,
/// The kind of ASCII class.
pub kind: ClassAsciiKind,
/// Whether the class is negated or not. e.g., `[[:alpha:]]` is not negated
/// but `[[:^alpha:]]` is.
pub negated: bool,
}
impl fmt::Display for ClassAscii {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ClassAsciiKind::*;
match self.kind {
Alnum if self.negated => "[:^alnum:]".fmt(f),
Alnum => "[:alnum:]".fmt(f),
Alpha if self.negated => "[:^alpha:]".fmt(f),
Alpha => "[:alpha:]".fmt(f),
Ascii if self.negated => "[:^ascii:]".fmt(f),
Ascii => "[:ascii:]".fmt(f),
Blank if self.negated => "[:^blank:]".fmt(f),
Blank => "[:blank:]".fmt(f),
Cntrl if self.negated => "[:^cntrl:]".fmt(f),
Cntrl => "[:cntrl:]".fmt(f),
Digit if self.negated => "[:^digit:]".fmt(f),
Digit => "[:digit:]".fmt(f),
Graph if self.negated => "[:^graph:]".fmt(f),
Graph => "[:graph:]".fmt(f),
Lower if self.negated => "[:^lower:]".fmt(f),
Lower => "[:lower:]".fmt(f),
Print if self.negated => "[:^print:]".fmt(f),
Print => "[:print:]".fmt(f),
Punct if self.negated => "[:^punct:]".fmt(f),
Punct => "[:punct:]".fmt(f),
Space if self.negated => "[:^space:]".fmt(f),
Space => "[:space:]".fmt(f),
Upper if self.negated => "[:^upper:]".fmt(f),
Upper => "[:upper:]".fmt(f),
Word if self.negated => "[:^word:]".fmt(f),
Word => "[:word:]".fmt(f),
Xdigit if self.negated => "[:^xdigit:]".fmt(f),
Xdigit => "[:xdigit:]".fmt(f),
}
}
}
/// The available ASCII character classes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassAsciiKind {
/// `[0-9A-Za-z]`
Alnum,
/// `[A-Za-z]`
Alpha,
/// `[\x00-\x7F]`
Ascii,
/// `[ \t]`
Blank,
/// `[\x00-\x1F\x7F]`
Cntrl,
/// `[0-9]`
Digit,
/// `[!-~]`
Graph,
/// `[a-z]`
Lower,
/// `[ -~]`
Print,
/// `[!-/:-@\[-`{-~]`
Punct,
/// `[\t\n\v\f\r ]`
Space,
/// `[A-Z]`
Upper,
/// `[0-9A-Za-z_]`
Word,
/// `[0-9A-Fa-f]`
Xdigit,
}
impl ClassAsciiKind {
/// Return the corresponding ClassAsciiKind variant for the given name.
///
/// The name given should correspond to the lowercase version of the
/// variant name. e.g., `cntrl` is the name for `ClassAsciiKind::Cntrl`.
///
/// If no variant with the corresponding name exists, then `None` is
/// returned.
pub fn from_name(name: &str) -> Option<ClassAsciiKind> {
use self::ClassAsciiKind::*;
match name {
"alnum" => Some(Alnum),
"alpha" => Some(Alpha),
"ascii" => Some(Ascii),
"blank" => Some(Blank),
"cntrl" => Some(Cntrl),
"digit" => Some(Digit),
"graph" => Some(Graph),
"lower" => Some(Lower),
"print" => Some(Print),
"punct" => Some(Punct),
"space" => Some(Space),
"upper" => Some(Upper),
"word" => Some(Word),
"xdigit" => Some(Xdigit),
_ => None,
}
}
}
/// A Unicode character class.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassUnicode {
/// The span of this class.
pub span: Span,
/// Whether this class is negated or not.
///
/// Note: be careful when using this attribute. This specifically refers
/// to whether the class is written as `\p` or `\P`, where the former
/// is `negated = true`. However, it also possible to write something like
/// `\P{scx!=Katakana}` which is actually equivalent to
/// `\p{scx=Katakana}` and is therefore not actually negated even though
/// `negated = true` here. To test whether this class is truly negated
/// or not, use the `is_negated` method.
pub negated: bool,
/// The kind of Unicode class.
pub kind: ClassUnicodeKind,
}
impl ClassUnicode {
/// Returns true if this class has been negated.
///
/// Note that this takes the Unicode op into account, if it's present.
/// e.g., `is_negated` for `\P{scx!=Katakana}` will return `false`.
pub fn is_negated(&self) -> bool {
match self.kind {
ClassUnicodeKind::NamedValue {
op: ClassUnicodeOpKind::NotEqual, ..
} => !self.negated,
_ => self.negated,
}
}
}
impl fmt::Display for ClassUnicode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.negated {
write!(f, r"\P{}", self.kind)
} else {
write!(f, r"\p{}", self.kind)
}
}
}
/// The available forms of Unicode character classes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassUnicodeKind {
/// A one letter abbreviated class, e.g., `\pN`.
OneLetter(char),
/// A binary property, general category or script. The string may be
/// empty.
Named(String),
/// A property name and an associated value.
NamedValue {
/// The type of Unicode op used to associate `name` with `value`.
op: ClassUnicodeOpKind,
/// The property name (which may be empty).
name: String,
/// The property value (which may be empty).
value: String,
},
}
impl fmt::Display for ClassUnicodeKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ClassUnicodeKind::*;
match *self {
OneLetter(c) => c.fmt(f),
Named(ref x) => write!(f, "{{{}}}", x),
NamedValue { ref op, ref name, ref value } => {
write!(f, "{{{}{}{}}}", name, op, value)
}
}
}
}
/// The type of op used in a Unicode character class.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassUnicodeOpKind {
/// A property set to a specific value, e.g., `\p{scx=Katakana}`.
Equal,
/// A property set to a specific value using a colon, e.g.,
/// `\p{scx:Katakana}`.
Colon,
/// A property that isn't a particular value, e.g., `\p{scx!=Katakana}`.
NotEqual,
}
impl ClassUnicodeOpKind {
/// Whether the op is an equality op or not.
pub fn is_equal(&self) -> bool {
match *self {
ClassUnicodeOpKind::Equal|ClassUnicodeOpKind::Colon => true,
_ => false,
}
}
}
impl fmt::Display for ClassUnicodeOpKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ClassUnicodeOpKind::*;
match *self {
Equal => '='.fmt(f),
Colon => ':'.fmt(f),
NotEqual => "!=".fmt(f),
}
}
}
/// A Unicode character class set, e.g., `[a-z0-9]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassSet {
/// The span of this class.
pub span: Span,
/// Whether this class is negated or not. e.g., `[a]` is not negated but
/// `[^a]` is.
pub negated: bool,
/// The top-level op of this set.
pub op: ClassSetOp,
}
impl fmt::Display for ClassSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.negated {
write!(f, r"[^{}]", self.op)
} else {
write!(f, r"[{}]", self.op)
}
}
}
/// An operation inside a character class set.
///
/// An operation is either a union of many things, or a binary operation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassSetOp {
/// A union of items in a class. A union may contain a single item.
Union(ClassSetUnion),
/// A single binary operation (i.e., &&, -- or ~~).
BinaryOp(ClassSetBinaryOp),
}
impl ClassSetOp {
/// Return the span of this character class set operation.
pub fn span(&self) -> &Span {
match *self {
ClassSetOp::Union(ref x) => &x.span,
ClassSetOp::BinaryOp(ref x) => &x.span,
}
}
}
impl fmt::Display for ClassSetOp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ClassSetOp::Union(ref x) => x.fmt(f),
ClassSetOp::BinaryOp(ref x) => x.fmt(f),
}
}
}
/// A union of items inside a character class set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClassSetUnion {
/// The span of the items in this operation. e.g., the `a-z0-9` in
/// `[^a-z0-9]`
pub span: Span,
/// The sequence of items that make up this union.
pub items: Vec<ClassSetItem>,
}
impl ClassSetUnion {
/// Push a new item in this union.
///
/// The ending position of this union's span is updated to the ending
/// position of the span of the item given. If the union is empty, then
/// the starting position of this union is set to the starting position
/// of this item.
///
/// In other words, if you only use this method to add items to a union
/// and you set the spans on each item correctly, then you should never
/// need to adjust the span of the union directly.
pub fn push(&mut self, item: ClassSetItem) {
if self.items.is_empty() {
self.span.start = item.span().start;
}
self.span.end = item.span().end;
self.items.push(item);
}
}
impl fmt::Display for ClassSetUnion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for x in &self.items {
try!(x.fmt(f));
}
Ok(())
}
}
/// A single component of a character class set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassSetItem {
/// A single literal.
Literal(Literal),
/// A range between two literals.
Range(ClassSetRange),
/// An ASCII character class, e.g., `[:alnum:]` or `[:punct:]`.
Ascii(ClassAscii),
/// A nested character class.
Class(Box<Class>),
}
impl ClassSetItem {
/// Return the span of this character class set item.