##// END OF EJS Templates
DFA refactoring
cin -
r161:2a8466f0cb8a v2
parent child
Show More
@@ -0,0 +1,25
1 using System;
2 using System.Collections.Generic;
3
4 namespace Implab.Parsing {
5 public interface IAlphabetBuilder<TSymbol> : IAlphabet<TSymbol> {
6 /// <summary>
7 /// ДобавляСт Π½ΠΎΠ²Ρ‹ΠΉ символ Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚, Ссли символ ΡƒΠΆΠ΅ Π±Ρ‹Π» Π΄ΠΎΠ±Π°Π²Π»Π΅Π½, Ρ‚ΠΎ
8 /// возвращаСтся Ρ€Π°Π½Π΅Π΅ сопоставлСнный с символом класс.
9 /// </summary>
10 /// <param name="symbol">Бимвол для добавлСния.</param>
11 /// <returns>ИндСкс класса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ попоставлСн с символом.</returns>
12 int DefineSymbol(TSymbol symbol);
13 /// <summary>
14 /// ДоабвляСм класс символов. ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚Π²Ρƒ ΡƒΠΊΠ°Π·Π°Π½Π½Ρ‹Ρ… исходных символов
15 /// Π±ΡƒΠ΄Π΅Ρ‚ сопоставлСн символ Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅.
16 /// </summary>
17 /// <param name="symbols">ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚ΠΎΠ² исходных символов</param>
18 /// <returns>Π˜Π΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ символа Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°.</returns>
19 int DefineClass(IEnumerable<TSymbol> symbols);
20
21
22
23 }
24 }
25
@@ -0,0 +1,9
1 using System;
2
3 namespace Implab.Parsing {
4 public interface IDFADefinitionBuilder<TInput, TState, TTag> : IDFADefinition<TInput, TState, TTag> {
5
6
7 }
8 }
9
@@ -1,262 +1,261
1 1 ο»Ώ<?xml version="1.0" encoding="utf-8"?>
2 2 <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3 3 <PropertyGroup>
4 4 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
5 5 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
6 6 <ProjectGuid>{F550F1F8-8746-4AD0-9614-855F4C4B7F05}</ProjectGuid>
7 7 <OutputType>Library</OutputType>
8 8 <RootNamespace>Implab</RootNamespace>
9 9 <AssemblyName>Implab</AssemblyName>
10 <ProductVersion>8.0.30703</ProductVersion>
11 <SchemaVersion>2.0</SchemaVersion>
12 <ReleaseVersion>0.2</ReleaseVersion>
13 10 <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
14 11 </PropertyGroup>
15 12 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
16 13 <DebugSymbols>true</DebugSymbols>
17 14 <DebugType>full</DebugType>
18 15 <Optimize>false</Optimize>
19 16 <OutputPath>bin\Debug</OutputPath>
20 17 <DefineConstants>TRACE;DEBUG;</DefineConstants>
21 18 <ErrorReport>prompt</ErrorReport>
22 19 <WarningLevel>4</WarningLevel>
23 20 <ConsolePause>false</ConsolePause>
24 21 <RunCodeAnalysis>true</RunCodeAnalysis>
25 22 </PropertyGroup>
26 23 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
27 24 <DebugType>full</DebugType>
28 25 <Optimize>true</Optimize>
29 26 <OutputPath>bin\Release</OutputPath>
30 27 <ErrorReport>prompt</ErrorReport>
31 28 <WarningLevel>4</WarningLevel>
32 29 <ConsolePause>false</ConsolePause>
33 30 </PropertyGroup>
34 31 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug 4.5|AnyCPU' ">
35 32 <DebugSymbols>true</DebugSymbols>
36 33 <DebugType>full</DebugType>
37 34 <Optimize>false</Optimize>
38 35 <OutputPath>bin\Debug</OutputPath>
39 36 <DefineConstants>TRACE;DEBUG;NET_4_5</DefineConstants>
40 37 <ErrorReport>prompt</ErrorReport>
41 38 <WarningLevel>4</WarningLevel>
42 39 <RunCodeAnalysis>true</RunCodeAnalysis>
43 40 <ConsolePause>false</ConsolePause>
44 41 </PropertyGroup>
45 42 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release 4.5|AnyCPU' ">
46 43 <Optimize>true</Optimize>
47 44 <OutputPath>bin\Release</OutputPath>
48 45 <ErrorReport>prompt</ErrorReport>
49 46 <WarningLevel>4</WarningLevel>
50 47 <ConsolePause>false</ConsolePause>
51 48 <DefineConstants>NET_4_5</DefineConstants>
52 49 </PropertyGroup>
53 50 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'DebugMono|AnyCPU' ">
54 51 <DebugSymbols>true</DebugSymbols>
55 52 <DebugType>full</DebugType>
56 53 <Optimize>false</Optimize>
57 54 <OutputPath>bin\Debug</OutputPath>
58 55 <DefineConstants>TRACE;DEBUG;NET_4_5;MONO</DefineConstants>
59 56 <ErrorReport>prompt</ErrorReport>
60 57 <WarningLevel>4</WarningLevel>
61 58 <RunCodeAnalysis>true</RunCodeAnalysis>
62 59 <ConsolePause>false</ConsolePause>
63 60 </PropertyGroup>
64 61 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'ReleaseMono|AnyCPU' ">
65 62 <Optimize>true</Optimize>
66 63 <OutputPath>bin\Release</OutputPath>
67 64 <DefineConstants>NET_4_5;MONO;</DefineConstants>
68 65 <ErrorReport>prompt</ErrorReport>
69 66 <WarningLevel>4</WarningLevel>
70 67 <ConsolePause>false</ConsolePause>
71 68 </PropertyGroup>
72 69 <ItemGroup>
73 70 <Reference Include="System" />
74 71 <Reference Include="System.Xml" />
75 72 <Reference Include="mscorlib" />
76 73 </ItemGroup>
77 74 <ItemGroup>
78 75 <Compile Include="CustomEqualityComparer.cs" />
79 76 <Compile Include="Diagnostics\ConsoleTraceListener.cs" />
80 77 <Compile Include="Diagnostics\EventText.cs" />
81 78 <Compile Include="Diagnostics\LogChannel.cs" />
82 79 <Compile Include="Diagnostics\LogicalOperation.cs" />
83 80 <Compile Include="Diagnostics\TextFileListener.cs" />
84 81 <Compile Include="Diagnostics\TraceLog.cs" />
85 82 <Compile Include="Diagnostics\TraceEvent.cs" />
86 83 <Compile Include="Diagnostics\TraceEventType.cs" />
87 84 <Compile Include="ICancellable.cs" />
88 85 <Compile Include="IProgressHandler.cs" />
89 86 <Compile Include="IProgressNotifier.cs" />
90 87 <Compile Include="IPromiseT.cs" />
91 88 <Compile Include="IPromise.cs" />
92 89 <Compile Include="IServiceLocator.cs" />
93 90 <Compile Include="ITaskController.cs" />
94 91 <Compile Include="JSON\JSONElementContext.cs" />
95 92 <Compile Include="JSON\JSONElementType.cs" />
96 93 <Compile Include="JSON\JSONGrammar.cs" />
97 94 <Compile Include="JSON\JSONParser.cs" />
98 95 <Compile Include="JSON\JSONScanner.cs" />
99 96 <Compile Include="JSON\JsonTokenType.cs" />
100 97 <Compile Include="JSON\JSONWriter.cs" />
101 98 <Compile Include="JSON\JSONXmlReader.cs" />
102 99 <Compile Include="JSON\JSONXmlReaderOptions.cs" />
103 100 <Compile Include="JSON\StringTranslator.cs" />
104 101 <Compile Include="Parallels\DispatchPool.cs" />
105 102 <Compile Include="Parallels\ArrayTraits.cs" />
106 103 <Compile Include="Parallels\MTQueue.cs" />
107 104 <Compile Include="Parallels\WorkerPool.cs" />
108 105 <Compile Include="Parsing\AltToken.cs" />
109 106 <Compile Include="Parsing\BinaryToken.cs" />
110 107 <Compile Include="Parsing\CatToken.cs" />
111 108 <Compile Include="Parsing\CDFADefinition.cs" />
112 109 <Compile Include="Parsing\DFABuilder.cs" />
113 110 <Compile Include="Parsing\DFAStateDescriptor.cs" />
114 111 <Compile Include="Parsing\DFAutomaton.cs" />
115 112 <Compile Include="Parsing\EDFADefinition.cs" />
116 113 <Compile Include="Parsing\EmptyToken.cs" />
117 114 <Compile Include="Parsing\EndToken.cs" />
118 115 <Compile Include="Parsing\EnumAlphabet.cs" />
119 116 <Compile Include="Parsing\Grammar.cs" />
120 117 <Compile Include="Parsing\IAlphabet.cs" />
121 118 <Compile Include="Parsing\IDFADefinition.cs" />
122 119 <Compile Include="Parsing\IVisitor.cs" />
123 120 <Compile Include="Parsing\ParserException.cs" />
124 121 <Compile Include="Parsing\Scanner.cs" />
125 122 <Compile Include="Parsing\StarToken.cs" />
126 123 <Compile Include="Parsing\SymbolToken.cs" />
127 124 <Compile Include="Parsing\Token.cs" />
128 125 <Compile Include="ProgressInitEventArgs.cs" />
129 126 <Compile Include="Properties\AssemblyInfo.cs" />
130 127 <Compile Include="Parallels\AsyncPool.cs" />
131 128 <Compile Include="Safe.cs" />
132 129 <Compile Include="ValueEventArgs.cs" />
133 130 <Compile Include="PromiseExtensions.cs" />
134 131 <Compile Include="SyncContextPromise.cs" />
135 132 <Compile Include="Diagnostics\OperationContext.cs" />
136 133 <Compile Include="Diagnostics\TraceContext.cs" />
137 134 <Compile Include="Diagnostics\LogEventArgs.cs" />
138 135 <Compile Include="Diagnostics\LogEventArgsT.cs" />
139 136 <Compile Include="Diagnostics\Extensions.cs" />
140 137 <Compile Include="PromiseEventType.cs" />
141 138 <Compile Include="Parallels\AsyncQueue.cs" />
142 139 <Compile Include="PromiseT.cs" />
143 140 <Compile Include="IDeferred.cs" />
144 141 <Compile Include="IDeferredT.cs" />
145 142 <Compile Include="Promise.cs" />
146 143 <Compile Include="PromiseTransientException.cs" />
147 144 <Compile Include="Parallels\Signal.cs" />
148 145 <Compile Include="Parallels\SharedLock.cs" />
149 146 <Compile Include="Diagnostics\ILogWriter.cs" />
150 147 <Compile Include="Diagnostics\ListenerBase.cs" />
151 148 <Compile Include="Parallels\BlockingQueue.cs" />
152 149 <Compile Include="AbstractEvent.cs" />
153 150 <Compile Include="AbstractPromise.cs" />
154 151 <Compile Include="AbstractPromiseT.cs" />
155 152 <Compile Include="FuncTask.cs" />
156 153 <Compile Include="FuncTaskBase.cs" />
157 154 <Compile Include="FuncTaskT.cs" />
158 155 <Compile Include="ActionChainTaskBase.cs" />
159 156 <Compile Include="ActionChainTask.cs" />
160 157 <Compile Include="ActionChainTaskT.cs" />
161 158 <Compile Include="FuncChainTaskBase.cs" />
162 159 <Compile Include="FuncChainTask.cs" />
163 160 <Compile Include="FuncChainTaskT.cs" />
164 161 <Compile Include="ActionTaskBase.cs" />
165 162 <Compile Include="ActionTask.cs" />
166 163 <Compile Include="ActionTaskT.cs" />
167 164 <Compile Include="ICancellationToken.cs" />
168 165 <Compile Include="SuccessPromise.cs" />
169 166 <Compile Include="SuccessPromiseT.cs" />
170 167 <Compile Include="PromiseAwaiterT.cs" />
171 168 <Compile Include="PromiseAwaiter.cs" />
172 169 <Compile Include="Components\ComponentContainer.cs" />
173 170 <Compile Include="Components\Disposable.cs" />
174 171 <Compile Include="Components\DisposablePool.cs" />
175 172 <Compile Include="Components\ObjectPool.cs" />
176 173 <Compile Include="Components\ServiceLocator.cs" />
177 174 <Compile Include="Components\IInitializable.cs" />
178 175 <Compile Include="TaskController.cs" />
179 176 <Compile Include="Components\App.cs" />
180 177 <Compile Include="Components\IRunnable.cs" />
181 178 <Compile Include="Components\ExecutionState.cs" />
182 179 <Compile Include="Components\RunnableComponent.cs" />
183 180 <Compile Include="Components\IFactory.cs" />
184 181 <Compile Include="Parsing\DFADefinition.cs" />
185 182 <Compile Include="Parsing\IndexedAlphabetBase.cs" />
186 183 <Compile Include="Parsing\CharAlphabet.cs" />
184 <Compile Include="Parsing\IAlphabetBuilder.cs" />
185 <Compile Include="Parsing\IDFADefinitionBuilder.cs" />
187 186 </ItemGroup>
188 187 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
189 188 <ItemGroup />
190 189 <ProjectExtensions>
191 190 <MonoDevelop>
192 191 <Properties>
193 192 <Policies>
194 193 <CSharpFormattingPolicy IndentSwitchBody="True" NamespaceBraceStyle="EndOfLine" ClassBraceStyle="EndOfLine" InterfaceBraceStyle="EndOfLine" StructBraceStyle="EndOfLine" EnumBraceStyle="EndOfLine" MethodBraceStyle="EndOfLine" ConstructorBraceStyle="EndOfLine" DestructorBraceStyle="EndOfLine" BeforeMethodDeclarationParentheses="False" BeforeMethodCallParentheses="False" BeforeConstructorDeclarationParentheses="False" NewLineBeforeConstructorInitializerColon="NewLine" NewLineAfterConstructorInitializerColon="SameLine" BeforeIndexerDeclarationBracket="False" BeforeDelegateDeclarationParentheses="False" NewParentheses="False" SpacesBeforeBrackets="False" inheritsSet="Mono" inheritsScope="text/x-csharp" scope="text/x-csharp" />
195 194 <TextStylePolicy FileWidth="120" EolMarker="Unix" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/x-csharp" />
196 195 <DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedHierarchical" ResourceNamePolicy="MSBuild" />
197 196 <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="application/xml" />
198 197 <XmlFormattingPolicy inheritsSet="Mono" inheritsScope="application/xml" scope="application/xml" />
199 198 <TextStylePolicy FileWidth="120" TabsToSpaces="False" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" />
200 199 <NameConventionPolicy>
201 200 <Rules>
202 201 <NamingRule Name="Namespaces" AffectedEntity="Namespace" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
203 202 <NamingRule Name="Types" AffectedEntity="Class, Struct, Enum, Delegate" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
204 203 <NamingRule Name="Interfaces" AffectedEntity="Interface" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
205 204 <RequiredPrefixes>
206 205 <String>I</String>
207 206 </RequiredPrefixes>
208 207 </NamingRule>
209 208 <NamingRule Name="Attributes" AffectedEntity="CustomAttributes" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
210 209 <RequiredSuffixes>
211 210 <String>Attribute</String>
212 211 </RequiredSuffixes>
213 212 </NamingRule>
214 213 <NamingRule Name="Event Arguments" AffectedEntity="CustomEventArgs" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
215 214 <RequiredSuffixes>
216 215 <String>EventArgs</String>
217 216 </RequiredSuffixes>
218 217 </NamingRule>
219 218 <NamingRule Name="Exceptions" AffectedEntity="CustomExceptions" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
220 219 <RequiredSuffixes>
221 220 <String>Exception</String>
222 221 </RequiredSuffixes>
223 222 </NamingRule>
224 223 <NamingRule Name="Methods" AffectedEntity="Methods" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
225 224 <NamingRule Name="Static Readonly Fields" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Protected, Public" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True" />
226 225 <NamingRule Name="Fields (Non Private)" AffectedEntity="Field" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
227 226 <NamingRule Name="ReadOnly Fields (Non Private)" AffectedEntity="ReadonlyField" VisibilityMask="Internal, Public" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False" />
228 227 <NamingRule Name="Fields (Private)" AffectedEntity="Field, ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
229 228 <RequiredPrefixes>
230 229 <String>m_</String>
231 230 </RequiredPrefixes>
232 231 </NamingRule>
233 232 <NamingRule Name="Static Fields (Private)" AffectedEntity="Field" VisibilityMask="Private" NamingStyle="CamelCase" IncludeInstanceMembers="False" IncludeStaticEntities="True">
234 233 <RequiredPrefixes>
235 234 <String>_</String>
236 235 </RequiredPrefixes>
237 236 </NamingRule>
238 237 <NamingRule Name="ReadOnly Fields (Private)" AffectedEntity="ReadonlyField" VisibilityMask="Private, Protected" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="False">
239 238 <RequiredPrefixes>
240 239 <String>m_</String>
241 240 </RequiredPrefixes>
242 241 </NamingRule>
243 242 <NamingRule Name="Constant Fields" AffectedEntity="ConstantField" VisibilityMask="VisibilityMask" NamingStyle="AllUpper" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
244 243 <NamingRule Name="Properties" AffectedEntity="Property" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
245 244 <NamingRule Name="Events" AffectedEntity="Event" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
246 245 <NamingRule Name="Enum Members" AffectedEntity="EnumMember" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
247 246 <NamingRule Name="Parameters" AffectedEntity="Parameter, LocalVariable" VisibilityMask="VisibilityMask" NamingStyle="CamelCase" IncludeInstanceMembers="True" IncludeStaticEntities="True" />
248 247 <NamingRule Name="Type Parameters" AffectedEntity="TypeParameter" VisibilityMask="VisibilityMask" NamingStyle="PascalCase" IncludeInstanceMembers="True" IncludeStaticEntities="True">
249 248 <RequiredPrefixes>
250 249 <String>T</String>
251 250 </RequiredPrefixes>
252 251 </NamingRule>
253 252 </Rules>
254 253 </NameConventionPolicy>
255 254 </Policies>
256 255 </Properties>
257 256 </MonoDevelop>
258 257 </ProjectExtensions>
259 258 <ItemGroup>
260 259 <Folder Include="Components\" />
261 260 </ItemGroup>
262 261 </Project> No newline at end of file
@@ -1,267 +1,285
1 1 using Implab;
2 2 using System;
3 3 using System.Collections.Generic;
4 4 using System.Diagnostics;
5 5 using System.Linq;
6 6
7 7 namespace Implab.Parsing {
8 public class DFADefinition : IDFADefinition {
9 readonly List<DFAStateDescriptior> m_states;
8 public class DFADefinition<TInput, TState, TTag> : IDFADefinition<TInput, TState, TTag> {
9 readonly List<DFAStateDescriptior<TTag>> m_states;
10 10
11 11 public const int INITIAL_STATE = 1;
12 12 public const int UNREACHEBLE_STATE = 0;
13 13
14 DFAStateDescriptior[] m_statesArray;
14 DFAStateDescriptior<TTag>[] m_statesArray;
15 15 readonly int m_alpabetSize;
16 16
17 17 public DFADefinition(int alphabetSize) {
18 m_states = new List<DFAStateDescriptior>();
18 m_states = new List<DFAStateDescriptior<TTag>>();
19 19 m_alpabetSize = alphabetSize;
20 20
21 m_states.Add(new DFAStateDescriptior());
22 }
23
24 public DFAStateDescriptior[] States {
25 get {
26 if (m_statesArray == null)
27 m_statesArray = m_states.ToArray();
28 return m_statesArray;
29 }
21 m_states.Add(new DFAStateDescriptior<TTag>());
30 22 }
31 23
32 24 public bool InitialStateIsFinal {
33 25 get {
34 26 return m_states[INITIAL_STATE].final;
35 27 }
36 28 }
37 29
38 30 public int AddState() {
39 31 var index = m_states.Count;
40 m_states.Add(new DFAStateDescriptior {
32 m_states.Add(new DFAStateDescriptior<TTag> {
41 33 final = false,
42 34 transitions = new int[AlphabetSize]
43 35 });
44 36 m_statesArray = null;
45 37
46 38 return index;
47 39 }
48 40
49 public int AddState(int[] tag) {
41 public int AddState(TTag[] tag) {
50 42 var index = m_states.Count;
51 43 bool final = tag != null && tag.Length != 0;
52 m_states.Add(new DFAStateDescriptior {
44 m_states.Add(new DFAStateDescriptior<TTag> {
53 45 final = final,
54 46 transitions = new int[AlphabetSize],
55 47 tag = final ? tag : null
56 48 });
57 49 m_statesArray = null;
58 50 return index;
59 51 }
60 52
61 public void DefineTransition(int s1,int s2, int symbol) {
62 Safe.ArgumentInRange(s1, 0, m_states.Count-1, "s1");
63 Safe.ArgumentInRange(s2, 0, m_states.Count-1, "s2");
64 Safe.ArgumentInRange(symbol, 0, AlphabetSize-1, "symbol");
53 public void DefineTransition(TState s1, TState s2, TInput symbol) {
54 int is1 = StateAlphabet.Translate(s1);
55 int is2 = StateAlphabet.Translate(s2);
56 int isym = InputAlphabet.Translate(symbol);
65 57
66 m_states[s1].transitions[symbol] = s2;
58 Safe.ArgumentAssert(is1 != 0, "s1");
59 Safe.ArgumentAssert(is2 != 0, "s2");
60 Safe.ArgumentAssert(isym != 0, "symbol");
61
62 m_states[is1].transitions[isym] = is2;
67 63 }
68 64
69 protected IDFADefinition Optimize<TA>(Func<IAlphabet<TA>, IDFADefinition> dfaFactory,IAlphabet<TA> sourceAlphabet, IAlphabet<TA> minimalAlphabet) {
65 #region IDFADefinition implementation
66
67 public DFAStateDescriptior<TTag>[] GetTransitionTable() {
68 if (m_statesArray == null)
69 m_statesArray = m_states.ToArray();
70 return m_statesArray;
71 }
72
73 public IAlphabet<TInput> InputAlphabet {
74 get {
75 throw new NotImplementedException();
76 }
77 }
78
79 public IAlphabet<TState> StateAlphabet {
80 get {
81 throw new NotImplementedException();
82 }
83 }
84
85 #endregion
86
87 protected IDFADefinition<> Optimize<TA>(Func<IAlphabet<TA>, IDFADefinition> dfaFactory,IAlphabet<TA> sourceAlphabet, IAlphabet<TA> minimalAlphabet) {
70 88 Safe.ArgumentNotNull(dfaFactory, "dfaFactory");
71 89 Safe.ArgumentNotNull(minimalAlphabet, "minimalAlphabet");
72 90
73 91 var setComparer = new CustomEqualityComparer<HashSet<int>>(
74 92 (x, y) => x.SetEquals(y),
75 93 (s) => s.Sum(x => x.GetHashCode())
76 94 );
77 95
78 96 var arrayComparer = new CustomEqualityComparer<int[]>(
79 97 (x,y) => (new HashSet<int>(x)).SetEquals(new HashSet<int>(y)),
80 98 (a) => a.Sum(x => x.GetHashCode())
81 99 );
82 100
83 101 var optimalStates = new HashSet<HashSet<int>>(setComparer);
84 102 var queue = new HashSet<HashSet<int>>(setComparer);
85 103
86 104 foreach (var g in Enumerable
87 105 .Range(INITIAL_STATE, m_states.Count-1)
88 106 .Select(i => new {
89 107 index = i,
90 108 descriptor = m_states[i]
91 109 })
92 110 .Where(x => x.descriptor.final)
93 111 .GroupBy(x => x.descriptor.tag, arrayComparer)
94 112 ) {
95 113 optimalStates.Add(new HashSet<int>(g.Select(x => x.index)));
96 114 }
97 115
98 116 var state = new HashSet<int>(
99 117 Enumerable
100 118 .Range(INITIAL_STATE, m_states.Count - 1)
101 119 .Where(i => !m_states[i].final)
102 120 );
103 121 optimalStates.Add(state);
104 122 queue.Add(state);
105 123
106 124 while (queue.Count > 0) {
107 125 var stateA = queue.First();
108 126 queue.Remove(stateA);
109 127
110 128 for (int c = 0; c < AlphabetSize; c++) {
111 129 var stateX = new HashSet<int>();
112 130
113 131 for(int s = 1; s < m_states.Count; s++) {
114 132 if (stateA.Contains(m_states[s].transitions[c]))
115 133 stateX.Add(s);
116 134 }
117 135
118 136 foreach (var stateY in optimalStates.ToArray()) {
119 137 if (stateX.Overlaps(stateY) && !stateY.IsSubsetOf(stateX)) {
120 138 var stateR1 = new HashSet<int>(stateY);
121 139 var stateR2 = new HashSet<int>(stateY);
122 140
123 141 stateR1.IntersectWith(stateX);
124 142 stateR2.ExceptWith(stateX);
125 143
126 144 optimalStates.Remove(stateY);
127 145 optimalStates.Add(stateR1);
128 146 optimalStates.Add(stateR2);
129 147
130 148 if (queue.Contains(stateY)) {
131 149 queue.Remove(stateY);
132 150 queue.Add(stateR1);
133 151 queue.Add(stateR2);
134 152 } else {
135 153 queue.Add(stateR1.Count <= stateR2.Count ? stateR1 : stateR2);
136 154 }
137 155 }
138 156 }
139 157 }
140 158 }
141 159
142 160 // строим ΠΊΠ°Ρ€Ρ‚Ρ‹ соотвСствия ΠΎΠΏΡ‚ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹Ρ… состояний с ΠΎΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½Ρ‹ΠΌΠΈ
143 161
144 162 var initialState = optimalStates.Single(x => x.Contains(INITIAL_STATE));
145 163
146 164 // ΠΊΠ°Ρ€Ρ‚Π° получСния ΠΎΠΏΡ‚ΠΈΠΌΠ°Π»ΡŒΠ½ΠΎΠ³ΠΎ состояния ΠΏΠΎ ΡΠΎΠΎΡ‚Π²Π΅ΡΡ‚Π²ΡƒΡŽΡ‰Π΅ΠΌΡƒ Π΅ΠΌΡƒ простому ΡΠΎΡΡ‚ΠΎΡΠ½ΠΈΡŽ
147 165 int[] reveseOptimalMap = new int[m_states.Count];
148 166 // ΠΊΠ°Ρ€Ρ‚Π° с индСксами ΠΎΠΏΡ‚ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹Ρ… состояний
149 167 HashSet<int>[] optimalMap = new HashSet<int>[optimalStates.Count + 1];
150 168 {
151 169 optimalMap[0] = new HashSet<int>(); // unreachable state
152 170 optimalMap[1] = initialState; // initial state
153 171 foreach (var ss in initialState)
154 172 reveseOptimalMap[ss] = 1;
155 173
156 174 int i = 2;
157 175 foreach (var s in optimalStates) {
158 176 if (s.SetEquals(initialState))
159 177 continue;
160 178 optimalMap[i] = s;
161 179 foreach (var ss in s)
162 180 reveseOptimalMap[ss] = i;
163 181 i++;
164 182 }
165 183 }
166 184
167 185 // ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹ΠΉ Π°Π»Ρ„Π°Π²ΠΈΡ‚
168 186
169 187 var minClasses = new HashSet<HashSet<int>>(setComparer);
170 188 var alphaQueue = new Queue<HashSet<int>>();
171 189 alphaQueue.Enqueue(new HashSet<int>(Enumerable.Range(0,AlphabetSize)));
172 190
173 191 for (int s = 1 ; s < optimalMap.Length; s++) {
174 192 var newQueue = new Queue<HashSet<int>>();
175 193
176 194 foreach (var A in alphaQueue) {
177 195 if (A.Count == 1) {
178 196 minClasses.Add(A);
179 197 continue;
180 198 }
181 199
182 200 // Ρ€Π°Π·Π»ΠΈΡ‡Π°Π΅ΠΌ классы символов, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ пСрСводят Π² Ρ€Π°Π·Π»ΠΈΡ‡Π½Ρ‹Π΅ ΠΎΠΏΡ‚ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹Π΅ состояния
183 201 // optimalState -> alphaClass
184 202 var classes = new Dictionary<int, HashSet<int>>();
185 203
186 204 foreach (var term in A) {
187 205 // ΠΈΡ‰Π΅ΠΌ всС ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄Ρ‹ класса ΠΏΠΎ символу term
188 206 var s2 = reveseOptimalMap[
189 207 optimalMap[s].Select(x => m_states[x].transitions[term]).FirstOrDefault(x => x != 0) // ΠΏΠ΅Ρ€Π²ΠΎΠ΅ допустимоС элСмСнтарноС состояниС, Ссли Π΅ΡΡ‚ΡŒ
190 208 ];
191 209
192 210 HashSet<int> A2;
193 211 if (!classes.TryGetValue(s2, out A2)) {
194 212 A2 = new HashSet<int>();
195 213 newQueue.Enqueue(A2);
196 214 classes[s2] = A2;
197 215 }
198 216 A2.Add(term);
199 217 }
200 218 }
201 219
202 220 if (newQueue.Count == 0)
203 221 break;
204 222 alphaQueue = newQueue;
205 223 }
206 224
207 225 foreach (var A in alphaQueue)
208 226 minClasses.Add(A);
209 227
210 228 var alphabetMap = sourceAlphabet.Reclassify(minimalAlphabet, minClasses);
211 229
212 230 // построСниС Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚Π°
213 231
214 232 var minimalDFA = dfaFactory(minimalAlphabet);
215 233
216 234 var states = new int[ optimalMap.Length ];
217 235 states[0] = UNREACHEBLE_STATE;
218 236
219 237 for(var s = INITIAL_STATE; s < states.Length; s++) {
220 238 var tags = optimalMap[s].SelectMany(x => m_states[x].tag ?? Enumerable.Empty<int>()).Distinct().ToArray();
221 239 if (tags.Length > 0)
222 240 states[s] = minimalDFA.AddState(tags);
223 241 else
224 242 states[s] = minimalDFA.AddState();
225 243 }
226 244
227 245 Debug.Assert(states[INITIAL_STATE] == INITIAL_STATE);
228 246
229 247 for (int s1 = 1; s1 < m_states.Count; s1++) {
230 248 for (int c = 0; c < AlphabetSize; c++) {
231 249 var s2 = m_states[s1].transitions[c];
232 250 if (s2 != UNREACHEBLE_STATE) {
233 251 minimalDFA.DefineTransition(
234 252 reveseOptimalMap[s1],
235 253 reveseOptimalMap[s2],
236 254 alphabetMap[c]
237 255 );
238 256 }
239 257 }
240 258 }
241 259
242 260 return minimalDFA;
243 261 }
244 262
245 263 public void PrintDFA<TA>(IAlphabet<TA> alphabet) {
246 264
247 265 var reverseMap = alphabet.CreateReverseMap();
248 266
249 267 for (int i = 1; i < reverseMap.Length; i++) {
250 268 Console.WriteLine("C{0}: {1}", i, String.Join(",", reverseMap[i]));
251 269 }
252 270
253 271 for (int i = 1; i < m_states.Count; i++) {
254 272 var s = m_states[i];
255 273 for (int c = 0; c < AlphabetSize; c++)
256 274 if (s.transitions[c] != UNREACHEBLE_STATE)
257 275 Console.WriteLine("S{0} -{1}-> S{2}{3}", i, String.Join(",", reverseMap[c]), s.transitions[c], m_states[s.transitions[c]].final ? "$" : "");
258 276 }
259 277 }
260 278
261 279 public int AlphabetSize {
262 280 get {
263 281 return m_alpabetSize;
264 282 }
265 283 }
266 284 }
267 285 }
@@ -1,13 +1,13
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4 4 using System.Text;
5 5 using System.Threading.Tasks;
6 6
7 7 namespace Implab.Parsing {
8 public struct DFAStateDescriptior {
8 public struct DFAStateDescriptior<TTag> {
9 9 public bool final;
10 public int[] tag;
10 public TTag[] tag;
11 11 public int[] transitions;
12 12 }
13 13 }
@@ -1,60 +1,48
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4 4 using System.Text;
5 5 using System.Threading.Tasks;
6 6
7 7 namespace Implab.Parsing {
8 8 /// <summary>
9 9 /// Алфавит. ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚Π²ΠΎ символов, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Ρ€Π°Π·Π±ΠΈΡ‚Ρ‹ Π½Π° классы, ΠΏΡ€ΠΈ этом классы ΠΈΠΌΠ΅ΡŽΡ‚ Π½Π΅ΠΏΡ€Π΅Ρ€Ρ‹Π²Π½ΡƒΡŽ Π½ΡƒΠΌΠ΅Ρ€Π°Ρ†ΠΈΡŽ,
10 10 /// Ρ‡Ρ‚ΠΎ позволяСт ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ ΠΈΡ… Π² качСствС индСксов массивов.
11 11 /// </summary>
12 12 /// <remarks>
13 13 /// <para>Алфавит являСтся ΡΡŽΡ€ΡŒΠ΅ΠΊΡ‚ΠΈΠ²Π½Ρ‹ΠΌ ΠΎΡ‚ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ΠΌ мноТСства символов Π² мноТСство индСксов, это позволяСт ΡΠΎΠΊΡ€Π°Ρ‚ΠΈΡ‚ΡŒ Ρ€Π°Π·ΠΌΠ΅Ρ€ Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹ ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ΠΎΠ² Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚Π°
14 14 /// для Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… символов, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ для Π½Π΅Π³ΠΎ Π½Π΅ Ρ€Π°Π·Π»ΠΈΡ‡ΠΈΠΌΡ‹.</para>
15 /// <para>Π”Π°Π»Π΅Π΅ символами Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° Π±ΡƒΠ΄Π΅ΠΌ Π½Π°Π·Ρ‹Π²Π°Ρ‚ΡŒ классы исходных символов.</para>
16 15 /// </remarks>
17 16 /// <typeparam name="TSymbol">Вип символов.</typeparam>
18 17 public interface IAlphabet<TSymbol> {
19 18 /// <summary>
20 /// ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ символов Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅.
19 /// ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ классов символов Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅.
21 20 /// </summary>
22 21 int Count { get; }
23 /// <summary>
24 /// ДобавляСт Π½ΠΎΠ²Ρ‹ΠΉ символ Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚, Ссли символ ΡƒΠΆΠ΅ Π±Ρ‹Π» Π΄ΠΎΠ±Π°Π²Π»Π΅Π½, Ρ‚ΠΎ
25 /// возвращаСтся Ρ€Π°Π½Π΅Π΅ сопоставлСнный с символом класс.
26 /// </summary>
27 /// <param name="symbol">Бимвол для добавлСния.</param>
28 /// <returns>ИндСкс класса, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ попоставлСн с символом.</returns>
29 int DefineSymbol(TSymbol symbol);
22
30 23 /// <summary>
31 /// ДоабвляСм класс символов. ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚Π²Ρƒ ΡƒΠΊΠ°Π·Π°Π½Π½Ρ‹Ρ… исходных символов
32 /// Π±ΡƒΠ΄Π΅Ρ‚ сопоставлСн символ Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅.
33 /// </summary>
34 /// <param name="symbols">ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚ΠΎΠ² исходных символов</param>
35 /// <returns>Π˜Π΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ символа Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°.</returns>
36 int DefineClass(IEnumerable<TSymbol> symbols);
37 /// <summary>
38 /// Π‘ΠΎΠ·Π΄Π°Π΅Ρ‚ ΠΊΠ°Ρ€Ρ‚Ρƒ ΠΎΠ±Ρ€Π°Ρ‚Π½ΠΎΠ³ΠΎ сопоставлСния символа Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° ΠΈ сопоставлСнным
24 /// Π‘ΠΎΠ·Π΄Π°Π΅Ρ‚ ΠΊΠ°Ρ€Ρ‚Ρƒ ΠΎΠ±Ρ€Π°Ρ‚Π½ΠΎΠ³ΠΎ сопоставлСния класса символов Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° ΠΈ сопоставлСнным
39 25 /// Π΅ΠΌΡƒ исходным символам.
40 26 /// </summary>
41 27 /// <returns></returns>
42 28 List<TSymbol>[] CreateReverseMap();
29
43 30 /// <summary>
44 31 /// Π‘ΠΎΠ·Π΄Π°Π΅Ρ‚ Π½ΠΎΠ²Ρ‹ΠΉ Π°Π»Ρ„Π°Π²ΠΈΡ‚ Π½Π° основС Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ, горппируя Π΅Π³ΠΎ сиволы Π² Π±ΠΎΠ»Π΅Π΅
45 32 /// ΠΊΡ€ΡƒΠΏΠ½Ρ‹Π΅ Π½Π΅ΠΏΠ΅Ρ€Π΅ΡΠ΅ΠΊΠ°ΡŽΡ‰ΠΈΠ΅ΡΡ классы символов.
46 33 /// </summary>
47 34 /// <param name="newAlphabet">Новый, пустой Π°Π»Ρ„Π°Π²ΠΈΡ‚, Π² ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠΌ Π±Ρ‹Π΄ΡƒΡ‚ ΠΎΠΏΡ€Π΅Π΄Π΅Π»Π΅Π½Ρ‹ классы.</param>
48 35 /// <param name="classes">ΠœΠ½ΠΎΠΆΠ΅ΡΡ‚Π²ΠΎ классов символов Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°.</param>
49 /// <returns>ΠšΠ°Ρ€Ρ‚Π° для ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄Π° символов Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ
50 /// Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° ΠΊ символам Π½ΠΎΠ²ΠΎΠ³ΠΎ.</returns>
51 int[] Reclassify(IAlphabet<TSymbol> newAlphabet, IEnumerable<ICollection<int>> classes);
36 /// <returns>ΠšΠ°Ρ€Ρ‚Π° для ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄Π° классов Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ
37 /// Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° ΠΊ классам Π½ΠΎΠ²ΠΎΠ³ΠΎ.</returns>
38 /// <remarks>ΠŸΠΎΠ»Π·Π²ΠΎΠ»ΡΠ΅Ρ‚ ΡƒΠΊΡ€ΡƒΠΏΠ½ΠΈΡ‚ΡŒ Π°Π»Ρ„Π°Π²ΠΈΡ‚, объСдинив классы Π² Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΌ Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅. Π˜ΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ ΠΏΡ€ΠΈ ΠΎΠΏΡ‚ΠΈΠΌΠΈΠ·Π°Ρ†ΠΈΠΈ Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚Π°.</remarks>
39 int[] Reclassify(IAlphabetBuilder<TSymbol> newAlphabet, IEnumerable<ICollection<int>> classes);
52 40
53 41 /// <summary>
54 42 /// ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΡƒΠ΅Ρ‚ Π²Ρ…ΠΎΠ΄Π½ΠΎΠΉ символ Π² индСкс символа ΠΈΠ· Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°.
55 43 /// </summary>
56 44 /// <param name="symobl">Π˜ΡΡ…ΠΎΠ΄Π½Ρ‹ΠΉ символ</param>
57 45 /// <returns>ИндСкс Π² Π°Π»Ρ„Π°Π²ΠΈΡ‚Π΅</returns>
58 46 int Translate(TSymbol symobl);
59 47 }
60 48 }
@@ -1,39 +1,61
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4 4 using System.Text;
5 5 using System.Threading.Tasks;
6 6
7 7 namespace Implab.Parsing {
8 8 /// <summary>
9 /// Π˜Π½Ρ‚Π΅Ρ€Ρ„Π΅ΠΉΡ для опрСдСлСния Π”ΠšΠ, позволяСт Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ состояния ΠΈ ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚ΡŒ ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄Ρ‹.
10 /// </summary>
11 public interface IDFADefinition {
12 /// <summary>
13 /// ДобавляСт состояниС Π² Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚.
14 /// </summary>
15 /// <returns>ИндСкс Π΄ΠΎΠ±Π°Π²Π»Π΅Π½Π½ΠΎΠ³ΠΎ состояния.</returns>
16 int AddState();
17 /// <summary>
18 /// ДобавляСт ΠΊΠΎΠ½Π΅Ρ‡Π½ΠΎΠ΅ состояниС с ΡƒΠΊΠ°Π·Π°Π½Π½Ρ‹ΠΌΠΈ ΠΌΠ΅Ρ‚ΠΊΠ°ΠΌΠΈ, Ссли ΠΌΠ΅Ρ‚ΠΊΠΈ Π½Π΅ Π·Π°Π΄Π°Π½Ρ‹, Ρ‚ΠΎ
19 /// Π΄ΠΎΠ±Π°Π²Π»Π΅Π½Π½ΠΎΠ΅ состояниС Π½Π΅ Π±ΡƒΠ΄Π΅Ρ‚ ΠΊΠΎΠ½Π΅Ρ‡Π½Ρ‹ΠΌ.
9 /// ΠŸΠΎΠ»Π½ΠΎΡΡ‚ΡŒΡŽ описываСт DFA Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚, Π΅Π³ΠΎ ΠΏΠΎΠ²Π΅Π΄Π΅Π½ΠΈΠ΅, состояниС ΠΈ Π²Ρ…ΠΎΠ΄Π½Ρ‹Π΅ символы.
20 10 /// </summary>
21 /// <param name="tags">ΠœΠ΅Ρ‚ΠΊΠΈ состояния.</param>
22 /// <returns>ИндСкс Π΄ΠΎΠ±Π°Π²Π»Π΅Π½Π½ΠΎΠ³ΠΎ состояния.</returns>
23 int AddState(int[] tags);
11 /// <example>
12 /// class MyAutomaton {
13 /// int m_current;
14 /// readonly DFAStateDescriptor<string>[] m_automaton;
15 /// readonly IAlphabet<MyCommands> m_commands;
16 ///
17 /// public MyAutomaton(IDFADefinition&lt;MyCommands,MyStates,string&gt; definition) {
18 /// m_current = definition.StateAlphabet.Translate(MyStates.Initial);
19 /// m_automaton = definition.GetTransitionTable();
20 /// m_commands = definition.InputAlphabet;
21 /// }
22 ///
23 /// // defined a method which will move the automaton to the next state
24 /// public void Move(MyCommands cmd) {
25 /// // use transition map to determine the next state
26 /// var next = m_automaton[m_current].transitions[m_commands.Translate(cmd)];
27 ///
28 /// // validate that we aren't in the unreachable state
29 /// if (next == DFAConst.UNREACHABLE_STATE)
30 /// throw new InvalidOperationException("The specified command is invalid");
31 ///
32 /// // if everything is ok
33 /// m_current = next;
34 /// }
35 /// }
36 /// </example>
37 public interface IDFADefinition<TInput, TState, TTag> {
24 38 /// <summary>
25 /// ΠžΠΏΡ€Π΅Π΄Π΅Π»ΡΠ΅Ρ‚ ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ ΠΌΠ΅ΠΆΠ΄Ρƒ состояниями.
39 /// Алфавит Π²Ρ…ΠΎΠ΄Π½Ρ‹Ρ… символов
26 40 /// </summary>
27 /// <param name="s1">Π˜ΡΡ…ΠΎΠ΄Π½ΠΎΠ΅ состояниС.</param>
28 /// <param name="s2">ΠšΠΎΠ½Π΅Ρ‡Π½ΠΎΠ΅ состояниС.</param>
29 /// <param name="input">Π’Ρ…ΠΎΠ΄Π½ΠΎΠΉ символ.</param>
30 void DefineTransition(int s1, int s2, int input);
41 /// <value>The input alphabet.</value>
42 IAlphabet<TInput> InputAlphabet {
43 get;
44 }
45
31 46 /// <summary>
32 /// Π Π°Π·ΠΌΠ΅Ρ€ Π²Ρ…ΠΎΠ΄Π½ΠΎΠ³ΠΎ Π°Π»Ρ„Π°Π²ΠΈΡ‚Π°.
47 /// Алфавит состояний Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚Π°
33 48 /// </summary>
34 /// <remarks>
35 /// Π Π°Π·ΠΌΠ΅Ρ€ Π²Ρ…ΠΎΠ΄Π½ΠΎΠ³ΠΎ Π°Π»Ρ„Π°Π²ΠΈΡ‚Π° опрСдСляСт количСство Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Ρ‹Ρ… Π²Ρ‹Ρ…ΠΎΠ΄ΠΎΠ² ΠΈΠ· ΠΎΠ΄Π½ΠΎΠ³ΠΎ состояния. <see cref="IAlphabet{TSymbol}.Count"/>
36 /// </remarks>
37 int AlphabetSize { get; }
49 /// <value>The state alphabet.</value>
50 IAlphabet<TState> StateAlphabet {
51 get;
52 }
53
54 /// <summary>
55 /// Π’Π°Π±Π»ΠΈΡ†Π° ΠΏΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ΠΎΠ² состояний Π°Π²Ρ‚ΠΎΠΌΠ°Ρ‚Π°
56 /// </summary>
57 /// <returns>The transition table.</returns>
58 DFAStateDescriptior<TTag>[] GetTransitionTable();
59
38 60 }
39 61 }
@@ -1,118 +1,123
1 1 using System;
2 2 using System.Collections.Generic;
3 3 using System.Linq;
4 4 using System.Text;
5 5 using System.Text.RegularExpressions;
6 6 using System.Diagnostics;
7 7
8 8 namespace Implab
9 9 {
10 10 public static class Safe
11 11 {
12 public static void ArgumentAssert(bool condition, string paramName) {
13 if (!condition)
14 throw new ArgumentException("The parameter is invalid", paramName);
15 }
16
12 17 public static void ArgumentMatch(string value, string paramName, Regex rx) {
13 18 if (rx == null)
14 19 throw new ArgumentNullException("rx");
15 20 if (!rx.IsMatch(value))
16 21 throw new ArgumentException(String.Format("The prameter value must match {0}", rx), paramName);
17 22 }
18 23
19 24 public static void ArgumentNotEmpty(string value, string paramName) {
20 25 if (String.IsNullOrEmpty(value))
21 26 throw new ArgumentException("The parameter can't be empty", paramName);
22 27 }
23 28
24 29 public static void ArgumentNotEmpty<T>(T[] value, string paramName) {
25 30 if (value == null || value.Length == 0)
26 31 throw new ArgumentException("The array must be not emty", paramName);
27 32 }
28 33
29 34 public static void ArgumentNotNull(object value, string paramName) {
30 35 if (value == null)
31 36 throw new ArgumentNullException(paramName);
32 37 }
33 38
34 39 public static void ArgumentInRange(int value, int min, int max, string paramName) {
35 40 if (value < min || value > max)
36 41 throw new ArgumentOutOfRangeException(paramName);
37 42 }
38 43
39 44 public static void Dispose(params IDisposable[] objects) {
40 45 foreach (var d in objects)
41 46 if (d != null)
42 47 d.Dispose();
43 48 }
44 49
45 50 public static void Dispose(params object[] objects) {
46 51 foreach (var obj in objects) {
47 52 var d = obj as IDisposable;
48 53 if (d != null)
49 54 d.Dispose();
50 55 }
51 56 }
52 57
53 58 public static void Dispose(object obj) {
54 59 var d = obj as IDisposable;
55 60 if (d != null)
56 61 d.Dispose();
57 62 }
58 63
59 64 [DebuggerStepThrough]
60 65 public static IPromise<T> WrapPromise<T>(Func<T> action) {
61 66 ArgumentNotNull(action, "action");
62 67
63 68 var p = new Promise<T>();
64 69 try {
65 70 p.Resolve(action());
66 71 } catch (Exception err) {
67 72 p.Reject(err);
68 73 }
69 74
70 75 return p;
71 76 }
72 77
73 78 [DebuggerStepThrough]
74 79 public static IPromise WrapPromise(Action action) {
75 80 ArgumentNotNull(action, "action");
76 81
77 82 var p = new Promise();
78 83 try {
79 84 action();
80 85 p.Resolve();
81 86 } catch (Exception err) {
82 87 p.Reject(err);
83 88 }
84 89
85 90 return p;
86 91 }
87 92
88 93 [DebuggerStepThrough]
89 94 public static IPromise InvokePromise(Func<IPromise> action) {
90 95 ArgumentNotNull(action, "action");
91 96
92 97 try {
93 98 var p = action();
94 99 if (p == null) {
95 100 var d = new Promise();
96 101 d.Reject(new Exception("The action returned null"));
97 102 p = d;
98 103 }
99 104 return p;
100 105 } catch (Exception err) {
101 106 var p = new Promise();
102 107 p.Reject(err);
103 108 return p;
104 109 }
105 110 }
106 111
107 112 [DebuggerStepThrough]
108 113 public static IPromise<T> InvokePromise<T>(Func<IPromise<T>> action) {
109 114 ArgumentNotNull(action, "action");
110 115
111 116 try {
112 117 return action() ?? Promise<T>.FromException(new Exception("The action returned null"));
113 118 } catch (Exception err) {
114 119 return Promise<T>.FromException(err);
115 120 }
116 121 }
117 122 }
118 123 }
General Comments 0
You need to be logged in to leave comments. Login now