~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
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Razor;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser;
using System.Web.Razor.Parser.SyntaxTree;
using System.Web.WebPages;

namespace MonoDevelop.RazorGenerator
{
	delegate void RazorCodeTransformer (
		RazorHost host, CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace,
		CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod);

	class RazorHost : RazorEngineHost
	{
		private readonly RazorCodeTransformer[] _transformers;
		private readonly string _fullPath;
		private readonly CodeDomProvider _codeDomProvider;
		private readonly CodeGeneratorOptions _codeGeneratorOptions;
		private string _defaultClassName;

		public RazorHost(string fullPath, CodeDomProvider codeDomProvider = null,
		                 RazorCodeTransformer[] transformers = null, CodeGeneratorOptions codeGeneratorOptions = null)
			: base(RazorCodeLanguage.GetLanguageByExtension(".cshtml"))
		{
			if (fullPath == null)
			{
				throw new ArgumentNullException("fullPath");
			}
			_transformers = transformers;
			_fullPath = fullPath;
			_codeDomProvider = codeDomProvider ?? new Microsoft.CSharp.CSharpCodeProvider ();
			base.DefaultNamespace = "ASP";
			EnableLinePragmas = true;

			base.GeneratedClassContext = new GeneratedClassContext(
				executeMethodName: GeneratedClassContext.DefaultExecuteMethodName,
				writeMethodName: GeneratedClassContext.DefaultWriteMethodName,
				writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName,
				writeToMethodName: "WriteTo",
				writeLiteralToMethodName: "WriteLiteralTo",
				templateTypeName: typeof(HelperResult).FullName,
				defineSectionMethodName: "DefineSection",
				beginContextMethodName: "BeginContext",
				endContextMethodName: "EndContext"
				)
			{
				ResolveUrlMethodName = "Href"
			};

			_codeGeneratorOptions = codeGeneratorOptions ?? new 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,
				BracingStyle = "C",
				// matches Razor built-in settings
				IndentString = String.Empty,
			};
		}

		public CodeDomProvider CodeDomProvider {
			get { return _codeDomProvider; }
		}

		public CodeGeneratorOptions CodeGeneratorOptions {
			get { return _codeGeneratorOptions; }
		}

		public string FullPath
		{
			get { return _fullPath; }
		}

		public override string DefaultClassName
		{
			get
			{
				return _defaultClassName ?? GetClassName();
			}
			set
			{
				if (!String.Equals(value, "__CompiledTemplate", StringComparison.OrdinalIgnoreCase))
				{
					//  By default RazorEngineHost assigns the name __CompiledTemplate. We'll ignore this assignment
					_defaultClassName = value;
				}
			}
		}

		public Func<RazorHost,ParserBase> ParserFactory { get; set; }

		public RazorCodeGenerator CodeGenerator { get; set; }

		public bool EnableLinePragmas { get; set; }

		public string GenerateCode (out CompilerErrorCollection errors)
		{
			errors = new CompilerErrorCollection ();

			// Create the engine
			RazorTemplateEngine engine = new RazorTemplateEngine(this);

			// Generate code
			GeneratorResults results = null;
			try
			{
				Stream stream = File.OpenRead(_fullPath);
				using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
				{
					results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath);
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}

			// Output errors
			foreach (RazorError error in results.ParserErrors) {
				errors.Add (new CompilerError (FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
			}

			try
			{
				using (StringWriter writer = new StringWriter()) {
					//Generate the code
					writer.WriteLine("#pragma warning disable 1591");
					_codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, _codeGeneratorOptions);
					writer.WriteLine("#pragma warning restore 1591");
					return writer.ToString();
				}
			} catch (Exception e) {
				errors.Add (new CompilerError (FullPath, 1, 1, null, e.ToString ()));
				//Returning null signifies that generation has failed
				return null;
			}
		}

		public override void PostProcessGeneratedCode(CodeGeneratorContext context)
		{
			if (_transformers == null) {
				return;
			}
			foreach (var t in _transformers) {
				t (this, context.CompileUnit, context.Namespace, context.GeneratedClass, context.TargetMethod);
			}
		}

		public override RazorCodeGenerator DecorateCodeGenerator(RazorCodeGenerator incomingCodeGenerator)
		{
			var codeGenerator = CodeGenerator ?? base.DecorateCodeGenerator(incomingCodeGenerator);
			codeGenerator.GenerateLinePragmas = EnableLinePragmas;
			return codeGenerator;
		}

		public override ParserBase DecorateCodeParser(ParserBase incomingCodeParser)
		{
			return ParserFactory != null? ParserFactory (this) : base.DecorateCodeParser(incomingCodeParser);
		}

		protected virtual string GetClassName()
		{
			string filename = Path.GetFileNameWithoutExtension(_fullPath);
			return ParserHelpers.SanitizeClassName(filename);
		}
	}
}