【优化】优化typescript 可空变量的定义,由 xxx?:yyy 改成 xxx:yyy|undefined

【新增】新增 code_typescript_editor_json 一个用于web的临时性生成方案
【优化】优化 typescript Vector{2,3,4}加载json的代码。 json['x']改成json.x
【优化】优化 typescript 格式及解决一些编译警告
main
walon 2021-09-03 12:52:51 +08:00
parent 412173f1c0
commit 533ab56f86
14 changed files with 409 additions and 165 deletions

View File

@ -105,7 +105,7 @@ namespace Luban.Job.Cfg.Defs
get get
{ {
var table = Assembly.GetCfgTable(Ref.FirstTable); var table = Assembly.GetCfgTable(Ref.FirstTable);
return $"{TsRefVarName} : {table.ValueTType.Apply(TypescriptDefineTypeNameVisitor.Ins)}{(IsNullable ? " | undefined" : " = undefined!")}"; return $"{TsRefVarName} : {table.ValueTType.Apply(TypescriptDefineTypeNameVisitor.Ins)}{(IsNullable ? "" : " = undefined!")}";
} }
} }

View File

@ -0,0 +1,95 @@
using Luban.Common.Protos;
using Luban.Job.Cfg.Defs;
using Luban.Job.Common;
using Luban.Job.Common.Defs;
using Luban.Job.Common.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Luban.Job.Cfg.Generate
{
[Render("code_typescript_editor_json")]
class TypescriptEditorCodeJsonRender : TypescriptCodeRenderBase
{
public override void Render(GenContext ctx)
{
string genType = ctx.GenType;
var args = ctx.GenArgs;
ctx.Render = this;
ctx.Lan = RenderFileUtil.GetLanguage(genType);
var lines = new List<string>(10000);
Action<List<string>> preContent = (fileContent) =>
{
fileContent.Add(StringTemplateUtil.GetTemplateString("config/typescript_json/vectors"));
fileContent.Add(@$"export namespace {ctx.TopModule} {{");
};
Action<List<string>> postContent = (fileContent) =>
{
fileContent.Add("}\n"); // end of topmodule
};
GenerateCode(ctx, "Types.ts", lines, preContent, postContent);
}
protected void GenerateCode(GenContext ctx, string outputFile, List<string> fileContent, Action<List<string>> preContent, Action<List<string>> postContent)
{
ctx.Tasks.Add(Task.Run(() =>
{
fileContent.Add(FileHeaderUtil.GetAutoGenerationHeader(ctx.Lan));
preContent?.Invoke(fileContent);
foreach (var c in ctx.Assembly.Types.Values)
{
switch (c)
{
case DefConst:
case DefEnum:
case DefBean:
case DefTable:
{
fileContent.Add(ctx.Render.RenderAny(c));
break;
}
}
}
postContent?.Invoke(fileContent);
var file = outputFile;
var md5 = CacheFileUtil.GenMd5AndAddCache(file, string.Join('\n', fileContent));
ctx.GenCodeFilesInOutputCodeDir.Add(new FileInfo() { FilePath = file, MD5 = md5 });
}));
}
public override string Render(DefEnum e)
{
var template = StringTemplateUtil.GetTemplate("config/typescript_editor_json/enum");
var result = template.RenderCode(e);
return result;
}
public override string Render(DefBean b)
{
var template = StringTemplateUtil.GetTemplate("config/typescript_editor_json/bean");
var result = template.RenderCode(b);
return result;
}
public override string Render(DefTable p)
{
var template = StringTemplateUtil.GetTemplate("config/typescript_editor_json/table");
var result = template.RenderCode(p);
return result;
}
public override string RenderService(string name, string module, List<DefTable> tables)
{
throw new NotSupportedException();
}
}
}

View File

@ -94,7 +94,7 @@ namespace Luban.Job.Cfg
return false; return false;
} }
if (!options.ValidateTypescriptRequire(options.GenType, ref errMsg)) if (options.GenType.Contains("typescript_bin") && !options.ValidateTypescriptRequire(options.GenType, ref errMsg))
{ {
return false; return false;
} }

View File

@ -36,8 +36,6 @@ namespace Luban.Job.Common
} }
public bool ValidateTypescriptRequire(string genType, ref string errMsg) public bool ValidateTypescriptRequire(string genType, ref string errMsg)
{
if (genType.Contains("typescript"))
{ {
if (!string.IsNullOrWhiteSpace(this.TypescriptBrightRequirePath) && !string.IsNullOrWhiteSpace(this.TypescriptBrightPackageName)) if (!string.IsNullOrWhiteSpace(this.TypescriptBrightRequirePath) && !string.IsNullOrWhiteSpace(this.TypescriptBrightPackageName))
{ {
@ -55,7 +53,6 @@ namespace Luban.Job.Common
errMsg = "while --embed_bright_types is false, should provide option --typescript_bright_require_path or --typescript_bright_package_name"; errMsg = "while --embed_bright_types is false, should provide option --typescript_bright_require_path or --typescript_bright_package_name";
return false; return false;
} }
}
return true; return true;
} }
} }

View File

@ -0,0 +1,142 @@
using Luban.Job.Common.Types;
namespace Luban.Job.Common.TypeVisitors
{
public class TypescriptDefineTypeNameUnderlyingVisitor : ITypeFuncVisitor<string>
{
public static TypescriptDefineTypeNameUnderlyingVisitor Ins { get; } = new();
public string Accept(TBool type)
{
return "boolean";
}
public string Accept(TByte type)
{
return "number";
}
public string Accept(TShort type)
{
return "number";
}
public string Accept(TFshort type)
{
return "number";
}
public string Accept(TInt type)
{
return "number";
}
public string Accept(TFint type)
{
return "number";
}
public string Accept(TLong type)
{
return type.IsBigInt ? "bigint" : "number";
}
public string Accept(TFlong type)
{
return "bigint";
}
public string Accept(TFloat type)
{
return "number";
}
public string Accept(TDouble type)
{
return "number";
}
public string Accept(TEnum type)
{
return type.DefineEnum.FullName;
}
public string Accept(TString type)
{
return "string";
}
public string Accept(TBytes type)
{
return "Uint8Array";
}
public string Accept(TText type)
{
return "string";
}
public string Accept(TBean type)
{
return type.Bean.FullName;
}
private string GetArrayType(TType elementType)
{
switch (elementType)
{
case TByte _: return "Uint8Array";
case TShort _:
case TFshort _: return "Int16Array";
case TInt _:
case TFint _: return "Int32Array";
case TLong _:
case TFlong _: return "Int64Array";
case TFloat _: return "Float32Array";
case TDouble _: return "Float64Array";
default: return $"{elementType.Apply(this)}[]";
}
}
public virtual string Accept(TArray type)
{
return GetArrayType(type.ElementType);
}
public virtual string Accept(TList type)
{
return $"{type.ElementType.Apply(this)}[]";
}
public virtual string Accept(TSet type)
{
return $"Set<{type.ElementType.Apply(this)}>";
}
public virtual string Accept(TMap type)
{
return $"Map<{type.KeyType.Apply(this)}, {type.ValueType.Apply(this)}>";
}
public string Accept(TVector2 type)
{
return "Vector2";
}
public string Accept(TVector3 type)
{
return "Vector3";
}
public string Accept(TVector4 type)
{
return "Vector4";
}
public string Accept(TDateTime type)
{
return "number";
}
}
}

View File

@ -2,141 +2,13 @@ using Luban.Job.Common.Types;
namespace Luban.Job.Common.TypeVisitors namespace Luban.Job.Common.TypeVisitors
{ {
public class TypescriptDefineTypeNameVisitor : ITypeFuncVisitor<string> public class TypescriptDefineTypeNameVisitor : DecoratorFuncVisitor<string>
{ {
public static TypescriptDefineTypeNameVisitor Ins { get; } = new TypescriptDefineTypeNameVisitor(); public static TypescriptDefineTypeNameVisitor Ins { get; } = new TypescriptDefineTypeNameVisitor();
public string Accept(TBool type) public override string DoAccept(TType type)
{ {
return "boolean"; return type.IsNullable ? $"{type.Apply(TypescriptDefineTypeNameUnderlyingVisitor.Ins)}|undefined" : type.Apply(TypescriptDefineTypeNameUnderlyingVisitor.Ins);
}
public string Accept(TByte type)
{
return "number";
}
public string Accept(TShort type)
{
return "number";
}
public string Accept(TFshort type)
{
return "number";
}
public string Accept(TInt type)
{
return "number";
}
public string Accept(TFint type)
{
return "number";
}
public string Accept(TLong type)
{
return type.IsBigInt ? "bigint" : "number";
}
public string Accept(TFlong type)
{
return "bigint";
}
public string Accept(TFloat type)
{
return "number";
}
public string Accept(TDouble type)
{
return "number";
}
public string Accept(TEnum type)
{
return type.DefineEnum.FullName;
}
public string Accept(TString type)
{
return "string";
}
public string Accept(TBytes type)
{
return "Uint8Array";
}
public string Accept(TText type)
{
return "string";
}
public string Accept(TBean type)
{
return type.Bean.FullName;
}
private string GetArrayType(TType elementType)
{
switch (elementType)
{
case TByte _: return "Uint8Array";
case TShort _:
case TFshort _: return "Int16Array";
case TInt _:
case TFint _: return "Int32Array";
case TLong _:
case TFlong _: return "Int64Array";
case TFloat _: return "Float32Array";
case TDouble _: return "Float64Array";
default: return $"{elementType.Apply(this)}[]";
}
}
public virtual string Accept(TArray type)
{
return GetArrayType(type.ElementType);
}
public virtual string Accept(TList type)
{
return $"{type.ElementType.Apply(this)}[]";
}
public virtual string Accept(TSet type)
{
return $"Set<{type.ElementType.Apply(this)}>";
}
public virtual string Accept(TMap type)
{
return $"Map<{type.KeyType.Apply(this)}, {type.ValueType.Apply(this)}>";
}
public string Accept(TVector2 type)
{
return "Vector2";
}
public string Accept(TVector3 type)
{
return "Vector3";
}
public string Accept(TVector4 type)
{
return "Vector4";
}
public string Accept(TDateTime type)
{
return "number";
} }
} }
} }

View File

@ -47,7 +47,7 @@ namespace Luban.Job.Db
{ {
return false; return false;
} }
if (!options.ValidateTypescriptRequire(options.GenType, ref errMsg)) if (options.GenType.Contains("typescript") && !options.ValidateTypescriptRequire(options.GenType, ref errMsg))
{ {
return false; return false;
} }

View File

@ -54,7 +54,7 @@ namespace Luban.Job.Proto
{ {
return false; return false;
} }
if (!options.ValidateTypescriptRequire(options.GenType, ref errMsg)) if (options.GenType.Contains("typescript") && !options.ValidateTypescriptRequire(options.GenType, ref errMsg))
{ {
return false; return false;
} }

View File

@ -187,6 +187,15 @@
<None Update="Templates\config\typescript_bin\vectors.tpl"> <None Update="Templates\config\typescript_bin\vectors.tpl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Templates\config\typescript_editor_json\bean.tpl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Templates\config\typescript_editor_json\enum.tpl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Templates\config\typescript_editor_json\table.tpl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Templates\config\typescript_json\bean.tpl"> <None Update="Templates\config\typescript_json\bean.tpl">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>

View File

@ -0,0 +1,50 @@
{{
name = x.name
parent_def_type = x.parent_def_type
export_fields = x.export_fields
hierarchy_export_fields = x.hierarchy_export_fields
}}
{{x.typescript_namespace_begin}}
{{~if x.comment != '' ~}}
/**
* {{x.comment}}
*/
{{~end~}}
export {{if x.is_abstract_type}}abstract {{end}}class {{name}}{{if parent_def_type}} extends {{x.parent}}{{end}} {
{{~if x.is_abstract_type~}}
static constructorFrom(_json_: any): {{name}}{
switch (_json_.__type__) {
{{~ for child in x.hierarchy_not_abstract_children~}}
case '{{child.name}}': return new {{child.full_name}}(_json_)
{{~end~}}
default: throw new Error()
}
}
{{~end~}}
constructor(_json_: any) {
{{~if parent_def_type~}}
super(_json_)
{{~end~}}
{{~ for field in export_fields ~}}
{{~if !field.ctype.is_nullable~}}
if (_json_.{{field.name}} === undefined) { throw new Error() }
{{~end~}}
{{ts_json_constructor ('this.' + field.ts_style_name) ( '_json_.' + field.name) field.ctype}}
{{~end~}}
}
{{~ for field in export_fields ~}}
{{~if field.comment != '' ~}}
/**
* {{field.comment}}
*/
{{~end~}}
{{field.ts_style_name}}: {{ts_define_type field.ctype}}
{{~end~}}
}
{{x.typescript_namespace_end}}

View File

@ -0,0 +1,25 @@
{{x.typescript_namespace_begin}}
{{~if x.comment != '' ~}}
/**
* {{x.comment}}
*/
{{~end~}}
export class {{x.name}} {
readonly id: number
readonly name: string
readonly alias: string
readonly comment: string
constructor(id: number, name: string, alias: string, comment: string) {
this.id = id
this.name = name
this.alias= alias
this.comment = comment
}
{{~for item in x.items ~}}
static readonly {{item.name}} = new {{x.name}}({{item.int_value}}, `{{item.name}}`, `{{item.alias}}`, `{{item.comment}}`)
{{~end~}}
}
{{x.typescript_namespace_end}}

View File

@ -0,0 +1,54 @@
{{
name = x.name
key_type = x.key_ttype
key_type1 = x.key_ttype1
key_type2 = x.key_ttype2
value_type = x.value_ttype
}}
{{x.typescript_namespace_begin}}
{{~if x.comment != '' ~}}
/**
* {{x.comment}}
*/
{{~end~}}
export class {{name}}{
{{~if x.is_map_table ~}}
private _dataMap: Map<{{ts_define_type key_type}}, {{ts_define_type value_type}}>
private _dataList: {{ts_define_type value_type}}[]
constructor(_json_: any) {
this._dataMap = new Map<{{ts_define_type key_type}}, {{ts_define_type value_type}}>()
this._dataList = []
for(var _json2_ of _json_) {
let _v: {{ts_define_type value_type}}
{{ts_json_constructor '_v' '_json2_' value_type}}
this._dataList.push(_v)
this._dataMap.set(_v.{{x.index_field.ts_style_name}}, _v)
}
}
getDataMap(): Map<{{ts_define_type key_type}}, {{ts_define_type value_type}}> { return this._dataMap; }
getDataList(): {{ts_define_type value_type}}[] { return this._dataList; }
get(key: {{ts_define_type key_type}}): {{ts_define_type value_type}} | undefined { return this._dataMap.get(key); }
{{~else~}}
private _data: {{ts_define_type value_type}}
constructor(_json_: any) {
if (_json_.length != 1) throw new Error('table mode=one, but size != 1')
{{ts_json_constructor 'this._data' '_json_[0]' value_type}}
}
getData(): {{ts_define_type value_type}} { return this._data; }
{{~ for field in value_type.bean.hierarchy_export_fields ~}}
{{~if field.comment != '' ~}}
/**
* {{field.comment}}
*/
{{~end~}}
get {{field.ts_style_name}}(): {{ts_define_type field.ctype}} { return this._data.{{field.ts_style_name}}; }
{{~end~}}
{{end}}
}
{{x.typescript_namespace_end}}

View File

@ -30,7 +30,7 @@ export {{if x.is_abstract_type}} abstract {{end}} class {{name}} {{if parent_def
{{~end~}} {{~end~}}
{{~ for field in export_fields ~}} {{~ for field in export_fields ~}}
{{~if !field.ctype.is_nullable~}} {{~if !field.ctype.is_nullable~}}
if (_json_.{{field.name}} == undefined) { throw new Error() } if (_json_.{{field.name}} === undefined) { throw new Error() }
{{~end~}} {{~end~}}
{{ts_json_constructor ('this.' + field.ts_style_name) ( '_json_.' + field.name) field.ctype}} {{ts_json_constructor ('this.' + field.ts_style_name) ( '_json_.' + field.name) field.ctype}}
{{~end~}} {{~end~}}
@ -42,7 +42,7 @@ export {{if x.is_abstract_type}} abstract {{end}} class {{name}} {{if parent_def
* {{field.comment}} * {{field.comment}}
*/ */
{{~end~}} {{~end~}}
readonly {{field.ts_style_name}}{{if field.is_nullable}}?{{end}}: {{ts_define_type field.ctype}} readonly {{field.ts_style_name}}: {{ts_define_type field.ctype}}
{{~if field.gen_ref~}} {{~if field.gen_ref~}}
{{field.ts_ref_validator_define}} {{field.ts_ref_validator_define}}
{{~end~}} {{~end~}}

View File

@ -1,8 +1,8 @@
export class Vector2 { export class Vector2 {
static deserializeFromJson(json: any): Vector2 { static deserializeFromJson(json: any): Vector2 {
let x = json['x'] let x = json.x
let y = json['y'] let y = json.y
if (x == null || y == null) { if (x == null || y == null) {
throw new Error() throw new Error()
} }
@ -19,9 +19,9 @@ export class Vector2 {
export class Vector3 { export class Vector3 {
static deserializeFromJson(json: any): Vector3 { static deserializeFromJson(json: any): Vector3 {
let x = json['x'] let x = json.x
let y = json['y'] let y = json.y
let z = json['z'] let z = json.z
if (x == null || y == null || z == null) { if (x == null || y == null || z == null) {
throw new Error() throw new Error()
} }
@ -41,10 +41,10 @@ export class Vector3 {
export class Vector4 { export class Vector4 {
static deserializeFromJson(json: any): Vector4 { static deserializeFromJson(json: any): Vector4 {
let x = json['x'] let x = json.x
let y = json['y'] let y = json.y
let z = json['z'] let z = json.z
let w = json['w'] let w = json.w
if (x == null || y == null || z == null || w == null) { if (x == null || y == null || z == null || w == null) {
throw new Error() throw new Error()
} }