This repository was archived by the owner on Oct 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 806
Expand file tree
/
Copy pathParser.cs
More file actions
242 lines (214 loc) · 10.8 KB
/
Parser.cs
File metadata and controls
242 lines (214 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.Core;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Editor.Search;
using ICSharpCode.SharpDevelop.Parser;
using ICSharpCode.SharpDevelop.Project;
namespace CSharpBinding.Parser
{
public class TParser : IParser
{
public IReadOnlyList<string> TaskListTokens { get; set; }
public bool CanParse(string fileName)
{
return Path.GetExtension(fileName).Equals(".CS", StringComparison.OrdinalIgnoreCase);
}
public ITextSource GetFileContent(FileName fileName)
{
return SD.FileService.GetFileContent(fileName);
}
public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested,
IProject parentProject, CancellationToken cancellationToken)
{
var csharpProject = parentProject as CSharpProject;
CSharpParser parser = new CSharpParser(csharpProject != null ? csharpProject.CompilerSettings : null);
SyntaxTree cu = parser.Parse(fileContent, fileName);
cu.Freeze();
CSharpUnresolvedFile file = cu.ToTypeSystem();
ParseInformation parseInfo;
if (fullParseInformationRequested)
parseInfo = new CSharpFullParseInformation(file, fileContent.Version, cu);
else
parseInfo = new ParseInformation(file, fileContent.Version, fullParseInformationRequested);
IDocument document = fileContent as IDocument;
AddCommentTags(cu, parseInfo.TagComments, fileContent, parseInfo.FileName, ref document);
if (fullParseInformationRequested) {
if (document == null)
document = new ReadOnlyDocument(fileContent, parseInfo.FileName);
((CSharpFullParseInformation)parseInfo).newFoldings = CreateNewFoldings(cu, document);
}
return parseInfo;
}
#region AddCommentTags
void AddCommentTags(SyntaxTree cu, IList<TagComment> tagComments, ITextSource fileContent, FileName fileName, ref IDocument document)
{
foreach (var comment in cu.Descendants.OfType<Comment>()) {
if (comment.CommentType == CommentType.InactiveCode)
continue;
string match;
if (comment.Content.ContainsAny(TaskListTokens, 0, out match)) {
if (document == null)
document = new ReadOnlyDocument(fileContent, fileName);
int commentSignLength = comment.CommentType == CommentType.Documentation || comment.CommentType == CommentType.MultiLineDocumentation ? 3 : 2;
int commentEndSignLength = comment.CommentType == CommentType.MultiLine || comment.CommentType == CommentType.MultiLineDocumentation ? 2 : 0;
int commentStartOffset = document.GetOffset(comment.StartLocation) + commentSignLength;
int commentEndOffset = document.GetOffset(comment.EndLocation) - commentEndSignLength;
int endOffset;
int searchOffset = 0;
// HACK: workaround for parser bug: uses \n instead of \r\n in comment.Content
string commentContent = document.GetText(commentStartOffset, Math.Abs(Math.Min(commentEndOffset - commentStartOffset + 1, commentEndOffset - commentStartOffset)));
do {
int start = commentStartOffset + searchOffset;
int absoluteOffset = document.IndexOf(match, start, document.TextLength - start, StringComparison.Ordinal);
var startLocation = document.GetLocation(absoluteOffset);
endOffset = Math.Min(document.GetLineByNumber(startLocation.Line).EndOffset, commentEndOffset);
string content = document.GetText(absoluteOffset, Math.Abs(endOffset - absoluteOffset));
if (content.Length < match.Length) {
// HACK: workaround parser bug with multi-line documentation comments
break;
}
tagComments.Add(new TagComment(content.Substring(0, match.Length), new DomRegion(cu.FileName, startLocation.Line, startLocation.Column), content.Substring(match.Length)));
searchOffset = Math.Abs(endOffset - commentStartOffset);
} while (commentContent.ContainsAny(TaskListTokens, searchOffset, out match));
}
}
}
#endregion
#region CreateNewFoldings
List<NewFolding> CreateNewFoldings(SyntaxTree syntaxTree, IDocument document)
{
FoldingVisitor v = new FoldingVisitor();
v.document = document;
syntaxTree.AcceptVisitor(v);
return v.foldings;
}
#endregion
public ResolveResult Resolve(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken)
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have SyntaxTree");
CSharpUnresolvedFile unresolvedFile = csParseInfo.UnresolvedFile;
var projectContents = compilation.Assemblies.Select(asm => asm.UnresolvedAssembly).OfType<IProjectContent>().ToList();
if (projectContents.All(pc => pc.GetFile(unresolvedFile.FileName) != unresolvedFile))
unresolvedFile = null;
return ResolveAtLocation.Resolve(compilation, unresolvedFile, csParseInfo.SyntaxTree, location, cancellationToken);
}
public ICodeContext ResolveContext(ParseInformation parseInfo, TextLocation location, ICompilation compilation, CancellationToken cancellationToken)
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have SyntaxTree");
CSharpUnresolvedFile unresolvedFile = csParseInfo.UnresolvedFile;
var projectContents = compilation.Assemblies.Select(asm => asm.UnresolvedAssembly).OfType<IProjectContent>().ToList();
if (projectContents.All(pc => pc.GetFile(unresolvedFile.FileName) != unresolvedFile))
unresolvedFile = null;
var syntaxTree = csParseInfo.SyntaxTree;
var node = syntaxTree.GetNodeAt(location);
if (node == null)
return null; // null result is allowed; the parser service will substitute a dummy context
var resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
return resolver.GetResolverStateBefore(node);
}
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action<SearchResultMatch> callback, CancellationToken cancellationToken)
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have SyntaxTree");
ReadOnlyDocument document = null;
IHighlighter highlighter = null;
new FindReferences().FindLocalReferences(
variable, csParseInfo.UnresolvedFile, csParseInfo.SyntaxTree, compilation,
delegate (AstNode node, ResolveResult result) {
if (document == null) {
document = new ReadOnlyDocument(fileContent, parseInfo.FileName);
highlighter = SD.EditorControlService.CreateHighlighter(document);
highlighter.BeginHighlighting();
}
var region = new DomRegion(parseInfo.FileName, node.StartLocation, node.EndLocation);
int offset = document.GetOffset(node.StartLocation);
int length = document.GetOffset(node.EndLocation) - offset;
var builder = SearchResultsPad.CreateInlineBuilder(node.StartLocation, node.EndLocation, document, highlighter);
var defaultTextColor = highlighter != null ? highlighter.DefaultTextColor : null;
callback(new SearchResultMatch(parseInfo.FileName, node.StartLocation, node.EndLocation, offset, length, builder, defaultTextColor));
}, cancellationToken);
if (highlighter != null) {
highlighter.Dispose();
}
}
static readonly Lazy<IAssemblyReference[]> defaultReferences = new Lazy<IAssemblyReference[]>(
delegate {
Assembly[] assemblies = {
typeof(object).Assembly,
typeof(Uri).Assembly,
typeof(Enumerable).Assembly
};
return assemblies.Select(asm => SD.AssemblyParserService.GetAssembly(FileName.Create(asm.Location))).ToArray();
});
public ICompilation CreateCompilationForSingleFile(FileName fileName, IUnresolvedFile unresolvedFile)
{
return new CSharpProjectContent()
.AddAssemblyReferences(defaultReferences.Value)
.AddOrUpdateFiles(unresolvedFile)
.CreateCompilation();
}
public ResolveResult ResolveSnippet(ParseInformation parseInfo, TextLocation location, string codeSnippet, ICompilation compilation, CancellationToken cancellationToken)
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have SyntaxTree");
CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, csParseInfo.SyntaxTree, csParseInfo.UnresolvedFile);
var node = csParseInfo.SyntaxTree.GetNodeAt(location);
CSharpResolver context;
if (node != null)
context = contextResolver.GetResolverStateAfter(node, cancellationToken);
else
context = new CSharpResolver(compilation);
CSharpParser parser = new CSharpParser();
var expr = parser.ParseExpression(codeSnippet);
if (parser.HasErrors)
return new ErrorResolveResult(SpecialType.UnknownType, PrintErrorsAsString(parser.Errors), TextLocation.Empty);
CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);
return snippetResolver.Resolve(expr, cancellationToken);
}
string PrintErrorsAsString(IEnumerable<Error> errors)
{
StringBuilder builder = new StringBuilder();
foreach (var error in errors)
builder.AppendLine(error.Message);
return builder.ToString();
}
}
}