/** The primary means of getting an instance of a template from this * group. Names must be absolute, fully-qualified names like a/b */ public virtual Template GetInstanceOf(string name) { if (name == null) { return(null); } //System.out.println("GetInstanceOf("+name+")"); CompiledTemplate c = LookupTemplate(name); if (c != null) { Template instanceST = CreateStringTemplate(); instanceST.groupThatCreatedThisInstance = this; instanceST.impl = c; if (instanceST.impl.FormalArguments != null) { instanceST.locals = new object[instanceST.impl.FormalArguments.Count]; for (int i = 0; i < instanceST.locals.Length; i++) { instanceST.locals[i] = Template.EmptyAttribute; } } return(instanceST); } return(null); }
public virtual string Show() { StringBuilder buf = new StringBuilder(); if (imports != null && imports.Count > 0) { buf.Append(" : " + imports); } foreach (string n in templates.Keys) { string name = n; CompiledTemplate c = templates[name]; if (c.isAnonSubtemplate || c == NotFoundTemplate) { continue; } int slash = name.LastIndexOf('/'); name = name.Substring(slash + 1, name.Length - slash - 1); buf.Append(name); buf.Append('('); if (c.FormalArguments != null) { buf.Append(string.Join(",", c.FormalArguments.Select(i => i.ToString()).ToArray())); } buf.Append(')'); buf.Append(" ::= <<" + Environment.NewLine); buf.Append(c.template + Environment.NewLine); buf.Append(">>" + Environment.NewLine); } return(buf.ToString()); }
private Template(string templateFile, string destinationPath, bool onlyBody) { _destinationPath = destinationPath; _fileName = templateFile; string contents = TemplateUtil.ReadTemplateContents(_fileName, _destinationPath); Match matchTitle = Regex.Match(contents, @"<title\s*>(?<title>.*?)</title>"); Match matchCopyToMaster = Regex.Match(contents, @"<!--\s*#STARTCOPY#\s*-->(?<text>.*?)<!--\s*#ENDCOPY#\s*-->", RegexOptions.IgnoreCase | RegexOptions.Singleline); if (matchTitle.Success) { _pageTitle = matchTitle.Groups["title"].Value; } if (matchCopyToMaster.Success) { _headSection = matchCopyToMaster.Groups["text"].Value; } if (onlyBody) { contents = TemplateUtil.ExtractBody(contents); } _parsedTemplate = PreParseTemplate(contents); _parsedTemplate.FileName = templateFile; }
static void Main(string[] args) { MacroProcessor.Register <Foo>(); double mSecFrequency = (Stopwatch.Frequency / 1000); string result = null; Stopwatch sw = Stopwatch.StartNew(); CompiledTemplate compiledTemplate = MacroProcessor.Compile("Hello, my name is [name] and I'm [age] years old"); Console.WriteLine($"Compilation duration : {sw.ElapsedTicks / mSecFrequency} msecs"); int iteration = 1000 * 1000; sw = Stopwatch.StartNew(); for (int i = 0; i < 1000 * 1000; i++) { result = MacroProcessor.Process("I'm [name], I'm [age] years old", new Foo(42, "Josh")); } Console.WriteLine($"Result: {result}"); Console.WriteLine($"AVG rendering duration : {sw.ElapsedTicks / iteration / mSecFrequency * 1000} usecs over {iteration} iterations"); System.Console.ReadKey(); }
public TemplateInformation(string enclosingTemplateName, IToken nameToken, IToken templateToken, CompiledTemplate template) { this._enclosingTemplateName = enclosingTemplateName; this._nameToken = nameToken; this._templateToken = templateToken; this._template = template; }
internal TemplateInformation GetTemplateInformation([NotNull] CompiledTemplate template) { Requires.NotNull(template, nameof(template)); Requires.Argument(template.NativeGroup == this, nameof(template), "The template must belong to the current group."); return(_compiledTemplateInformation[template]); }
/// <summary> /// Executed a compiled Twofold template. /// </summary> /// <typeparam name="T">The argument type of the template main method.</typeparam> /// <param name="compiledTemplate">The compiled Twofold template.</param> /// <param name="arguments">The arguments which is given to the template main method.</param> /// <returns>The generated target text or null if an error occured.</returns> /// <exception cref="ArgumentNullException">If compiledTemplate is null.</exception> public Target Run(CompiledTemplate compiledTemplate, params object[] arguments) { var templateExecuter = new TemplateExecuter(this.MessageHandler); Target target = templateExecuter.Execute(compiledTemplate, arguments); return(target); }
internal ITemplate GetTemplate(string templateText, IDictionary <string, object?> variableTemplate, string templateName, string?templatePath) { Settings.IsReadOnly = true; return(Settings.DynamicTemplates ? (ITemplate)DynamicTemplate.LoadTemplate(this, templateText, templateName, templatePath) : CompiledTemplate.LoadTemplate(this, templateText, variableTemplate, templateName, templatePath)); }
public virtual void RawDefineTemplate(string name, CompiledTemplate code, IToken defT) { CompiledTemplate prev; templates.TryGetValue(name, out prev); if (prev != null) { if (!prev.isRegion) { ErrorManager.CompiletimeError(ErrorType.TEMPLATE_REDEFINITION, null, defT); return; } if (prev.isRegion && prev.regionDefType == Template.RegionType.Embedded) { ErrorManager.CompiletimeError(ErrorType.EMBEDDED_REGION_REDEFINITION, null, defT, GetUnmangledTemplateName(name)); return; } else if (prev.isRegion && prev.regionDefType == Template.RegionType.Explicit) { ErrorManager.CompiletimeError(ErrorType.REGION_REDEFINITION, null, defT, GetUnmangledTemplateName(name)); return; } } code.NativeGroup = this; templates[name] = code; }
public virtual CompiledTemplate DefineTemplate(string templateName, IToken nameT, List <FormalArgument> args, string template, IToken templateToken) { if (templateName == null || templateName.Length == 0) { throw new ArgumentException("empty template name"); } if (templateName.IndexOf('.') >= 0) { throw new ArgumentException("cannot have '.' in template names"); } template = Utility.TrimOneStartingNewline(template); template = Utility.TrimOneTrailingNewline(template); // compile, passing in templateName as enclosing name for any embedded regions CompiledTemplate code = Compile(FileName, templateName, args, template, templateToken); code.name = templateName; RawDefineTemplate(templateName, code, nameT); code.DefineArgumentDefaultValueTemplates(this); code.DefineImplicitlyDefinedTemplates(this); // define any anonymous subtemplates return(code); }
public override CompiledTemplate DefineTemplateAlias(IToken aliasT, IToken targetT) { CompiledTemplate result = base.DefineTemplateAlias(aliasT, targetT); _templateInformation.Add(new TemplateInformation(aliasT, targetT, result)); return(result); }
internal TemplateInformation GetTemplateInformation(CompiledTemplate template) { Contract.Requires <ArgumentNullException>(template != null, "template"); Contract.Requires <ArgumentException>(template.NativeGroup == this); Contract.Ensures(Contract.Result <TemplateInformation>() != null); return(_compiledTemplateInformation[template]); }
public Template(TemplateGroup group, string template) { groupThatCreatedThisInstance = group; impl = groupThatCreatedThisInstance.Compile(group.FileName, null, null, template, null); impl.hasFormalArgs = false; impl.name = UnknownName; impl.DefineImplicitlyDefinedTemplates(groupThatCreatedThisInstance); }
internal CompiledTemplate GetTemplate <T>(string templateText, CompiledScope scope, string templateName, string?templatePath) { Settings.IsReadOnly = true; if (Settings.DynamicTemplates) { throw new NotImplementedException(); } return(CompiledTemplate.LoadTemplate(this, templateText, scope, templateName, templatePath)); }
public override CompiledTemplate DefineTemplate(string templateName, IToken nameT, List <FormalArgument> args, string template, IToken templateToken) { CompiledTemplate result = base.DefineTemplate(templateName, nameT, args, template, templateToken); TemplateInformation info = new TemplateInformation(nameT, templateToken, result); _templateInformation.Add(info); _compiledTemplateInformation.Add(result, info); return(result); }
public override CompiledTemplate DefineRegion(string enclosingTemplateName, IToken regionT, string template, IToken templateToken) { CompiledTemplate result = base.DefineRegion(enclosingTemplateName, regionT, template, templateToken); TemplateInformation info = new TemplateInformation(enclosingTemplateName, regionT, templateToken, result); _templateInformation.Add(info); _compiledTemplateInformation.Add(result, info); return(result); }
/// <summary> /// Initializes a new instance of the <see cref="XLTemplate"/> class. /// </summary> /// <param name="dialect">An instance <see cref="IDialect" /> used to define the domain-specific language properties.</param> /// <param name="template">A <see cref="string" /> value that is compiled and used for evaluation.</param> /// <exception cref="ArgumentNullException">Either <paramref name="dialect" /> or <paramref name="template" /> parameters are <c>null</c>.</exception> /// <exception cref="ParseException">Parsing error during template compilation.</exception> /// <exception cref="Expressions.ExpressionException">Expression parsing error during template compilation.</exception> /// <exception cref="InterpreterException">Lexical error during template compilation.</exception> /// <remarks> /// The value supplied in the <paramref name="template" /> parameter will be parsed, <c>lexed</c> and interpreted in the constructor. There are a number of exceptions /// that can be thrown at this stage. /// </remarks> public XLTemplate([NotNull] IDialect dialect, [NotNull] string template) { Expect.NotNull(nameof(dialect), dialect); Expect.NotNull(nameof(template), template); Dialect = dialect; Template = template; /* Compile template */ _compiledTemplate = Compile(); }
protected Template(Template prototype, bool shadowLocals) { if (prototype == null) { throw new ArgumentNullException("prototype"); } this.impl = prototype.impl; this.locals = shadowLocals || prototype.locals == null ? prototype.locals : (object[])prototype.locals.Clone(); this.groupThatCreatedThisInstance = prototype.groupThatCreatedThisInstance; }
public CompiledTemplate CreateTemplate(string filePath, string templateName) { CompiledTemplate compiledTemplate = new CompiledTemplate(); compiledTemplate.filePath = filePath; compiledTemplate.guid = Guid.NewGuid().ToString().Replace('-', '_'); compiledTemplate.templateId = compiledTemplates.size; compiledTemplates.Add(compiledTemplate); compiledTemplate.templateMetaData = new TemplateMetaData(compiledTemplate.templateId, filePath, null, null); compiledTemplate.templateName = templateName; return(compiledTemplate); }
public Template(TemplateGroup group, string template) { if (group == null) throw new ArgumentNullException("group"); groupThatCreatedThisInstance = group; impl = groupThatCreatedThisInstance.Compile(group.FileName, null, null, template, null); impl.HasFormalArgs = false; impl.Name = UnknownName; impl.DefineImplicitlyDefinedTemplates(groupThatCreatedThisInstance); }
protected Template(Template prototype, bool shadowLocals) { if (prototype == null) throw new ArgumentNullException("prototype"); this.impl = prototype.impl; if (shadowLocals && prototype.locals != null) this.locals = (object[])prototype.locals.Clone(); else if (impl.FormalArguments != null && impl.FormalArguments.Count > 0) this.locals = new object[impl.FormalArguments.Count]; this.groupThatCreatedThisInstance = prototype.groupThatCreatedThisInstance; }
// for testing public virtual CompiledTemplate DefineTemplate(string name, string template) { try { CompiledTemplate impl = DefineTemplate(name, new CommonToken(GroupParser.ID, name), null, template, null); return(impl); } catch (TemplateException) { Console.Error.WriteLine("eh?"); } return(null); }
public string ProcessTemplate(string name, Dictionary <string, object> sessionParams) { CompiledTemplate t4gen = GetTemplate(name, sessionParams); string result = t4gen.Process(); ShowErrors(name); if (BuilderSettings.Verbosity > 1) { Console.Out.WriteLine("Generated source code:"); Console.Out.WriteLine(result == null ? "[No code was generated]" : result); } return(result); }
protected internal virtual CompiledTemplate LookupImportedTemplate(string name) { //System.out.println("look for "+name+" in "+imports); if (imports == null) { return(null); } foreach (TemplateGroup g in imports) { CompiledTemplate code = g.LookupTemplate(name); if (code != null) { return(code); } } return(null); }
/// <summary> /// Construct an <see cref="ExpressionTemplate"/>. /// </summary> /// <param name="template">The template text.</param> /// <param name="formatProvider">Optionally, an <see cref="IFormatProvider"/> to use when formatting /// embedded values.</param> /// <param name="nameResolver">Optionally, a <see cref="NameResolver"/> /// with which to resolve function names that appear in the template.</param> public ExpressionTemplate( string template, IFormatProvider?formatProvider = null, NameResolver?nameResolver = null) { if (template == null) { throw new ArgumentNullException(nameof(template)); } if (!TemplateParser.TryParse(template, out var parsed, out var error)) { throw new ArgumentException(error); } _compiled = TemplateCompiler.Compile(parsed, DefaultFunctionNameResolver.Build(nameResolver)); _formatProvider = formatProvider; }
protected static string Evaluate(CompiledTemplate <EvaluationContext> compiledTemplate, StringComparer comparer, params KeyValuePair <string, object>[] values) { var context = CreateContext(comparer); foreach (var kvp in values) { context.SetProperty(kvp.Key, kvp.Value); } string result; using (var sw = new StringWriter()) { compiledTemplate.Evaluate(sw, context); result = sw.ToString(); } return(result); }
public virtual CompiledTemplate DefineRegion(string enclosingTemplateName, IToken regionT, string template, IToken templateToken) { string name = regionT.Text; template = Utility.TrimOneStartingNewline(template); template = Utility.TrimOneTrailingNewline(template); CompiledTemplate code = Compile(FileName, enclosingTemplateName, null, template, regionT); string mangled = GetMangledRegionName(enclosingTemplateName, name); if (LookupTemplate(mangled) == null) { ErrorManager.CompiletimeError(ErrorType.NO_SUCH_REGION, null, regionT, enclosingTemplateName, name); return(new CompiledTemplate()); } code.name = mangled; code.isRegion = true; code.regionDefType = Template.RegionType.Explicit; RawDefineTemplate(mangled, code, regionT); code.DefineArgumentDefaultValueTemplates(this); code.DefineImplicitlyDefinedTemplates(this); // define any anonymous subtemplates return(code); }
/// <summary> /// Create a view. /// </summary> /// <param name="context">Context to render</param> public void Render(IControllerContext context, IViewData viewData, TextWriter writer) { string layoutName; if (context.LayoutName != null) { layoutName = context.LayoutName; } else { var controllerName = context.ControllerUri.TrimEnd('/'); int pos = controllerName.LastIndexOf('/'); layoutName = context.ControllerUri; layoutName += pos == -1 ? controllerName + ".haml" : controllerName.Substring(pos + 1) + ".haml"; if (!MvcServer.CurrentMvc.ViewProvider.Exists(layoutName)) { layoutName = "Shared/Application.haml"; } } string viewPath = context.ViewPath + ".haml"; CompiledTemplate template = _templateEngine.Compile(new List <string> { layoutName, viewPath }, typeof(NHamlView)); var instance = (NHamlView)template.CreateInstance(); instance.ViewData = viewData; instance.Render(writer); }
public CompiledTemplateRecord(CompiledTemplate compiledTemplate) { this.compiledTemplate = compiledTemplate; LastUse = DateTime.Now; }
public ViciCompiledTemplate(CompiledTemplate compiledTemplate) { CompiledTemplate = compiledTemplate; }
public CompiledTemplate Compile(IViewSource template, CompiledTemplate master, CompiledTemplate defaultMaster, object context, Type BaseType) { Invariant.ArgumentNotNull( template, "template" ); var opts = (TemplateOptions)Options.Clone(); var origtype = opts.TemplateBaseType; if (BaseType != null) { opts.TemplateBaseType = BaseType; } List<MetaNode> data; if (template.ParseResult.Metadata.TryGetValue("assembly", out data)) { foreach (var assemblyNode in data) { opts.AddReference(assemblyNode.Value); } } if (template.ParseResult.Metadata.TryGetValue("namespace", out data)) { foreach (var namespaceNode in data) { opts.AddUsing(namespaceNode.Value); } } MetaNode pagedefiniton = MetaDataFiller.FillAndGetPageDefinition(template.ParseResult.Metadata, opts); if (pagedefiniton.Attributes.Find(x => x.Name == "Inherits") != null) { string inherittype = ((TextChunk)((TextNode)pagedefiniton.Attributes.Find(x => x.Name == "Inherits").Value).Chunks[0]).Text; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var modelType = assembly.GetType(inherittype, false, true); if (modelType != null) { opts.TemplateBaseType = ProxyExtractor.GetNonProxiedType(modelType); } } } if (template.ParseResult.Metadata.TryGetValue("type", out data)) { if ((opts.TemplateBaseType.IsGenericTypeDefinition) || ((BaseType!= null) && (origtype.IsGenericTypeDefinition))) { string modeltypestring = data[0].Value; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var modelType = assembly.GetType(modeltypestring, false, true); if (modelType != null) { if (opts.TemplateBaseType.IsGenericTypeDefinition) { opts.TemplateBaseType = opts.TemplateBaseType.MakeGenericType(ProxyExtractor.GetNonProxiedType(modelType)); break; } else if (origtype.IsGenericTypeDefinition) { opts.TemplateBaseType = origtype.MakeGenericType(ProxyExtractor.GetNonProxiedType(modelType)); break; } } } } } if (opts.TemplateBaseType.IsGenericTypeDefinition) { opts.TemplateBaseType = opts.TemplateBaseType.MakeGenericType(typeof(object)); } // check if there is a default masterpagefile definition inside the content page. // If yes, use that instead of the defaultTemplate if (master == null) { AttributeNode masterNode = pagedefiniton.Attributes.Find(x => x.Name == "MasterPageFile"); if (masterNode != null) { string masterName = ((TextChunk)((TextNode)masterNode.Value).Chunks[0]).Text; master = Compile(masterName); } else { if (defaultMaster != null) { master = defaultMaster; } } } var templateCacheKey = template.Path; if (master != null) templateCacheKey = templateCacheKey + master.ContentFile.Path + opts.TemplateBaseType.FullName; CompiledTemplate compiledTemplate; lock( _compiledTemplateCache ) { var key = templateCacheKey.ToString(); if( !_compiledTemplateCache.TryGetValue( key, out compiledTemplate ) ) { compiledTemplate = new CompiledTemplate(opts, opts.TemplateBaseType, context, master, template); _compiledTemplateCache.Add( key, compiledTemplate ); return compiledTemplate; } } if( Options.AutoRecompile ) { compiledTemplate.Recompile(); } return compiledTemplate; }