More passing tests.
[castle.git] / MonoRail / Castle.MonoRail.Views.Brail / BooViewEngine.cs
blob10b58430425893de686cbde845a580730c3ad9d5
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.CompilerServices;
24 using System.Runtime.Serialization;
25 using System.Text;
26 using System.Threading;
27 using System.Web;
28 using Boo.Lang.Compiler;
29 using Boo.Lang.Compiler.IO;
30 using Boo.Lang.Compiler.Pipelines;
31 using Boo.Lang.Compiler.Steps;
32 using Boo.Lang.Parser;
33 using Castle.Core.Logging;
34 using Castle.MonoRail.Framework.Test;
35 using Core;
36 using Framework;
38 public class BooViewEngine : ViewEngineBase, IInitializable
40 private static BooViewEngineOptions options;
42 /// <summary>
43 /// This field holds all the cache of all the
44 /// compiled types (not instances) of all the views that Brail nows of.
45 /// </summary>
46 private readonly Hashtable compilations = Hashtable.Synchronized(
47 new Hashtable(StringComparer.InvariantCultureIgnoreCase));
49 /// <summary>
50 /// used to hold the constructors of types, so we can avoid using
51 /// Activator (which takes a long time
52 /// </summary>
53 private readonly Hashtable constructors = new Hashtable();
55 private string baseSavePath;
57 /// <summary>
58 /// This is used to add a reference to the common scripts for each compiled scripts
59 /// </summary>
60 private Assembly common;
62 private ILogger logger;
64 public override bool SupportsJSGeneration
66 get { return true; }
69 public override string ViewFileExtension
71 get { return ".brail"; }
74 public override string JSGeneratorFileExtension
76 get { return ".brailjs"; }
79 public string ViewRootDir
81 get { return ViewSourceLoader.ViewRootDir; }
84 public BooViewEngineOptions Options
86 get { return options; }
87 set { options = value; }
90 #region IInitializable Members
92 public void Initialize()
94 if (options == null) InitializeConfig();
96 string baseDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
97 Log("Base Directory: " + baseDir);
98 baseSavePath = Path.Combine(baseDir, options.SaveDirectory);
99 Log("Base Save Path: " + baseSavePath);
101 if (options.SaveToDisk && !Directory.Exists(baseSavePath))
103 Directory.CreateDirectory(baseSavePath);
104 Log("Created directory " + baseSavePath);
107 CompileCommonScripts();
109 ViewSourceLoader.ViewChanged += OnViewChanged;
112 #endregion
114 // Process a template name and output the results to the user
115 // This may throw if an error occured and the user is not local (which would
116 // cause the yellow screen of death)
117 public override void Process(String templateName, TextWriter output, IEngineContext context, IController controller,
118 IControllerContext controllerContext)
120 Log("Starting to process request for {0}", templateName);
121 string file = templateName + ViewFileExtension;
122 BrailBase view;
123 // Output may be the layout's child output if a layout exists
124 // or the context.Response.Output if the layout is null
125 LayoutViewOutput layoutViewOutput = GetOutput(output, context, controller, controllerContext);
126 // Will compile on first time, then save the assembly on the cache.
127 view = GetCompiledScriptInstance(file, layoutViewOutput.Output, context, controller, controllerContext);
128 if (controller != null)
129 controller.PreSendView(view);
131 Log("Executing view {0}", templateName);
135 view.Run();
137 catch (Exception e)
139 HandleException(templateName, view, e);
142 if (layoutViewOutput.Layout != null)
144 layoutViewOutput.Layout.SetParent(view);
148 layoutViewOutput.Layout.Run();
150 catch (Exception e)
152 HandleException(controllerContext.LayoutNames[0], layoutViewOutput.Layout, e);
155 Log("Finished executing view {0}", templateName);
156 if (controller != null)
157 controller.PostSendView(view);
160 public override void Process(string templateName, string layoutName, TextWriter output,
161 IDictionary<string, object> parameters)
163 ControllerContext controllerContext = new ControllerContext();
164 if (layoutName != null)
166 controllerContext.LayoutNames = new string[] { layoutName };
168 foreach (KeyValuePair<string, object> pair in parameters)
170 controllerContext.PropertyBag[pair.Key] = pair.Value;
172 Process(templateName, output, null, null, controllerContext);
175 public override void ProcessPartial(string partialName, TextWriter output, IEngineContext context,
176 IController controller, IControllerContext controllerContext)
178 Log("Generating partial for {0}", partialName);
182 string file = ResolveTemplateName(partialName);
183 BrailBase view = GetCompiledScriptInstance(file, output, context, controller, controllerContext);
184 Log("Executing partial view {0}", partialName);
185 view.Run();
186 Log("Finished executing partial view {0}", partialName);
188 catch (Exception ex)
190 if (Logger != null && Logger.IsErrorEnabled)
192 Logger.Error("Could not generate JS", ex);
195 throw new MonoRailException("Error generating partial: " + partialName, ex);
199 public override object CreateJSGenerator(JSCodeGeneratorInfo generatorInfo, IEngineContext context,
200 IController controller,
201 IControllerContext controllerContext)
203 return new BrailJSGenerator(generatorInfo.CodeGenerator, generatorInfo.LibraryGenerator,
204 generatorInfo.Extensions, generatorInfo.ElementExtensions);
207 public override void GenerateJS(string templateName, TextWriter output, JSCodeGeneratorInfo generatorInfo,
208 IEngineContext context, IController controller, IControllerContext controllerContext)
210 Log("Generating JS for {0}", templateName);
214 object generator = CreateJSGenerator(generatorInfo, context, controller, controllerContext);
215 AdjustJavascriptContentType(context);
216 string file = ResolveJSTemplateName(templateName);
217 BrailBase view = GetCompiledScriptInstance(file,
218 //we use the script just to build the generator, not to output to the user
219 new StringWriter(),
220 context, controller, controllerContext);
221 Log("Executing JS view {0}", templateName);
222 view.AddProperty("page", generator);
223 view.Run();
225 output.WriteLine(generator);
226 Log("Finished executing JS view {0}", templateName);
228 catch (Exception ex)
230 if (Logger != null && Logger.IsErrorEnabled)
232 Logger.Error("Could not generate JS", ex);
235 throw new MonoRailException("Error generating JS. Template: " + templateName, ex);
239 /// <summary>
240 /// Wraps the specified content in the layout using the
241 /// context to output the result.
242 /// </summary>
243 /// <param name="contents"></param>
244 /// <param name="context"></param>
245 /// <param name="controller"></param>
246 /// <param name="controllerContext"></param>
247 public override void RenderStaticWithinLayout(String contents, IEngineContext context, IController controller,
248 IControllerContext controllerContext)
250 LayoutViewOutput layoutViewOutput = GetOutput(context.Response.Output, context, controller, controllerContext);
251 layoutViewOutput.Output.Write(contents);
252 // here we don't need to pass parameters from the layout to the view,
253 if (layoutViewOutput.Layout != null)
255 layoutViewOutput.Layout.Run();
259 private void HandleException(string templateName, BrailBase view, Exception e)
261 StringBuilder sb = new StringBuilder();
262 sb.Append("Exception on process view: ").AppendLine(templateName);
263 sb.Append("Last accessed variable: ").Append(view.LastVariableAccessed);
264 string msg = sb.ToString();
265 sb.Append("Exception: ").AppendLine(e.ToString());
266 Log(msg);
267 throw new MonoRailException(msg, e);
270 private void OnViewChanged(object sender, FileSystemEventArgs e)
272 string path = e.FullPath.Substring(ViewRootDir.Length);
273 if (path.Length > 0 && (path[0] == Path.DirectorySeparatorChar ||
274 path[0] == Path.AltDirectorySeparatorChar))
276 path = path.Substring(1);
278 if (path.IndexOf(options.CommonScriptsDirectory) != -1)
280 Log("Detected a change in commons scripts directory " + options.CommonScriptsDirectory + ", recompiling site");
281 // need to invalidate the entire CommonScripts assembly
282 // not worrying about concurrency here, since it is assumed
283 // that changes here are rare. Note, this force a recompile of the
284 // whole site!
287 WaitForFileToBecomeAvailableForReading(e);
288 CompileCommonScripts();
290 catch (Exception ex)
292 // we failed to recompile the commons scripts directory, but because we are running
293 // on another thread here, and exception would kill the application, so we log it
294 // and continue on. CompileCommonScripts() will only change the global state if it has
295 // successfully compiled the commons scripts directory.
296 Log("Failed to recompile the commons scripts directory! {0}", ex);
299 else
301 Log("Detected a change in {0}, removing from complied cache", e.Name);
302 // Will cause a recompilation
303 compilations[path] = null;
307 private static void WaitForFileToBecomeAvailableForReading(FileSystemEventArgs e)
309 // We may need to wait while the file is being written and closed to disk
310 int retries = 10;
311 bool successfullyOpenedFile = false;
312 while (retries != 0 && successfullyOpenedFile == false)
314 retries -= 1;
317 using (File.OpenRead(e.FullPath))
319 successfullyOpenedFile = true;
322 catch (IOException)
324 //The file is probably in locked because it is currently being written to,
325 // will wait a while for it to be freed.
326 // again, this isn't something that need to be very robust, it runs on a separate thread
327 // and if it fails, it is not going to do any damage
328 Thread.Sleep(250);
333 public void SetViewSourceLoader(IViewSourceLoader loader)
335 ViewSourceLoader = loader;
338 // Get configuration options if they exists, if they do not exist, load the default ones
339 // Create directory to save the compiled assemblies if required.
340 // pre-compile the common scripts
341 public override void Service(IServiceProvider serviceProvider)
343 base.Service(serviceProvider);
344 ILoggerFactory loggerFactory = serviceProvider.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
345 if (loggerFactory != null)
346 logger = loggerFactory.Create(GetType());
349 // Check if a layout has been defined. If it was, then the layout would be created
350 // and will take over the output, otherwise, the context.Reposne.Output is used,
351 // and layout is null
352 private LayoutViewOutput GetOutput(TextWriter output, IEngineContext context, IController controller,
353 IControllerContext controllerContext)
355 BrailBase layout = null;
356 if (controllerContext.LayoutNames != null && controllerContext.LayoutNames.Length != 0)
358 string layoutTemplate = controllerContext.LayoutNames[0];
359 if (layoutTemplate.StartsWith("/") == false)
361 layoutTemplate = "layouts\\" + layoutTemplate;
363 string layoutFilename = layoutTemplate + ViewFileExtension;
364 layout = GetCompiledScriptInstance(layoutFilename, output,
365 context, controller, controllerContext);
366 output = layout.ChildOutput = new StringWriter();
368 return new LayoutViewOutput(output, layout);
371 /// <summary>
372 /// This takes a filename and return an instance of the view ready to be used.
373 /// If the file does not exist, an exception is raised
374 /// The cache is checked to see if the file has already been compiled, and it had been
375 /// a check is made to see that the compiled instance is newer then the file's modification date.
376 /// If the file has not been compiled, or the version on disk is newer than the one in memory, a new
377 /// version is compiled.
378 /// Finally, an instance is created and returned
379 /// </summary>
380 public BrailBase GetCompiledScriptInstance(
381 string file,
382 TextWriter output,
383 IEngineContext context,
384 IController controller, IControllerContext controllerContext)
386 bool batch = options.BatchCompile;
388 // normalize filename - replace / or \ to the system path seperator
389 string filename = file.Replace('/', Path.DirectorySeparatorChar)
390 .Replace('\\', Path.DirectorySeparatorChar);
392 Log("Getting compiled instnace of {0}", filename);
394 Type type;
396 if (compilations.ContainsKey(filename))
398 type = (Type)compilations[filename];
399 if (type != null)
401 Log("Got compiled instance of {0} from cache", filename);
402 return CreateBrailBase(context, controller, controllerContext, output, type);
404 // if file is in compilations and the type is null,
405 // this means that we need to recompile. Since this usually means that
406 // the file was changed, we'll set batch to false and procceed to compile just
407 // this file.
408 Log("Cache miss! Need to recompile {0}", filename);
409 batch = false;
412 type = CompileScript(filename, batch);
414 if (type == null)
416 throw new MonoRailException("Could not find a view with path " + filename);
419 return CreateBrailBase(context, controller, controllerContext, output, type);
422 private BrailBase CreateBrailBase(IEngineContext context, IController controller, IControllerContext controllerContext,
423 TextWriter output, Type type)
425 ConstructorInfo constructor = (ConstructorInfo)constructors[type];
426 BrailBase self = (BrailBase)FormatterServices.GetUninitializedObject(type);
427 constructor.Invoke(self, new object[] { this, output, context, controller, controllerContext });
428 return self;
431 // Compile a script (or all scripts in a directory), save the compiled result
432 // to the cache and return the compiled type.
433 // If an error occurs in batch compilation, then an attempt is made to compile just the single
434 // request file.
435 [MethodImpl(MethodImplOptions.Synchronized)]
436 public Type CompileScript(string filename, bool batch)
438 IDictionary<ICompilerInput, string> inputs2FileName = GetInput(filename, batch);
439 string name = NormalizeName(filename);
440 Log("Compiling {0} to {1} with batch: {2}", filename, name, batch);
441 CompilationResult result = DoCompile(inputs2FileName.Keys, name);
443 if (result.Context.Errors.Count > 0)
445 if (batch == false)
447 RaiseCompilationException(filename, inputs2FileName, result);
449 //error compiling a batch, let's try a single file
450 return CompileScript(filename, false);
452 Type type;
453 foreach (ICompilerInput input in inputs2FileName.Keys)
455 string viewName = Path.GetFileNameWithoutExtension(input.Name);
456 string typeName = TransformToBrailStep.GetViewTypeName(viewName);
457 type = result.Context.GeneratedAssembly.GetType(typeName);
458 Log("Adding {0} to the cache", type.FullName);
459 constructors[type] = type.GetConstructor(new Type[]
461 typeof(BooViewEngine),
462 typeof(TextWriter),
463 typeof(IEngineContext),
464 typeof(IController),
465 typeof(IControllerContext)
467 compilations[inputs2FileName[input]] = type;
469 type = (Type)compilations[filename];
470 return type;
473 private void RaiseCompilationException(string filename, IDictionary<ICompilerInput, string> inputs2FileName,
474 CompilationResult result)
476 string errors = result.Context.Errors.ToString(true);
477 Log("Failed to compile {0} because {1}", filename, errors);
478 StringBuilder code = new StringBuilder();
479 foreach (ICompilerInput input in inputs2FileName.Keys)
481 code.AppendLine()
482 .Append(result.Processor.GetInputCode(input))
483 .AppendLine();
485 throw new HttpParseException("Error compiling Brail code",
486 result.Context.Errors[0],
487 filename,
488 code.ToString(), result.Context.Errors[0].LexicalInfo.Line);
491 // If batch compilation is set to true, this would return all the view scripts
492 // in the director (not recursive!)
493 // Otherwise, it would return just the single file
494 private IDictionary<ICompilerInput, string> GetInput(string filename, bool batch)
496 Dictionary<ICompilerInput, string> input2FileName = new Dictionary<ICompilerInput, string>();
497 if (batch == false)
499 input2FileName.Add(CreateInput(filename), filename);
500 return input2FileName;
502 // use the System.IO.Path to get the folder name even though
503 // we are using the ViewSourceLoader to load the actual file
504 string directory = Path.GetDirectoryName(filename);
505 foreach (string file in ViewSourceLoader.ListViews(directory))
507 ICompilerInput input = CreateInput(file);
508 input2FileName.Add(input, file);
510 return input2FileName;
513 // create an input from a resource name
514 public ICompilerInput CreateInput(string name)
516 IViewSource viewSrc = ViewSourceLoader.GetViewSource(name);
517 if (viewSrc == null)
519 throw new MonoRailException("{0} is not a valid view", name);
521 // I need to do it this way because I can't tell
522 // when to dispose of the stream.
523 // It is not expected that this will be a big problem, the string
524 // will go away after the compile is done with them.
525 using (StreamReader stream = new StreamReader(viewSrc.OpenViewStream()))
527 return new StringInput(name, stream.ReadToEnd());
531 /// <summary>
532 /// Perform the actual compilation of the scripts
533 /// Things to note here:
534 /// * The generated assembly reference the Castle.MonoRail.MonoRailBrail and Castle.MonoRail.Framework assemblies
535 /// * If a common scripts assembly exist, it is also referenced
536 /// * The AddBrailBaseClassStep compiler step is added - to create a class from the view's code
537 /// * The ProcessMethodBodiesWithDuckTyping is replaced with ReplaceUknownWithParameters
538 /// this allows to use naked parameters such as (output context.IsLocal) without using
539 /// any special syntax
540 /// * The FixTryGetParameterConditionalChecks is run afterward, to transform "if ?Error" to "if not ?Error isa IgnoreNull"
541 /// * The ExpandDuckTypedExpressions is replace with a derived step that allows the use of Dynamic Proxy assemblies
542 /// * The IntroduceGlobalNamespaces step is removed, to allow to use common variables such as
543 /// date and list without accidently using the Boo.Lang.BuiltIn versions
544 /// </summary>
545 /// <param name="files"></param>
546 /// <param name="name"></param>
547 /// <returns></returns>
548 private CompilationResult DoCompile(IEnumerable<ICompilerInput> files, string name)
550 ICompilerInput[] filesAsArray = new List<ICompilerInput>(files).ToArray();
551 BooCompiler compiler = SetupCompiler(filesAsArray);
552 string filename = Path.Combine(baseSavePath, name);
553 compiler.Parameters.OutputAssembly = filename;
554 // this is here and not in SetupCompiler since CompileCommon is also
555 // using SetupCompiler, and we don't want reference to the old common from the new one
556 if (common != null)
557 compiler.Parameters.References.Add(common);
558 // pre procsssor needs to run before the parser
559 BrailPreProcessor processor = new BrailPreProcessor(this);
560 compiler.Parameters.Pipeline.Insert(0, processor);
561 // inserting the add class step after the parser
562 compiler.Parameters.Pipeline.Insert(2, new TransformToBrailStep(options));
563 compiler.Parameters.Pipeline.Replace(typeof(ProcessMethodBodiesWithDuckTyping),
564 new ReplaceUknownWithParameters());
565 compiler.Parameters.Pipeline.Replace(typeof(ExpandDuckTypedExpressions),
566 new ExpandDuckTypedExpressions_WorkaroundForDuplicateVirtualMethods());
567 compiler.Parameters.Pipeline.Replace(typeof(InitializeTypeSystemServices),
568 new InitializeCustomTypeSystem());
569 compiler.Parameters.Pipeline.InsertBefore(typeof(ReplaceUknownWithParameters),
570 new FixTryGetParameterConditionalChecks());
571 compiler.Parameters.Pipeline.RemoveAt(compiler.Parameters.Pipeline.Find(typeof(IntroduceGlobalNamespaces)));
573 return new CompilationResult(compiler.Run(), processor);
576 // Return the output filename for the generated assembly
577 // The filename is dependant on whatever we are doing a batch
578 // compile or not, if it's a batch compile, then the directory name
579 // is used, if it's just a single file, we're using the file's name.
580 // '/' and '\' are replaced with '_', I'm not handling ':' since the path
581 // should never include it since I'm converting this to a relative path
582 public string NormalizeName(string filename)
584 string name = filename;
585 name = name.Replace(Path.AltDirectorySeparatorChar, '_');
586 name = name.Replace(Path.DirectorySeparatorChar, '_');
588 return name + "_BrailView.dll";
591 // Compile all the common scripts to a common assemblies
592 // an error in the common scripts would raise an exception.
593 public bool CompileCommonScripts()
595 if (options.CommonScriptsDirectory == null)
596 return false;
598 // the demi.boo is stripped, but GetInput require it.
599 string demiFile = Path.Combine(options.CommonScriptsDirectory, "demi.brail");
600 IDictionary<ICompilerInput, string> inputs = GetInput(demiFile, true);
601 ICompilerInput[] inputsAsArray = new List<ICompilerInput>(inputs.Keys).ToArray();
602 BooCompiler compiler = SetupCompiler(inputsAsArray);
603 string outputFile = Path.Combine(baseSavePath, "CommonScripts.dll");
604 compiler.Parameters.OutputAssembly = outputFile;
605 CompilerContext result = compiler.Run();
606 if (result.Errors.Count > 0)
607 throw new MonoRailException(result.Errors.ToString(true));
608 common = result.GeneratedAssembly;
609 compilations.Clear();
610 return true;
613 // common setup for the compiler
614 private static BooCompiler SetupCompiler(IEnumerable<ICompilerInput> files)
616 BooCompiler compiler = new BooCompiler();
617 compiler.Parameters.Ducky = true;
618 compiler.Parameters.Debug = options.Debug;
619 if (options.SaveToDisk)
620 compiler.Parameters.Pipeline = new CompileToFile();
621 else
622 compiler.Parameters.Pipeline = new CompileToMemory();
623 // replace the normal parser with white space agnostic one.
624 compiler.Parameters.Pipeline.RemoveAt(0);
625 compiler.Parameters.Pipeline.Insert(0, new WSABooParsingStep());
626 foreach (ICompilerInput file in files)
628 compiler.Parameters.Input.Add(file);
630 foreach (Assembly assembly in options.AssembliesToReference)
632 compiler.Parameters.References.Add(assembly);
634 compiler.Parameters.OutputType = CompilerOutputType.Library;
635 return compiler;
638 private static void InitializeConfig()
640 InitializeConfig("brail");
642 if (options == null)
644 InitializeConfig("Brail");
647 if (options == null)
649 options = new BooViewEngineOptions();
653 private static void InitializeConfig(string sectionName)
655 options = ConfigurationManager.GetSection(sectionName) as BooViewEngineOptions;
658 private void Log(string msg, params object[] items)
660 if (logger == null || logger.IsDebugEnabled == false)
661 return;
662 logger.DebugFormat(msg, items);
665 public bool ConditionalPreProcessingOnly(string name)
667 return String.Equals(
668 Path.GetExtension(name),
669 JSGeneratorFileExtension,
670 StringComparison.InvariantCultureIgnoreCase);
673 #region Nested type: CompilationResult
675 private class CompilationResult
677 private readonly CompilerContext context;
678 private readonly BrailPreProcessor processor;
680 public CompilationResult(CompilerContext context, BrailPreProcessor processor)
682 this.context = context;
683 this.processor = processor;
686 public CompilerContext Context
688 get { return context; }
691 public BrailPreProcessor Processor
693 get { return processor; }
697 #endregion
699 #region Nested type: LayoutViewOutput
701 private class LayoutViewOutput
703 private readonly BrailBase layout;
704 private readonly TextWriter output;
706 public LayoutViewOutput(TextWriter output, BrailBase layout)
708 this.layout = layout;
709 this.output = output;
712 public BrailBase Layout
714 get { return layout; }
717 public TextWriter Output
719 get { return output; }
723 #endregion