cgen: global/const fixes

pull/13827/head
Alexander Medvednikov 2022-03-25 23:32:50 +03:00
parent ea4410cdb5
commit 0248349e7c
2 changed files with 12 additions and 6 deletions

View File

@ -4371,17 +4371,23 @@ fn (mut g Gen) global_decl(node ast.GlobalDecl) {
if field.has_expr && mut anon_fn_expr is ast.AnonFn { if field.has_expr && mut anon_fn_expr is ast.AnonFn {
g.gen_anon_fn_decl(mut anon_fn_expr) g.gen_anon_fn_decl(mut anon_fn_expr)
fn_type_name := g.get_anon_fn_type_name(mut anon_fn_expr, field.name) fn_type_name := g.get_anon_fn_type_name(mut anon_fn_expr, field.name)
g.definitions.writeln('$fn_type_name = ${g.table.sym(field.typ).name}; // global') g.definitions.writeln('$fn_type_name = ${g.table.sym(field.typ).name}; // global2')
continue continue
} }
g.definitions.write_string('$visibility_kw$styp $attributes $field.name') g.definitions.write_string('$visibility_kw$styp $attributes $field.name')
if field.has_expr { if field.has_expr {
if field.expr.is_literal() && should_init { if g.pref.translated {
g.definitions.write_string(' = ${g.expr_string(field.expr)}')
} else if field.expr.is_literal() && should_init {
// Simple literals can be initialized right away in global scope in C.
// e.g. `int myglobal = 10;`
g.definitions.write_string(' = ${g.expr_string(field.expr)}') g.definitions.write_string(' = ${g.expr_string(field.expr)}')
} else { } else {
g.global_init.writeln('\t$field.name = ${g.expr_string(field.expr)}; // global') // More complex expressions need to be moved to `_vinit()`
// e.g. `__global ( mygblobal = 'hello ' + world' )`
g.global_init.writeln('\t$field.name = ${g.expr_string(field.expr)}; // 3global')
} }
} else { } else if !g.pref.translated { // don't zero globals from C code
default_initializer := g.type_default(field.typ) default_initializer := g.type_default(field.typ)
if default_initializer == '{0}' && should_init { if default_initializer == '{0}' && should_init {
g.definitions.write_string(' = {0}') g.definitions.write_string(' = {0}')
@ -4391,7 +4397,7 @@ fn (mut g Gen) global_decl(node ast.GlobalDecl) {
} }
} }
} }
g.definitions.writeln('; // global') g.definitions.writeln('; // global4')
} }
} }

View File

@ -39,7 +39,7 @@ const (
const builtin_module_names = ['builtin', 'strconv', 'strings', 'dlmalloc'] const builtin_module_names = ['builtin', 'strconv', 'strings', 'dlmalloc']
pub fn module_is_builtin(mod string) bool { pub fn module_is_builtin(mod string) bool {
return mod in util.builtin_module_names return mod in util.builtin_module_parts
} }
pub fn tabs(n int) string { pub fn tabs(n int) string {