From 8fb747a2e478c97309a475c9664ba79bb445e26d Mon Sep 17 00:00:00 2001 From: Pavel Shevaev Date: Fri, 5 May 2023 12:12:49 +0300 Subject: [PATCH] Adding initial support for null structs (but not generic ones) --- src/codegen.inc.php | 34 +++++++++++++++++++++++----------- tpl/macro.twig | 14 +++++++++----- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/codegen.inc.php b/src/codegen.inc.php index bf8631d..72d00de 100644 --- a/src/codegen.inc.php +++ b/src/codegen.inc.php @@ -348,23 +348,30 @@ function var_reset($name, \mtgType $type, $default = null) else if($type instanceof \mtgMetaStruct) { $str = ""; - $is_pod = $type->hasToken('POD'); - if($is_pod) - $str .= "$name.reset(); "; - else - $str .= "Meta.Reset(ref $name); "; + if(!is_null_str($default)) + { + $is_pod = $type->hasToken('POD'); + if($is_pod) + $str .= "$name.reset(); "; + else + $str .= "Meta.Reset(ref $name); "; + } if($default) { $default = is_array($default) ? $default : json_decode($default, true); - if(!is_array($default)) - throw new Exception("Bad default value for struct: $default"); - - foreach($default as $k => $v) + if(is_array($default)) { - $kf = $type->getField($k); - $str .= var_reset("$name." . $kf->getName(), $kf->getType(), $v); + foreach($default as $k => $v) + { + $kf = $type->getField($k); + $str .= var_reset("$name." . $kf->getName(), $kf->getType(), $v); + } } + else if($default === null) + $str .= "$name = default; "; + else + throw new Exception("Bad default value for struct: " . var_export($default, true)); } } else @@ -372,6 +379,11 @@ function var_reset($name, \mtgType $type, $default = null) return $str; } +function is_null_str($default) +{ + return is_string($default) && json_decode($default, true) === null; +} + function var_sync($fname, \mtgType $type, $buf, array $tokens, $opts) { $optional = array_key_exists('optional', $tokens); diff --git a/tpl/macro.twig b/tpl/macro.twig index 79fc2ad..44479ec 100644 --- a/tpl/macro.twig +++ b/tpl/macro.twig @@ -128,14 +128,18 @@ public FieldsMask fields_mask; {%- macro decl_struct_field(o, f) -%} {{_self.attributes(f)}} -public {{f.type|cs_type|obscure_type(f)}} {{f.name}} {% if not has_token(o, 'POD') -%} {{_self.decl_init_value(f.type)}} {%- endif -%}; +public {{f.type|cs_type|obscure_type(f)}} {{f.name}} {% if not has_token(o, 'POD') -%} {{_self.decl_init_value(f)}} {%- endif -%}; {%- endmacro -%} -{% macro decl_init_value(type) %} -{%- if type is instanceof('\\mtgBuiltinType') -%} -{%- if type.isstring -%} = ""{%- endif -%} +{% macro decl_init_value(f) %} +{%- if f.type is instanceof('\\mtgBuiltinType') -%} +{%- if f.type.isstring -%} = ""{%- endif -%} {%- else -%} -= new {{type|cs_type}}() +{%- if has_token(f, 'default') and token(f, 'default') == 'null' -%} +/*null*/ +{%- else -%} += new {{f.type|cs_type}}() +{%- endif -%} {%- endif -%} {% endmacro %}