From ee00d80931fe88091787acc05c3cc1f5b7e3a544 Mon Sep 17 00:00:00 2001 From: playX Date: Tue, 13 Jul 2021 15:36:06 +0300 Subject: [PATCH] v.gen.js: support global declarations in the JS backend (#10773) --- vlib/v/gen/js/js.v | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/vlib/v/gen/js/js.v b/vlib/v/gen/js/js.v index 3aa284e46c..d910612eaa 100644 --- a/vlib/v/gen/js/js.v +++ b/vlib/v/gen/js/js.v @@ -105,6 +105,7 @@ pub fn gen(files []&ast.File, table &ast.Table, pref &pref.Preferences) string { g.find_class_methods(file.stmts) g.escape_namespace() } + for file in files { g.file = file g.enter_namespace(g.file.mod.name) @@ -120,6 +121,7 @@ pub fn gen(files []&ast.File, table &ast.Table, pref &pref.Preferences) string { g.gen_builtin_type_defs() g.generated_builtin = true } + g.stmts(file.stmts) // store the current namespace g.escape_namespace() @@ -292,6 +294,7 @@ pub fn (mut g JsGen) init() { g.definitions.writeln('// Generated by the V compiler\n') g.definitions.writeln('"use strict";') g.definitions.writeln('') + g.definitions.writeln('var \$global = (new Function("return this"))();') } pub fn (g JsGen) hashes() string { @@ -418,6 +421,27 @@ fn (mut g JsGen) write_v_source_line_info(pos token.Position) { } } +fn (mut g JsGen) gen_global_decl(node ast.GlobalDecl) { + mod := if g.pref.build_mode == .build_module { 'enumerable: false' } else { 'enumerable: true' } + for field in node.fields { + if field.has_expr { + tmp_var := g.new_tmp_var() + g.write('const $tmp_var = ') + g.expr(field.expr) + g.writeln(';') + g.writeln('Object.defineProperty(\$global,"$field.name", { + configurable: false, + $mod , + writable: true, + value: $tmp_var + } + ); // global') + } else { + // TODO(playXE): Initialize with default value of type + } + } +} + fn (mut g JsGen) stmt(node ast.Stmt) { g.stmt_start_pos = g.ns.out.len match node { @@ -480,7 +504,9 @@ fn (mut g JsGen) stmt(node ast.Stmt) { g.writeln('') } ast.GlobalDecl { - // TODO + g.write_v_source_line_info(node.pos) + g.gen_global_decl(node) + g.writeln('') } ast.GotoLabel { g.write_v_source_line_info(node.pos) @@ -903,6 +929,7 @@ fn (mut g JsGen) gen_method_decl(it ast.FnDecl) { if is_main { // there is no concept of main in JS but we do have iife g.writeln('/* program entry point */') + g.write('(') if has_go { g.write('async ')