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