162
|
1 using Implab;
|
|
2 using System;
|
|
3 using System.Linq;
|
|
4
|
|
5 namespace Implab.Automaton.RegularExpressions {
|
|
6 public abstract class Token<TTag> {
|
|
7 public abstract void Accept(IVisitor<TTag> visitor);
|
|
8
|
|
9 public Token<TTag> Extend() {
|
|
10 return Cat(new EndToken<TTag>());
|
|
11 }
|
|
12
|
165
|
13 public Token<TTag> Tag(TTag tag) {
|
162
|
14 return Cat(new EndToken<TTag>(tag));
|
|
15 }
|
|
16
|
|
17 public Token<TTag> Cat(Token<TTag> right) {
|
|
18 return new CatToken<TTag>(this, right);
|
|
19 }
|
|
20
|
|
21 public Token<TTag> Or(Token<TTag> right) {
|
|
22 return new AltToken<TTag>(this, right);
|
|
23 }
|
|
24
|
|
25 public Token<TTag> Optional() {
|
|
26 return Or(new EmptyToken<TTag>());
|
|
27 }
|
|
28
|
|
29 public Token<TTag> EClosure() {
|
|
30 return new StarToken<TTag>(this);
|
|
31 }
|
|
32
|
|
33 public Token<TTag> Closure() {
|
|
34 return Cat(new StarToken<TTag>(this));
|
|
35 }
|
|
36
|
|
37 public Token<TTag> Repeat(int count) {
|
|
38 Token<TTag> token = null;
|
|
39
|
|
40 for (int i = 0; i < count; i++)
|
|
41 token = token != null ? token.Cat(this) : this;
|
|
42 return token ?? new EmptyToken<TTag>();
|
|
43 }
|
|
44
|
|
45 public Token<TTag> Repeat(int min, int max) {
|
|
46 if (min > max || min < 1)
|
|
47 throw new ArgumentOutOfRangeException();
|
|
48 var token = Repeat(min);
|
|
49
|
|
50 for (int i = min; i < max; i++)
|
165
|
51 token = token.Cat( Optional() );
|
162
|
52 return token;
|
|
53 }
|
|
54
|
165
|
55 public static Token<TTag> New(params int[] set) {
|
162
|
56 Safe.ArgumentNotNull(set, "set");
|
|
57 Token<TTag> token = null;
|
|
58 foreach(var c in set.Distinct())
|
|
59 token = token == null ? new SymbolToken<TTag>(c) : token.Or(new SymbolToken<TTag>(c));
|
|
60 return token;
|
|
61 }
|
|
62 }
|
|
63 }
|