mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
v.gen.js: support global declarations in the JS backend (#10773)
This commit is contained in:
parent
d444dbd4d9
commit
ee00d80931
@ -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 ')
|
||||
|
Loading…
Reference in New Issue
Block a user