/// <summary> /// Returns the base placeholders /// </summary> /// <returns>List of template placeholders</returns> public List<ExportTemplatePlaceholder> GetNodePlaceholders<T>(string objectKey) { List<ExportTemplatePlaceholder> placeholders = new List<ExportTemplatePlaceholder>(); placeholders.AddRange(ScribanPlaceholderGenerator.GetPlaceholdersForObject<T>(_localizerFactory, objectKey)); placeholders.RemoveAll(p => p.Name.EndsWith(string.Format(".{0}", StandardMemberRenamer.Rename(nameof(ScribanExportNpc.UnusedFields))))); return placeholders; }
/// <summary> /// Returns the Export Template Placeholders for a rendering object /// </summary> /// <param name="localizerFactory">Localizer factor</param> /// <param name="languageKeyGenerator">Language key generator, null to not use it</param> /// <param name="languageKeyValueDesc">Description value for the language key to describe in which context this can be used</param> /// <returns>Export Template Placeholder</returns> public static List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType <T>(IStringLocalizerFactory localizerFactory, IScribanLanguageKeyGenerator languageKeyGenerator, string languageKeyValueDesc) { List <ExportTemplatePlaceholder> placeholders = new List <ExportTemplatePlaceholder>(); if (languageKeyGenerator != null) { placeholders.AddRange(languageKeyGenerator.GetExportTemplatePlaceholders(languageKeyValueDesc)); } placeholders.AddRange(ScribanPlaceholderGenerator.GetPlaceholdersForObject <T>(localizerFactory, ExportConstants.ScribanActionObjectKey)); placeholders.RemoveAll(p => p.Name.EndsWith(string.Format(".{0}", StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.UnusedFields))))); return(placeholders); }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { string languageKeyValueDesc = string.Format("{0}.{1}.{2} | field.{3}", ExportConstants.ScribanActionObjectKey, StandardMemberRenamer.Rename(nameof(ScribanMoveNpcActionDataBase.Npc)), StandardMemberRenamer.Rename(nameof(ScribanMoveNpcActionDataBase.Npc.Name)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.Value))); if (_isTeleport) { return(ScribanActionRenderingUtil.GetExportTemplatePlaceholdersForType <ScribanMoveNpcActionDataBase>(_localizerFactory, _scribanLanguageKeyGenerator, languageKeyValueDesc)); } else { return(ScribanActionRenderingUtil.GetExportTemplatePlaceholdersForType <ScribanMoveNpcActionData>(_localizerFactory, _scribanLanguageKeyGenerator, languageKeyValueDesc)); } }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { List <ExportTemplatePlaceholder> exportPlaceholders = new List <ExportTemplatePlaceholder>(); if (_languageKeyGenerator != null) { exportPlaceholders.AddRange(_languageKeyGenerator.GetExportTemplatePlaceholders(GetLanguageKeyValueDesc())); } exportPlaceholders.AddRange(ScribanPlaceholderGenerator.GetPlaceholdersForObject <ScribanRenderingClass>(_localizerFactory, GetObjectKey())); exportPlaceholders.RemoveAll(p => p.Name.EndsWith(string.Format(".{0}", StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.UnusedFields))))); return(exportPlaceholders); }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { if (templateType != TemplateType.LanguageFile) { return(new List <ExportTemplatePlaceholder>()); } string unusedFieldsKey = string.Format(".{0}", StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.UnusedFields))); List <ExportTemplatePlaceholder> languagePlaceholders = ScribanPlaceholderGenerator.GetPlaceholdersForObject <ScribanExportLanguageFile>(_localizerFactory, LanguageObjectKey); languagePlaceholders.RemoveAll(p => p.Name.EndsWith(unusedFieldsKey)); languagePlaceholders.AddRange(ScribanPlaceholderGenerator.GetPlaceholdersForObject <ScribanExportLanguageKey>(_localizerFactory, LanguageKeyEntryObjectKey)); return(languagePlaceholders); }
/// <summary> /// Adds the placeholder definition for a property /// </summary> /// <param name="placeholders">Placeholders to fill</param> /// <param name="property">Property</param> /// <param name="localizerFactory">Localizer factory</param> /// <param name="objectPrefix">Object prefix for the key</param> /// <param name="localizers">Localizers</param> private static void AddPropertyLabel(List <ExportTemplatePlaceholder> placeholders, PropertyInfo property, IStringLocalizerFactory localizerFactory, string objectPrefix, Dictionary <Type, IStringLocalizer> localizers) { IStringLocalizer localizer = EnsureLocalizer(localizerFactory, localizers, property.DeclaringType); string propertyName = StandardMemberRenamer.Rename(property.Name); string placeholderName = string.Format("{0}.{1}", objectPrefix, propertyName); placeholders.Add(new ExportTemplatePlaceholder { Name = placeholderName, Description = localizer[string.Format("PlaceholderDesc_{0}", property.Name)] }); if (Attribute.IsDefined(property, typeof(ScribanExportValueObjectLabel))) { placeholders.AddRange(GetValueLabelPlaceholders(property.PropertyType, localizerFactory, placeholderName, localizers)); placeholders.AddRange(GetKeyCollectionPlaceholders(property.PropertyType, localizerFactory, placeholderName, localizers)); } }
/// <summary> /// Collects the ids of the fields that were referenced by name /// </summary> /// <param name="objectPrefix">Prefix of the object during export</param> /// <param name="parsedTemplate">Parsed scriban template</param> /// <param name="fields">Parsed fields</param> /// <returns>Ids of the used fields</returns> private static IEnumerable <string> CollectUsedFieldIds(string objectPrefix, Template parsedTemplate, ScribanFlexFieldDictionary fields) { string fieldsPrefix = string.Format("{0}.{1}.", objectPrefix, StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.Fields))); Regex valueRegex = new Regex(string.Format("\\s?{0}([a-zA-Z\\d]*)", Regex.Escape(fieldsPrefix))); List <ScriptStatement> statements = ScribanStatementExtractor.ExtractPlainNonTextStatements(parsedTemplate); foreach (ScriptStatement curStatement in statements) { string statement = curStatement.ToString(); Match valueMatch = valueRegex.Match(statement); if (valueMatch.Success) { string fieldName = valueMatch.Groups[1].Value.Trim(); if (fields.ContainsKey(fieldName)) { yield return(fields[fieldName].Id); } } } }
static KalkConsoleKey() { var names = Enum.GetNames <ConsoleKey>(); var values = Enum.GetValues <ConsoleKey>(); for (var i = 0; i < names.Length; i++) { var name = StandardMemberRenamer.Rename(names[i]); var key = values[i]; if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) { name = ('0' + (key - ConsoleKey.D0)).ToString(CultureInfo.InvariantCulture); } MapKey(name, key); } MapKey("left", ConsoleKey.LeftArrow); MapKey("right", ConsoleKey.RightArrow); MapKey("up", ConsoleKey.UpArrow); MapKey("down", ConsoleKey.DownArrow); }
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); }
private static List <KalkModuleToGenerate> FindIntrinsics(Compilation compilation) { var regexName = new Regex(@"^\s*\w+\s+(_\w+)"); int count = 0; var intelDoc = XDocument.Load("intel-intrinsics-data-latest.xml"); var nameToDoc = intelDoc.Descendants("intrinsic").Where(x => IntrinsicsSupports.Contains(x.Attribute("tech").Value ?? string.Empty)).ToDictionary(x => x.Attribute("name").Value, x => x); var generatedIntrinsics = new Dictionary <string, KalkIntrinsicToGenerate>(); foreach (var type in new Type[] { typeof(System.Runtime.Intrinsics.X86.Sse.X64), typeof(System.Runtime.Intrinsics.X86.Sse), typeof(System.Runtime.Intrinsics.X86.Sse2), typeof(System.Runtime.Intrinsics.X86.Sse2.X64), typeof(System.Runtime.Intrinsics.X86.Sse3), typeof(System.Runtime.Intrinsics.X86.Ssse3), typeof(System.Runtime.Intrinsics.X86.Sse41), typeof(System.Runtime.Intrinsics.X86.Sse41.X64), typeof(System.Runtime.Intrinsics.X86.Sse42), typeof(System.Runtime.Intrinsics.X86.Sse42.X64), typeof(System.Runtime.Intrinsics.X86.Aes), typeof(System.Runtime.Intrinsics.X86.Avx), typeof(System.Runtime.Intrinsics.X86.Avx2), typeof(System.Runtime.Intrinsics.X86.Bmi1), typeof(System.Runtime.Intrinsics.X86.Bmi1.X64), typeof(System.Runtime.Intrinsics.X86.Bmi2), typeof(System.Runtime.Intrinsics.X86.Bmi2.X64), }) { var x86Sse = compilation.GetTypeByMetadataName(type.FullName); foreach (var method in x86Sse.GetMembers().OfType <IMethodSymbol>().Where(x => x.IsStatic)) { if (method.Parameters.Length == 0) { continue; } var groupName = type.FullName.Substring(type.FullName.LastIndexOf('.') + 1).Replace("+", string.Empty); var docGroupName = type.Name == "X64" ? type.DeclaringType.Name : type.Name; var xmlDocStr = method.GetDocumentationCommentXml(); if (string.IsNullOrEmpty(xmlDocStr)) { continue; } var xmlDoc = XElement.Parse($"<root>{xmlDocStr.Trim()}</root>"); var elements = xmlDoc.Elements().First(); var csharpSummary = GetCleanedString(elements); var summaryTrimmed = csharpSummary.Replace("unsigned", string.Empty); var match = regexName.Match(summaryTrimmed); if (!match.Success) { continue; } var rawIntrinsicName = match.Groups[1].Value; var intrinsicName = rawIntrinsicName.TrimStart('_'); var desc = new KalkIntrinsicToGenerate { Name = intrinsicName, Class = groupName, MethodSymbol = method, IsFunc = true, }; bool hasInteldoc = false; if (nameToDoc.TryGetValue(rawIntrinsicName, out var elementIntelDoc)) { hasInteldoc = true; desc.Description = GetCleanedString(elementIntelDoc.Descendants("description").FirstOrDefault()); foreach (var parameter in elementIntelDoc.Descendants("parameter")) { desc.Params.Add(new KalkParamDescriptor(parameter.Attribute("varname").Value, parameter.Attribute("type").Value)); } desc.Description = desc.Description.Replace("[round_note]", string.Empty).Trim(); desc.Description = desc.Description + "\n\n" + csharpSummary; } else { desc.Description = csharpSummary; } // Patching special methods switch (desc.Name) { case "mm_prefetch": if (method.Name.EndsWith("0")) { desc.Name += "0"; } else if (method.Name.EndsWith("1")) { desc.Name += "1"; } else if (method.Name.EndsWith("2")) { desc.Name += "2"; } else if (method.Name.EndsWith("Temporal")) { desc.Name += "nta"; } else { goto default; } break; case "mm_round_sd": case "mm_round_ss": case "mm_round_pd": case "mm_round_ps": case "mm256_round_pd": case "mm256_round_ps": Debug.Assert(method.Name.StartsWith("Round")); var postfix = method.Name.Substring("Round".Length); Debug.Assert(hasInteldoc); if (desc.Name != "mm_round_ps" && desc.Name != "mm256_round_ps" && (desc.Params.Count >= 2 && method.Parameters.Length == 1)) { desc.Name += "1"; } if (!postfix.StartsWith("CurrentDirection")) { postfix = StandardMemberRenamer.Rename(postfix); desc.Name = $"{desc.Name}_{postfix}"; } // Remove rounding from doc var index = desc.Params.FindIndex(x => x.Name == "rounding"); if (index >= 0) { desc.Params.RemoveAt(index); } break; case "mm_rcp_ss": case "mm_rsqrt_ss": case "mm_sqrt_ss": if (method.Parameters.Length == 1) { desc.Name += "1"; } break; case "mm_sqrt_sd": case "mm_ceil_sd": case "mm_floor_sd": if (method.Parameters.Length == 1) { desc.Name += "1"; } break; default: if (hasInteldoc) { if (method.Parameters.Length != desc.Params.Count) { Console.WriteLine($"Parameters not matching for {method.ToDisplayString()}. Expecting: {desc.Params.Count} but got {method.Parameters.Length} "); } } break; } desc.CSharpName = desc.Name; desc.Names.Add(desc.Name); desc.RealReturnType = method.ReturnType.ToDisplayString(); if (desc.RealReturnType == "bool") { desc.RealReturnType = "KalkBool"; } desc.ReturnType = method.ReturnType is INamedTypeSymbol retType && retType.IsGenericType ? "object" : desc.RealReturnType; desc.GenericCompatibleRealReturnType = method.ReturnType is IPointerTypeSymbol ? "IntPtr" : desc.RealReturnType; (desc.BaseNativeReturnType, desc.NativeReturnType) = GetBaseTypeAndType(method.ReturnType); desc.HasPointerArguments = false; for (int i = 0; i < method.Parameters.Length; i++) { var intrinsicParameter = new KalkIntrinsicParameterToGenerate(); var parameter = method.Parameters[i]; intrinsicParameter.Name = i < desc.Params.Count ? desc.Params[i].Name : parameter.Name; var parameterType = method.Parameters[i].Type; intrinsicParameter.Type = parameterType is INamedTypeSymbol paramType && paramType.IsGenericType || parameterType is IPointerTypeSymbol ? "object" : parameter.Type.ToDisplayString(); intrinsicParameter.RealType = parameter.Type.ToDisplayString(); intrinsicParameter.GenericCompatibleRealType = parameterType is IPointerTypeSymbol ? "IntPtr" : intrinsicParameter.RealType; if (parameterType is IPointerTypeSymbol) { desc.HasPointerArguments = true; } (intrinsicParameter.BaseNativeType, intrinsicParameter.NativeType) = GetBaseTypeAndType(parameter.Type); desc.Parameters.Add(intrinsicParameter); } // public object mm_add_ps(object left, object right) => ProcessArgs<float, Vector128<float>, float, Vector128<float>, float, Vector128<float>>(left, right, Sse.Add); var methodDeclaration = new StringBuilder(); methodDeclaration.Append($"public {desc.ReturnType} {desc.Name}("); for (int i = 0; i < desc.Parameters.Count; i++) { var parameter = desc.Parameters[i]; if (i > 0) { methodDeclaration.Append(", "); } methodDeclaration.Append($"{parameter.Type} {parameter.Name}"); } bool isAction = method.ReturnType.ToDisplayString() == "void"; desc.IsAction = isAction; desc.IsFunc = !desc.IsAction; methodDeclaration.Append(isAction ? $") => ProcessAction<" : $") => ({desc.ReturnType})ProcessFunc<"); var castBuilder = new StringBuilder(isAction ? "Action<" : "Func<"); for (int i = 0; i < desc.Parameters.Count; i++) { var parameter = desc.Parameters[i]; if (i > 0) { methodDeclaration.Append(", "); castBuilder.Append(", "); } methodDeclaration.Append($"{parameter.BaseNativeType}, {parameter.NativeType}"); castBuilder.Append($"{parameter.Type}"); } if (!isAction) { if (desc.Parameters.Count > 0) { methodDeclaration.Append(", "); castBuilder.Append(", "); } methodDeclaration.Append($"{desc.BaseNativeReturnType}, {desc.NativeReturnType}"); castBuilder.Append($"{desc.ReturnType}"); } methodDeclaration.Append($">("); castBuilder.Append($">"); // Gets any memory alignment RequiredAlignments.TryGetValue(intrinsicName, out int memAlign); for (int i = 0; i < desc.Parameters.Count; i++) { var parameter = desc.Parameters[i]; methodDeclaration.Append($"{parameter.Name}, "); if (memAlign > 0 && parameter.Name == "mem_addr") { methodDeclaration.Append($"{memAlign}, "); } } var finalSSEMethod = $"{method.ContainingType.ToDisplayString()}.{method.Name}"; var sseMethodName = desc.HasPointerArguments ? $"{groupName}_{method.Name}{count}" : finalSSEMethod; methodDeclaration.Append(sseMethodName); methodDeclaration.Append(");"); desc.Cast = $"({castBuilder})"; desc.MethodDeclaration = methodDeclaration.ToString(); if (desc.HasPointerArguments) { methodDeclaration.Clear(); castBuilder.Clear(); castBuilder.Append(isAction ? "Action<" : "Func<"); for (int i = 0; i < desc.Parameters.Count; i++) { var parameter = desc.Parameters[i]; if (i > 0) { castBuilder.Append(", "); } castBuilder.Append($"{parameter.GenericCompatibleRealType}"); } if (!isAction) { castBuilder.Append($", {desc.GenericCompatibleRealReturnType}"); } castBuilder.Append(">"); methodDeclaration.Append($"private unsafe readonly static {castBuilder} {sseMethodName} = new {castBuilder}(("); for (int i = 0; i < desc.Parameters.Count; i++) { if (i > 0) { methodDeclaration.Append(", "); } methodDeclaration.Append($"arg{i}"); } methodDeclaration.Append($") => {finalSSEMethod}("); for (int i = 0; i < desc.Parameters.Count; i++) { if (i > 0) { methodDeclaration.Append(", "); } var parameter = desc.Parameters[i]; methodDeclaration.Append($"({parameter.RealType})arg{i}"); } methodDeclaration.Append("));"); desc.IndirectMethodDeclaration = methodDeclaration.ToString(); } desc.Category = $"Vector Hardware Intrinsics / {docGroupName.ToUpperInvariant()}"; generatedIntrinsics.TryGetValue(desc.Name, out var existingDesc); // TODO: handle line for comments desc.Description = desc.Description.Trim().Replace("\r\n", "\n"); if (existingDesc == null || desc.Parameters[0].BaseNativeType == "float") { generatedIntrinsics[desc.Name] = desc; } desc.IsSupported = true; count++; } } Console.WriteLine($"{generatedIntrinsics.Count} intrinsics"); var intrinsics = generatedIntrinsics.Values.Where(x => x.IsSupported).ToList(); var intrinsicsPerClass = intrinsics.GroupBy(x => x.Class).ToDictionary(x => x.Key, y => y.OrderBy(x => x.Name).ToList()); var modules = new List <KalkModuleToGenerate>(); foreach (var keyPair in intrinsicsPerClass.OrderBy(x => x.Key)) { var module = new KalkModuleToGenerate { Namespace = "Kalk.Core.Modules.HardwareIntrinsics", ClassName = $"{keyPair.Key}IntrinsicsModule", Category = keyPair.Value.First().Category }; module.Members.AddRange(keyPair.Value); modules.Add(module); } return(modules); }
/// <summary> /// Returns the placeholders for a template /// </summary> /// <param name="templateType">Template Type</param> /// <returns>List of template placeholders</returns> public List <ExportTemplatePlaceholder> GetPlaceholdersForTemplate(TemplateType templateType) { List <ExportTemplatePlaceholder> placeholders = _languageKeyGenerator.GetExportTemplatePlaceholders(string.Format("{0}.{1}", ExportConstants.ScribanChoiceOptionObjectKey, StandardMemberRenamer.Rename(nameof(ScribanChoiceOption.Text)))); placeholders.AddRange(GetNodePlaceholders <ScribanChoice>(ChoiceKey)); return(placeholders); }
public static string ScriptPrettyName(this Type type) { if (type == null) { return("null"); } if (type == typeof(bool)) { return("bool"); } if (type == typeof(byte)) { return("byte"); } if (type == typeof(sbyte)) { return("sbyte"); } if (type == typeof(ushort)) { return("ushort"); } if (type == typeof(short)) { return("short"); } if (type == typeof(uint)) { return("uint"); } if (type == typeof(int)) { return("int"); } if (type == typeof(ulong)) { return("ulong"); } if (type == typeof(long)) { return("long"); } if (type == typeof(string)) { return("string"); } if (type == typeof(float)) { return("float"); } if (type == typeof(double)) { return("double"); } if (type == typeof(decimal)) { return("decimal"); } if (type == typeof(BigInteger)) { return("bigint"); } if (type.IsEnum) { return("enum"); } if (type == typeof(ScriptRange)) { return("range"); } if (type == typeof(ScriptArray) || typeof(System.Collections.IList).IsAssignableFrom(type)) { return("array"); } if (typeof(IScriptObject).IsAssignableFrom(type)) { return("object"); } if (typeof(IScriptCustomFunction).IsAssignableFrom(type)) { return("function"); } string name = type.Name; var indexOfGenerics = name.IndexOf('`'); if (indexOfGenerics > 0) { name = name.Substring(0, indexOfGenerics); var builder = new StringBuilder(); builder.Append(name); builder.Append('<'); var genericArguments = type.GenericTypeArguments; for (var i = 0; i < genericArguments.Length; i++) { var argType = genericArguments[i]; if (i > 0) { builder.Append(", "); } builder.Append(ScriptPrettyName(argType)); } builder.Append('>'); name = builder.ToString(); } var typeNameAttr = type.GetCustomAttribute <ScriptTypeNameAttribute>(); if (typeNameAttr != null) { return(typeNameAttr.TypeName); } // For any Scriban ScriptXxxYyy name, return xxx_yyy if (type.Namespace != null && type.Namespace.StartsWith("Scriban.")) { if (name.StartsWith("Script")) { name = name.Substring("Script".Length); } return(StandardMemberRenamer.Rename(name)); } return(name); }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { string languageKeyValueDesc = string.Format("{0}.{1}.{2} | {0}.{3}.{4}", ExportConstants.ScribanActionObjectKey, StandardMemberRenamer.Rename(nameof(ScribanValueActionData.ValueObject)), StandardMemberRenamer.Rename(nameof(ScribanValueActionData.ValueObject.Name)), StandardMemberRenamer.Rename(nameof(ScribanValueActionData.TargetField)), StandardMemberRenamer.Rename(nameof(ScribanValueActionData.TargetField.Value))); return(ScribanActionRenderingUtil.GetExportTemplatePlaceholdersForType <ScribanValueActionData>(_localizerFactory, _scribanLanguageKeyGenerator, languageKeyValueDesc)); }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { List <ExportTemplatePlaceholder> exportPlaceholders = new List <ExportTemplatePlaceholder>(); if (templateType != TemplateType.ObjectNpc && templateType != TemplateType.ObjectSkillList) { return(exportPlaceholders); } if (templateType == TemplateType.ObjectSkillList) { exportPlaceholders.AddRange(_languageKeyGenerator.GetExportTemplatePlaceholders(string.Format("{0}.name || {0}.field.name", SkillPlaceholderDefintionPrefix))); } IStringLocalizer stringLocalizer = _localizerFactory.Create(typeof(NpcSkillValueCollector)); exportPlaceholders.Add(new ExportTemplatePlaceholder(ExportConstants.ScribanNpcSkillsObjectKey, stringLocalizer["PlaceholderDesc_Skills"])); List <ExportTemplatePlaceholder> skillPlaceholders = ScribanPlaceholderGenerator.GetPlaceholdersForObject <ScribanExportSkill>(_localizerFactory, SkillPlaceholderDefintionPrefix); skillPlaceholders.RemoveAll(p => p.Name == string.Format("{0}.{1}", SkillPlaceholderDefintionPrefix, StandardMemberRenamer.Rename(nameof(ScribanExportSkill.UnusedFields)))); exportPlaceholders.AddRange(skillPlaceholders); return(exportPlaceholders); }
/// <summary> /// Parses the snippets of a template /// </summary> /// <param name="template">Template to parse</param> /// <returns>List of found snippets</returns> private List <ExportTemplateSnippet> ParseSnippets(ExportTemplate template) { string snippetRegexFormat = string.Format("(\\s|^){0}\\.{1}\\.(.*?)\\.({2}|{3}|{4})", ExportConstants.ScribanExportSnippetsObjectKey, StandardMemberRenamer.Rename(nameof(ScribanExportSnippetsData.Snippets)), StandardMemberRenamer.Rename(nameof(ScribanExportSnippet.InitialFunction)), StandardMemberRenamer.Rename(nameof(ScribanExportSnippet.AdditionalFunctions)), StandardMemberRenamer.Rename(nameof(ScribanExportSnippet.AllFunctions))); Regex exportSnippetRegex = new Regex(snippetRegexFormat, RegexOptions.Multiline); Template parsedTemplate = Template.Parse(template.Code); List <ExportTemplateSnippet> snippets = new List <ExportTemplateSnippet>(); List <ScriptStatement> statementsToCheck = ScribanStatementExtractor.ExtractPlainNonTextStatements(parsedTemplate); foreach (ScriptStatement curStatement in statementsToCheck) { if (curStatement is ScriptRawStatement) { continue; } string statement = curStatement.ToString(); MatchCollection snippetMatches = exportSnippetRegex.Matches(statement); if (!snippetMatches.Any()) { continue; } AddNewSnippets(snippets, snippetMatches); } return(snippets); }
/// <summary> /// Returns the object key for scriban /// </summary> /// <returns>Object key</returns> protected override string GetLanguageKeyValueDesc() { return(string.Format("{0}.{1}.{2} | field.{3}", GetObjectKey(), StandardMemberRenamer.Rename(nameof(ScribanQuestStateConditionData.Quest)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.Name)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.Value)))); }
/// <summary> /// Generates a language key from a call hierarchy /// </summary> /// <param name="templateContext">Template context</param> /// <param name="callerContext">Call context</param> /// <param name="callHierarchy">Call hierarchy</param> /// <returns>Language key</returns> private async ValueTask <object> GenerateLanguageKeyFromCallHierarchy(TemplateContext templateContext, ScriptNode callerContext, List <string> callHierarchy) { if (callHierarchy.Count < 2) { _errorCollection.AddCanNotGenerateLanguageKey(ScribanErrorUtil.FormatScribanSpan(callerContext.Span)); return("<<INVALID ARGUMENTS FOR LANGKEY>>"); } string objectNameValue = StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.Name)); string fieldValue = StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.Value)); string unescapedFieldValue = StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.UnescapedValue)); string textLineValue = StandardMemberRenamer.Rename(nameof(ScribanTextLine.TextLine)); string choiceText = StandardMemberRenamer.Rename(nameof(ScribanChoiceOption.Text)); string addQuestText = StandardMemberRenamer.Rename(nameof(ScribanAddQuestTextActionData.Text)); string floatingTextData = StandardMemberRenamer.Rename(nameof(ScribanShowFloatingTextActionData.Text)); if (callHierarchy[callHierarchy.Count - 1] == objectNameValue || callHierarchy[callHierarchy.Count - 1] == fieldValue || callHierarchy[callHierarchy.Count - 1] == unescapedFieldValue) { ScriptNode parentObjectExpression = BuildParentObjectValueScriptExpression(callHierarchy); object parentObject = templateContext.Evaluate(parentObjectExpression); if (parentObject == null) { _errorCollection.AddCanNotGenerateLanguageKey(ScribanErrorUtil.FormatScribanSpan(callerContext.Span)); return("<<INVALID ARGUMENTS FOR LANGKEY>>"); } if (parentObject is ScribanFlexFieldObject) { ScribanFlexFieldObject langObject = (ScribanFlexFieldObject)parentObject; return(await _languageKeyGenerator.GetFlexFieldNameKey(langObject.Id, langObject.Name, langObject.ExportObjectType)); } else if (parentObject is ScribanFlexFieldField) { return(await GenerateFlexFieldLanguageKey(callerContext, (ScribanFlexFieldField)parentObject)); } } else if (callHierarchy[callHierarchy.Count - 1] == textLineValue) { ScriptNode parentObjectExpression = BuildParentObjectValueScriptExpression(callHierarchy); object parentObject = templateContext.Evaluate(parentObjectExpression); if (parentObject is ScribanTextLine) { ScribanTextLine textLine = (ScribanTextLine)parentObject; return(await _languageKeyGenerator.GetDialogTextLineKey(textLine.NodeObject.Id, textLine.NodeObject.Name, textLine.IsPlayerLine?ExportConstants.LanguageKeyTypePlayer : ExportConstants.LanguageKeyTypeNpc, textLine.NodeId, textLine.UnescapedTextLine)); } } else if (callHierarchy[callHierarchy.Count - 1] == choiceText || callHierarchy[callHierarchy.Count - 1] == addQuestText || callHierarchy[callHierarchy.Count - 1] == floatingTextData) { ScriptNode parentObjectExpression = BuildParentObjectValueScriptExpression(callHierarchy); object parentObject = templateContext.Evaluate(parentObjectExpression); if (parentObject is ScribanChoiceOption) { ScribanChoiceOption choiceOption = (ScribanChoiceOption)parentObject; return(await _languageKeyGenerator.GetDialogTextLineKey(choiceOption.ParentChoice.NodeObject.Id, choiceOption.ParentChoice.NodeObject.Name, ExportConstants.LanguageKeyTypeChoice, string.Format("{0}_{1}", choiceOption.ParentChoice.NodeId, choiceOption.Id), choiceOption.UnescapedText)); } else if (parentObject is ScribanAddQuestTextActionData) { ScribanAddQuestTextActionData addQuestTextData = (ScribanAddQuestTextActionData)parentObject; return(await _languageKeyGenerator.GetDialogTextLineKey(addQuestTextData.FlexFieldObject.Id, addQuestTextData.Quest.Name, ExportConstants.LanguageKeyTypeQuest, addQuestTextData.NodeStep.Id, addQuestTextData.UnescapedText)); } else if (parentObject is ScribanShowFloatingTextActionData) { ScribanShowFloatingTextActionData showFloatingTextData = (ScribanShowFloatingTextActionData)parentObject; string languageKeyType = ExportConstants.LanguageKeyTypeNpc; if (showFloatingTextData.TargetNpc != null && showFloatingTextData.TargetNpc.IsPlayer) { languageKeyType = ExportConstants.LanguageKeyTypePlayer; } return(await _languageKeyGenerator.GetDialogTextLineKey(showFloatingTextData.FlexFieldObject.Id, showFloatingTextData.FlexFieldObject.Name, languageKeyType, showFloatingTextData.NodeStep.Id, showFloatingTextData.UnescapedText)); } } _errorCollection.AddCanNotGenerateLanguageKey(ScribanErrorUtil.FormatScribanSpan(callerContext.Span)); return("<<UNSUPPORTED PROPERTY FOR LANGKEY>>"); }
/// <summary> /// Returns the placeholders for a template /// </summary> /// <param name="templateType">Template Type</param> /// <returns>List of template placeholders</returns> public List <ExportTemplatePlaceholder> GetPlaceholdersForTemplate(TemplateType templateType) { List <ExportTemplatePlaceholder> placeholders = GetNodePlaceholders <ScribanReferenceData>(ReferenceKey); placeholders.AddRange(_languageKeyGenerator.GetExportTemplatePlaceholders(string.Format("{0}.{1}.{2} | {0}.{3}.{4} | {0}.{5}.{6} | {0}.{7}.{8} | field.value", ReferenceKey, StandardMemberRenamer.Rename(nameof(ReferenceNodeData.Npc)), StandardMemberRenamer.Rename(nameof(KortistoNpc.Name)), StandardMemberRenamer.Rename(nameof(ReferenceNodeData.Item)), StandardMemberRenamer.Rename(nameof(StyrItem.Name)), StandardMemberRenamer.Rename(nameof(ReferenceNodeData.Skill)), StandardMemberRenamer.Rename(nameof(EvneSkill.Name)), StandardMemberRenamer.Rename(nameof(ReferenceNodeData.Quest)), StandardMemberRenamer.Rename(nameof(AikaQuest.Name))))); return(placeholders); }
/// <summary> /// Returns the placeholders for a template /// </summary> /// <param name="templateType">Template Type</param> /// <returns>List of template placeholders</returns> public List <ExportTemplatePlaceholder> GetPlaceholdersForTemplate(TemplateType templateType) { List <ExportTemplatePlaceholder> placeholders = _languageKeyGenerator.GetExportTemplatePlaceholders(string.Format("{0}.{1}", TextLineKey, StandardMemberRenamer.Rename(nameof(ScribanTextLine.TextLine)))); placeholders.AddRange(GetNodePlaceholders <ScribanTextLine>(TextLineKey)); return(placeholders); }
/// <summary> /// Returns the object key for scriban /// </summary> /// <returns>Object key</returns> protected override string GetLanguageKeyValueDesc() { return(string.Format("{0}.{1}.{2} | {0}.{3}.{2} | field.{4}", GetObjectKey(), StandardMemberRenamer.Rename(nameof(ScribanLearnedSkillConditionData.Npc)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldObject.Name)), StandardMemberRenamer.Rename(nameof(ScribanLearnedSkillConditionData.SelectedSkill)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.Value)))); }
/// <summary> /// Returns the Export Template Placeholders for a Template Type /// </summary> /// <param name="templateType">Template Type</param> /// <returns>Export Template Placeholder</returns> public override List <ExportTemplatePlaceholder> GetExportTemplatePlaceholdersForType(TemplateType templateType) { string languageKeyValueDesc = string.Format("{0}.{1}.{2} | field.{3}", ExportConstants.ScribanActionObjectKey, StandardMemberRenamer.Rename(nameof(ScribanSetDailyRoutineEventStateActionData.Npc)), StandardMemberRenamer.Rename(nameof(ScribanSetDailyRoutineEventStateActionData.Npc.Name)), StandardMemberRenamer.Rename(nameof(ScribanFlexFieldField.Name))); return(ScribanActionRenderingUtil.GetExportTemplatePlaceholdersForType <ScribanSetDailyRoutineEventStateActionData>(_localizerFactory, _scribanLanguageKeyGenerator, languageKeyValueDesc)); }