v2 / vlib / v / gen / c / ctempvars.v
72 lines · 67 sloc · 1.94 KB · 07c796b670d9e498ccb25605af189617f61ec295
Raw
1module c
2
3import v.ast
4
5fn (mut g Gen) new_ctemp_var(expr ast.Expr, expr_type ast.Type) ast.CTempVar {
6 return ast.CTempVar{
7 name: g.new_tmp_var()
8 typ: expr_type
9 is_ptr: expr_type.is_ptr()
10 orig: expr
11 }
12}
13
14fn (mut g Gen) new_ctemp_var_then_gen(expr ast.Expr, expr_type ast.Type) ast.CTempVar {
15 mut x := g.new_ctemp_var(expr, expr_type)
16 g.gen_ctemp_var(mut x)
17 return x
18}
19
20fn (mut g Gen) expr_to_ctemp_before_stmt(expr ast.Expr, expr_type ast.Type) ast.CTempVar {
21 mut stmt_str := if g.inside_ternary > 0 {
22 g.go_before_ternary().trim_space()
23 } else {
24 g.go_before_last_stmt().trim_space()
25 }
26 if g.inside_return && stmt_str.ends_with('return') {
27 stmt_str += ' '
28 }
29 g.empty_line = true
30 mut x := g.new_ctemp_var(expr, expr_type)
31 g.gen_ctemp_var(mut x)
32 g.write(stmt_str)
33 return x
34}
35
36fn (mut g Gen) gen_ctemp_var(mut tvar ast.CTempVar) {
37 styp := g.styp(tvar.typ)
38 final_sym := g.table.final_sym(tvar.typ)
39 if final_sym.info is ast.ArrayFixed {
40 tvar.is_fixed_ret = final_sym.info.is_fn_ret
41 if tvar.is_fixed_ret {
42 g.writeln('${styp} ${tvar.name};')
43 g.write('memcpy(${tvar.name}.ret_arr, ')
44 g.expr(tvar.orig)
45 g.writeln(' , sizeof(${styp[3..]}));')
46 } else if tvar.orig is ast.ArrayInit && tvar.orig.has_val && !tvar.orig.has_init
47 && !tvar.orig.has_len && !tvar.orig.has_cap && !tvar.orig.has_index {
48 g.write('${styp} ${tvar.name} = ')
49 g.expr(tvar.orig)
50 g.writeln(';')
51 } else {
52 g.writeln('${styp} ${tvar.name};')
53 g.write('memcpy(&${tvar.name}, ')
54 g.expr(tvar.orig)
55 g.writeln(' , sizeof(${styp}));')
56 }
57 } else if final_sym.info is ast.FnType {
58 g.write_fn_ptr_decl(final_sym.info, tvar.name)
59 g.write(' = ')
60 g.expr(tvar.orig)
61 g.writeln(';')
62 } else {
63 if g.pref.gc_mode in [.boehm_full, .boehm_incr, .boehm_full_opt, .boehm_incr_opt]
64 && g.contains_ptr(tvar.typ) {
65 g.write('volatile ')
66 }
67 g.write('${styp} ${tvar.name} = ')
68 g.expr(tvar.orig)
69 g.writeln(';')
70 }
71 g.set_current_pos_as_last_stmt_pos()
72}
73