├── .gitattributes
├── .gitignore
├── CodeParser.Test
├── CodeParser.Test.csproj
├── Examples
│ ├── HelloWorld.cs
│ ├── HelloWorld.js
│ ├── HelloWorld.py
│ └── Helloworld.cpp
├── ParserHelper.cs
├── ParserTest
│ ├── CSharpParserTest.cs
│ ├── CodeParserTest.cs
│ ├── CppParserTest.cs
│ ├── JavaScriptParserTest.cs
│ └── PythonParserTest.cs
└── Program.cs
├── CodeParser.Viewer
├── App.config
├── CodeParser.Viewer.csproj
├── Model
│ ├── SqlSyntaxError.cs
│ └── TokenInfo.cs
├── Program.cs
├── Properties
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ ├── Settings.Designer.cs
│ └── Settings.settings
├── Resources
│ └── magic.ico
├── SqlSyntaxErrorListener.cs
├── frmMain.cs
├── frmMain.designer.cs
├── frmMain.resx
└── packages.config
├── CodeParser.sln
├── CodeParser
├── CodeParser.csproj
├── Manager
│ └── ParserManager.cs
├── Model
│ └── ParserInfo.cs
└── Parser
│ ├── C
│ ├── CBaseListener.cs
│ ├── CLexer.cs
│ ├── CListener.cs
│ └── CParser.cs
│ ├── CSharp
│ ├── CSharpLexer.cs
│ ├── CSharpLexerBase.cs
│ ├── CSharpParser.cs
│ ├── CSharpParserBase.cs
│ ├── CSharpParserBaseListener.cs
│ └── CSharpParserListener.cs
│ ├── Cpp
│ ├── CPP14BaseListener.cs
│ ├── CPP14Lexer.cs
│ ├── CPP14Listener.cs
│ └── CPP14Parser.cs
│ ├── Java
│ ├── Java8Lexer.cs
│ ├── Java8Parser.cs
│ ├── Java8ParserBaseListener.cs
│ ├── Java8ParserListener.cs
│ ├── Java9BaseListener.cs
│ ├── Java9Lexer.cs
│ ├── Java9LexerBase.cs
│ ├── Java9Listener.cs
│ ├── Java9Parser.cs
│ ├── Java9ParserBaseListener.cs
│ └── Java9ParserListener.cs
│ ├── JavaScript
│ ├── JavaScriptLexer.cs
│ ├── JavaScriptLexerBase.cs
│ ├── JavaScriptParser.cs
│ ├── JavaScriptParserBase.cs
│ ├── JavaScriptParserBaseListener.cs
│ └── JavaScriptParserListener.cs
│ ├── LexerDispatchingErrorListener.cs
│ ├── MySql
│ ├── IMySqlRecognizerCommon.cs
│ ├── MySqlBaseLexer.cs
│ ├── MySqlBaseRecognizer.cs
│ ├── MySqlLexer.cs
│ ├── MySqlMode.cs
│ ├── MySqlParser.cs
│ ├── MySqlParserBaseListener.cs
│ ├── MySqlParserListener.cs
│ ├── MySqlParsersCommon.cs
│ ├── MySqlRecognizerCommon.cs
│ └── MySqlServerVersion.cs
│ ├── ParserDispatchingErrorListener.cs
│ ├── Php
│ ├── PhpLexer.cs
│ ├── PhpLexerBase.cs
│ ├── PhpParser.cs
│ ├── PhpParserBaseListener.cs
│ └── PhpParserListener.cs
│ ├── PlSql
│ ├── PlSqlLexer.cs
│ ├── PlSqlLexerBase.cs
│ ├── PlSqlParser.cs
│ ├── PlSqlParserBase.cs
│ ├── PlSqlParserBaseListener.cs
│ └── PlSqlParserListener.cs
│ ├── PostgreSql
│ ├── PostgreSqlLexer.cs
│ ├── PostgreSqlLexerBase.cs
│ ├── PostgreSqlParser.cs
│ ├── PostgreSqlParserBase.cs
│ ├── PostgreSqlParserBaseListener.cs
│ └── PostgreSqlParserListener.cs
│ ├── Python
│ ├── Python3Lexer.cs
│ ├── Python3LexerBase.cs
│ ├── Python3Parser.cs
│ ├── Python3ParserBaseListener.cs
│ └── Python3ParserListener.cs
│ ├── SQLite
│ ├── SQLiteLexer.cs
│ ├── SQLiteParser.cs
│ ├── SQLiteParserBaseListener.cs
│ └── SQLiteParserListener.cs
│ └── TSql
│ ├── TSqlLexer.cs
│ ├── TSqlParser.cs
│ ├── TSqlParserBaseListener.cs
│ └── TSqlParserListener.cs
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
262 | /CodeParser.Test/Examples/Tsql_view.sql
263 | /CodeParser.Test/ParserTest/TsqlParserTest.cs
264 |
--------------------------------------------------------------------------------
/CodeParser.Test/CodeParser.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | PreserveNewest
22 |
23 |
24 | PreserveNewest
25 |
26 |
27 | PreserveNewest
28 |
29 |
30 | PreserveNewest
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/CodeParser.Test/Examples/HelloWorld.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.IO;
6 |
7 | namespace Demo
8 | {
9 | public interface ISpeech
10 | {
11 | string Name { get; }
12 | void SayHello(string word);
13 | }
14 |
15 | public delegate void SayHelloHandler(string word);
16 |
17 | public class CSharpHelloWord : ISpeech
18 | {
19 | public event SayHelloHandler OnSayHello;
20 |
21 | public string owner;
22 | public string Owner
23 | {
24 | get { return this.owner; }
25 | set { this.owner = value; }
26 | }
27 |
28 | public void SayHello(string word)
29 | {
30 | Console.WriteLine(word);
31 | }
32 | }
33 |
34 | public enum SayMode
35 | {
36 | Default,
37 | Custom
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/CodeParser.Test/Examples/HelloWorld.js:
--------------------------------------------------------------------------------
1 | import { Helper } from '/modules/util.js';
2 |
3 | var owner = "";
4 |
5 | function test(word) {
6 | var helloWord = new helloWord();
7 | helloWord.sayHello(word);
8 | }
9 |
10 | var helloWord = {
11 | owner: "",
12 | target: "",
13 | sayHello: function (word) {
14 | alert(word);
15 | }
16 | };
17 |
18 | export function sayHello(word) {
19 | test("Hello");
20 | }
21 |
22 | export { sayHello as say };
--------------------------------------------------------------------------------
/CodeParser.Test/Examples/HelloWorld.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | class HelloWorld():
4 | owner = ""
5 | target = ""
6 | def sayHello(self, word):
7 | print(word)
8 |
9 | x = HelloWorld()
10 |
11 | x.sayHello("Hello")
12 |
--------------------------------------------------------------------------------
/CodeParser.Test/Examples/Helloworld.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 | main()
7 | {
8 | cout << "Hello World!";
9 | return 0;
10 | }
11 |
12 | class HelloWorld
13 | {
14 | public:
15 | string owner, target;
16 | int age;
17 |
18 |
19 | public:
20 | void sayHello(string word)
21 | {
22 | cout << word;
23 | }
24 |
25 | void test()
26 | {
27 | cout << "Test";
28 | }
29 | };
30 |
31 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Reflection;
4 |
5 | namespace CodeParser.Test
6 | {
7 | public class ParserHelper
8 | {
9 |
10 | public static CodeParserTest GetParserTest(string language)
11 | {
12 | var assembly = Assembly.GetExecutingAssembly();
13 | var typeArray = assembly.ExportedTypes;
14 |
15 | var types = (from type in typeArray
16 | where type.IsSubclassOf(typeof(CodeParserTest))
17 | select type).ToList();
18 |
19 | foreach (var type in types)
20 | {
21 | CodeParserTest codeParserTest = (CodeParserTest)Activator.CreateInstance(type);
22 |
23 | if (codeParserTest.Language == language)
24 | {
25 | return codeParserTest;
26 | }
27 | }
28 |
29 | return null;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserTest/CSharpParserTest.cs:
--------------------------------------------------------------------------------
1 | using Antlr4.Runtime;
2 | using Antlr4.Runtime.Tree;
3 | using System;
4 | using System.IO;
5 | using System.Linq;
6 | using static CSharpParser;
7 |
8 | namespace CodeParser.Test
9 | {
10 | public class CSharpParserTest : CodeParserTest
11 | {
12 | public override string Language => "C#";
13 |
14 | public override void Parse(FileInfo file)
15 | {
16 | Lexer lexer = new CSharpLexer(CharStreams.fromPath(file.FullName));
17 |
18 | CommonTokenStream tokens = new CommonTokenStream(lexer);
19 |
20 | CSharpParser parser = new CSharpParser(tokens);
21 |
22 | ParserRuleContext context = parser.compilation_unit();
23 |
24 | var children = context.children;
25 |
26 | foreach (IParseTree child in children)
27 | {
28 | this.ParseNode(child);
29 | }
30 | }
31 |
32 | private void ParseNode(IParseTree node)
33 | {
34 | if (node is Using_directivesContext)
35 | {
36 | Using_directivesContext usingContext = node as Using_directivesContext;
37 | UsingNamespaceDirectiveContext[] usingNamespaces = usingContext.GetRuleContexts();
38 | foreach (UsingNamespaceDirectiveContext ns in usingNamespaces)
39 | {
40 | string name = ns.namespace_or_type_name().GetText();
41 | this.WriteKeyValue("Using", name);
42 | }
43 | }
44 | else if (node is Namespace_member_declarationsContext)
45 | {
46 | Namespace_member_declarationsContext nsMemberContext = node as Namespace_member_declarationsContext;
47 |
48 | Namespace_member_declarationContext[] members = nsMemberContext.namespace_member_declaration();
49 |
50 | foreach (Namespace_member_declarationContext member in members)
51 | {
52 | Type memberType = member.children[0].GetType();
53 |
54 | Namespace_declarationContext[] nses = member.GetRuleContexts();
55 | Type_declarationContext[] types = member.GetRuleContexts();
56 |
57 | foreach (Namespace_declarationContext ns in nses)
58 | {
59 | string name = this.GetNodeName(ns.qualified_identifier().identifier().First());
60 |
61 | this.WriteKeyValue("Namespace", name);
62 |
63 | var childMembers = ns.namespace_body().namespace_member_declarations().namespace_member_declaration();
64 |
65 | foreach (var childMember in childMembers)
66 | {
67 | var childMemberDeclaration = childMember.children[0];
68 |
69 | if (childMemberDeclaration is Type_declarationContext)
70 | {
71 | this.ParseTypeDeclaration(childMemberDeclaration as Type_declarationContext);
72 | }
73 | }
74 | }
75 |
76 | foreach (Type_declarationContext t in types)
77 | {
78 | this.ParseTypeDeclaration(t);
79 | }
80 | }
81 | }
82 | }
83 |
84 | private void ParseTypeDeclaration(Type_declarationContext node)
85 | {
86 | Class_definitionContext classContext = node.class_definition();
87 | Interface_definitionContext interfaceContext = node.interface_definition();
88 | Delegate_definitionContext delegateContext = node.delegate_definition();
89 | Enum_definitionContext enumContext = node.enum_definition();
90 |
91 | bool isClass = classContext != null;
92 | bool isInterface = interfaceContext != null;
93 | bool isDelegate = delegateContext != null;
94 | bool isEnum = enumContext != null;
95 |
96 | string type = "";
97 | string name = "";
98 | if (isClass)
99 | {
100 | type = "Class";
101 | name = this.GetNodeName(classContext.identifier());
102 | }
103 | else if (isInterface)
104 | {
105 | type = "Interface";
106 | name = this.GetNodeName(interfaceContext.identifier());
107 | }
108 | else if (isDelegate)
109 | {
110 | type = "Delegate";
111 | name = this.GetNodeName(delegateContext.identifier());
112 | }
113 | else if (isEnum)
114 | {
115 | type = "Enum";
116 | name = this.GetNodeName(enumContext.identifier());
117 | }
118 |
119 | if (!string.IsNullOrEmpty(name))
120 | {
121 | this.WriteLine();
122 | this.WriteKeyValue(type, name);
123 | }
124 |
125 | if (isClass)
126 | {
127 | this.WriteBeginBrace();
128 | this.ParseClassDeclaration(classContext);
129 | this.WriteEndBrace();
130 | }
131 | else if (isInterface)
132 | {
133 | this.WriteBeginBrace();
134 | this.ParseInterfaceDeclaration(interfaceContext);
135 | this.WriteEndBrace();
136 | }
137 | }
138 |
139 | private void ParseClassDeclaration(Class_definitionContext node)
140 | {
141 | var members = node.class_body().class_member_declarations().class_member_declaration();
142 | foreach (var member in members)
143 | {
144 | Common_member_declarationContext child = member.GetRuleContext(0);
145 |
146 | if (child is Common_member_declarationContext)
147 | {
148 | Common_member_declarationContext commonMemberContext = child as Common_member_declarationContext;
149 |
150 | Event_declarationContext eventContext = commonMemberContext.event_declaration();
151 | Typed_member_declarationContext typeMemberContext = commonMemberContext.typed_member_declaration();
152 | Method_declarationContext methodContext = commonMemberContext.method_declaration();
153 |
154 | string type = "";
155 | string name = "";
156 |
157 | if (eventContext != null)
158 | {
159 | type = "Event";
160 | name = eventContext.variable_declarators().GetText();
161 | }
162 |
163 | if (typeMemberContext != null)
164 | {
165 | Field_declarationContext field = typeMemberContext.field_declaration();
166 | Property_declarationContext property = typeMemberContext.property_declaration();
167 |
168 | if (field != null)
169 | {
170 | type = "Field";
171 | name = field.variable_declarators().GetText();
172 | }
173 | else if (property != null)
174 | {
175 | type = "Property";
176 | name = property.member_name().GetText();
177 | }
178 | }
179 | else if (methodContext != null)
180 | {
181 | type = "Method";
182 | name = methodContext.method_member_name().GetText();
183 | }
184 |
185 | if (!string.IsNullOrEmpty(name))
186 | {
187 | this.WriteKeyValue(type, name);
188 | }
189 | }
190 | }
191 | }
192 |
193 | private void ParseInterfaceDeclaration(Interface_definitionContext node)
194 | {
195 | var members = node.class_body().class_member_declarations();
196 |
197 | foreach (var member in members.children)
198 | {
199 | if (member is Interface_member_declarationContext)
200 | {
201 | Interface_member_declarationContext memberContext = member as Interface_member_declarationContext;
202 | Type_Context typeContext = memberContext.type_();
203 |
204 | bool isProperty = typeContext != null;
205 |
206 | IdentifierContext identifierContext = memberContext.identifier();
207 |
208 | if (identifierContext != null)
209 | {
210 | string name = this.GetNodeName(identifierContext);
211 | this.WriteKeyValue((isProperty ? "Property" : "Method"), name);
212 | }
213 | }
214 | }
215 | }
216 |
217 | protected string GetNodeName(IdentifierContext node)
218 | {
219 | return node.GetText();
220 | }
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserTest/CodeParserTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace CodeParser.Test
5 | {
6 | public abstract class CodeParserTest
7 | {
8 | public virtual string SubFolder { get; set; }
9 | public abstract string Language { get; }
10 |
11 | protected int indent = 0;
12 |
13 | public void Parse(ParserInfo info)
14 | {
15 | DirectoryInfo di = new DirectoryInfo("Examples" + (!string.IsNullOrEmpty(this.SubFolder) ? ("/" + this.SubFolder) : ""));
16 |
17 | FileInfo[] files = di.GetFiles("*" + info.FileExtension);
18 |
19 | foreach (var file in files)
20 | {
21 | this.WriteLine();
22 | this.WriteLine($"{file.Name}");
23 | this.WriteBeginBoundaryLine();
24 | this.Parse(file);
25 | this.WriteEndBoundaryLine();
26 | }
27 | }
28 |
29 | protected void WriteLine()
30 | {
31 | this.WriteLine("");
32 | }
33 |
34 | protected void WriteBeginBoundaryLine()
35 | {
36 | this.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
37 | }
38 |
39 | protected void WriteEndBoundaryLine()
40 | {
41 | this.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
42 | }
43 |
44 | protected void WriteBeginBrace(int indent = 0)
45 | {
46 | this.WriteLine(this.GetIndent(indent) + "{");
47 | }
48 |
49 | protected void WriteEndBrace(int indent = 0)
50 | {
51 | this.WriteLine(this.GetIndent(indent) + "}");
52 | }
53 |
54 | public virtual void Parse(FileInfo file) { }
55 |
56 | protected void WriteKeyValue(string key, string value, int indent=0)
57 | {
58 | this.WriteLine(this.GetIndent(indent) + $"{key}:{value}");
59 | }
60 |
61 | protected void WriteLine(string text, int indent=0)
62 | {
63 | Console.WriteLine(this.GetIndent(indent) + text);
64 | }
65 |
66 | protected void Write(string text, int indent = 0)
67 | {
68 | Console.Write(this.GetIndent(indent) + text);
69 | }
70 |
71 | private string GetIndent(int indent)
72 | {
73 | return "".PadLeft(indent, ' ');
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserTest/CppParserTest.cs:
--------------------------------------------------------------------------------
1 | using Antlr4.Runtime;
2 | using Antlr4.Runtime.Tree;
3 | using System.IO;
4 | using static CPP14Parser;
5 |
6 | namespace CodeParser.Test
7 | {
8 | public class CppParserTest : CodeParserTest
9 | {
10 | public override string Language => "C++";
11 |
12 | public override void Parse(FileInfo file)
13 | {
14 | Lexer lexer = new CPP14Lexer(CharStreams.fromPath(file.FullName));
15 |
16 | CommonTokenStream tokens = new CommonTokenStream(lexer);
17 |
18 | CPP14Parser parser = new CPP14Parser(tokens);
19 |
20 | ParserRuleContext context = parser.translationunit();
21 |
22 | var children = context.children;
23 |
24 | foreach (IParseTree child in children)
25 | {
26 | this.ParseNode(child);
27 | }
28 | }
29 |
30 | private void ParseNode(IParseTree node)
31 | {
32 | if (node is DeclarationseqContext)
33 | {
34 | DeclarationseqContext declarationseqContext = node as DeclarationseqContext;
35 | this.ParseDeclarationseq(declarationseqContext);
36 | }
37 | }
38 |
39 | private void ParseDeclarationseq(DeclarationseqContext node)
40 | {
41 | DeclarationseqContext declareSq = node.declarationseq();
42 | DeclarationContext declare = node.declaration();
43 |
44 | if (declareSq != null)
45 | {
46 | this.ParseDeclarationseq(declareSq);
47 | }
48 |
49 | if (declare != null)
50 | {
51 | AttributedeclarationContext attribute = declare.attributedeclaration();
52 | FunctiondefinitionContext function = declare.functiondefinition();
53 | BlockdeclarationContext block = declare.blockdeclaration();
54 |
55 | if (block != null)
56 | {
57 | UsingdirectiveContext usingDirective = block.usingdirective();
58 | SimpledeclarationContext simpleDeclaration = block.simpledeclaration();
59 |
60 | if (usingDirective != null)
61 | {
62 | string name = usingDirective.namespacename().GetText();
63 |
64 | this.WriteKeyValue("Using", name);
65 | }
66 | else if (simpleDeclaration != null)
67 | {
68 | DeclspecifierseqContext[] decls = simpleDeclaration.GetRuleContexts();
69 |
70 | foreach (DeclspecifierseqContext decl in decls)
71 | {
72 | DeclspecifierContext declSpec = decl.declspecifier();
73 | TypespecifierContext typeSpec = declSpec.typespecifier();
74 |
75 | if (typeSpec != null)
76 | {
77 | ClassspecifierContext classSpec = typeSpec.classspecifier();
78 | EnumspecifierContext enumSpec = typeSpec.enumspecifier();
79 |
80 | if (classSpec != null)
81 | {
82 | string className = classSpec.classhead().classheadname().GetText();
83 |
84 | this.WriteLine();
85 | this.WriteKeyValue("Class", className);
86 | this.WriteBeginBrace();
87 |
88 | MemberspecificationContext[] members = classSpec.GetRuleContexts();
89 |
90 | foreach (MemberspecificationContext member in members)
91 | {
92 | MemberspecificationContext[] memberSpecs = member.GetRuleContexts();
93 |
94 | foreach (MemberspecificationContext memberSpec in memberSpecs)
95 | {
96 | MemberdeclarationContext memberDeclaration = memberSpec.memberdeclaration();
97 | MemberspecificationContext memberSpecDeclaration = memberSpec.memberspecification();
98 |
99 | this.ParseMemberDeclaration(memberDeclaration);
100 | this.ParseMemberSpecification(memberSpecDeclaration);
101 | }
102 | }
103 |
104 | this.WriteEndBrace();
105 | }
106 | }
107 | }
108 | }
109 | }
110 | else if (function != null)
111 | {
112 | this.ParseFunction(function);
113 | }
114 | }
115 | }
116 |
117 | private void ParseFunction(FunctiondefinitionContext node)
118 | {
119 | PtrdeclaratorContext[] ptrs = node.declarator().GetRuleContexts();
120 |
121 | foreach (PtrdeclaratorContext ptr in ptrs)
122 | {
123 | NoptrdeclaratorContext noptr = ptr.noptrdeclarator();
124 | string name = noptr.noptrdeclarator().GetText();
125 |
126 | this.WriteKeyValue("Function", name);
127 | }
128 | }
129 |
130 | private void ParseMemberDeclaration(MemberdeclarationContext node)
131 | {
132 | if (node != null)
133 | {
134 | MemberspecificationContext[] memberSpecs = node.GetRuleContexts();
135 |
136 | MemberdeclaratorlistContext[] fields = node.GetRuleContexts();
137 | FunctiondefinitionContext[] funcs = node.GetRuleContexts();
138 |
139 | if (fields != null)
140 | {
141 | foreach (MemberdeclaratorlistContext field in fields)
142 | {
143 | foreach (string name in field.GetText().Split(','))
144 | {
145 | this.WriteKeyValue("Field", name);
146 | }
147 | }
148 | }
149 |
150 | if (funcs != null)
151 | {
152 | foreach (FunctiondefinitionContext func in funcs)
153 | {
154 | this.ParseFunction(func);
155 | }
156 | }
157 | }
158 | }
159 |
160 | private void ParseMemberSpecification(MemberspecificationContext node)
161 | {
162 | if (node != null)
163 | {
164 | MemberdeclarationContext[] members = node.GetRuleContexts();
165 | MemberspecificationContext[] memberSpecs = node.GetRuleContexts();
166 |
167 | foreach (MemberdeclarationContext member in members)
168 | {
169 | this.ParseMemberDeclaration(member);
170 | }
171 |
172 | foreach (MemberspecificationContext memberSpec in memberSpecs)
173 | {
174 | this.ParseMemberSpecification(memberSpec);
175 | }
176 | }
177 | }
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserTest/JavaScriptParserTest.cs:
--------------------------------------------------------------------------------
1 | using Antlr4.Runtime;
2 | using Antlr4.Runtime.Tree;
3 | using System.IO;
4 | using System.Linq;
5 | using static JavaScriptParser;
6 |
7 | namespace CodeParser.Test
8 | {
9 | public class JavaScriptParserTest : CodeParserTest
10 | {
11 | public override string Language => "JavaScript";
12 |
13 | public override void Parse(FileInfo file)
14 | {
15 | Lexer lexer = new JavaScriptLexer(CharStreams.fromPath(file.FullName));
16 |
17 | CommonTokenStream tokens = new CommonTokenStream(lexer);
18 |
19 | JavaScriptParser parser = new JavaScriptParser(tokens);
20 |
21 | ParserRuleContext context = parser.program();
22 |
23 | var children = context.children;
24 |
25 | foreach (IParseTree child in children)
26 | {
27 | this.ParseNode(child);
28 | }
29 | }
30 |
31 | private void ParseNode(IParseTree node)
32 | {
33 | if (node is SourceElementsContext)
34 | {
35 | SourceElementsContext elementsContext = node as SourceElementsContext;
36 | SourceElementContext[] srcElements = elementsContext.sourceElement();
37 | foreach (SourceElementContext srcElement in srcElements)
38 | {
39 | StatementContext statementContext = srcElement.statement();
40 | VariableStatementContext varStatementContext = statementContext.variableStatement();
41 | FunctionDeclarationContext functionContext = statementContext.functionDeclaration();
42 | ImportStatementContext importContext = statementContext.importStatement();
43 | ExportStatementContext exportContext = statementContext.exportStatement();
44 |
45 | if (varStatementContext != null)
46 | {
47 | VariableDeclarationListContext variableListContex = varStatementContext.variableDeclarationList();
48 |
49 | if (variableListContex != null)
50 | {
51 | var variables = variableListContex.children;
52 |
53 | foreach (var variable in variables)
54 | {
55 | if (variable is VariableDeclarationContext)
56 | {
57 | VariableDeclarationContext declarationContext = variable as VariableDeclarationContext;
58 | string name = declarationContext.assignable().GetText();
59 |
60 | ObjectLiteralExpressionContext[] exps = declarationContext.GetRuleContexts();
61 |
62 | if (exps == null || exps.Length == 0)
63 | {
64 | this.WriteKeyValue("Field", name);
65 | }
66 | else
67 | {
68 | this.WriteKeyValue("Class", name);
69 | this.WriteBeginBrace();
70 |
71 | foreach (ObjectLiteralExpressionContext exp in exps)
72 | {
73 | ObjectLiteralContext literalContext = exp.objectLiteral();
74 | PropertyAssignmentContext[] properties = literalContext.propertyAssignment();
75 |
76 | foreach (PropertyAssignmentContext property in properties)
77 | {
78 | PropertyNameContext propertyNameContext = property.GetRuleContext(0);
79 | FunctionExpressionContext funcExpContext = property.GetRuleContext(0);
80 |
81 | bool isFunction = funcExpContext != null;
82 |
83 | string propertyName = propertyNameContext.identifierName().GetText();
84 |
85 | this.WriteKeyValue(isFunction ? "Function" : "Property", propertyName);
86 | }
87 | }
88 |
89 | this.WriteEndBrace();
90 | }
91 | }
92 | }
93 | }
94 | }
95 | else if (functionContext != null)
96 | {
97 | string name = functionContext.identifier().GetText();
98 | this.WriteKeyValue("Function", name);
99 | }
100 | else if (importContext != null)
101 | {
102 | ImportFromBlockContext fromContext = importContext.importFromBlock();
103 | ModuleItemsContext[] moduleItems = fromContext.GetRuleContexts();
104 | foreach (ModuleItemsContext module in moduleItems)
105 | {
106 | AliasNameContext[] aliasNames = module.aliasName();
107 | foreach (AliasNameContext aliasName in aliasNames)
108 | {
109 | string name = aliasName.identifierName().LastOrDefault().GetText();
110 | this.WriteKeyValue("Import", name);
111 | }
112 | }
113 | }
114 | else if (exportContext != null)
115 | {
116 | DeclarationContext[] declarations = exportContext.GetRuleContexts();
117 | ExportFromBlockContext[] exportBlocks = exportContext.GetRuleContexts();
118 |
119 | foreach (DeclarationContext declaration in declarations)
120 | {
121 | FunctionDeclarationContext funcContext = declaration.functionDeclaration();
122 |
123 | if (funcContext != null)
124 | {
125 | string name = funcContext.identifier().GetText();
126 |
127 | this.WriteKeyValue("Export", name);
128 | }
129 | }
130 |
131 | foreach (ExportFromBlockContext exportBlock in exportBlocks)
132 | {
133 | ModuleItemsContext[] moduleItems = exportBlock.GetRuleContexts();
134 | foreach (ModuleItemsContext module in moduleItems)
135 | {
136 | AliasNameContext[] aliasNames = module.aliasName();
137 | foreach (AliasNameContext aliasName in aliasNames)
138 | {
139 | IdentifierNameContext[] identifierNames = aliasName.identifierName();
140 | string name = identifierNames.LastOrDefault().identifier().GetText();
141 | this.WriteKeyValue("Export", name);
142 | }
143 | }
144 | }
145 | }
146 | }
147 | }
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/CodeParser.Test/ParserTest/PythonParserTest.cs:
--------------------------------------------------------------------------------
1 | using Antlr4.Runtime;
2 | using Antlr4.Runtime.Tree;
3 | using System.IO;
4 | using System.Linq;
5 | using static Python3Parser;
6 |
7 | namespace CodeParser.Test
8 | {
9 | public class PythonParserTest : CodeParserTest
10 | {
11 | public override string Language => "Python3";
12 |
13 | public override void Parse(FileInfo file)
14 | {
15 | Lexer lexer = new Python3Lexer(CharStreams.fromPath(file.FullName));
16 |
17 | CommonTokenStream tokens = new CommonTokenStream(lexer);
18 |
19 | Python3Parser parser = new Python3Parser(tokens);
20 |
21 | ParserRuleContext context = parser.file_input();
22 |
23 | var children = context.children;
24 |
25 | foreach (IParseTree child in children)
26 | {
27 | this.ParseNode(child);
28 | }
29 | }
30 |
31 | private void ParseNode(IParseTree node)
32 | {
33 | if (node is StmtContext stmtContext)
34 | {
35 | Compound_stmtContext compound_Stmt = stmtContext.compound_stmt();
36 |
37 | if (compound_Stmt != null)
38 | {
39 | ClassdefContext[] classdefs = compound_Stmt.GetRuleContexts();
40 |
41 | foreach (ClassdefContext classdef in classdefs)
42 | {
43 | string name = classdef.NAME().GetText();
44 |
45 | this.WriteLine();
46 | this.WriteKeyValue("Class", name);
47 |
48 | this.WriteBeginBrace();
49 |
50 | this.ParseClassContext(classdef);
51 |
52 | this.WriteEndBrace();
53 | }
54 | }
55 | }
56 | }
57 |
58 | private void ParseClassContext(ClassdefContext node)
59 | {
60 | var suits = node.GetRuleContexts();
61 |
62 | foreach (SuiteContext suit in suits)
63 | {
64 | var stmts = suit.stmt();
65 |
66 | foreach (StmtContext stmt in stmts)
67 | {
68 | Simple_stmtContext simple_Stmt = stmt.simple_stmt();
69 | Compound_stmtContext compound_Stmt = stmt.compound_stmt();
70 |
71 | if (compound_Stmt != null)
72 | {
73 | var funcs = compound_Stmt.GetRuleContexts();
74 |
75 | foreach (FuncdefContext func in funcs)
76 | {
77 | string name = func.NAME().GetText();
78 |
79 | this.WriteKeyValue("Method", name);
80 | }
81 | }
82 | else if (simple_Stmt != null)
83 | {
84 | var exprs = simple_Stmt.GetRuleContexts();
85 |
86 | foreach (var expr in exprs)
87 | {
88 | Testlist_star_exprContext[] ss = expr.GetRuleContexts();
89 |
90 | string name = ss.FirstOrDefault()?.GetText();
91 |
92 | if (!string.IsNullOrEmpty(name))
93 | {
94 | this.WriteKeyValue("Field", name);
95 | }
96 | }
97 | }
98 | }
99 | }
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/CodeParser.Test/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace CodeParser.Test
4 | {
5 | class Program
6 | {
7 | static void Main(string[] args)
8 | {
9 | Parse("Python3");
10 | Parse("C#");
11 | Parse("JavaScript");
12 | Parse("C++");
13 |
14 | Console.ReadLine();
15 | }
16 |
17 | static void Parse(string language)
18 | {
19 | CodeParserTest codeParserTest = ParserHelper.GetParserTest(language);
20 | if (codeParserTest != null)
21 | {
22 | ParserInfo info = ParserManager.GetParserInfoByLanguage(language);
23 |
24 | if(info!=null)
25 | {
26 | codeParserTest.Parse(info);
27 | }
28 | else
29 | {
30 | Console.WriteLine($"Can't get ParserInfo for language \"{language}\".");
31 | }
32 | }
33 | else
34 | {
35 | Console.WriteLine($"There's no parser test class for language \"{language}\".");
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/CodeParser.Viewer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {8E724F0A-1E47-45EF-918F-ED468F046289}
8 | WinExe
9 | CodeParser.Viewer
10 | CodeParser.Viewer
11 | v4.6.1
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 | Resources\magic.ico
37 |
38 |
39 |
40 | ..\packages\Antlr4.Runtime.Standard.4.10.1\lib\netstandard2.0\Antlr4.Runtime.Standard.dll
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | Form
57 |
58 |
59 | frmMain.cs
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | frmMain.cs
68 |
69 |
70 | ResXFileCodeGenerator
71 | Resources.Designer.cs
72 | Designer
73 |
74 |
75 | True
76 | Resources.resx
77 | True
78 |
79 |
80 |
81 | SettingsSingleFileGenerator
82 | Settings.Designer.cs
83 |
84 |
85 | True
86 | Settings.settings
87 | True
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | {fd9c0211-571b-497b-88b4-fc145e07f03c}
99 | CodeParser
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Model/SqlSyntaxError.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Text;
3 |
4 | namespace CodeParser.Viewer
5 | {
6 | public class SqlSyntaxError
7 | {
8 | public List Items = new List();
9 |
10 | public override string ToString()
11 | {
12 | StringBuilder sb = new StringBuilder();
13 |
14 | foreach(SqlSyntaxErrorItem item in this.Items)
15 | {
16 | sb.AppendLine($"{item.Text}(Line={item.Line},Column={item.Column},StartIndex={item.StartIndex},StopIndex={item.StopIndex}):{item.Message};");
17 | }
18 |
19 | return sb.ToString();
20 | }
21 | }
22 |
23 | public class SqlSyntaxErrorItem
24 | {
25 | public int Line { get; set; }
26 | public int Column { get; set; }
27 | public int StartIndex { get; set; }
28 | public int StopIndex { get; set; }
29 | public string Text { get; set; }
30 | public string Message { get; set; }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Model/TokenInfo.cs:
--------------------------------------------------------------------------------
1 | namespace CodeParser.Viewer
2 | {
3 | public class TokenInfo
4 | {
5 | public int? StartIndex { get; set; }
6 | public int? StopIndex { get; set; }
7 | public int? ChildCount { get; set; }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace CodeParser.Viewer
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// 应用程序的主入口点。
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new frmMain());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("CodeParser.Viewer")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CodeParser.Viewer")]
13 | [assembly: AssemblyCopyright("Copyright © 2020")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("8e724f0a-1e47-45ef-918f-ed468f046289")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本:4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将会丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CodeParser.Viewer.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// 返回此类使用的缓存的 ResourceManager 实例。
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CodeParser.Viewer.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// 重写当前线程的 CurrentUICulture 属性
51 | /// 重写当前线程的 CurrentUICulture 属性。
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 |
63 | ///
64 | /// 查找类似于 (图标) 的 System.Drawing.Icon 类型的本地化资源。
65 | ///
66 | internal static System.Drawing.Icon magic {
67 | get {
68 | object obj = ResourceManager.GetObject("magic", resourceCulture);
69 | return ((System.Drawing.Icon)(obj));
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 |
122 | ..\Resources\magic.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
123 |
124 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CodeParser.Viewer.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/Resources/magic.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/victor-wiki/CodeParser/f1e7ea683c2b20b5365926a2f21fdf3360a75d3d/CodeParser.Viewer/Resources/magic.ico
--------------------------------------------------------------------------------
/CodeParser.Viewer/SqlSyntaxErrorListener.cs:
--------------------------------------------------------------------------------
1 | using Antlr4.Runtime;
2 | using System.IO;
3 |
4 | namespace CodeParser.Viewer
5 | {
6 | public class SqlSyntaxErrorListener : BaseErrorListener
7 | {
8 | public bool HasError => this.Error != null && this.Error.Items.Count > 0;
9 | public SqlSyntaxError Error { get; private set; }
10 |
11 | public override void SyntaxError(TextWriter output, IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
12 | {
13 | if (this.Error == null)
14 | {
15 | this.Error = new SqlSyntaxError();
16 | }
17 |
18 | if (offendingSymbol is CommonToken token)
19 | {
20 | SqlSyntaxErrorItem errorItem = new SqlSyntaxErrorItem();
21 |
22 | errorItem.StartIndex = token.StartIndex;
23 | errorItem.StopIndex = token.StopIndex;
24 | errorItem.Line = token.Line;
25 | errorItem.Column = token.Column + 1;
26 | errorItem.Text = token.Text;
27 | errorItem.Message = msg;
28 |
29 | this.Error.Items.Add(errorItem);
30 | }
31 |
32 | base.SyntaxError(output, recognizer, offendingSymbol, line, charPositionInLine, msg, e);
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/CodeParser.Viewer/frmMain.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Drawing;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Reflection;
9 | using System.Text;
10 | using System.Text.RegularExpressions;
11 | using System.Threading.Tasks;
12 | using System.Windows.Forms;
13 | using Antlr4.Runtime;
14 | using Antlr4.Runtime.Tree;
15 |
16 | namespace CodeParser.Viewer
17 | {
18 | public partial class frmMain : Form
19 | {
20 | private string coderPaserDllName = "CodeParser.dll";
21 | private Assembly assembly = null;
22 | private List parserTypes = new List();
23 | private Parser parser = null;
24 | private Color selectionBackColor = ColorTranslator.FromHtml("#0078D7");
25 | private Dictionary dictTokenInfo = new Dictionary();
26 | private SqlSyntaxError error;
27 |
28 | public delegate void AddNodeDelegate(TreeNode node);
29 |
30 | private static List ignoreMethods = new List()
31 | {
32 | "Eof"
33 | };
34 |
35 | public frmMain()
36 | {
37 | RichTextBox.CheckForIllegalCrossThreadCalls = false;
38 | TreeView.CheckForIllegalCrossThreadCalls = false;
39 | TextBox.CheckForIllegalCrossThreadCalls = false;
40 | Label.CheckForIllegalCrossThreadCalls = false;
41 |
42 | InitializeComponent();
43 | }
44 |
45 | private void frmMain_Load(object sender, EventArgs e)
46 | {
47 | this.InitControls();
48 | }
49 |
50 | private void InitControls()
51 | {
52 | this.LoadParsers();
53 |
54 | this.cboParser.SelectedIndex = -1;
55 | }
56 |
57 | private bool IsSqlParser()
58 | {
59 | string parserName = this.cboParser.Text;
60 |
61 | if (!string.IsNullOrEmpty(parserName))
62 | {
63 | if (parserName == nameof(MySqlParser) ||
64 | parserName == nameof(TSqlParser) ||
65 | parserName == nameof(PlSqlParser) ||
66 | parserName == nameof(PostgreSqlParser) ||
67 | parserName == nameof(SQLiteParser)
68 | )
69 | {
70 | return true;
71 | }
72 | }
73 | return false;
74 | }
75 |
76 | private void LoadParsers()
77 | {
78 | this.assembly = Assembly.LoadFrom(this.coderPaserDllName);
79 | var typeArray = this.assembly.ExportedTypes;
80 |
81 | this.parserTypes = (from type in typeArray
82 | where type.IsSubclassOf(typeof(Parser)) && !type.IsAbstract
83 | orderby type.Name
84 | select type).ToList();
85 |
86 | this.cboParser.DataSource = this.parserTypes;
87 | this.cboParser.DisplayMember = "Name";
88 | this.cboParser.ValueMember = "Name";
89 | }
90 |
91 | private Type GetLexerType(string name)
92 | {
93 | return (from type in this.assembly.ExportedTypes
94 | where type.IsSubclassOf(typeof(Lexer)) && type.Name == name
95 | orderby type.Name
96 | select type).FirstOrDefault();
97 | }
98 |
99 | private void LoadFromFile()
100 | {
101 | string content = this.GetFileContent();
102 | this.txtText.Text = this.IsSqlParser() ? content.ToUpper() : content;
103 | this.LoadTree();
104 | }
105 |
106 | private void btnOpenFile_Click(object sender, EventArgs e)
107 | {
108 | this.SelectFile();
109 | }
110 |
111 | private void SelectFile()
112 | {
113 | if (this.cboParser.SelectedIndex < 0)
114 | {
115 | MessageBox.Show("Please select a parser first.");
116 | return;
117 | }
118 |
119 | ParserInfo info = this.GetParserInfo();
120 |
121 | if (info == null)
122 | {
123 | return;
124 | }
125 |
126 | string extension = info.FileExtension;
127 |
128 | string filter = $"{info.Language} files|*{extension}|all files|*.*";
129 |
130 | this.openFileDialog1.FileName = "";
131 | this.openFileDialog1.Filter = filter;
132 |
133 | if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
134 | {
135 | this.txtFile.Text = this.openFileDialog1.FileName;
136 |
137 | this.LoadFromFile();
138 | }
139 | }
140 |
141 | private ParserInfo GetParserInfo()
142 | {
143 | string parserName = this.cboParser.Text;
144 |
145 | ParserInfo info = ParserManager.GetParserInfoByName(parserName);
146 |
147 | if (info == null)
148 | {
149 | MessageBox.Show($"Can't get ParserInfo for parser \"{parserName}\".");
150 | return null;
151 | }
152 |
153 | return info;
154 | }
155 |
156 | private void txtFile_TextChanged(object sender, EventArgs e)
157 | {
158 | if (File.Exists(this.txtFile.Text))
159 | {
160 | this.LoadFromFile();
161 | }
162 | }
163 |
164 | private void ClearValues()
165 | {
166 | this.txtChildCount.Text = "";
167 | this.txtTypeName.Text = "";
168 |
169 | this.ClearSelection();
170 | }
171 |
172 | private void ClearSelection()
173 | {
174 | int start = this.txtText.SelectionStart;
175 |
176 | this.txtText.SelectAll();
177 | this.txtText.SelectionBackColor = Color.White;
178 | this.txtText.SelectionColor = Color.Black;
179 | this.txtText.SelectionStart = start;
180 | this.txtText.SelectionLength = 0;
181 | }
182 |
183 | private void LoadTree()
184 | {
185 | Task.Run(()=> this.InternalLoadTree());
186 | }
187 |
188 | private void InternalLoadTree()
189 | {
190 | this.ClearValues();
191 | this.txtMessage.Text = "is parsing...";
192 |
193 | this.tvParserNodes.Nodes.Clear();
194 | this.dictTokenInfo.Clear();
195 |
196 | if (this.cboParser.SelectedIndex < 0)
197 | {
198 | return;
199 | }
200 |
201 | if (string.IsNullOrEmpty(this.txtText.Text))
202 | {
203 | return;
204 | }
205 |
206 | string parserName = this.cboParser.Text;
207 |
208 | Type parserType = this.parserTypes.FirstOrDefault(item => item.Name == parserName);
209 |
210 | Type lexerType = this.GetLexerType(parserType.Name.Replace("Parser", "Lexer"));
211 |
212 | Lexer lexer = (Lexer)Activator.CreateInstance(lexerType, new object[] { CharStreams.fromString(this.txtText.Text) });
213 |
214 | CommonTokenStream tokens = new CommonTokenStream(lexer);
215 |
216 | this.parser = (Parser)Activator.CreateInstance(parserType, new object[] { tokens });
217 |
218 | var errorListener = new SqlSyntaxErrorListener();
219 |
220 | this.parser.AddErrorListener(errorListener);
221 |
222 | ParserInfo info = this.GetParserInfo();
223 |
224 | if (info == null)
225 | {
226 | return;
227 | }
228 |
229 | var rootMethod = parserType.GetMethod(info.EntryRuleName);
230 |
231 | object value = rootMethod.Invoke(this.parser, new object[] { });
232 |
233 | this.error = errorListener.Error;
234 |
235 | if (this.chkHighlightingErrors.Checked)
236 | {
237 | this.HighlightingError();
238 | }
239 |
240 | TreeNode rootNode = this.CreateTreeNode(info.EntryRuleName);
241 | rootNode.Tag = value;
242 |
243 | this.txtMessage.Text = "is loading tree...";
244 |
245 | AddNodeDelegate @delegate = new AddNodeDelegate(this.AddTreeNode);
246 | this.Invoke(@delegate, rootNode);
247 |
248 | rootNode.Expand();
249 |
250 | rootNode.EnsureVisible();
251 |
252 | this.txtMessage.Text = "";
253 | }
254 |
255 | private void AddTreeNode(TreeNode node)
256 | {
257 | this.tvParserNodes.Nodes.Add(node);
258 |
259 | this.AddChildNodes(node, false);
260 | }
261 |
262 | public void HighlightingError()
263 | {
264 | if (this.error != null)
265 | {
266 | bool enabled = this.chkHighlightingErrors.Checked;
267 |
268 | foreach (var item in this.error.Items)
269 | {
270 | this.txtText.SelectionStart = item.StartIndex;
271 | this.txtText.SelectionLength = item.StopIndex - item.StartIndex + 1;
272 |
273 | this.txtText.SelectionColor = enabled ? Color.Red : Color.Black;
274 | this.txtText.SelectionBackColor = enabled ? Color.Yellow : Color.White;
275 | }
276 | }
277 |
278 | this.txtText.SelectionStart = 0;
279 | this.txtText.SelectionLength = 0;
280 | this.txtText.Focus();
281 | }
282 |
283 | private void AddChildNodes(TreeNode node, bool expand)
284 | {
285 | object value = node.Tag;
286 |
287 | if (value == null)
288 | {
289 | return;
290 | }
291 |
292 | List