Starting to port Brail tests to new test approach.
[castle.git] / MonoRail / Castle.MonoRail.Views.Brail / BooViewEngine.cs
blob55d6e0d00b71573827127178e9c71b14ce12ec26
1 // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.MonoRail.Views.Brail
17 using System;
18 using System.Collections;
19 using System.Collections.Generic;
20 using System.Configuration;
21 using System.IO;
22 using System.Reflection;
23 using System.Runtime.Serialization;
24 using System.Text;
25 using System.Threading;
26 using System.Web;
27 using Boo.Lang.Compiler;
28 using Boo.Lang.Compiler.IO;
29 using Boo.Lang.Compiler.Pipelines;
30 using Boo.Lang.Compiler.Steps;
31 using Boo.Lang.Parser;
32 using Castle.Core.Logging;
33 using Castle.MonoRail.Framework.Test;
34 using Core;
35 using Framework;
37 public class BooViewEngine : ViewEngineBase, IInitializable
39 private static BooViewEngineOptions options;
41 /// <summary>
42 /// This field holds all the cache of all the
43 /// compiled types (not instances) of all the views that Brail nows of.
44 /// </summary>
45 private readonly Hashtable compilations = Hashtable.Synchronized(
46 new Hashtable(StringComparer.InvariantCultureIgnoreCase));
48 /// <summary>
49 /// used to hold the constructors of types, so we can avoid using
50 /// Activator (which takes a long time
51 /// </summary>
52 private readonly Hashtable constructors = new Hashtable();
54 private string baseSavePath;
56 /// <summary>
57 /// This is used to add a reference to the common scripts for each compiled scripts
58 /// </summary>
59 private Assembly common;
61 private ILogger logger;
63 public override bool SupportsJSGeneration
65 get { return true; }
68 public override string ViewFileExtension
70 get { return ".brail"; }
73 public override string JSGeneratorFileExtension
75 get { return ".brailjs"; }
78 public string ViewRootDir
80 get { return ViewSourceLoader.ViewRootDir; }
83 public BooViewEngineOptions Options
85 get { return options; }
86 set { options = value; }
89 #region IInitializable Members
91 public void Initialize()
93 if (options == null) InitializeConfig();
95 string baseDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
96 Log("Base Directory: " + baseDir);
97 baseSavePath = Path.Combine(baseDir, options.SaveDirectory);
98 Log("Base Save Path: " + baseSavePath);
100 if (options.SaveToDisk && !Directory.Exists(baseSavePath))
102 Directory.CreateDirectory(baseSavePath);
103 Log("Created directory " + baseSavePath);
106 CompileCommonScripts();
108 ViewSourceLoader.ViewChanged += OnViewChanged;
111 #endregion
113 // Process a template name and output the results to the user
114 // This may throw if an error occured and the user is not local (which would
115 // cause the yellow screen of death)
116 public override void Process(String templateName, TextWriter output, IEngineContext context, IController controller,
117 IControllerContext controllerContext)
119 Log("Starting to process request for {0}", templateName);
120 string file = templateName + ViewFileExtension;
121 BrailBase view;
122 // Output may be the layout's child output if a layout exists
123 // or the context.Response.Output if the layout is null
124 LayoutViewOutput layoutViewOutput = GetOutput(output, context, controller, controllerContext);
125 // Will compile on first time, then save the assembly on the cache.
126 view = GetCompiledScriptInstance(file, layoutViewOutput.Output, context, controller, controllerContext);
127 if (controller != null)
128 controller.PreSendView(view);
130 Log("Executing view {0}", templateName);
134 view.Run();
136 catch (Exception e)
138 HandleException(templateName, view, e);
141 if (layoutViewOutput.Layout != null)
143 layoutViewOutput.Layout.SetParent(view);
147 layoutViewOutput.Layout.Run();
149 catch (Exception e)
151 HandleException(controllerContext.LayoutNames[0], layoutViewOutput.Layout, e);
154 Log("Finished executing view {0}", templateName);
155 if (controller != null)
156 controller.PostSendView(view);
159 public override void Process(string templateName, string layoutName, TextWriter output,
160 IDictionary<string, object> parameters)
162 ControllerContext controllerContext = new ControllerContext();
163 if (layoutName != null)
165 controllerContext.LayoutNames = new string[] { layoutName };
167 foreach (KeyValuePair<string, object> pair in parameters)
169 controllerContext.PropertyBag[pair.Key] = pair.Value;
171 Process(templateName, output, null, null, controllerContext);
174 public override void ProcessPartial(string partialName, TextWriter output, IEngineContext context,
175 IController controller, IControllerContext controllerContext)
177 Log("Generating partial for {0}", partialName);
181 string file = ResolveTemplateName(partialName);
182 BrailBase view = GetCompiledScriptInstance(file, output, context, controller, controllerContext);
183 Log("Executing partial view {0}", partialName);
184 view.Run();
185 Log("Finished executing partial view {0}", partialName);
187 catch (Exception ex)
189 if (Logger != null && Logger.IsErrorEnabled)
191 Logger.Error("Could not generate JS", ex);
194 throw new MonoRailException("Error generating partial: " + partialName, ex);
198 public override object CreateJSGenerator(JSCodeGeneratorInfo generatorInfo, IEngineContext context,
199 IController controller,
200 IControllerContext controllerContext)
202 return new BrailJSGenerator(generatorInfo.CodeGenerator, generatorInfo.LibraryGenerator,
203 generatorInfo.Extensions, generatorInfo.ElementExtensions);
206 public override void GenerateJS(string templateName, TextWriter output, JSCodeGeneratorInfo generatorInfo,
207 IEngineContext context, IController controller, IControllerContext controllerContext)
209 Log("Generating JS for {0}", templateName);
213 object generator = CreateJSGenerator(generatorInfo, context, controller, controllerContext);
214 AdjustJavascriptContentType(context);
215 string file = ResolveJSTemplateName(templateName);
216 BrailBase view = GetCompiledScriptInstance(file,
217 //we use the script just to build the generator, not to output to the user
218 new StringWriter(),
219 context, controller, controllerContext);
220 Log("Executing JS view {0}", templateName);
221 view.AddProperty("page", generator);
222 view.Run();
224 output.WriteLine(generator);
225 Log("Finished executing JS view {0}", templateName);
227 catch (Exception ex)
229 if (Logger != null && Logger.IsErrorEnabled)
231 Logger.Error("Could not generate JS", ex);
234 throw new MonoRailException("Error generating JS. Template: " + templateName, ex);
238 /// <summary>
239 /// Wraps the specified content in the layout using the
240 /// context to output the result.
241 /// </summary>
242 /// <param name="contents"></param>
243 /// <param name="context"></param>
244 /// <param name="controller"></param>
245 /// <param name="controllerContext"></param>
246 public override void RenderStaticWithinLayout(String contents, IEngineContext context, IController controller,
247 IControllerContext controllerContext)
249 LayoutViewOutput layoutViewOutput = GetOutput(context.Response.Output, context, controller, controllerContext);
250 layoutViewOutput.Output.Write(contents);
251 // here we don't need to pass parameters from the layout to the view,
252 if (layoutViewOutput.Layout != null)
254 layoutViewOutput.Layout.Run();
258 private void HandleException(string templateName, BrailBase view, Exception e)
260 StringBuilder sb = new StringBuilder();
261 sb.Append("Exception on process view: ").AppendLine(templateName);
262 sb.Append("Last accessed variable: ").Append(view.LastVariableAccessed);
263 string msg = sb.ToString();
264 sb.Append("Exception: ").AppendLine(e.ToString());
265 Log(msg);
266 throw new MonoRailException(msg, e);
269 private void OnViewChanged(object sender, FileSystemEventArgs e)
271 string path = e.FullPath.Substring(ViewRootDir.Length);
272 if (path.Length > 0 && (path[0] == Path.DirectorySeparatorChar ||
273 path[0] == Path.AltDirectorySeparatorChar))
275 path = path.Substring(1);
277 if (path.IndexOf(options.CommonScriptsDirectory) != -1)
279 Log("Detected a change in commons scripts directory " + options.CommonScriptsDirectory + ", recompiling site");
280 // need to invalidate the entire CommonScripts assembly
281 // not worrying about concurrency here, since it is assumed
282 // that changes here are rare. Note, this force a recompile of the
283 // whole site!
286 WaitForFileToBecomeAvailableForReading(e);
287 CompileCommonScripts();
289 catch (Exception ex)
291 // we failed to recompile the commons scripts directory, but because we are running
292 // on another thread here, and exception would kill the application, so we log it
293 // and continue on. CompileCommonScripts() will only change the global state if it has
294 // successfully compiled the commons scripts directory.
295 Log("Failed to recompile the commons scripts directory! {0}", ex);
298 else
300 Log("Detected a change in {0}, removing from complied cache", e.Name);
301 // Will cause a recompilation
302 compilations[path] = null;
306 private static void WaitForFileToBecomeAvailableForReading(FileSystemEventArgs e)
308 // We may need to wait while the file is being written and closed to disk
309 int retries = 10;
310 bool successfullyOpenedFile = false;
311 while (retries != 0 && successfullyOpenedFile == false)
313 retries -= 1;
316 using (File.OpenRead(e.FullPath))
318 successfullyOpenedFile = true;
321 catch (IOException)
323 //The file is probably in locked because it is currently being written to,
324 // will wait a while for it to be freed.
325 // again, this isn't something that need to be very robust, it runs on a separate thread
326 // and if it fails, it is not going to do any damage
327 Thread.Sleep(250);
332 public void SetViewSourceLoader(IViewSourceLoader loader)
334 ViewSourceLoader = loader;
337 // Get configuration options if they exists, if they do not exist, load the default ones
338 // Create directory to save the compiled assemblies if required.
339 // pre-compile the common scripts
340 public override void Service(IServiceProvider serviceProvider)
342 base.Service(serviceProvider);
343 ILoggerFactory loggerFactory = serviceProvider.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
344 if (loggerFactory != null)
345 logger = loggerFactory.Create(GetType());
348 // Check if a layout has been defined. If it was, then the layout would be created
349 // and will take over the output, otherwise, the context.Reposne.Output is used,
350 // and layout is null
351 private LayoutViewOutput GetOutput(TextWriter output, IEngineContext context, IController controller,
352 IControllerContext controllerContext)
354 BrailBase layout = null;
355 if (controllerContext.LayoutNames != null && controllerContext.LayoutNames.Length != 0)
357 string layoutTemplate = controllerContext.LayoutNames[0];
358 if (layoutTemplate.StartsWith("/") == false)
360 layoutTemplate = "layouts\\" + layoutTemplate;
362 string layoutFilename = layoutTemplate + ViewFileExtension;
363 layout = GetCompiledScriptInstance(layoutFilename, output,
364 context, controller, controllerContext);
365 output = layout.ChildOutput = new StringWriter();
367 return new LayoutViewOutput(output, layout);
370 /// <summary>
371 /// This takes a filename and return an instance of the view ready to be used.
372 /// If the file does not exist, an exception is raised
373 /// The cache is checked to see if the file has already been compiled, and it had been
374 /// a check is made to see that the compiled instance is newer then the file's modification date.
375 /// If the file has not been compiled, or the version on disk is newer than the one in memory, a new
376 /// version is compiled.
377 /// Finally, an instance is created and returned
378 /// </summary>
379 public BrailBase GetCompiledScriptInstance(
380 string file,
381 TextWriter output,
382 IEngineContext context,
383 IController controller, IControllerContext controllerContext)
385 bool batch = options.BatchCompile;
387 // normalize filename - replace / or \ to the system path seperator
388 string filename = file.Replace('/', Path.DirectorySeparatorChar)
389 .Replace('\\', Path.DirectorySeparatorChar);
391 Log("Getting compiled instnace of {0}", filename);
393 Type type;
395 if (compilations.ContainsKey(filename))
397 type = (Type)compilations[filename];
398 if (type != null)
400 Log("Got compiled instance of {0} from cache", filename);
401 return CreateBrailBase(context, controller, controllerContext, output, type);
403 // if file is in compilations and the type is null,
404 // this means that we need to recompile. Since this usually means that
405 // the file was changed, we'll set batch to false and procceed to compile just
406 // this file.
407 Log("Cache miss! Need to recompile {0}", filename);
408 batch = false;
411 type = CompileScript(filename, batch);
413 if (type == null)
415 throw new MonoRailException("Could not find a view with path " + filename);
418 return CreateBrailBase(context, controller, controllerContext, output, type);
421 private BrailBase CreateBrailBase(IEngineContext context, IController controller, IControllerContext controllerContext,
422 TextWriter output, Type type)
424 ConstructorInfo constructor = (ConstructorInfo)constructors[type];
425 BrailBase self = (BrailBase)FormatterServices.GetUninitializedObject(type);
426 constructor.Invoke(self, new object[] { this, output, context, controller, controllerContext });
427 return self;
430 // Compile a script (or all scripts in a directory), save the compiled result
431 // to the cache and return the compiled type.
432 // If an error occurs in batch compilation, then an attempt is made to compile just the single
433 // request file.
434 public Type CompileScript(string filename, bool batch)
436 IDictionary<ICompilerInput, string> inputs2FileName = GetInput(filename, batch);
437 string name = NormalizeName(filename);
438 Log("Compiling {0} to {1} with batch: {2}", filename, name, batch);
439 CompilationResult result = DoCompile(inputs2FileName.Keys, name);
441 if (result.Context.Errors.Count > 0)
443 if (batch == false)
445 RaiseCompilationException(filename, inputs2FileName, result);
447 //error compiling a batch, let's try a single file
448 return CompileScript(filename, false);
450 Type type;
451 foreach (ICompilerInput input in inputs2FileName.Keys)
453 string viewName = Path.GetFileNameWithoutExtension(input.Name);
454 string typeName = TransformToBrailStep.GetViewTypeName(viewName);
455 type = result.Context.GeneratedAssembly.GetType(typeName);
456 Log("Adding {0} to the cache", type.FullName);
457 compilations[inputs2FileName[input]] = type;
458 constructors[type] = type.GetConstructor(new Type[]
460 typeof(BooViewEngine),
461 typeof(TextWriter),
462 typeof(IEngineContext),
463 typeof(IController),
464 typeof(IControllerContext)
467 type = (Type)compilations[filename];
468 return type;
471 private void RaiseCompilationException(string filename, IDictionary<ICompilerInput, string> inputs2FileName,
472 CompilationResult result)
474 string errors = result.Context.Errors.ToString(true);
475 Log("Failed to compile {0} because {1}", filename, errors);
476 StringBuilder code = new StringBuilder();
477 foreach (ICompilerInput input in inputs2FileName.Keys)
479 code.AppendLine()
480 .Append(result.Processor.GetInputCode(input))
481 .AppendLine();
483 throw new HttpParseException("Error compiling Brail code",
484 result.Context.Errors[0],
485 filename,
486 code.ToString(), result.Context.Errors[0].LexicalInfo.Line);
489 // If batch compilation is set to true, this would return all the view scripts
490 // in the director (not recursive!)
491 // Otherwise, it would return just the single file
492 private IDictionary<ICompilerInput, string> GetInput(string filename, bool batch)
494 Dictionary<ICompilerInput, string> input2FileName = new Dictionary<ICompilerInput, string>();
495 if (batch == false)
497 input2FileName.Add(CreateInput(filename), filename);
498 return input2FileName;
500 // use the System.IO.Path to get the folder name even though
501 // we are using the ViewSourceLoader to load the actual file
502 string directory = Path.GetDirectoryName(filename);
503 foreach (string file in ViewSourceLoader.ListViews(directory))
505 ICompilerInput input = CreateInput(file);
506 input2FileName.Add(input, file);
508 return input2FileName;
511 // create an input from a resource name
512 public ICompilerInput CreateInput(string name)
514 IViewSource viewSrc = ViewSourceLoader.GetViewSource(name);
515 if (viewSrc == null)
517 throw new MonoRailException("{0} is not a valid view", name);
519 // I need to do it this way because I can't tell
520 // when to dispose of the stream.
521 // It is not expected that this will be a big problem, the string
522 // will go away after the compile is done with them.
523 using (StreamReader stream = new StreamReader(viewSrc.OpenViewStream()))
525 return new StringInput(name, stream.ReadToEnd());
529 /// <summary>
530 /// Perform the actual compilation of the scripts
531 /// Things to note here:
532 /// * The generated assembly reference the Castle.MonoRail.MonoRailBrail and Castle.MonoRail.Framework assemblies
533 /// * If a common scripts assembly exist, it is also referenced
534 /// * The AddBrailBaseClassStep compiler step is added - to create a class from the view's code
535 /// * The ProcessMethodBodiesWithDuckTyping is replaced with ReplaceUknownWithParameters
536 /// this allows to use naked parameters such as (output context.IsLocal) without using
537 /// any special syntax
538 /// * The FixTryGetParameterConditionalChecks is run afterward, to transform "if ?Error" to "if not ?Error isa IgnoreNull"
539 /// * The ExpandDuckTypedExpressions is replace with a derived step that allows the use of Dynamic Proxy assemblies
540 /// * The IntroduceGlobalNamespaces step is removed, to allow to use common variables such as
541 /// date and list without accidently using the Boo.Lang.BuiltIn versions
542 /// </summary>
543 /// <param name="files"></param>
544 /// <param name="name"></param>
545 /// <returns></returns>
546 private CompilationResult DoCompile(IEnumerable<ICompilerInput> files, string name)
548 ICompilerInput[] filesAsArray = new List<ICompilerInput>(files).ToArray();
549 BooCompiler compiler = SetupCompiler(filesAsArray);
550 string filename = Path.Combine(baseSavePath, name);
551 compiler.Parameters.OutputAssembly = filename;
552 // this is here and not in SetupCompiler since CompileCommon is also
553 // using SetupCompiler, and we don't want reference to the old common from the new one
554 if (common != null)
555 compiler.Parameters.References.Add(common);
556 // pre procsssor needs to run before the parser
557 BrailPreProcessor processor = new BrailPreProcessor(this);
558 compiler.Parameters.Pipeline.Insert(0, processor);
559 // inserting the add class step after the parser
560 compiler.Parameters.Pipeline.Insert(2, new TransformToBrailStep(options));
561 compiler.Parameters.Pipeline.Replace(typeof(ProcessMethodBodiesWithDuckTyping),
562 new ReplaceUknownWithParameters());
563 compiler.Parameters.Pipeline.Replace(typeof(ExpandDuckTypedExpressions),
564 new ExpandDuckTypedExpressions_WorkaroundForDuplicateVirtualMethods());
565 compiler.Parameters.Pipeline.Replace(typeof(InitializeTypeSystemServices),
566 new InitializeCustomTypeSystem());
567 compiler.Parameters.Pipeline.InsertBefore(typeof(ReplaceUknownWithParameters),
568 new FixTryGetParameterConditionalChecks());
569 compiler.Parameters.Pipeline.RemoveAt(compiler.Parameters.Pipeline.Find(typeof(IntroduceGlobalNamespaces)));
571 return new CompilationResult(compiler.Run(), processor);
574 // Return the output filename for the generated assembly
575 // The filename is dependant on whatever we are doing a batch
576 // compile or not, if it's a batch compile, then the directory name
577 // is used, if it's just a single file, we're using the file's name.
578 // '/' and '\' are replaced with '_', I'm not handling ':' since the path
579 // should never include it since I'm converting this to a relative path
580 public string NormalizeName(string filename)
582 string name = filename;
583 name = name.Replace(Path.AltDirectorySeparatorChar, '_');
584 name = name.Replace(Path.DirectorySeparatorChar, '_');
586 return name + "_BrailView.dll";
589 // Compile all the common scripts to a common assemblies
590 // an error in the common scripts would raise an exception.
591 public bool CompileCommonScripts()
593 if (options.CommonScriptsDirectory == null)
594 return false;
596 // the demi.boo is stripped, but GetInput require it.
597 string demiFile = Path.Combine(options.CommonScriptsDirectory, "demi.brail");
598 IDictionary<ICompilerInput, string> inputs = GetInput(demiFile, true);
599 ICompilerInput[] inputsAsArray = new List<ICompilerInput>(inputs.Keys).ToArray();
600 BooCompiler compiler = SetupCompiler(inputsAsArray);
601 string outputFile = Path.Combine(baseSavePath, "CommonScripts.dll");
602 compiler.Parameters.OutputAssembly = outputFile;
603 CompilerContext result = compiler.Run();
604 if (result.Errors.Count > 0)
605 throw new MonoRailException(result.Errors.ToString(true));
606 common = result.GeneratedAssembly;
607 compilations.Clear();
608 return true;
611 // common setup for the compiler
612 private static BooCompiler SetupCompiler(IEnumerable<ICompilerInput> files)
614 BooCompiler compiler = new BooCompiler();
615 compiler.Parameters.Ducky = true;
616 compiler.Parameters.Debug = options.Debug;
617 if (options.SaveToDisk)
618 compiler.Parameters.Pipeline = new CompileToFile();
619 else
620 compiler.Parameters.Pipeline = new CompileToMemory();
621 // replace the normal parser with white space agnostic one.
622 compiler.Parameters.Pipeline.RemoveAt(0);
623 compiler.Parameters.Pipeline.Insert(0, new WSABooParsingStep());
624 foreach (ICompilerInput file in files)
626 compiler.Parameters.Input.Add(file);
628 foreach (Assembly assembly in options.AssembliesToReference)
630 compiler.Parameters.References.Add(assembly);
632 compiler.Parameters.OutputType = CompilerOutputType.Library;
633 return compiler;
636 private static void InitializeConfig()
638 InitializeConfig("brail");
640 if (options == null)
642 InitializeConfig("Brail");
645 if (options == null)
647 options = new BooViewEngineOptions();
651 private static void InitializeConfig(string sectionName)
653 options = ConfigurationManager.GetSection(sectionName) as BooViewEngineOptions;
656 private void Log(string msg, params object[] items)
658 if (logger == null || logger.IsDebugEnabled == false)
659 return;
660 logger.DebugFormat(msg, items);
663 public bool ConditionalPreProcessingOnly(string name)
665 return String.Equals(
666 Path.GetExtension(name),
667 JSGeneratorFileExtension,
668 StringComparison.InvariantCultureIgnoreCase);
671 #region Nested type: CompilationResult
673 private class CompilationResult
675 private readonly CompilerContext context;
676 private readonly BrailPreProcessor processor;
678 public CompilationResult(CompilerContext context, BrailPreProcessor processor)
680 this.context = context;
681 this.processor = processor;
684 public CompilerContext Context
686 get { return context; }
689 public BrailPreProcessor Processor
691 get { return processor; }
695 #endregion
697 #region Nested type: LayoutViewOutput
699 private class LayoutViewOutput
701 private readonly BrailBase layout;
702 private readonly TextWriter output;
704 public LayoutViewOutput(TextWriter output, BrailBase layout)
706 this.layout = layout;
707 this.output = output;
710 public BrailBase Layout
712 get { return layout; }
715 public TextWriter Output
717 get { return output; }
721 #endregion