diff Implab/Automaton/RegularExpressions/Token.cs @ 162:0526412bbb26 ref20160224

DFA refactoring
author cin
date Wed, 24 Feb 2016 08:39:53 +0300
parents
children e227e78d72e4
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Implab/Automaton/RegularExpressions/Token.cs	Wed Feb 24 08:39:53 2016 +0300
@@ -0,0 +1,63 @@
+using Implab;
+using System;
+using System.Linq;
+
+namespace Implab.Automaton.RegularExpressions {
+    public abstract class Token<TTag> {
+        public abstract void Accept(IVisitor<TTag> visitor);
+
+        public Token<TTag> Extend() {
+            return Cat(new EndToken<TTag>());
+        }
+
+        public Token<TTag> Tag<T>(T tag) where T : IConvertible {
+            return Cat(new EndToken<TTag>(tag));
+        }
+
+        public Token<TTag> Cat(Token<TTag> right) {
+            return new CatToken<TTag>(this, right);
+        }
+
+        public Token<TTag> Or(Token<TTag> right) {
+            return new AltToken<TTag>(this, right);
+        }
+
+        public Token<TTag> Optional() {
+            return Or(new EmptyToken<TTag>());
+        }
+
+        public Token<TTag> EClosure() {
+            return new StarToken<TTag>(this);
+        }
+
+        public Token<TTag> Closure() {
+            return Cat(new StarToken<TTag>(this));
+        }
+
+        public Token<TTag> Repeat(int count) {
+            Token<TTag> token = null;
+
+            for (int i = 0; i < count; i++)
+                token = token != null ? token.Cat(this) : this;
+            return token ?? new EmptyToken<TTag>();
+        }
+
+        public Token<TTag> Repeat(int min, int max) {
+            if (min > max || min < 1)
+                throw new ArgumentOutOfRangeException();
+            var token = Repeat(min);
+
+            for (int i = min; i < max; i++)
+                token = token.Cat( this.Optional() );
+            return token;
+        }
+
+        public static Token<TTag> New<T>(params T[] set) where T : struct, IConvertible {
+            Safe.ArgumentNotNull(set, "set");
+            Token<TTag> token = null;
+            foreach(var c in set.Distinct())
+                token = token == null ? new SymbolToken<TTag>(c) : token.Or(new SymbolToken<TTag>(c));
+            return token;
+        }
+    }
+}