public void WriteSVInterface(EsiInterface iface, FileInfo to) { var svTypeWriter = new EsiSystemVerilogTypeWriter(C); string SimpleTypeString(EsiType type) { try { return(svTypeWriter.GetSVTypeSimple(type, useName: true)); } catch (Exception e) { C.Log.Error("Exception in getting a typestring for '{type}': {e}", type, e); return("<exception>"); } } C.Log.Information("Starting SV interface generation for {iface} to file {file}", iface, to.Name); var paramTypes = iface.Methods.SelectMany(m => m.Params.Select(p => p.Type)); var returnTypes = iface.Methods.SelectMany(m => m.Returns.Select(p => p.Type)); var usedTypes = paramTypes.Concat(returnTypes).Distinct(); var s = new ScriptObject(); s.Add("iface", iface); s.Add("usedTypes", usedTypes); s.Import("SimpleTypeString", new Func <EsiType, string>(SimpleTypeString)); SVUtils.RenderTemplate("sv/full_interface.sv.sbntxt", s, to); }
public void WriteSVTypeInterface(EsiNamedType type, FileInfo to, FileInfo headerFile) { var s = new ScriptObject(); s.Add("header", headerFile); s.Add("type", type); SVUtils.RenderTemplate("sv/type_interface.sv.sbntxt", s, to); }
/// <summary> /// Builds the template context for exporting /// </summary> /// <param name="renderingObject">Rendering object to export</param> /// <param name="errorCollection">Error Collection</param> /// <returns>Template context</returns> private TemplateContext BuildTemplateContext(ScribanRenderingClass renderingObject, ExportPlaceholderErrorCollection errorCollection) { ScriptObject exportObject = new ScriptObject(); exportObject.Add(GetObjectKey(), renderingObject); if (_languageKeyGenerator != null) { exportObject.Add(ExportConstants.ScribanLanguageKeyName, _languageKeyGenerator); } TemplateContext context = new TemplateContext(); context.TemplateLoader = new ScribanIncludeTemplateLoader(_exportCachedDbAccess, errorCollection); context.PushGlobal(exportObject); return(context); }
public static ScriptObject WrapScriptObject(string key, ScriptObject obj) { var wrapper = new ScriptObject(); wrapper.Add(key, obj); return(wrapper); }
/// <summary> /// Transforms the template from plain source and inserts variables. /// </summary> /// <param name="input"></param> /// <param name="callerTemplate"></param> /// <returns></returns> public string TransformTemplate(string input, SpartanTemplate callerTemplate) { // Create a template instance and populate it with data. Template template = Template.Parse(input); var context = new TemplateContext() { TemplateLoader = new DefaultTemplateLoader() }; var tempParams = new ScriptObject(); foreach (var pair in callerTemplate.TemplateContext) { tempParams.Add(pair.Key, pair.Value); } // TODO: Clean this up! context.PushGlobal(tempParams); string result = template.Render(context); // Return the string. return(result); }
public static ScriptObject ToScriptObject(this WorkContext workContext) { var scriptObject = new ScriptObject(); scriptObject.Import(workContext); scriptObject.Import(typeof(CommonFilters)); scriptObject.Import(typeof(CommerceFilters)); scriptObject.Import(typeof(TranslationFilter)); scriptObject.Import(typeof(UrlFilters)); scriptObject.Import(typeof(MoneyFilters)); scriptObject.Import(typeof(HtmlFilters)); scriptObject.Import(typeof(StringFilters)); scriptObject.Import(typeof(ArrayFilters)); scriptObject.Import(typeof(MathFilters)); scriptObject.Import(typeof(StandardFilters)); scriptObject.Import(typeof(FeatureFilter)); //TODO: blank isn't same as was in previous version now it is only represents a null check, need to find out solution or replace in themes == blank check to to .empty? == false expression scriptObject.SetValue("blank", EmptyScriptObject.Default, true); //Store special layout setter action in the context, it is allows to set the WorkContext.Layout property from template during rendering in the CommonFilters.Layout function Action <string> layoutSetter = (layout) => workContext.Layout = layout; scriptObject.Add("layout_setter", layoutSetter); return(scriptObject); }
public void AdditionWorksWithNumbers() { var text = @"{{a+b}}"; var compiledTemplate = Template.Parse(text); var scriptObject1 = new ScriptObject(); scriptObject1.Add("a", 1); scriptObject1.Add("b", 2); var context = new TemplateContext(); context.PushGlobal(scriptObject1); var result = compiledTemplate.Render(context); compiledTemplate.HasErrors.Should().BeFalse(); result.Should().Be("3"); }
/// <summary> /// Builds the template context for exporting /// </summary> /// <param name="conditionData">Condition data to export</param> /// <returns>Template context</returns> private TemplateContext BuildTemplateContext(ScribanCondition conditionData) { ScriptObject exportObject = new ScriptObject(); exportObject.Add(ConditionKey, conditionData); TemplateContext context = new TemplateContext(); context.TemplateLoader = new ScribanIncludeTemplateLoader(_exportCachedDbAccess, _errorCollection); context.PushGlobal(exportObject); return(context); }
/// <summary> /// Adds or updates a value /// </summary> /// <param name="scriptObject">Script object that is being updated</param> /// <param name="key">Key</param> /// <param name="value">Value</param> public static void AddOrUpdate(this ScriptObject scriptObject, string key, object value) { if (scriptObject.ContainsKey(key)) { scriptObject[key] = value; } else { scriptObject.Add(key, value); } }
private static ScriptObject BuildScriptObject(ExpandoObject expando) { var dict = (IDictionary <string, object>)expando; var scriptObject = new ScriptObject(); foreach (var kv in dict) { var renamedKey = StandardMemberRenamer.Rename(kv.Key); if (kv.Value is ExpandoObject expandoValue) { scriptObject.Add(renamedKey, BuildScriptObject(expandoValue)); } else { scriptObject.Add(renamedKey, kv.Value); } } return(scriptObject); }
public static ScriptObject WrapScriptObject(string key, ScriptObject[] objs) { var wrapper = new ScriptObject(); var objFirst = objs[0]; for (int i = 1; i < objs.Length; i++) { var obj = objs[i]; objFirst.Import(obj); } wrapper.Add(key, objFirst); return(wrapper); }
private static void GenerateFor(string outputDir, EngineApi engineApi, EngineClass @class) { string scope = (string.IsNullOrEmpty(@class.Scope) ? "Global" : @class.Scope); var scriptObject = new ScriptObject(); scriptObject.Add("class", @class); scriptObject.Add("scope", scope); string output = ClassTemplate.Render(@class, scope); string dir = $"{outputDir}/Classes/{scope.Replace('.', '/')}"; Console.WriteLine($"{dir}/{@class.Name}.cs"); Directory.CreateDirectory(dir); using (StreamWriter SW = new StreamWriter($"{dir}/{@class.Name}.cs") ) { SW.Write(output); } }
public TemplateContext Make(object obj) { var scriptObj = new ScriptObject(); scriptObj.Import(obj); scriptObj.Import("ident", new Func <string, string>((str) => Utils.Ident(str, _options.IdentSize))); scriptObj.Add("left_pad", Utils.Ident("", _options.IdentSize)); var context = new TemplateContext(); context.PushGlobal(scriptObj); return(context); }
/// <summary> /// Collects the values for an export /// </summary> /// <param name="templateType">Template type</param> /// <param name="parsedTemplate">Parsed scriban template</param> /// <param name="scriptObject">Scriban script object to fill</param> /// <param name="data">Export Data</param> /// <returns>Task</returns> public override async Task CollectValues(TemplateType templateType, Template parsedTemplate, ScriptObject scriptObject, ExportObjectData data) { InputObject inputObject = data.ExportData[ExportConstants.ExportDataObject] as InputObject; if (inputObject == null) { return; } _languageKeyGenerator.SetErrorCollection(_errorCollection); GoNorthProject project = await _exportCachedDbAccess.GetUserProject(); ExportSettings exportSettings = await _exportCachedDbAccess.GetExportSettings(project.Id); ExportClass exportObject = BuildExportObject(parsedTemplate, inputObject, exportSettings); scriptObject.Add(GetObjectKey(), exportObject); scriptObject.Add(ExportConstants.ScribanLanguageKeyName, _languageKeyGenerator); scriptObject.Add(FlexFieldAttributeListRenderer.AttributeListFunctionName, new FlexFieldAttributeListRenderer(_templatePlaceholderResolver, _exportCachedDbAccess, _defaultTemplateProvider, _errorCollection, data)); AddAdditionalScriptObjectValues(templateType, parsedTemplate, scriptObject, data); }
/// <summary> /// Builds the template context for exporting /// </summary> /// <param name="cachedDbAccess">Cached database access</param> /// <param name="errorCollection">Error collection</param> /// <param name="renderingObject">Rendering object to export</param> /// <param name="languageKeyGenerator">Language key generator, null to not use it</param> /// <param name="stepRenderer">Action Step renderer</param> /// <param name="flexFieldObject">Flex field object to which the dialog belongs</param> /// <param name="curStep">Current step that is rendered</param> /// <param name="nextStep">Next step that is being rendered</param> /// <returns>Template context</returns> private static TemplateContext BuildTemplateContext <T>(IExportCachedDbAccess cachedDbAccess, ExportPlaceholderErrorCollection errorCollection, T renderingObject, IScribanLanguageKeyGenerator languageKeyGenerator, IActionStepRenderer stepRenderer, FlexFieldObject flexFieldObject, ExportDialogData curStep, ExportDialogData nextStep) where T : class { ScriptObject exportObject = new ScriptObject(); exportObject.Add(ExportConstants.ScribanActionObjectKey, renderingObject); if (languageKeyGenerator != null) { exportObject.Add(ExportConstants.ScribanLanguageKeyName, languageKeyGenerator); } if (stepRenderer != null && stepRenderer.UsesValueObject()) { exportObject.Add(stepRenderer.GetValueObjectKey(), stepRenderer.GetValueObject(curStep, nextStep, flexFieldObject)); } TemplateContext context = new TemplateContext(); context.TemplateLoader = new ScribanIncludeTemplateLoader(cachedDbAccess, errorCollection); context.PushGlobal(exportObject); return(context); }
/// <summary> /// 将普通对象转换为 ScriptObject /// </summary> /// <param name="obj"></param> /// <returns></returns> public static ScriptObject ObjectToScriptObject(object obj) { ScriptObject sobj = new ScriptObject(); var type = obj.GetType(); var properties = type.GetProperties(); for (int i = 0; i < properties.Length; i++) { var prop = properties[i]; var name = prop.Name.ToLower(); var val = prop.GetValue(obj); sobj.Add(name, val); } return(sobj); }
public void DictionaryStringStringCanBeUsedInsteadOfScriptObject() { var text = @"{{model.test}}"; var compiledTemplate = Template.Parse(text); var scriptObject1 = new ScriptObject(); var dict = new Dictionary <string, string> { ["test"] = "123" }; scriptObject1.Add("model", dict); var context = new TemplateContext(); context.PushGlobal(scriptObject1); var result = compiledTemplate.Render(context); compiledTemplate.HasErrors.Should().BeFalse(); result.Should().Be("123"); }
public static ScriptObject Create(Random random) { var language = new TemplateLanguage(); var so = new ScriptObject(); AddMethods(random, so); so.Import(language); var substitutionValues = GenerateLiteralSubstitutions(random) .Concat(NumericalSubstitutions.SelectMany(kv => Range(1, 5) .Select(i => ($"{kv.Key}{i}", kv.Value(random))))); foreach (var(substitution, value) in substitutionValues) { so.Add(substitution, value); } return(so); }
private static object ConvertFromToml(object element) { switch (element) { case TomlArray tomlArray: var array = new ScriptArray(); foreach (var value in tomlArray) { array.Add(ConvertFromToml(value)); } return(array); case TomlTable tomlTable: var obj = new ScriptObject(); foreach (var keyValue in tomlTable) { obj.Add(keyValue.Key, ConvertFromToml(keyValue.Value)); } return(obj); case TomlTableArray tomlTableArray: var tableArray = new ScriptArray(); foreach (var value in tomlTableArray) { tableArray.Add(ConvertFromToml(value)); } return(tableArray); case TomlValue tomlValue: return(tomlValue.ValueAsObject); case string str: return(str); case int value: return(value); case float valuef: return(valuef); case double valued: return(valued); case long valuel: return(valuel); case DateTime datetime: return(datetime); case bool bValue: return(bValue ? BoolTrue : BoolFalse); case null: return(null); default: throw new NotSupportedException($"The TomlObject {element?.GetType()} is not supported"); } return(null); }
/// <summary> /// Adds all shared values to the export script object /// </summary> /// <param name="scriptObject">Script object to fill</param> private void AddSharedScriptObjectValues(ScriptObject scriptObject) { scriptObject.Add(IndentMultiLineRenderer.IndentMUltilineFunctionName, new IndentMultiLineRenderer()); }
public void AddDataToTemplate(string key, object value) { scriptObject.Add(key, value); context.PushGlobal(scriptObject); }
/// <summary> /// This is similar to the Powershell command `ConvertFrom-StringData`, but uses the character "`" instead /// of "\"" as the escape character. /// /// For a list of characters that must be escaped, refer to /// the [MSDN documentation](https://msdn.microsoft.com/library/system.text.regularexpressions.regex.unescape) /// </summary> /// <param name="context">The template context.</param> /// <param name="span">The source span.</param> /// <param name="text">Text in the string data syntax.</param> /// <returns> /// An object representing key-value pairs of strings. /// </returns> /// <remarks> /// ```template-text /// {{ localized = include 'localization.txt' | object.from_string /// localized.foo /// }} /// ``` /// ```html /// bar! /// ``` /// </remarks> public static ScriptObject FromString(TemplateContext context, SourceSpan span, string text) { if (string.IsNullOrEmpty(text)) { return(new ScriptObject()); } // char ` is our escape char // we need to escape `` so it turns out as ` const string escapeChar = "`"; const string reservedSequence = escapeChar + escapeChar; // encodeAs is just an arbitary string. you don't need to escape encodeAs but choosing // something unique helps with the speed const string encodeAs = "^~^"; string inputEscaped = text.Replace(encodeAs, encodeAs + "2").Replace(reservedSequence, encodeAs + "1"); string inputRegexEscaped = inputEscaped.Replace("\\", "\\\\").Replace(escapeChar, "\\"); ScriptObject dataObj = new ScriptObject(); string[] textLines = inputRegexEscaped.Split('\n'); foreach (string textLine in textLines) { if (string.IsNullOrEmpty(textLine)) { continue; } string line = textLine.Trim(); if (string.IsNullOrEmpty(line)) { continue; } else if (line[0] == '#') { continue; } const string kvpDelimiter = "="; int kvpDelimiterIndex = line.IndexOf(kvpDelimiter); if (kvpDelimiterIndex <= 0) { throw new ScriptRuntimeException(span, RS.InvalidStringDataLine); } string itemName = line.Substring(0, kvpDelimiterIndex).Trim(); // +1 is ok, b'cos we already know there is a = somewhere string itemRawValue = line.Substring(kvpDelimiterIndex + 1).TrimStart(); string itemValue = Regex.Unescape(itemRawValue).Replace( encodeAs + "1", reservedSequence).Replace( encodeAs + "2", encodeAs).Replace( reservedSequence, escapeChar); if (dataObj.ContainsKey(itemName)) { dataObj[itemName] = itemValue; } else { dataObj.Add(itemName, itemValue); } } return(dataObj); }
/// <summary> /// Selects the response to use based on the match results from the previous filters. Ties are broken randomly. /// </summary> /// <param name="port">The port containing necessary data</param> /// <returns>Port containing processed data</returns> public override T Process(T port) { if (!IsPipelineValid(ref port, GetType())) { return(port); } var bestScenarios = port.HeaderMatchResults .Concat(port.BodyMatchResults) .Concat(port.QueryMatchResults) .Concat(port.URLMatchResults) .GroupBy(scenario => scenario.ScenarioId) .Where(scenarioGrouping => !scenarioGrouping.Select(scenarioGroup => scenarioGroup.Match) .Contains(MatchResultType.Fail)) .Select(match => new { ScenarioId = match.Key, Score = match.Where(x => x.Match.Equals(MatchResultType.Success)).Sum(x => (int)x.Match), DefaultScenario = match.Select(x => x.DefaultScenario).First() }) .OrderByDescending(match => match.Score) .ToList(); // if there are no default scenarios, then choose the first scenario as the best var bestScenario = bestScenarios.Where(scenario => scenario.Score == bestScenarios.FirstOrDefault().Score) .Where(scenario => scenario.DefaultScenario) .FirstOrDefault() ?? bestScenarios.FirstOrDefault(); // if all scenarios do not match and there is a default scenario (which also doesn't match), use the default scenario if (bestScenario == null && port.Scenarios.Any(scenario => scenario.defaultScenario)) { bestScenario = port.Scenarios.Where(scenario => scenario.defaultScenario).Select(match => new { ScenarioId = match.Id, Score = 0, DefaultScenario = match.defaultScenario }).FirstOrDefault(); } if (port.Scenarios.Any()) { port.Policies = (bestScenario == null ? port.Scenarios.First().Policies : port.Scenarios.First(scenario => scenario.Id.Equals(bestScenario.ScenarioId)).Policies) ?? new List <Policy>(); } port.SelectedResponse = bestScenario != null?port.Scenarios.First(scenario => scenario.Id.Equals(bestScenario.ScenarioId)).Response : port.Scenarios.Count() > 0 ? port.Scenarios.First().Response : new MockResponse(); if (port.SelectedResponse.Type == ResponseType.TEMPLATED) { var request = new ScriptObject(); try { var requestObject = JObject.Parse(port.Body); request.Add("request", requestObject); templateContext.PushGlobal(request); } catch (JsonReaderException) { // can ignore because response does not have to be valid JSON // request.* globals cannot be defined as they are bound to the JSON // incoming response } try { var template = Template.Parse(port.SelectedResponse.Body); port.SelectedResponse.Body = template.Render(templateContext); } // if the template rendering fails, the exception type is null but the error message is non-empty catch (Exception e) when(e is InvalidOperationException || e is ArgumentNullException || e.Source.Equals("Scriban")) { port.SelectedResponse = new MockResponse(); } } return(port); }