v4 / vlib / v / gen / c / ctempvars.v
75 lines · 70 sloc · 2.01 KB · 03f27857f5066555691ffbb6b56708440de55ac0
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 if g.pref.is_vlines && stmt_str.contains('#line') {
34 g.writeln('')
35 }
36 return x
37}
38
39fn (mut g Gen) gen_ctemp_var(mut tvar ast.CTempVar) {
40 styp := g.styp(tvar.typ)
41 final_sym := g.table.final_sym(tvar.typ)
42 if final_sym.info is ast.ArrayFixed {
43 tvar.is_fixed_ret = final_sym.info.is_fn_ret
44 if tvar.is_fixed_ret {
45 g.writeln('${styp} ${tvar.name};')
46 g.write('memcpy(${tvar.name}.ret_arr, ')
47 g.expr(tvar.orig)
48 g.writeln(' , sizeof(${styp[3..]}));')
49 } else if tvar.orig is ast.ArrayInit && tvar.orig.has_val && !tvar.orig.has_init
50 && !tvar.orig.has_len && !tvar.orig.has_cap && !tvar.orig.has_index {
51 g.write('${styp} ${tvar.name} = ')
52 g.expr(tvar.orig)
53 g.writeln(';')
54 } else {
55 g.writeln('${styp} ${tvar.name};')
56 g.write('memcpy(&${tvar.name}, ')
57 g.expr(tvar.orig)
58 g.writeln(' , sizeof(${styp}));')
59 }
60 } else if final_sym.info is ast.FnType {
61 g.write_fn_ptr_decl(final_sym.info, tvar.name)
62 g.write(' = ')
63 g.expr(tvar.orig)
64 g.writeln(';')
65 } else {
66 if g.pref.gc_mode in [.boehm_full, .boehm_incr, .boehm_full_opt, .boehm_incr_opt]
67 && g.contains_ptr(tvar.typ) {
68 g.write('volatile ')
69 }
70 g.write('${styp} ${tvar.name} = ')
71 g.expr(tvar.orig)
72 g.writeln(';')
73 }
74 g.set_current_pos_as_last_stmt_pos()
75}
76