Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CSharpParsedDocument.cs « MonoDevelop.CSharp.Parser « CSharpBinding « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 49eace75d58782083146ca2ecb200b8e0d33f020 (plain)
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//
// CSharpParsedDocument.cs
//
// Author:
//       Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com)
//
// 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 MonoDevelop.Ide.TypeSystem;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using MonoDevelop.Ide.Editor;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using MonoDevelop.Core;
using MonoDevelop.Core.Text;

namespace MonoDevelop.CSharp.Parser
{
	class CSharpParsedDocument : ParsedDocument
	{
		static string[] tagComments;

		internal SyntaxTree Unit {
			get;
			set;
		}

		static CSharpParsedDocument ()
		{
			UpdateTags ();
			MonoDevelop.Ide.Tasks.CommentTag.SpecialCommentTagsChanged += delegate {
				UpdateTags ();
			};
		}

		static void UpdateTags ()
		{
			tagComments = MonoDevelop.Ide.Tasks.CommentTag.SpecialCommentTags.Select (t => t.Tag).ToArray ();
		}

		public CSharpParsedDocument (string fileName) : base (fileName)
		{
		}
		

		#region implemented abstract members of ParsedDocument

		IReadOnlyList<Comment> comments;
		object commentLock = new object ();

		public override Task<IReadOnlyList<Comment>> GetCommentsAsync (CancellationToken cancellationToken = default(CancellationToken))
		{
			if (comments == null) {
				return Task.Run (delegate {
					lock (commentLock) {
						if (comments == null) {
							var visitor = new CommentVisitor (cancellationToken);
							if (Unit != null)
								try {
									visitor.Visit (Unit.GetRoot (cancellationToken));
								} catch (OperationCanceledException) {
								}
							comments = visitor.Comments;
						}
					}
					return comments;
				});
			}
			return Task.FromResult (comments);
		}


		class CommentVisitor : CSharpSyntaxWalker
		{
			public readonly List<Comment> Comments = new List<Comment> ();

			CancellationToken cancellationToken;

			public CommentVisitor (CancellationToken cancellationToken) : base(SyntaxWalkerDepth.Trivia)
			{
				this.cancellationToken = cancellationToken;
			}

			static DocumentRegion GetRegion (SyntaxTrivia trivia)
			{
				var fullSpan = trivia.FullSpan;
				var text = trivia.ToString ();
				if (text.Length > 2) {
					if (text [text.Length - 2] == '\r' && text [text.Length - 1] == '\n')
						fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan (fullSpan.Start, fullSpan.Length - 2);
					else if (NewLine.IsNewLine (text [text.Length - 1]))
						fullSpan = new Microsoft.CodeAnalysis.Text.TextSpan (fullSpan.Start, fullSpan.Length - 1);
				}
				try {
					var lineSpan = trivia.SyntaxTree.GetLineSpan (fullSpan);
					return (DocumentRegion)lineSpan;
				} catch (Exception) {
					return DocumentRegion.Empty;
				}
			}

			public override void VisitBlock (BlockSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				base.VisitBlock (node);
			}

			bool StartsLine (SyntaxTrivia trivia)
			{
				var sourceText = trivia.SyntaxTree.GetText (cancellationToken);
				Microsoft.CodeAnalysis.Text.TextLine textLine;
				try {
					textLine = sourceText.Lines.GetLineFromPosition (trivia.SpanStart);
				} catch (ArgumentOutOfRangeException) {
					return false;
				}
				//We need start of trivia.FullSpan and not trivia.SpanStart
				//because in case of documentation /// <summary...
				//trivia.SpanStart is space after /// and not 1st /
				//so with trivia.FullSpan.Start we get index of 1st /
				var startSpan = trivia.FullSpan.Start;
				for (int i = textLine.Start; i < startSpan; i++) {
					char ch = sourceText [i];
					if (!char.IsWhiteSpace (ch))
						return false;
				}
				return true;
			}

			static string CropStart (string text, string crop)
			{
				text = text.Trim ();
				if (text.StartsWith (crop))
					return text.Substring (crop.Length).TrimStart ();
				return text;
			}

			public override void VisitTrivia (SyntaxTrivia trivia)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				base.VisitTrivia (trivia);
				switch (trivia.Kind ()) {
				case SyntaxKind.MultiLineCommentTrivia:
				case SyntaxKind.MultiLineDocumentationCommentTrivia:
					{
						var cmt = new Comment (CropStart (trivia.ToString (), "/*"));
						cmt.CommentStartsLine = StartsLine(trivia);
						cmt.CommentType = CommentType.Block;
						cmt.OpenTag = "/*";
						cmt.ClosingTag = "*/";
						cmt.Region = GetRegion (trivia);
						Comments.Add (cmt);
						break;
					}
				case SyntaxKind.SingleLineCommentTrivia:
					{
						var cmt = new Comment (CropStart (trivia.ToString (), "//"));
						cmt.CommentStartsLine = StartsLine(trivia);
						cmt.CommentType = CommentType.SingleLine;
						cmt.OpenTag = "//";
						cmt.Region = GetRegion (trivia);
						Comments.Add (cmt);
						break;
					}
				case SyntaxKind.SingleLineDocumentationCommentTrivia:
					{
						var cmt = new Comment (CropStart (trivia.ToString (), "///"));
						cmt.CommentStartsLine = StartsLine(trivia);
						cmt.IsDocumentation = true;
						cmt.CommentType = CommentType.Documentation;
						cmt.OpenTag = "///";
						cmt.ClosingTag = "*/";
						cmt.Region = GetRegion (trivia);
						Comments.Add (cmt);
						break;
					}

				}

			}
		}

		IReadOnlyList<Tag> tags;
		object tagLock = new object ();
		public override Task<IReadOnlyList<Tag>> GetTagCommentsAsync (CancellationToken cancellationToken = default(CancellationToken))
		{
			if (tags == null) {
				return Task.Run (delegate {
					lock (tagLock) {
						if (tags == null) {
							var visitor = new SemanticTagVisitor (cancellationToken);
							if (Unit != null) {
								try {
									visitor.Visit (Unit.GetRoot (cancellationToken));
								} catch {
								}
							}
							tags = visitor.Tags;
						}
						return tags;
					}
				});
			}
			return Task.FromResult (tags);
		}

		sealed class SemanticTagVisitor : CSharpSyntaxWalker
		{
			public List<Tag> Tags =  new List<Tag> ();
			CancellationToken cancellationToken;

			public SemanticTagVisitor () : base (SyntaxWalkerDepth.Trivia)
			{
			}

			public SemanticTagVisitor (CancellationToken cancellationToken) : base (SyntaxWalkerDepth.Trivia)
			{
				this.cancellationToken = cancellationToken;
			}

			public override void VisitBlock (BlockSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				base.VisitBlock (node);
			}

			public override void VisitTrivia (SyntaxTrivia trivia)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				if (trivia.IsKind (SyntaxKind.SingleLineCommentTrivia) || 
					trivia.IsKind (SyntaxKind.MultiLineCommentTrivia) || 
					trivia.IsKind (SyntaxKind.SingleLineDocumentationCommentTrivia)) {
					var trimmedContent = trivia.ToString ().TrimStart ('/', ' ', '*');
					foreach (string tag in tagComments) {
						if (!trimmedContent.StartsWith (tag, StringComparison.Ordinal))
							continue;
						var loc = trivia.GetLocation ().GetLineSpan ();
						Tags.Add (new Tag (tag, trimmedContent, new DocumentRegion (loc.StartLinePosition, loc.EndLinePosition)));
						break;
					}
				}
			}

			public override void VisitThrowStatement (Microsoft.CodeAnalysis.CSharp.Syntax.ThrowStatementSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				base.VisitThrowStatement (node);
				var createExpression = node.Expression as ObjectCreationExpressionSyntax;
				if (createExpression == null)
					return;
				var st = createExpression.Type.ToString ();
				if (st == "NotImplementedException" || st == "System.NotImplementedException") {
					var loc = node.GetLocation ().GetLineSpan ();
					if (createExpression.ArgumentList.Arguments.Count > 0) {
						Tags.Add (new Tag ("High", GettextCatalog.GetString ("NotImplementedException({0}) thrown.", createExpression.ArgumentList.Arguments.First ().ToString ()), new DocumentRegion (loc.StartLinePosition, loc.EndLinePosition)));
					} else {
						Tags.Add (new Tag ("High", GettextCatalog.GetString ("NotImplementedException thrown."), new DocumentRegion (loc.StartLinePosition, loc.EndLinePosition)));
					}
				}
			}
		}

		IReadOnlyList<FoldingRegion> foldings;
		SemaphoreSlim foldingsSemaphore = new SemaphoreSlim (1, 1);

		public override Task<IReadOnlyList<FoldingRegion>> GetFoldingsAsync (CancellationToken cancellationToken = default(CancellationToken))
		{
			if (foldings == null) {
				return Task.Run (async delegate {
					bool locked = false;
					try {
						locked = await foldingsSemaphore.WaitAsync (Timeout.Infinite, cancellationToken);
						if (foldings == null)
							foldings = (await GenerateFoldings (cancellationToken)).ToList ();
					} catch (OperationCanceledException) {
						return new List<FoldingRegion> ();
					} finally {
						if (locked)
							foldingsSemaphore.Release ();
					}
					return foldings;
				});
			}

			return Task.FromResult (foldings);
		}

		async Task<IEnumerable<FoldingRegion>> GenerateFoldings (CancellationToken cancellationToken)
		{
			return GenerateFoldingsInternal (await GetCommentsAsync (cancellationToken), cancellationToken);
		}

		IEnumerable<FoldingRegion> GenerateFoldingsInternal (IReadOnlyList<Comment> comments, CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
				yield break;

			foreach (var fold in comments.ToFolds ())
				yield return fold;

			if (cancellationToken.IsCancellationRequested)
				yield break;

			var visitor = new FoldingVisitor (cancellationToken);
			if (Unit != null) {
				try {
					visitor.Visit (Unit.GetRoot (cancellationToken));
				} catch (Exception) { }
			}

			if (cancellationToken.IsCancellationRequested)
				yield break;
			foreach (var fold in visitor.Foldings)
				yield return fold;
		}

		class FoldingVisitor : CSharpSyntaxWalker
		{
			public readonly List<FoldingRegion> Foldings = new List<FoldingRegion> ();
			CancellationToken cancellationToken;

			public FoldingVisitor (CancellationToken cancellationToken) : base(SyntaxWalkerDepth.Trivia)
			{
				this.cancellationToken = cancellationToken;
			}

			void AddUsings (SyntaxNode parent)
			{
				SyntaxNode firstChild = null, lastChild = null;
				foreach (var child in parent.ChildNodes ()) {
					cancellationToken.ThrowIfCancellationRequested ();
					if (child is UsingDirectiveSyntax) {
						if (firstChild == null) {
							firstChild = child;
						}
						lastChild = child;
						continue;
					}
					if (firstChild != null)
						break;
				}

				if (firstChild != null && firstChild != lastChild) {
					var first = firstChild.GetLocation ().GetLineSpan ();
					var last = lastChild.GetLocation ().GetLineSpan ();

					Foldings.Add (new FoldingRegion (new DocumentRegion (first.StartLinePosition, last.EndLinePosition), FoldType.Undefined));
				}
			}

			public override void VisitCompilationUnit (Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddUsings (node);
				base.VisitCompilationUnit (node);
			}

			void AddFolding (SyntaxToken openBrace, SyntaxToken closeBrace, FoldType type)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				openBrace = openBrace.GetPreviousToken (false, false, true, true);

				try {
					var first = openBrace.GetLocation ().GetLineSpan ();
					var last = closeBrace.GetLocation ().GetLineSpan ();

					if (first.EndLinePosition.Line != last.EndLinePosition.Line)
						Foldings.Add (new FoldingRegion (new DocumentRegion (first.EndLinePosition, last.EndLinePosition), type));
				} catch (ArgumentOutOfRangeException) {}
			}

			Stack<SyntaxTrivia> regionStack = new Stack<SyntaxTrivia> ();
			public override void VisitTrivia (SyntaxTrivia trivia)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				base.VisitTrivia (trivia);
				if (trivia.IsKind (SyntaxKind.RegionDirectiveTrivia)) {
					regionStack.Push (trivia);
				} else if (trivia.IsKind (SyntaxKind.EndRegionDirectiveTrivia)) {
					if (regionStack.Count == 0)
						return;
					var regionStart = regionStack.Pop ();
					try {
						var first = regionStart.GetLocation ().GetLineSpan ();
						var last = trivia.GetLocation ().GetLineSpan ();
						var v = regionStart.ToString ();
						v = v.Substring ("#region".Length).Trim ();
						if (v.Length == 0)
							v = "...";
						Foldings.Add (new FoldingRegion(v, new DocumentRegion(first.StartLinePosition, last.EndLinePosition), FoldType.UserRegion, true));
					} catch (ArgumentOutOfRangeException) { }
				}
			}

			public override void VisitNamespaceDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.NamespaceDeclarationSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddUsings (node);
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, FoldType.Undefined);
				base.VisitNamespaceDeclaration (node);
			}

			public override void VisitClassDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, FoldType.Type);
				base.VisitClassDeclaration (node);
			}

			public override void VisitStructDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, FoldType.Type);
				base.VisitStructDeclaration (node);
			}

			public override void VisitInterfaceDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, FoldType.Type);
				base.VisitInterfaceDeclaration (node);
			}

			public override void VisitEnumDeclaration (Microsoft.CodeAnalysis.CSharp.Syntax.EnumDeclarationSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, FoldType.Type);
				base.VisitEnumDeclaration (node);
			}

			public override void VisitBlock (Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax node)
			{
				cancellationToken.ThrowIfCancellationRequested ();
				AddFolding (node.OpenBraceToken, node.CloseBraceToken, node.Parent is MemberDeclarationSyntax ? FoldType.Member : FoldType.Undefined);
				base.VisitBlock (node);
			}
		}

		static readonly IReadOnlyList<Error> emptyErrors = new Error[0];
		IReadOnlyList<Error> errors;
		SemaphoreSlim errorLock = new SemaphoreSlim (1, 1);

		public override async Task<IReadOnlyList<Error>> GetErrorsAsync (CancellationToken cancellationToken = default(CancellationToken))
		{
			var model = GetAst<SemanticModel> ();
			if (model == null)
				return emptyErrors;

			if (errors != null)
				return errors;
			
			bool locked = await errorLock.WaitAsync (Timeout.Infinite, cancellationToken).ConfigureAwait (false);
			try {
				if (errors == null) {
					try {
						errors = model
							.GetDiagnostics (null, cancellationToken)
							.Where (diag => diag.Severity == DiagnosticSeverity.Error || diag.Severity == DiagnosticSeverity.Warning)
							.Select ((Diagnostic diag) => new Error (GetErrorType (diag.Severity), diag.Id, diag.GetMessage (), GetRegion (diag)) { Tag = diag })
							.ToList ();
					} catch (OperationCanceledException) {
						errors = emptyErrors;
					} catch (Exception e) {
						LoggingService.LogError ("Error while getting diagnostics.", e);
						errors = emptyErrors;
					}
				}
			} finally {
				if (locked)
					errorLock.Release ();
			}
			
			return errors;
		}

		static DocumentRegion GetRegion (Diagnostic diagnostic)
		{
			try {
				var lineSpan = diagnostic.Location.GetLineSpan ();
				return new DocumentRegion (lineSpan.StartLinePosition, lineSpan.EndLinePosition);
			} catch (Exception) {
				return DocumentRegion.Empty;
			}
		}

		static ErrorType GetErrorType (DiagnosticSeverity severity)
		{
			switch (severity) {
			case DiagnosticSeverity.Error:
				return ErrorType.Error;
			case DiagnosticSeverity.Warning:
				return ErrorType.Warning;
			}
			return ErrorType.Unknown;
		}

		#endregion
	}
}