Mercurial > pub > ImplabNet
view Implab/Automaton/RegularExpressions/Grammar.cs @ 163:419aa51b04fd ref20160224
JSON moved to Formats namespace
Working in RegularDFA
author | cin |
---|---|
date | Wed, 24 Feb 2016 20:12:52 +0300 |
parents | 0526412bbb26 |
children | ec35731ae299 |
line wrap: on
line source
using Implab; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Implab.Automaton.RegularExpressions { /// <summary> /// Базовый абстрактный класс. Грамматика, позволяет формулировать выражения над алфавитом типа <c>char</c>. /// </summary> public abstract class Grammar<TSymbol, TTag> { public abstract IAlphabetBuilder<TSymbol> Alphabet { get; } public SymbolToken<TTag> UnclassifiedToken() { return new SymbolToken<TTag>(DFAConst.UNCLASSIFIED_INPUT); } public void DefineAlphabet(IEnumerable<TSymbol> alphabet) { Safe.ArgumentNotNull(alphabet, "alphabet"); foreach (var ch in alphabet) Alphabet.DefineSymbol(ch); } public Token<TTag> SymbolToken(TSymbol symbol) { return Token<TTag>.New(TranslateOrAdd(symbol)); } public Token<TTag> SymbolToken(IEnumerable<TSymbol> symbols) { Safe.ArgumentNotNull(symbols, "symbols"); return Token<TTag>.New(TranslateOrAdd(symbols).ToArray()); } public Token<TTag> SymbolSetToken(params TSymbol[] set) { return SymbolToken(set); } int TranslateOrAdd(TSymbol ch) { var t = Alphabet.Translate(ch); if (t == DFAConst.UNCLASSIFIED_INPUT) t = Alphabet.DefineSymbol(ch); return t; } IEnumerable<int> TranslateOrAdd(IEnumerable<TSymbol> symbols) { return symbols.Distinct().Select(TranslateOrAdd); } int TranslateOrDie(TSymbol ch) { var t = Alphabet.Translate(ch); if (t == DFAConst.UNCLASSIFIED_INPUT) throw new ApplicationException(String.Format("Symbol '{0}' is UNCLASSIFIED", ch)); return t; } IEnumerable<int> TranslateOrDie(IEnumerable<TSymbol> symbols) { return symbols.Distinct().Select(TranslateOrDie); } public Token<TTag> SymbolTokenExcept(IEnumerable<TSymbol> symbols) { Safe.ArgumentNotNull(symbols, "symbols"); return Token<TTag>.New( Enumerable.Range(0, Alphabet.Count).Except(TranslateOrDie(symbols)).ToArray() ); } protected CDFADefinition BuildDFA(Token<TTag> lang) { Safe.ArgumentNotNull(lang, "lang"); var dfa = new CDFADefinition(Alphabet); var builder = new RegularDFABuilder<TTag>(); lang.Accept( builder ); builder.BuildDFA(dfa); if (dfa.InitialStateIsFinal) throw new ApplicationException("The specified language contains empty token"); return dfa.Optimize(); } //protected abstract TGrammar CreateInstance(); } }