##// END OF EJS Templates
Merge pull request !2 from ImplabNet v3...
Merge pull request !2 from ImplabNet v3 Changes from branch: V3

File last commit:

r289:95896f882995 v3.0.14 v3
r294:abef3ebaa230 merge default
Show More
Grammar.cs
73 lines | 2.4 KiB | text/x-csharp | CSharpLexer
cin
Added tests for Implab.ServiceHost.Unity configuration loader.
r289 using Implab;
using System;
using System.Collections.Generic;
using System.Linq;
using Implab.Automaton;
using Implab.Automaton.RegularExpressions;
namespace Implab.Formats {
/// <summary>
/// Базовый абстрактный класс. Грамматика, позволяет формулировать выражения над алфавитом типа <c>char</c>.
/// </summary>
public abstract class Grammar<TSymbol> {
protected abstract IAlphabetBuilder<TSymbol> AlphabetBuilder {
get;
}
protected SymbolToken UnclassifiedToken() {
return new SymbolToken(AutomatonConst.UnclassifiedInput);
}
protected void DefineAlphabet(IEnumerable<TSymbol> alphabet) {
Safe.ArgumentNotNull(alphabet, "alphabet");
foreach (var ch in alphabet)
AlphabetBuilder.DefineSymbol(ch);
}
protected Token SymbolToken(TSymbol symbol) {
return Token.New(TranslateOrAdd(symbol));
}
protected Token SymbolToken(IEnumerable<TSymbol> symbols) {
Safe.ArgumentNotNull(symbols, "symbols");
return Token.New(TranslateOrAdd(symbols).ToArray());
}
protected Token SymbolSetToken(params TSymbol[] set) {
return SymbolToken(set);
}
int TranslateOrAdd(TSymbol ch) {
var t = AlphabetBuilder.Translate(ch);
if (t == AutomatonConst.UnclassifiedInput)
t = AlphabetBuilder.DefineSymbol(ch);
return t;
}
IEnumerable<int> TranslateOrAdd(IEnumerable<TSymbol> symbols) {
return symbols.Distinct().Select(TranslateOrAdd);
}
int TranslateOrDie(TSymbol ch) {
var t = AlphabetBuilder.Translate(ch);
if (t == AutomatonConst.UnclassifiedInput)
throw new ApplicationException(String.Format("Symbol '{0}' is UNCLASSIFIED", ch));
return t;
}
IEnumerable<int> TranslateOrDie(IEnumerable<TSymbol> symbols) {
return symbols.Distinct().Select(TranslateOrDie);
}
protected Token SymbolTokenExcept(IEnumerable<TSymbol> symbols) {
Safe.ArgumentNotNull(symbols, "symbols");
return Token.New( Enumerable.Range(0, AlphabetBuilder.Count).Except(TranslateOrDie(symbols)).ToArray() );
}
}
}