~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

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
//
// RazorCSharpParser.cs
//
// Author:
//		Piotr Dowgiallo <sparekd@gmail.com>
//
// Copyright (c) 2012 Piotr Dowgiallo
//
// 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.Linq;
using System.Text;
using MonoDevelop.Ide.TypeSystem;
using System.Web.Razor;
using System.Web.Mvc.Razor;
using System.Threading;
using System.Web.Razor.Text;
using MonoDevelop.Ide;
using Mono.TextEditor;
using MonoDevelop.Ide.Gui;
using ICSharpCode.NRefactory.TypeSystem;
using System.Web.Razor.Parser;
using System.Web.Razor.Parser.SyntaxTree;
using System.IO;
using MonoDevelop.Core;
using MonoDevelop.AspNet.Parser;
using System.Web.Configuration;
using System.Web.WebPages.Razor.Configuration;
using System.Web.WebPages.Razor;
using System.Configuration;
using MonoDevelop.Projects;
using MonoDevelop.AspNet.StateEngine;

namespace MonoDevelop.AspNet.Mvc.Parser
{
	public class RazorCSharpParser : TypeSystemParser
	{
		RazorEditorParserFixed.RazorEditorParser editorParser;
		DocumentParseCompleteEventArgs capturedArgs;
		AutoResetEvent parseComplete;
		ChangeInfo lastChange;
		string lastParsedFile;
		TextDocument currentDocument;
		AspMvcProject aspProject;
		DotNetProject project;
		IList<TextDocument> openDocuments;

		public IList<TextDocument> OpenDocuments { get { return openDocuments; } }

		public RazorCSharpParser ()
		{
			openDocuments = new List<TextDocument> ();

			IdeApp.Exited += delegate {
				//HACK: workaround for Mono's not shutting downs IsBackground threads in WaitAny calls
				if (editorParser != null) {
					DisposeCurrentParser ();
				}
			};
		}

		public override ParsedDocument Parse (bool storeAst, string fileName, System.IO.TextReader content, Projects.Project project = null)
		{
			currentDocument = openDocuments.FirstOrDefault (d => d != null && d.FileName == fileName);
			// We need document and project to be loaded to correctly initialize Razor Host.
			this.project = project as DotNetProject;
			if (this.project == null || (currentDocument == null && !TryAddDocument (fileName)))
				return new RazorCSharpParsedDocument (fileName, new RazorCSharpPageInfo ());

			this.aspProject = project as AspMvcProject;

			EnsureParserInitializedFor (fileName);

			var errors = new List<Error> ();

			using (var source = new SeekableTextReader (content)) {
				var textChange = CreateTextChange (source);
				var parseResult = editorParser.CheckForStructureChanges (textChange);
				if (parseResult == PartialParseResult.Rejected) {
					parseComplete.WaitOne ();
					if (!capturedArgs.GeneratorResults.Success)
						GetRazorErrors (errors);
				}
			}

			ParseHtmlDocument (errors);
			CreateCSharpParsedDocument ();
			ClearLastChange ();

			RazorHostKind kind = RazorHostKind.WebPage;
			if (editorParser.Host is WebCodeRazorHost) {
				kind = RazorHostKind.WebCode;
			} else if (editorParser.Host is MonoDevelop.RazorGenerator.RazorHost) {
				kind = RazorHostKind.Template;
			}

			var pageInfo = new RazorCSharpPageInfo () {
				HtmlRoot = htmlParsedDocument,
				GeneratorResults = capturedArgs.GeneratorResults,
				Spans = editorParser.CurrentParseTree.Flatten (),
				CSharpParsedFile = parsedCodeFile,
				CSharpCode = csharpCode,
				Errors = errors,
				FoldingRegions = GetFoldingRegions (),
				Comments = comments,
				Compilation = CreateCompilation (),
				HostKind = kind,
			};

			return new RazorCSharpParsedDocument (fileName, pageInfo);
		}

		bool TryAddDocument (string fileName)
		{
			var guiDoc = IdeApp.Workbench.GetDocument (fileName);
			if (guiDoc != null && guiDoc.Editor != null) {
				currentDocument = guiDoc.Editor.Document;
				currentDocument.TextReplacing += OnTextReplacing;
				lock (this) {
					var newDocs = new List<TextDocument> (openDocuments);
					newDocs.Add (currentDocument);
					openDocuments = newDocs;
				}
				guiDoc.Closed += (sender, args) =>
				{
					var doc = sender as Document;
					if (doc.Editor != null && doc.Editor.Document != null) {
						lock (this) {
							openDocuments = new List<TextDocument> (openDocuments.Where (d => d != doc.Editor.Document));
						}
					}

					if (lastParsedFile == doc.FileName && editorParser != null) {
						DisposeCurrentParser ();
					}
				};
				return true;
			}
			return false;
		}

		void EnsureParserInitializedFor (string fileName)
		{
			if (lastParsedFile == fileName && editorParser != null)
				return;

			if (editorParser != null)
				DisposeCurrentParser ();

			CreateParserFor (fileName);
		}

		void CreateParserFor (string fileName)
		{
			editorParser = new RazorEditorParserFixed.RazorEditorParser (CreateRazorHost (fileName), fileName);

			parseComplete = new AutoResetEvent (false);
			editorParser.DocumentParseComplete += (sender, args) =>
			{
				capturedArgs = args;
				parseComplete.Set ();
			};

			lastParsedFile = fileName;
		}

		RazorEngineHost CreateRazorHost (string fileName)
		{
			var projectFile = project.GetProjectFile (fileName);
			if (projectFile != null && projectFile.Generator == "RazorTemplatePreprocessor") {
				var h = MonoDevelop.RazorGenerator.PreprocessedRazorHost.Create (fileName);
				h.DesignTimeMode = true;
				h.EnableLinePragmas = false;
				return h;
			}

			string virtualPath = "~/Views/Default.cshtml";
			if (aspProject != null)
				virtualPath = aspProject.LocalToVirtualPath (fileName);

			WebPageRazorHost host = null;

			// Try to create host using web.config file
			var webConfigMap = new WebConfigurationFileMap ();
			if (aspProject != null) {
				var vdm = new VirtualDirectoryMapping (aspProject.BaseDirectory.Combine ("Views"), true, "web.config");
			webConfigMap.VirtualDirectories.Add ("/", vdm);
			}
			Configuration configuration;
			try {
				configuration = WebConfigurationManager.OpenMappedWebConfiguration (webConfigMap, "/");
			} catch {
				configuration = null;
			}
			if (configuration != null) {
				var rws = configuration.GetSectionGroup (RazorWebSectionGroup.GroupName) as RazorWebSectionGroup;
				if (rws != null) {
					host = WebRazorHostFactory.CreateHostFromConfig (rws, virtualPath, fileName);
					host.DesignTimeMode = true;
				}
			}

			if (host == null) {
				host = new MvcWebPageRazorHost (virtualPath, fileName) { DesignTimeMode = true };
				// Add default namespaces from Razor section
				host.NamespaceImports.Add ("System.Web.Mvc");
				host.NamespaceImports.Add ("System.Web.Mvc.Ajax");
				host.NamespaceImports.Add ("System.Web.Mvc.Html");
				host.NamespaceImports.Add ("System.Web.Routing");
			}

			return host;
		}

		void DisposeCurrentParser ()
		{
			editorParser.Dispose ();
			editorParser = null;
			parseComplete.Dispose ();
			parseComplete = null;
			ClearLastChange ();
		}

		void ClearLastChange ()
		{
			lastChange = null;
		}

		TextChange CreateTextChange (SeekableTextReader source)
		{
			if (lastChange == null)
				return new TextChange (0, 0, new SeekableTextReader (String.Empty), 0, source.Length, source);
			if (lastChange.DeleteChange)
				return new TextChange (lastChange.StartOffset, lastChange.AbsoluteLength, lastChange.Buffer,
					lastChange.StartOffset,	0, source);
			return new TextChange (lastChange.StartOffset, 0, lastChange.Buffer, lastChange.StartOffset,
				lastChange.AbsoluteLength, source);
		}

		void GetRazorErrors (List<Error> errors)
		{
			foreach (var error in capturedArgs.GeneratorResults.ParserErrors) {
				int off = error.Location.AbsoluteIndex;
				if (error.Location.CharacterIndex > 0 && error.Length == 1)
					off--;
				errors.Add (new Error (ErrorType.Error, error.Message, currentDocument.OffsetToLocation (off)));
			}
		}

		Xml.StateEngine.XDocument htmlParsedDocument;
		IList<Comment> comments;

		void ParseHtmlDocument (List<Error> errors)
		{
			var sb = new StringBuilder ();
			var spanList = new List<Span> ();
			comments = new List<Comment> ();

			Action<Span> action = (Span span) =>
			{
				if (span.Kind == SpanKind.Markup) {
					sb.Append (span.Content);
					spanList.Add (span);
				} else {
					for (int i = 0; i < span.Content.Length; i++) {
						char ch = span.Content[i];
						if (ch != '\r' && ch != '\n')
							sb.Append (' ');
						else
							sb.Append (ch);
					}
					if (span.Kind == SpanKind.Comment) {
						var comment = new Comment (span.Content)
						{
							OpenTag = "@*",
							ClosingTag = "*@",
							CommentType = CommentType.Block,
						};
						comment.Region = new DomRegion (
							currentDocument.OffsetToLocation (span.Start.AbsoluteIndex - comment.OpenTag.Length),
							currentDocument.OffsetToLocation (span.Start.AbsoluteIndex + span.Length + comment.ClosingTag.Length));
						comments.Add (comment);
					}
				}
			};

			editorParser.CurrentParseTree.Accept (new CallbackVisitor (action));

			var parser = new Xml.StateEngine.Parser (new AspNetFreeState (), true);

			try {
				parser.Parse (new StringReader (sb.ToString ()));
			} catch (Exception ex) {
				LoggingService.LogError ("Unhandled error parsing html in Razor document '" + (lastParsedFile ?? "") + "'", ex);
			}

			htmlParsedDocument = parser.Nodes.GetRoot ();
			errors.AddRange (parser.Errors);
		}

		IEnumerable<FoldingRegion> GetFoldingRegions ()
		{
			var foldingRegions = new List<FoldingRegion> ();
			GetHtmlFoldingRegions (foldingRegions);
			GetRazorFoldingRegions (foldingRegions);
			return foldingRegions;
		}

		void GetHtmlFoldingRegions (List<FoldingRegion> foldingRegions)
		{
			if (htmlParsedDocument != null) {
				var d = new AspNetParsedDocument (null, WebSubtype.Html, null, htmlParsedDocument);
				foldingRegions.AddRange (d.Foldings);
			}
		}

		void GetRazorFoldingRegions (List<FoldingRegion> foldingRegions)
		{
			var blocks = new List<Block> ();
			GetBlocks (editorParser.CurrentParseTree, blocks);
			foreach (var block in blocks) {
				var beginLine = currentDocument.GetLineByOffset (block.Start.AbsoluteIndex);
				var endLine = currentDocument.GetLineByOffset (block.Start.AbsoluteIndex + block.Length);
				if (beginLine != endLine)
					foldingRegions.Add (new FoldingRegion (RazorUtils.GetShortName (block),
						new DomRegion (currentDocument.OffsetToLocation (block.Start.AbsoluteIndex),
							currentDocument.OffsetToLocation (block.Start.AbsoluteIndex + block.Length))));
			}
		}

		void GetBlocks (Block root, IList<Block> blocks)
		{
			foreach (var block in root.Children.Where (n => n.IsBlock).Select (n => n as Block)) {
				if (block.Type != BlockType.Comment && block.Type != BlockType.Markup)
					blocks.Add (block);
				if (block.Type != BlockType.Helper)
					GetBlocks (block, blocks);
			}
		}

		ParsedDocumentDecorator parsedCodeFile;
		string csharpCode;

		void CreateCSharpParsedDocument ()
		{
			var parser = new ICSharpCode.NRefactory.CSharp.CSharpParser ();
			ICSharpCode.NRefactory.CSharp.SyntaxTree unit;
			csharpCode = CreateCodeFile ();
			using (var sr = new StringReader (csharpCode)) {
				unit = parser.Parse (sr, "Generated.cs");
			}
			unit.Freeze ();
			var parsedDoc = unit.ToTypeSystem ();
			parsedCodeFile = new ParsedDocumentDecorator (parsedDoc) { Ast = unit };
		}

		string CreateCodeFile ()
		{
			var unit = capturedArgs.GeneratorResults.GeneratedCode;
			var provider = project.LanguageBinding.GetCodeDomProvider ();
			using (var sw = new StringWriter ()) {
				provider.GenerateCodeFromCompileUnit (unit, sw, new System.CodeDom.Compiler.CodeGeneratorOptions ()	{
					// HACK: we use true, even though razor uses false, to work around a mono bug where it omits the 
					// line ending after "#line hidden", resulting in the unparseable "#line hiddenpublic"
					BlankLinesBetweenMembers = true,
					// matches Razor built-in settings
					IndentString = String.Empty,
				});
				return sw.ToString ();
			}
		}

		// Creates compilation that includes underlying C# file for Razor view
		ICompilation CreateCompilation ()
		{
			return TypeSystemService.GetProjectContext (project).AddOrUpdateFiles (parsedCodeFile.ParsedFile).CreateCompilation ();
		}

		void OnTextReplacing (object sender, DocumentChangeEventArgs e)
		{
			if (lastChange == null)
				lastChange = new ChangeInfo (e.Offset, new SeekableTextReader((sender as TextDocument).Text));
			if (e.ChangeDelta > 0) {
				lastChange.Length += e.InsertionLength;
			} else {
				lastChange.Length -= e.RemovalLength;
			}
		}
	}

	class ChangeInfo
	{
		int offset;

		public ChangeInfo (int off, SeekableTextReader buffer)
		{
			offset = off;
			Length = 0;
			Buffer = buffer;
		}

		public int StartOffset {
			get	{ return offset; }
			private set { }
		}

		public int Length { get; set; }
		public int AbsoluteLength {
			get { return Math.Abs (Length); }
			private set { }
		}

		public SeekableTextReader Buffer { get; set; }
		public bool DeleteChange { get { return Length < 0; } }
	}
}