v/vlib/v/gen/cgen.v

3078 lines
82 KiB
V
Raw Normal View History

2020-04-05 18:03:36 +02:00
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
2019-12-30 08:30:24 +01:00
module gen
2019-12-24 18:54:43 +01:00
2020-04-14 19:32:23 +02:00
import strings
import v.ast
import v.table
import v.pref
import v.token
import v.util
import v.depgraph
import term
2019-12-24 18:54:43 +01:00
const (
c_reserved = ['delete', 'exit', 'unix', 'error', 'calloc', 'malloc', 'free', 'panic', 'auto',
'char'
'default'
'do'
'double'
2020-04-20 08:30:42 +02:00
'extern'
'float'
2020-04-20 09:04:17 +02:00
'inline'
'int'
'long'
'register'
2020-04-21 05:07:49 +02:00
'restrict'
'short'
'signed'
'sizeof'
'static'
'switch'
'typedef'
'union'
'unsigned'
'void'
2020-04-21 05:07:49 +02:00
'volatile'
'while'
]
)
fn foo(t token.Token) {
util.full_hash()
}
2019-12-24 18:54:43 +01:00
struct Gen {
out strings.Builder
cheaders strings.Builder
includes strings.Builder // all C #includes required by V modules
typedefs strings.Builder
typedefs2 strings.Builder
definitions strings.Builder // typedefs, defines etc (everything that goes to the top of the file)
inits strings.Builder // contents of `void _vinit(){}`
gowrappers strings.Builder // all go callsite wrappers
stringliterals strings.Builder // all string literals (they depend on tos3() beeing defined
auto_str_funcs strings.Builder // function bodies of all auto generated _str funcs
table &table.Table
pref &pref.Preferences
mut:
file ast.File
fn_decl &ast.FnDecl // pointer to the FnDecl we are currently inside otherwise 0
tmp_count int
variadic_args map[string]int
is_c_call bool // e.g. `C.printf("v")`
is_assign_lhs bool // inside left part of assign expr (for array_set(), etc)
is_assign_rhs bool // inside right part of assign after `=` (val expr)
is_array_set bool
is_amp bool // for `&Foo{}` to merge PrefixExpr `&` and StructInit `Foo{}`; also for `&byte(0)` etc
optionals []string // to avoid duplicates TODO perf, use map
inside_ternary bool // ?: comma separated statements on a single line
stmt_start_pos int
right_is_opt bool
autofree bool
indent int
empty_line bool
is_test bool
assign_op token.Kind // *=, =, etc (for array_set)
defer_stmts []ast.DeferStmt
defer_ifdef string
str_types []string // types that need automatic str() generation
threaded_fns []string // for generating unique wrapper types and fns for `go xxx()`
2020-04-09 03:55:37 +02:00
array_fn_definitions []string // array equality functions that have been defined
2020-04-14 00:37:47 +02:00
is_json_fn bool // inside json.encode()
2019-12-24 18:54:43 +01:00
}
const (
tabs = ['', '\t', '\t\t', '\t\t\t', '\t\t\t\t', '\t\t\t\t\t', '\t\t\t\t\t\t', '\t\t\t\t\t\t\t',
'\t\t\t\t\t\t\t\t'
]
)
2020-03-30 17:21:32 +02:00
pub fn cgen(files []ast.File, table &table.Table, pref &pref.Preferences) string {
if true { // if
x := 10 // line
2020-04-05 18:03:36 +02:00
// sep
y := 20
2020-04-22 01:52:56 +02:00
_ = x
_ = y
2020-04-05 18:03:36 +02:00
} else {
}
2020-03-22 12:06:33 +01:00
// println('start cgen2')
mut g := Gen{
out: strings.new_builder(1000)
cheaders: strings.new_builder(8192)
includes: strings.new_builder(100)
typedefs: strings.new_builder(100)
2020-04-06 18:46:46 +02:00
typedefs2: strings.new_builder(100)
2020-01-02 08:30:15 +01:00
definitions: strings.new_builder(100)
gowrappers: strings.new_builder(100)
2020-04-04 22:06:47 +02:00
stringliterals: strings.new_builder(100)
auto_str_funcs: strings.new_builder(100)
2020-03-21 09:29:16 +01:00
inits: strings.new_builder(100)
table: table
2020-03-30 17:21:32 +02:00
pref: pref
fn_decl: 0
2020-03-21 19:52:19 +01:00
autofree: true
indent: -1
2019-12-28 11:02:06 +01:00
}
g.init()
2020-04-08 13:53:11 +02:00
//
mut autofree_used := false
2019-12-30 12:10:46 +01:00
for file in files {
2020-03-21 19:52:19 +01:00
g.file = file
2020-03-22 12:06:33 +01:00
// println('\ncgen "$g.file.path" nr_stmts=$file.stmts.len')
building_v := true && (g.file.path.contains('/vlib/') || g.file.path.contains('cmd/v'))
is_test := g.file.path.ends_with('.vv') || g.file.path.ends_with('_test.v')
2020-03-24 22:35:05 +01:00
if g.file.path.ends_with('_test.v') {
g.is_test = is_test
}
if g.file.path == '' || is_test || building_v || !g.pref.autofree {
// cgen test or building V
2020-03-22 12:06:33 +01:00
// println('autofree=false')
2020-03-21 19:52:19 +01:00
g.autofree = false
2020-04-05 18:03:36 +02:00
} else {
2020-03-22 12:06:33 +01:00
g.autofree = true
autofree_used = true
}
2020-02-17 22:50:04 +01:00
g.stmts(file.stmts)
2019-12-24 18:54:43 +01:00
}
2020-03-22 12:06:33 +01:00
if autofree_used {
g.autofree = true // so that void _vcleanup is generated
2020-03-22 12:06:33 +01:00
}
2020-03-14 13:15:07 +01:00
g.write_variadic_types()
2020-03-21 11:47:23 +01:00
// g.write_str_definitions()
2020-04-10 18:11:43 +02:00
if g.pref.build_mode != .build_module {
// no init in builtin.o
g.write_init_function()
}
if g.is_test {
g.write_tests_main()
}
2020-04-08 13:53:11 +02:00
//
2020-04-04 22:06:47 +02:00
g.finish()
return g.hashes() +
'\n// V typedefs:\n' + g.typedefs.str() +
'\n// V typedefs2:\n' + g.typedefs2.str() +
'\n// V cheaders:\n' + g.cheaders.str() +
'\n// V includes:\n' + g.includes.str() +
'\n// V definitions:\n' + g.definitions.str() +
'\n// V gowrappers:\n' + g.gowrappers.str() +
'\n// V stringliterals:\n' + g.stringliterals.str() +
'\n// V auto str functions:\n' + g.auto_str_funcs.str() +
'\n// V out\n' + g.out.str() +
'\n// THE END.'
2020-04-02 13:49:59 +02:00
}
2020-04-05 18:03:36 +02:00
pub fn (g Gen) hashes() string {
mut res := c_commit_hash_default.replace('@@@', util.vhash())
2020-04-05 18:03:36 +02:00
res += c_current_commit_hash_default.replace('@@@', util.githash(g.pref.building_v))
2020-04-02 13:49:59 +02:00
return res
}
pub fn (mut g Gen) init() {
g.cheaders.writeln('// Generated by the V compiler')
g.cheaders.writeln('#include <inttypes.h>') // int64_t etc
g.cheaders.writeln(c_builtin_types)
g.cheaders.writeln(c_headers)
2020-03-21 07:10:53 +01:00
g.definitions.writeln('\nstring _STR(const char*, ...);\n')
g.definitions.writeln('\nstring _STR_TMP(const char*, ...);\n')
2020-03-10 23:21:26 +01:00
g.write_builtin_types()
g.write_typedef_types()
2020-03-28 17:37:22 +01:00
g.write_typeof_functions()
2020-04-10 18:11:43 +02:00
if g.pref.build_mode != .build_module {
// _STR functions should not be defined in builtin.o
g.write_str_fn_definitions()
}
2020-03-05 23:27:21 +01:00
g.write_sorted_types()
g.write_multi_return_types()
2020-03-06 12:06:41 +01:00
g.definitions.writeln('// end of definitions #endif')
2020-04-08 13:53:11 +02:00
//
2020-04-04 22:06:47 +02:00
g.stringliterals.writeln('')
g.stringliterals.writeln('// >> string literal consts')
2020-04-10 18:11:43 +02:00
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('void vinit_string_literals(){')
}
2020-04-04 22:06:47 +02:00
}
pub fn (mut g Gen) finish() {
2020-04-10 18:11:43 +02:00
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('}')
}
2020-04-04 22:06:47 +02:00
g.stringliterals.writeln('// << string literal consts')
g.stringliterals.writeln('')
2020-03-05 23:27:21 +01:00
}
pub fn (mut g Gen) write_typeof_functions() {
2020-04-04 22:06:47 +02:00
g.writeln('')
2020-03-28 17:37:22 +01:00
g.writeln('// >> typeof() support for sum types')
for typ in g.table.types {
if typ.kind == .sum_type {
sum_info := typ.info as table.SumType
2020-03-31 06:34:59 +02:00
tidx := g.table.find_type_idx(typ.name)
2020-03-28 17:37:22 +01:00
g.writeln('char * v_typeof_sumtype_${tidx}(int sidx) { /* ${typ.name} */ ')
g.writeln(' switch(sidx) {')
g.writeln(' case $tidx: return "$typ.name";')
for v in sum_info.variants {
subtype := g.table.get_type_symbol(v)
g.writeln(' case $v: return "$subtype.name";')
}
g.writeln(' default: return "unknown ${typ.name}";')
g.writeln(' }')
g.writeln('}')
}
}
g.writeln('// << typeof() support for sum types')
2020-04-04 22:06:47 +02:00
g.writeln('')
2020-03-28 17:37:22 +01:00
}
2020-03-06 13:43:22 +01:00
// V type to C type
pub fn (mut g Gen) typ(t table.Type) string {
2020-03-06 22:36:51 +01:00
nr_muls := table.type_nr_muls(t)
sym := g.table.get_type_symbol(t)
mut styp := sym.name.replace('.', '__')
2020-03-06 22:36:51 +01:00
if nr_muls > 0 {
styp += strings.repeat(`*`, nr_muls)
}
if styp.starts_with('C__') {
styp = styp[3..]
2020-03-31 15:18:25 +02:00
if sym.kind == .struct_ {
2020-04-04 14:32:42 +02:00
info := sym.info as table.Struct
if !info.is_typedef {
styp = 'struct $styp'
}
2020-03-31 15:18:25 +02:00
}
}
if table.type_is(t, .optional) {
2020-04-06 18:46:46 +02:00
// Register an optional
2020-03-13 05:57:51 +01:00
styp = 'Option_' + styp
if table.type_is_ptr(t) {
styp = styp.replace('*', '_ptr')
}
2020-03-15 08:18:42 +01:00
if !(styp in g.optionals) {
2020-04-06 18:46:46 +02:00
// println(styp)
x := styp // .replace('*', '_ptr') // handle option ptrs
g.typedefs2.writeln('typedef Option $x;')
2020-03-15 08:18:42 +01:00
g.optionals << styp
}
2020-03-13 05:57:51 +01:00
}
2020-03-06 22:36:51 +01:00
return styp
}
2020-04-08 13:53:11 +02:00
//
pub fn (mut g Gen) write_typedef_types() {
2020-03-06 13:43:22 +01:00
for typ in g.table.types {
match typ.kind {
.alias {
parent := &g.table.types[typ.parent_idx]
styp := typ.name.replace('.', '__')
parent_styp := parent.name.replace('.', '__')
g.definitions.writeln('typedef $parent_styp $styp;')
}
.array {
styp := typ.name.replace('.', '__')
g.definitions.writeln('typedef array $styp;')
}
.map {
styp := typ.name.replace('.', '__')
g.definitions.writeln('typedef map $styp;')
}
2020-03-16 10:12:03 +01:00
.function {
info := typ.info as table.FnType
func := info.func
if !info.has_decl && !info.is_anon {
2020-04-19 04:44:39 +02:00
fn_name := if func.is_c {
func.name.replace('.', '__')
2020-04-17 21:59:19 +02:00
} else if info.is_anon {
typ.name
2020-04-19 04:44:39 +02:00
} else {
c_name(func.name)
2020-04-17 21:59:19 +02:00
}
2020-03-16 10:12:03 +01:00
g.definitions.write('typedef ${g.typ(func.return_type)} (*$fn_name)(')
for i, arg in func.args {
2020-03-16 10:12:03 +01:00
g.definitions.write(g.typ(arg.typ))
if i < func.args.len - 1 {
g.definitions.write(',')
}
}
g.definitions.writeln(');')
}
}
else {
continue
}
2020-04-05 18:03:36 +02:00
}
2020-03-06 13:43:22 +01:00
}
}
pub fn (mut g Gen) write_multi_return_types() {
g.definitions.writeln('// multi return structs')
for typ in g.table.types {
// sym := g.table.get_type_symbol(typ)
if typ.kind != .multi_return {
continue
}
name := typ.name.replace('.', '__')
info := typ.info as table.MultiReturn
g.definitions.writeln('typedef struct {')
// TODO copy pasta StructDecl
// for field in struct_info.fields {
for i, mr_typ in info.types {
type_name := g.typ(mr_typ)
2020-03-05 00:43:02 +01:00
g.definitions.writeln('\t$type_name arg${i};')
}
g.definitions.writeln('} $name;\n')
// g.typedefs.writeln('typedef struct $name $name;')
}
2019-12-24 18:54:43 +01:00
}
pub fn (mut g Gen) write_variadic_types() {
2020-03-24 09:42:16 +01:00
if g.variadic_args.size > 0 {
2020-03-14 13:15:07 +01:00
g.definitions.writeln('// variadic structs')
}
2020-03-24 09:42:16 +01:00
for type_str, arg_len in g.variadic_args {
2020-03-14 13:15:07 +01:00
typ := table.Type(type_str.int())
type_name := g.typ(typ)
struct_name := 'varg_' + type_name.replace('*', '_ptr')
g.definitions.writeln('struct $struct_name {')
g.definitions.writeln('\tint len;')
g.definitions.writeln('\t$type_name args[$arg_len];')
g.definitions.writeln('};\n')
g.typedefs.writeln('typedef struct $struct_name $struct_name;')
}
}
2020-04-05 18:03:36 +02:00
pub fn (g Gen) save() {
}
2019-12-24 18:54:43 +01:00
pub fn (mut g Gen) write(s string) {
if g.indent > 0 && g.empty_line {
g.out.write(tabs[g.indent])
// g.line_len += g.indent * 4
}
2019-12-24 18:54:43 +01:00
g.out.write(s)
g.empty_line = false
2019-12-24 18:54:43 +01:00
}
pub fn (mut g Gen) writeln(s string) {
if g.indent > 0 && g.empty_line {
g.out.write(tabs[g.indent])
}
2019-12-24 18:54:43 +01:00
g.out.writeln(s)
g.empty_line = true
2019-12-24 18:54:43 +01:00
}
pub fn (mut g Gen) new_tmp_var() string {
g.tmp_count++
return 'tmp$g.tmp_count'
}
pub fn (mut g Gen) reset_tmp_count() {
g.tmp_count = 0
}
fn (mut g Gen) stmts(stmts []ast.Stmt) {
g.indent++
if g.inside_ternary {
g.write(' ( ')
}
for i, stmt in stmts {
2020-02-07 14:49:14 +01:00
g.stmt(stmt)
if g.inside_ternary && i < stmts.len - 1 {
g.write(', ')
}
}
if g.inside_ternary {
g.write(' ) ')
2020-02-07 14:49:14 +01:00
}
g.indent--
2020-02-07 14:49:14 +01:00
}
fn (mut g Gen) stmt(node ast.Stmt) {
2020-03-19 15:18:29 +01:00
g.stmt_start_pos = g.out.len
2020-01-06 16:13:12 +01:00
// println('cgen.stmt()')
// g.writeln('//// stmt start')
2019-12-28 14:11:05 +01:00
match node {
ast.InterfaceDecl {
g.writeln('//interface')
g.writeln('struct $it.name {')
g.writeln('\tvoid* _object;')
g.writeln('\tint _interface_idx;')
g.writeln('};')
}
2020-03-02 18:43:41 +01:00
ast.AssertStmt {
g.gen_assert_stmt(it)
2020-03-26 10:27:46 +01:00
}
ast.AssignStmt {
g.gen_assign_stmt(it)
2020-03-02 18:43:41 +01:00
}
ast.Attr {
2020-04-09 00:35:13 +02:00
if it.name == 'inline' {
g.writeln(it.name)
} else {
g.writeln('//[$it.name]')
}
2020-03-02 18:43:41 +01:00
}
2020-03-25 14:24:48 +01:00
ast.Block {
g.writeln('{')
g.stmts(it.stmts)
g.writeln('}')
}
2020-03-02 18:43:41 +01:00
ast.BranchStmt {
// continue or break
2020-03-05 00:43:02 +01:00
g.write(it.tok.kind.str())
g.writeln(';')
2020-03-02 18:43:41 +01:00
}
ast.ConstDecl {
2020-04-10 18:11:43 +02:00
// if g.pref.build_mode != .build_module {
2020-03-06 14:03:35 +01:00
g.const_decl(it)
2020-04-10 18:11:43 +02:00
// }
}
2020-03-02 18:43:41 +01:00
ast.CompIf {
2020-03-27 14:44:30 +01:00
g.comp_if(it)
2020-03-02 18:43:41 +01:00
}
ast.DeferStmt {
mut defer_stmt := *it
defer_stmt.ifdef = g.defer_ifdef
g.defer_stmts << defer_stmt
}
2020-02-25 11:52:41 +01:00
ast.EnumDecl {
2020-04-09 19:23:49 +02:00
enum_name := it.name.replace('.', '__')
2020-03-31 20:26:15 +02:00
g.typedefs.writeln('typedef enum {')
mut cur_enum_expr := ''
mut cur_enum_offset := 0
2020-04-11 19:06:53 +02:00
for j, field in it.fields {
g.typedefs.write('\t${enum_name}_${field.name}')
2020-04-10 14:44:01 +02:00
if field.has_expr {
2020-04-09 19:23:49 +02:00
g.typedefs.write(' = ')
2020-03-31 19:43:11 +02:00
pos := g.out.len
2020-04-10 14:44:01 +02:00
g.expr(field.expr)
2020-04-09 19:23:49 +02:00
expr_str := g.out.after(pos)
g.out.go_back(expr_str.len)
g.typedefs.write(expr_str)
cur_enum_expr = expr_str
cur_enum_offset = 0
2020-03-31 19:43:11 +02:00
}
cur_value := if cur_enum_offset > 0 {
'${cur_enum_expr}+${cur_enum_offset}'
} else {
cur_enum_expr
}
g.typedefs.writeln(', // ${cur_value}')
cur_enum_offset++
2020-02-25 11:52:41 +01:00
}
g.typedefs.writeln('} ${enum_name};\n')
2020-02-25 11:52:41 +01:00
}
2020-03-02 18:43:41 +01:00
ast.ExprStmt {
g.expr(it.expr)
2020-03-18 19:56:59 +01:00
expr := it.expr
// no ; after an if expression }
2020-03-18 19:56:59 +01:00
match expr {
ast.IfExpr {}
else {
if !g.inside_ternary {
g.writeln(';')
}
}
2020-04-05 18:03:36 +02:00
}
2020-03-02 18:43:41 +01:00
}
2019-12-28 14:11:05 +01:00
ast.FnDecl {
g.fn_decl = it // &it
g.gen_fn_decl(it)
g.writeln('')
2019-12-28 14:11:05 +01:00
}
2020-03-02 18:43:41 +01:00
ast.ForCStmt {
g.write('for (')
2020-04-05 18:15:12 +02:00
if !it.has_init {
g.write('; ')
} else {
g.stmt(it.init)
}
if it.has_cond {
g.expr(it.cond)
}
2020-03-02 18:43:41 +01:00
g.write('; ')
if it.has_inc {
g.expr(it.inc)
}
2020-03-02 18:43:41 +01:00
g.writeln(') {')
g.stmts(it.stmts)
2020-03-02 18:43:41 +01:00
g.writeln('}')
}
ast.ForInStmt {
g.for_in(it)
2020-03-02 18:43:41 +01:00
}
ast.ForStmt {
g.write('while (')
2020-04-05 18:15:12 +02:00
if it.is_inf {
g.write('1')
} else {
g.expr(it.cond)
}
2020-03-07 06:02:32 +01:00
g.writeln(') {')
g.stmts(it.stmts)
2020-03-02 18:43:41 +01:00
g.writeln('}')
}
ast.GlobalDecl {
2020-03-06 22:36:51 +01:00
styp := g.typ(it.typ)
2020-03-06 16:31:40 +01:00
g.definitions.writeln('$styp $it.name; // global')
2020-03-02 18:43:41 +01:00
}
ast.GoStmt {
2020-04-03 15:18:17 +02:00
g.go_stmt(it)
}
ast.GotoLabel {
g.writeln('$it.name:')
}
2020-03-25 17:24:55 +01:00
ast.GotoStmt {
g.writeln('goto $it.name;')
}
2020-03-02 18:43:41 +01:00
ast.HashStmt {
2020-03-05 00:43:02 +01:00
// #include etc
2020-03-15 00:46:08 +01:00
typ := it.val.all_before(' ')
if typ == 'include' {
g.includes.writeln('// added by module `$it.mod`:')
g.includes.writeln('#$it.val')
}
if typ == 'define' {
2020-04-06 14:22:56 +02:00
g.definitions.writeln('#$it.val')
2020-03-15 00:46:08 +01:00
}
2020-03-02 18:43:41 +01:00
}
ast.Import {}
ast.InterfaceDecl {
g.writeln('// interface')
}
ast.Module {}
2019-12-28 14:11:05 +01:00
ast.Return {
if g.defer_stmts.len > 0 {
g.write_defer_stmts()
}
2020-03-13 05:57:51 +01:00
g.return_statement(it)
2019-12-28 14:11:05 +01:00
}
ast.StructDecl {
2020-04-05 23:30:16 +02:00
name := if it.is_c { it.name.replace('.', '__') } else { c_name(it.name) }
2020-03-05 23:27:21 +01:00
// g.writeln('typedef struct {')
// for field in it.fields {
// field_type_sym := g.table.get_type_symbol(field.typ)
// g.writeln('\t$field_type_sym.name $field.name;')
// }
// g.writeln('} $name;')
2020-04-08 01:20:55 +02:00
if it.is_c {
return
}
if it.is_union {
g.typedefs.writeln('typedef union $name $name;')
} else {
g.typedefs.writeln('typedef struct $name $name;')
}
}
ast.TypeDecl {
2020-03-16 03:19:26 +01:00
g.writeln('// TypeDecl')
}
2020-03-02 18:43:41 +01:00
ast.UnsafeStmt {
g.stmts(it.stmts)
}
2019-12-28 14:11:05 +01:00
else {
2020-02-25 11:52:41 +01:00
verror('cgen.stmt(): unhandled node ' + typeof(node))
2019-12-28 14:11:05 +01:00
}
}
}
fn (mut g Gen) write_defer_stmts() {
for defer_stmt in g.defer_stmts {
g.writeln('// defer')
if defer_stmt.ifdef.len > 0 {
g.writeln(defer_stmt.ifdef)
g.stmts(defer_stmt.stmts)
2020-04-11 11:41:48 +02:00
g.writeln('')
g.writeln('#endif')
2020-04-05 18:03:36 +02:00
} else {
g.stmts(defer_stmt.stmts)
}
}
}
fn (mut g Gen) for_in(it ast.ForInStmt) {
if it.is_range {
// `for x in 1..10 {`
i := g.new_tmp_var()
g.write('for (int $i = ')
g.expr(it.cond)
g.write('; $i < ')
g.expr(it.high)
g.writeln('; $i++) {')
g.writeln('\tint $it.val_var = $i;')
g.stmts(it.stmts)
g.writeln('}')
2020-04-05 18:03:36 +02:00
} else if it.kind == .array {
// `for num in nums {`
g.writeln('// FOR IN array')
styp := g.typ(it.val_type)
2020-04-04 14:08:38 +02:00
cond_type_is_ptr := table.type_is_ptr(it.cond_type)
atmp := g.new_tmp_var()
atmp_type := if cond_type_is_ptr { 'array *' } else { 'array' }
g.write('${atmp_type} ${atmp} = ')
g.expr(it.cond)
g.writeln(';')
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
2020-04-05 18:15:12 +02:00
if cond_type_is_ptr {
g.writeln('for (int $i = 0; $i < ${atmp}->len; $i++) {')
2020-04-14 19:32:23 +02:00
} else {
g.writeln('for (int $i = 0; $i < ${atmp}.len; $i++) {')
2020-04-05 18:15:12 +02:00
}
if cond_type_is_ptr {
g.writeln('\t$styp $it.val_var = (($styp*)${atmp}->data)[$i];')
2020-04-14 19:32:23 +02:00
} else {
g.writeln('\t$styp $it.val_var = (($styp*)${atmp}.data)[$i];')
2020-04-05 18:15:12 +02:00
}
g.stmts(it.stmts)
g.writeln('}')
2020-04-05 18:03:36 +02:00
} else if it.kind == .map {
2020-04-11 19:06:53 +02:00
// `for key, val in map {`
g.writeln('// FOR IN map')
key_styp := g.typ(it.key_type)
val_styp := g.typ(it.val_type)
keys_tmp := 'keys_' + g.new_tmp_var()
idx := g.new_tmp_var()
2020-04-05 23:30:16 +02:00
key := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
zero := g.type_default(it.val_type)
g.write('array_$key_styp $keys_tmp = map_keys(&')
g.expr(it.cond)
g.writeln(');')
g.writeln('for (int $idx = 0; $idx < ${keys_tmp}.len; $idx++) {')
g.writeln('\t$key_styp $key = (($key_styp*)${keys_tmp}.data)[$idx];')
g.write('\t$val_styp $it.val_var = (*($val_styp*)map_get3(')
g.expr(it.cond)
g.writeln(', $key, &($val_styp[]){ $zero }));')
g.stmts(it.stmts)
g.writeln('}')
2020-04-05 18:03:36 +02:00
} else if table.type_is(it.cond_type, .variadic) {
g.writeln('// FOR IN cond_type/variadic')
2020-04-05 23:30:16 +02:00
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
styp := g.typ(it.cond_type)
g.write('for (int $i = 0; $i < ')
g.expr(it.cond)
g.writeln('.len; $i++) {')
g.write('$styp $it.val_var = ')
g.expr(it.cond)
g.writeln('.args[$i];')
g.stmts(it.stmts)
g.writeln('}')
2020-04-05 18:03:36 +02:00
} else if it.kind == .string {
2020-04-05 23:30:16 +02:00
i := if it.key_var == '' { g.new_tmp_var() } else { it.key_var }
g.write('for (int $i = 0; $i < ')
g.expr(it.cond)
g.writeln('.len; $i++) {')
g.write('byte $it.val_var = ')
g.expr(it.cond)
g.writeln('.str[$i];')
g.stmts(it.stmts)
g.writeln('}')
}
}
2020-03-17 15:13:55 +01:00
// use instead of expr() when you need to cast to sum type (can add other casts also)
fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type, exp_type table.Type) {
2020-03-17 15:13:55 +01:00
// cast to sum type
2020-03-24 12:55:41 +01:00
if exp_type != table.void_type {
2020-03-16 07:42:45 +01:00
exp_sym := g.table.get_type_symbol(exp_type)
if exp_sym.kind == .sum_type {
sum_info := exp_sym.info as table.SumType
if got_type in sum_info.variants {
got_sym := g.table.get_type_symbol(got_type)
2020-03-17 15:13:55 +01:00
got_styp := g.typ(got_type)
exp_styp := g.typ(exp_type)
got_idx := table.type_idx(got_type)
2020-03-17 16:40:41 +01:00
g.write('/* sum type cast */ ($exp_styp) {.obj = memdup(&(${got_styp}[]) {')
2020-03-17 15:13:55 +01:00
g.expr(expr)
g.write('}, sizeof($got_styp)), .typ = $got_idx /* $got_sym.name */}')
2020-03-18 10:42:56 +01:00
return
2020-03-16 07:42:45 +01:00
}
}
}
2020-03-17 15:13:55 +01:00
// no cast
2020-03-16 07:42:45 +01:00
g.expr(expr)
}
fn (mut g Gen) gen_assert_stmt(a ast.AssertStmt) {
g.writeln('// assert')
2020-04-13 01:53:26 +02:00
g.inside_ternary = true
g.write('if (')
g.expr(a.expr)
2020-04-13 01:53:26 +02:00
g.write(')')
g.inside_ternary = false
2020-04-05 16:08:16 +02:00
s_assertion := a.expr.str().replace('"', "\'")
mut mod_path := g.file.path
2020-04-05 16:08:16 +02:00
$if windows {
mod_path = g.file.path.replace('\\', '\\\\')
}
if g.is_test {
g.writeln('{')
g.writeln(' g_test_oks++;')
g.writeln(' cb_assertion_ok( tos3("${mod_path}"), ${a.pos.line_nr+1}, tos3("assert ${s_assertion}"), tos3("${g.fn_decl.name}()") );')
g.writeln('}else{')
g.writeln(' g_test_fails++;')
g.writeln(' cb_assertion_failed( tos3("${mod_path}"), ${a.pos.line_nr+1}, tos3("assert ${s_assertion}"), tos3("${g.fn_decl.name}()") );')
g.writeln(' exit(1);')
2020-03-30 17:21:32 +02:00
g.writeln(' // TODO')
g.writeln(' // Maybe print all vars in a test function if it fails?')
g.writeln('}')
2020-03-30 17:21:32 +02:00
return
}
2020-03-30 17:21:32 +02:00
g.writeln('{}else{')
g.writeln(' eprintln( tos3("${mod_path}:${a.pos.line_nr+1}: FAIL: fn ${g.fn_decl.name}(): assert $s_assertion"));')
2020-03-30 17:21:32 +02:00
g.writeln(' exit(1);')
g.writeln('}')
}
fn (mut g Gen) gen_assign_stmt(assign_stmt ast.AssignStmt) {
2020-03-22 13:19:45 +01:00
// g.write('/*assign_stmt*/')
2020-04-01 13:38:05 +02:00
if assign_stmt.is_static {
g.write('static ')
}
if assign_stmt.left.len > assign_stmt.right.len {
2020-03-26 14:58:11 +01:00
// multi return
mut or_stmts := []ast.Stmt
mut return_type := table.void_type
match assign_stmt.right[0] {
ast.CallExpr {
2020-03-31 06:34:59 +02:00
or_stmts = it.or_block.stmts
return_type = it.return_type
}
2020-03-31 06:34:59 +02:00
else {}
2020-04-05 18:03:36 +02:00
}
is_optional := table.type_is(return_type, .optional)
mr_var_name := 'mr_$assign_stmt.pos.pos'
2020-03-31 06:34:59 +02:00
mr_styp := g.typ(return_type)
g.write('$mr_styp $mr_var_name = ')
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = true
2020-03-31 06:34:59 +02:00
g.expr(assign_stmt.right[0])
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = false
2020-03-31 06:34:59 +02:00
if is_optional {
g.or_block(mr_var_name, or_stmts, return_type)
2020-03-20 04:59:06 +01:00
}
g.writeln(';')
for i, ident in assign_stmt.left {
if ident.kind == .blank_ident {
continue
}
ident_var_info := ident.var_info()
styp := g.typ(ident_var_info.typ)
if assign_stmt.op == .decl_assign {
g.write('$styp ')
}
g.expr(ident)
2020-03-31 06:34:59 +02:00
if is_optional {
mr_styp2 := mr_styp[7..] // remove Option_
2020-03-31 06:34:59 +02:00
g.writeln(' = (*(${mr_styp2}*)${mr_var_name}.data).arg$i;')
2020-04-05 18:03:36 +02:00
} else {
2020-03-31 06:34:59 +02:00
g.writeln(' = ${mr_var_name}.arg$i;')
}
}
2020-04-05 18:03:36 +02:00
} else {
2020-04-05 02:08:10 +02:00
// `a := 1` | `a,b := 1,2`
for i, ident in assign_stmt.left {
val := assign_stmt.right[i]
ident_var_info := ident.var_info()
2020-03-10 23:21:26 +01:00
styp := g.typ(ident_var_info.typ)
mut is_call := false
mut or_stmts := []ast.Stmt
mut return_type := table.void_type
2020-03-31 06:34:59 +02:00
match val {
ast.CallExpr {
is_call = true
or_stmts = it.or_block.stmts
return_type = it.return_type
}
ast.AnonFn {
// TODO: no buffer fiddling
ret_styp := g.typ(it.decl.return_type)
g.write('$ret_styp (*$ident.name) (')
def_pos := g.definitions.len
g.fn_args(it.decl.args, it.decl.is_variadic)
g.definitions.go_back(g.definitions.len - def_pos)
g.write(') = ')
g.expr(*it)
g.writeln(';')
continue
}
2020-03-31 06:34:59 +02:00
else {}
2020-04-05 18:03:36 +02:00
}
gen_or := is_call && table.type_is(return_type, .optional)
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = true
if ident.kind == .blank_ident {
2020-03-31 06:34:59 +02:00
if is_call {
2020-03-10 23:21:26 +01:00
g.expr(val)
2020-04-05 18:03:36 +02:00
} else {
2020-03-10 23:21:26 +01:00
g.write('{$styp _ = ')
g.expr(val)
g.writeln(';}')
}
2020-04-05 18:03:36 +02:00
} else {
2020-03-22 13:19:45 +01:00
right_sym := g.table.get_type_symbol(assign_stmt.right_types[i])
mut is_fixed_array_init := false
2020-03-12 10:07:42 +01:00
match val {
ast.ArrayInit { is_fixed_array_init = it.is_fixed }
2020-03-12 10:07:42 +01:00
else {}
2020-04-05 18:03:36 +02:00
}
2020-03-17 15:13:55 +01:00
is_decl := assign_stmt.op == .decl_assign
2020-04-05 18:03:36 +02:00
// g.write('/*assign_stmt*/')
2020-03-17 15:13:55 +01:00
if is_decl {
g.write('$styp ')
}
g.expr(ident)
if g.autofree && right_sym.kind in [.array, .string] {
if g.gen_clone_assignment(val, right_sym, true) {
g.writeln(';')
// g.expr_var_name = ''
return
}
2020-03-22 13:40:53 +01:00
}
if is_fixed_array_init {
g.write('= {0}')
} else {
2020-03-12 10:07:42 +01:00
g.write(' = ')
2020-04-05 18:15:12 +02:00
if !is_decl {
g.expr_with_cast(val, assign_stmt.left_types[i], ident_var_info.typ)
} else {
g.expr(val)
}
}
2020-03-31 06:34:59 +02:00
if gen_or {
g.or_block(ident.name, or_stmts, return_type)
}
}
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = false
g.writeln(';')
}
}
}
fn (mut g Gen) gen_clone_assignment(val ast.Expr, right_sym table.TypeSymbol, add_eq bool) bool {
mut is_ident := false
match val {
ast.Ident { is_ident = true }
ast.SelectorExpr { is_ident = true }
else { return false }
}
if g.autofree && right_sym.kind == .array && is_ident {
// `arr1 = arr2` => `arr1 = arr2.clone()`
if add_eq {
g.write('=')
}
g.write(' array_clone(&')
g.expr(val)
g.write(')')
2020-04-05 18:03:36 +02:00
} else if g.autofree && right_sym.kind == .string && is_ident {
if add_eq {
g.write('=')
}
// `str1 = str2` => `str1 = str2.clone()`
g.write(' string_clone(')
g.expr(val)
g.write(')')
}
return true
}
fn (mut g Gen) free_scope_vars(pos int) {
2020-03-25 10:26:54 +01:00
scope := g.file.scope.innermost(pos)
for _, obj in scope.objects {
match obj {
ast.Var {
// println('//////')
// println(var.name)
// println(var.typ)
// if var.typ == 0 {
// // TODO why 0?
// continue
// }
2020-04-15 01:45:27 +02:00
v := *it
sym := g.table.get_type_symbol(v.typ)
is_optional := table.type_is(v.typ, .optional)
if sym.kind == .array && !is_optional {
2020-04-15 01:45:27 +02:00
g.writeln('array_free($v.name); // autofreed')
2020-03-25 10:26:54 +01:00
}
if sym.kind == .string && !is_optional {
// Don't free simple string literals.
2020-04-15 01:45:27 +02:00
t := typeof(v.expr)
match v.expr {
ast.StringLiteral {
g.writeln('// str literal')
continue
}
else {
// NOTE/TODO: assign_stmt multi returns variables have no expr
// since the type comes from the called fns return type
g.writeln('// other ' + t)
continue
}
}
2020-04-15 01:45:27 +02:00
g.writeln('string_free($v.name); // autofreed')
2020-03-25 10:26:54 +01:00
}
}
else {}
2020-03-25 10:26:54 +01:00
}
}
}
fn (mut g Gen) expr(node ast.Expr) {
// println('cgen expr() line_nr=$node.pos.line_nr')
2019-12-24 18:54:43 +01:00
match node {
2020-02-17 22:50:04 +01:00
ast.ArrayInit {
type_sym := g.table.get_type_symbol(it.typ)
2020-03-12 09:29:52 +01:00
if type_sym.kind != .array_fixed {
2020-04-22 01:52:56 +02:00
// elem_sym := g.table.get_type_symbol(it.elem_type)
2020-03-15 07:42:45 +01:00
elem_type_str := g.typ(it.elem_type)
2020-03-21 19:52:19 +01:00
if it.exprs.len == 0 {
2020-04-15 20:12:06 +02:00
// use __new_array to fix conflicts when the name of the variable is new_array
g.write('__new_array($it.exprs.len, $it.exprs.len, sizeof($elem_type_str))')
2020-04-05 18:03:36 +02:00
} else {
len := it.exprs.len
g.write('new_array_from_c_array($len, $len, sizeof($elem_type_str), ')
g.write('($elem_type_str[$len]){\n\t\t')
2020-03-21 19:52:19 +01:00
for expr in it.exprs {
g.expr(expr)
g.write(', ')
}
g.write('\n})')
2020-03-12 09:29:52 +01:00
}
2020-04-05 18:03:36 +02:00
} else {
2020-02-17 22:50:04 +01:00
}
}
ast.AsCast {
2020-03-18 13:55:46 +01:00
styp := g.typ(it.typ)
expr_type_sym := g.table.get_type_symbol(it.expr_type)
if expr_type_sym.kind == .sum_type {
g.write('/* as */ *($styp*)')
g.expr(it.expr)
g.write('.obj')
}
}
2020-01-06 16:13:12 +01:00
ast.AssignExpr {
2020-03-31 06:34:59 +02:00
g.assign_expr(it)
2020-01-06 16:13:12 +01:00
}
ast.Assoc {
2020-03-19 07:59:01 +01:00
g.assoc(it)
}
2020-02-17 22:50:04 +01:00
ast.BoolLiteral {
g.write(it.val.str())
}
2019-12-29 07:24:17 +01:00
ast.CallExpr {
2020-03-21 19:52:19 +01:00
g.call_expr(it)
}
ast.CastExpr {
2020-03-10 23:21:26 +01:00
// g.write('/*cast*/')
if g.is_amp {
// &Foo(0) => ((Foo*)0)
g.out.go_back(1)
}
sym := g.table.get_type_symbol(it.typ)
2020-04-07 18:51:39 +02:00
if sym.kind == .string && !table.type_is_ptr(it.typ) {
// `string(x)` needs `tos()`, but not `&string(x)
// `tos(str, len)`, `tos2(str)`
2020-04-05 18:15:12 +02:00
if it.has_arg {
g.write('tos(')
} else {
g.write('tos2(')
}
2020-03-07 16:23:10 +01:00
g.expr(it.expr)
expr_sym := g.table.get_type_symbol(it.expr_type)
if expr_sym.kind == .array {
// if we are casting an array, we need to add `.data`
g.write('.data')
}
2020-03-07 16:23:10 +01:00
if it.has_arg {
// len argument
g.write(', ')
2020-03-07 16:23:10 +01:00
g.expr(it.arg)
}
g.write(')')
2020-04-05 18:03:36 +02:00
} else if sym.kind == .sum_type {
g.expr_with_cast(it.expr, it.expr_type, it.typ)
2020-04-05 18:03:36 +02:00
} else {
// styp := g.table.Type_to_str(it.typ)
2020-03-10 23:21:26 +01:00
styp := g.typ(it.typ)
// g.write('($styp)(')
g.write('(($styp)(')
// if g.is_amp {
// g.write('*')
// }
// g.write(')(')
2020-03-07 16:23:10 +01:00
g.expr(it.expr)
2020-03-10 23:21:26 +01:00
g.write('))')
2020-03-07 16:23:10 +01:00
}
2019-12-29 07:24:17 +01:00
}
ast.CharLiteral {
g.write("'$it.val'")
}
ast.EnumVal {
// g.write('${it.mod}${it.enum_name}_$it.val')
styp := g.typ(it.typ)
g.write('${styp}_$it.val')
}
ast.FloatLiteral {
g.write(it.val)
}
2019-12-28 14:11:05 +01:00
ast.Ident {
2020-03-13 05:57:51 +01:00
g.ident(it)
2019-12-24 18:54:43 +01:00
}
ast.IfExpr {
2020-03-17 16:40:41 +01:00
g.if_expr(it)
}
ast.IfGuardExpr {
g.write('/* guard */')
}
ast.IndexExpr {
g.index_expr(it)
}
ast.InfixExpr {
2020-03-07 16:39:15 +01:00
g.infix_expr(it)
}
ast.IntegerLiteral {
2020-03-26 17:14:24 +01:00
if it.val.starts_with('0o') {
g.write('0')
g.write(it.val[2..])
2020-04-05 18:03:36 +02:00
} else {
g.write(it.val) // .int().str())
2020-03-26 17:14:24 +01:00
}
}
2020-02-07 14:49:14 +01:00
ast.MatchExpr {
2020-03-16 03:56:38 +01:00
g.match_expr(it)
2020-02-07 14:49:14 +01:00
}
2020-03-07 08:13:00 +01:00
ast.MapInit {
2020-04-11 16:24:21 +02:00
key_typ_str := g.typ(it.key_type)
value_typ_str := g.typ(it.value_type)
2020-03-07 08:13:00 +01:00
size := it.vals.len
2020-03-07 14:31:40 +01:00
if size > 0 {
2020-03-17 15:13:55 +01:00
g.write('new_map_init($size, sizeof($value_typ_str), (${key_typ_str}[$size]){')
2020-03-07 08:13:00 +01:00
for expr in it.keys {
g.expr(expr)
g.write(', ')
}
2020-03-17 15:13:55 +01:00
g.write('}, (${value_typ_str}[$size]){')
2020-03-07 08:13:00 +01:00
for expr in it.vals {
g.expr(expr)
g.write(', ')
}
g.write('})')
2020-04-05 18:03:36 +02:00
} else {
g.write('new_map_1(sizeof($value_typ_str))')
2020-03-07 08:13:00 +01:00
}
}
ast.None {
2020-03-13 05:57:51 +01:00
g.write('opt_none()')
}
ast.ParExpr {
g.write('(')
g.expr(it.expr)
g.write(')')
}
ast.PostfixExpr {
g.expr(it.expr)
g.write(it.op.str())
}
ast.PrefixExpr {
2020-03-10 23:21:26 +01:00
if it.op == .amp {
g.is_amp = true
}
2020-03-06 20:25:38 +01:00
// g.write('/*pref*/')
2020-03-10 23:21:26 +01:00
g.write(it.op.str())
// g.write('(')
g.expr(it.right)
// g.write(')')
2020-03-10 23:21:26 +01:00
g.is_amp = false
}
ast.SizeOf {
if it.type_name != '' {
g.write('sizeof($it.type_name)')
} else {
styp := g.typ(it.typ)
2020-04-11 16:24:21 +02:00
g.write('sizeof(/*typ*/$styp)')
}
}
ast.StringLiteral {
2020-04-02 10:15:35 +02:00
if it.is_raw {
2020-04-05 18:03:36 +02:00
escaped_val := it.val.replace_each(['"', '\\"', '\\', '\\\\'])
2020-04-02 10:15:35 +02:00
g.write('tos3("$escaped_val")')
return
}
2020-04-07 18:51:39 +02:00
escaped_val := it.val.replace_each(['"', '\\"', '\r\n', '\\n', '\n', '\\n'])
2020-04-01 17:14:17 +02:00
if g.is_c_call || it.is_c {
2020-03-21 07:10:53 +01:00
// In C calls we have to generate C strings
// `C.printf("hi")` => `printf("hi");`
g.write('"$escaped_val"')
2020-04-05 18:03:36 +02:00
} else {
g.write('tos3("$escaped_val")')
}
}
2020-03-21 07:01:06 +01:00
ast.StringInterLiteral {
g.string_inter_literal(it)
}
ast.StructInit {
2020-04-05 02:08:10 +02:00
// `user := User{name: 'Bob'}`
g.struct_init(it)
}
ast.SelectorExpr {
g.expr(it.expr)
2020-03-08 19:38:27 +01:00
// if table.type_nr_muls(it.expr_type) > 0 {
if table.type_is_ptr(it.expr_type) {
2020-03-07 04:45:35 +01:00
g.write('->')
2020-04-05 18:03:36 +02:00
} else {
2020-03-11 05:25:11 +01:00
// g.write('. /*typ= $it.expr_type */') // ${g.typ(it.expr_type)} /')
2020-03-07 04:45:35 +01:00
g.write('.')
}
2020-03-11 05:25:11 +01:00
if it.expr_type == 0 {
verror('cgen: SelectorExpr typ=0 field=$it.field')
}
g.write(c_name(it.field))
}
ast.Type {
2020-03-16 03:19:26 +01:00
// match sum Type
// g.write('/* Type */')
type_idx := table.type_idx(it.typ)
sym := g.table.get_type_symbol(it.typ)
g.write('$type_idx /* $sym.name */')
}
2020-03-19 12:15:39 +01:00
ast.TypeOf {
2020-03-28 17:37:22 +01:00
g.typeof_expr(it)
2020-03-19 12:15:39 +01:00
}
2020-04-17 21:59:19 +02:00
ast.AnonFn {
// TODO: dont fiddle with buffers
2020-04-17 21:59:19 +02:00
pos := g.out.len
def_pos := g.definitions.len
g.stmt(it.decl)
2020-04-17 21:59:19 +02:00
fn_body := g.out.after(pos)
g.out.go_back(fn_body.len)
g.definitions.go_back(g.definitions.len - def_pos)
2020-04-17 21:59:19 +02:00
g.definitions.write(fn_body)
fsym := g.table.get_type_symbol(it.typ)
g.write('&${fsym.name}')
2020-04-17 21:59:19 +02:00
}
2019-12-24 18:54:43 +01:00
else {
// #printf("node=%d\n", node.typ);
println(term.red('cgen.expr(): bad node ' + typeof(node)))
2019-12-24 18:54:43 +01:00
}
}
}
fn (mut g Gen) typeof_expr(node ast.TypeOf) {
2020-03-28 17:37:22 +01:00
sym := g.table.get_type_symbol(node.expr_type)
if sym.kind == .sum_type {
// When encountering a .sum_type, typeof() should be done at runtime,
// because the subtype of the expression may change:
2020-03-31 06:34:59 +02:00
sum_type_idx := table.type_idx(node.expr_type)
2020-03-28 17:37:22 +01:00
g.write('tos3( /* ${sym.name} */ v_typeof_sumtype_${sum_type_idx}( (')
g.expr(node.expr)
g.write(').typ ))')
2020-04-05 18:03:36 +02:00
} else if sym.kind == .array_fixed {
fixed_info := sym.info as table.ArrayFixed
2020-04-16 21:04:27 +02:00
typ_name := g.table.get_type_name(fixed_info.elem_type)
g.write('tos3("[$fixed_info.size]${typ_name}")')
} else if sym.kind == .function {
info := sym.info as table.FnType
fn_info := info.func
mut repr := 'fn ('
2020-04-16 21:04:27 +02:00
for i, arg in fn_info.args {
if i > 0 {
repr += ', '
}
repr += g.table.get_type_name(arg.typ)
}
repr += ')'
if fn_info.return_type != table.void_type {
repr += ' ${g.table.get_type_name(fn_info.return_type)}'
}
g.write('tos3("$repr")')
2020-04-05 18:03:36 +02:00
} else {
2020-03-28 17:37:22 +01:00
g.write('tos3("${sym.name}")')
}
}
fn (mut g Gen) enum_expr(node ast.Expr) {
match node {
ast.EnumVal { g.write(it.val) }
else { g.expr(node) }
}
}
fn (mut g Gen) assign_expr(node ast.AssignExpr) {
2020-03-31 06:34:59 +02:00
// g.write('/*assign_expr*/')
mut is_call := false
mut or_stmts := []ast.Stmt
mut return_type := table.void_type
2020-03-31 06:34:59 +02:00
match node.val {
ast.CallExpr {
is_call = true
or_stmts = it.or_block.stmts
return_type = it.return_type
}
else {}
}
gen_or := is_call && table.type_is(return_type, .optional)
2020-04-05 23:30:16 +02:00
tmp_opt := if gen_or { g.new_tmp_var() } else { '' }
2020-03-31 06:34:59 +02:00
if gen_or {
rstyp := g.typ(return_type)
g.write('$rstyp $tmp_opt =')
}
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = true
2020-03-31 06:34:59 +02:00
if ast.expr_is_blank_ident(node.left) {
if is_call {
g.expr(node.val)
2020-04-05 18:03:36 +02:00
} else {
2020-04-08 00:46:16 +02:00
// g.write('{${g.typ(node.left_type)} _ = ')
g.write('{')
2020-03-31 06:34:59 +02:00
g.expr(node.val)
g.writeln(';}')
}
2020-04-05 18:03:36 +02:00
} else {
2020-03-31 10:11:47 +02:00
g.is_assign_lhs = true
if table.type_is(node.right_type, .optional) {
2020-03-31 06:34:59 +02:00
g.right_is_opt = true
}
mut str_add := false
2020-03-31 06:34:59 +02:00
if node.left_type == table.string_type_idx && node.op == .plus_assign {
// str += str2 => `str = string_add(str, str2)`
g.expr(node.left)
g.write(' = string_add(')
str_add = true
}
g.assign_op = node.op
g.expr(node.left)
// arr[i] = val => `array_set(arr, i, val)`, not `array_get(arr, i) = val`
if !g.is_array_set && !str_add {
g.write(' $node.op.str() ')
2020-04-05 18:03:36 +02:00
} else if str_add {
2020-03-31 06:34:59 +02:00
g.write(', ')
}
2020-03-31 10:11:47 +02:00
g.is_assign_lhs = false
right_sym := g.table.get_type_symbol(node.right_type)
// left_sym := g.table.get_type_symbol(node.left_type)
mut cloned := false
// !g.is_array_set
if g.autofree && right_sym.kind in [.array, .string] {
if g.gen_clone_assignment(node.val, right_sym, false) {
cloned = true
}
}
if !cloned {
g.expr_with_cast(node.val, node.right_type, node.left_type)
}
2020-03-31 06:34:59 +02:00
if g.is_array_set {
g.write(' })')
g.is_array_set = false
2020-04-05 18:03:36 +02:00
} else if str_add {
2020-03-31 06:34:59 +02:00
g.write(')')
}
g.right_is_opt = false
}
if gen_or {
g.or_block(tmp_opt, or_stmts, return_type)
}
2020-03-31 10:11:47 +02:00
g.is_assign_rhs = false
2020-03-31 06:34:59 +02:00
}
fn (mut g Gen) infix_expr(node ast.InfixExpr) {
// println('infix_expr() op="$node.op.str()" line_nr=$node.pos.line_nr')
// g.write('/*infix*/')
2020-03-07 16:39:15 +01:00
// if it.left_type == table.string_type_idx {
2020-03-12 10:07:42 +01:00
// g.write('/*$node.left_type str*/')
2020-03-07 16:39:15 +01:00
// }
// string + string, string == string etc
// g.infix_op = node.op
2020-04-09 03:55:37 +02:00
left_sym := g.table.get_type_symbol(node.left_type)
2020-04-16 15:32:11 +02:00
if node.op == .key_is {
g.is_expr(node)
return
}
2020-04-09 03:55:37 +02:00
right_sym := g.table.get_type_symbol(node.right_type)
if node.left_type == table.ustring_type_idx && node.op != .key_in && node.op != .not_in {
fn_name := match node.op {
.plus { 'ustring_add(' }
.eq { 'ustring_eq(' }
.ne { 'ustring_ne(' }
.lt { 'ustring_lt(' }
.le { 'ustring_le(' }
.gt { 'ustring_gt(' }
.ge { 'ustring_ge(' }
else { '/*node error*/' }
}
g.write(fn_name)
g.expr(node.left)
g.write(', ')
g.expr(node.right)
g.write(')')
} else if node.left_type == table.string_type_idx && node.op != .key_in && node.op != .not_in {
2020-03-12 10:07:42 +01:00
fn_name := match node.op {
.plus { 'string_add(' }
.eq { 'string_eq(' }
.ne { 'string_ne(' }
.lt { 'string_lt(' }
.le { 'string_le(' }
.gt { 'string_gt(' }
.ge { 'string_ge(' }
else { '/*node error*/' }
2020-04-05 18:03:36 +02:00
}
2020-03-07 16:39:15 +01:00
g.write(fn_name)
2020-03-12 10:07:42 +01:00
g.expr(node.left)
2020-03-07 16:39:15 +01:00
g.write(', ')
2020-03-12 10:07:42 +01:00
g.expr(node.right)
2020-03-07 16:39:15 +01:00
g.write(')')
2020-04-09 03:55:37 +02:00
} else if node.op in [.eq, .ne] && left_sym.kind == .array && right_sym.kind == .array {
styp := g.table.value_type(node.left_type)
ptr_typ := g.typ(node.left_type).split('_')[1]
if !(ptr_typ in g.array_fn_definitions) {
sym := g.table.get_type_symbol(left_sym.array_info().elem_type)
g.generate_array_equality_fn(ptr_typ, styp, sym)
}
if node.op == .eq {
g.write('${ptr_typ}_arr_eq(')
} else if node.op == .ne {
g.write('!${ptr_typ}_arr_eq(')
}
g.expr(node.left)
g.write(', ')
g.expr(node.right)
g.write(')')
2020-04-11 21:31:54 +02:00
} else if node.op in [.key_in, .not_in] {
if node.op == .not_in {
g.write('!')
}
if right_sym.kind == .array {
2020-03-19 16:12:46 +01:00
match node.right {
ast.ArrayInit {
// `a in [1,2,3]` optimization => `a == 1 || a == 2 || a == 3`
// avoids an allocation
// g.write('/*in opt*/')
g.write('(')
2020-03-19 16:12:46 +01:00
g.in_optimization(node.left, it)
g.write(')')
2020-03-19 16:12:46 +01:00
return
}
else {}
2020-04-05 18:03:36 +02:00
}
styp := g.typ(node.left_type)
g.write('_IN($styp, ')
g.expr(node.left)
g.write(', ')
g.expr(node.right)
g.write(')')
2020-04-05 18:03:36 +02:00
} else if right_sym.kind == .map {
g.write('_IN_MAP(')
g.expr(node.left)
g.write(', ')
g.expr(node.right)
g.write(')')
2020-04-05 18:03:36 +02:00
} else if right_sym.kind == .string {
g.write('string_contains(')
g.expr(node.right)
g.write(', ')
g.expr(node.left)
g.write(')')
}
2020-04-07 18:51:39 +02:00
} else if node.op == .left_shift && g.table.get_type_symbol(node.left_type).kind == .array {
2020-04-05 02:08:10 +02:00
// arr << val
2020-03-10 23:21:26 +01:00
tmp := g.new_tmp_var()
2020-03-15 00:46:08 +01:00
sym := g.table.get_type_symbol(node.left_type)
info := sym.info as table.Array
if right_sym.kind == .array && info.elem_type != node.right_type {
// push an array => PUSH_MANY, but not if pushing an array to 2d array (`[][]int << []int`)
2020-03-15 00:46:08 +01:00
g.write('_PUSH_MANY(&')
g.expr(node.left)
2020-03-15 00:46:08 +01:00
g.write(', (')
g.expr_with_cast(node.right, node.right_type, node.left_type)
2020-03-15 00:46:08 +01:00
styp := g.typ(node.left_type)
g.write('), $tmp, $styp)')
2020-04-05 18:03:36 +02:00
} else {
2020-03-15 00:46:08 +01:00
// push a single element
elem_type_str := g.typ(info.elem_type)
g.write('array_push(&')
g.expr(node.left)
g.write(', &($elem_type_str[]){ ')
g.expr_with_cast(node.right, node.right_type, info.elem_type)
g.write(' })')
2020-03-15 00:46:08 +01:00
}
2020-04-08 13:53:11 +02:00
} else if (node.left_type == node.right_type) && node.left_type in [table.f32_type_idx,
table.f64_type_idx
] && node.op in [.eq, .ne] {
// floats should be compared with epsilon
if node.left_type == table.f64_type_idx {
if node.op == .eq {
g.write('f64_eq(')
} else {
g.write('f64_ne(')
}
2020-04-08 13:53:11 +02:00
} else {
if node.op == .eq {
g.write('f32_eq(')
} else {
g.write('f32_ne(')
}
}
g.expr(node.left)
g.write(',')
g.expr(node.right)
g.write(')')
2020-04-10 18:11:43 +02:00
} else if node.op in [.plus, .minus, .mul, .div, .mod] && (left_sym.name[0].is_capital() ||
left_sym.name.contains('.')) && left_sym.kind != .alias {
2020-04-08 22:34:14 +02:00
// !left_sym.is_number() {
2020-04-08 22:12:42 +02:00
g.write(g.typ(node.left_type))
g.write('_')
g.write(util.replace_op(node.op.str()))
g.write('(')
g.expr(node.left)
g.write(', ')
g.expr(node.right)
g.write(')')
2020-04-05 18:03:36 +02:00
} else {
need_par := node.op in [.amp, .pipe, .xor] // `x & y == 0` => `(x & y) == 0` in C
2020-03-26 10:44:59 +01:00
if need_par {
g.write('(')
}
2020-03-12 10:07:42 +01:00
g.expr(node.left)
g.write(' $node.op.str() ')
g.expr(node.right)
2020-03-26 10:44:59 +01:00
if need_par {
g.write(')')
}
2020-03-07 16:39:15 +01:00
}
}
fn (mut g Gen) match_expr(node ast.MatchExpr) {
2020-03-16 03:56:38 +01:00
// println('match expr typ=$it.expr_type')
// TODO
2020-03-18 12:23:32 +01:00
if node.cond_type == 0 {
2020-03-16 03:56:38 +01:00
g.writeln('// match 0')
return
}
2020-04-13 01:53:26 +02:00
was_inside_ternary := g.inside_ternary
is_expr := (node.is_expr && node.return_type != table.void_type) || was_inside_ternary
if is_expr {
g.inside_ternary = true
2020-03-18 12:34:27 +01:00
// g.write('/* EM ret type=${g.typ(node.return_type)} expected_type=${g.typ(node.expected_type)} */')
}
2020-03-18 12:23:32 +01:00
type_sym := g.table.get_type_symbol(node.cond_type)
mut tmp := ''
2020-03-16 03:56:38 +01:00
if type_sym.kind != .void {
tmp = g.new_tmp_var()
}
// styp := g.typ(node.expr_type)
// g.write('$styp $tmp = ')
// g.expr(node.cond)
// g.writeln(';') // $it.blocks.len')
2020-03-16 03:56:38 +01:00
// mut sum_type_str = ''
for j, branch in node.branches {
2020-04-14 01:03:31 +02:00
is_last := j == node.branches.len - 1
if branch.is_else || node.is_expr && is_last {
2020-04-13 01:53:26 +02:00
if node.branches.len > 1 {
if is_expr {
// TODO too many branches. maybe separate ?: matches
g.write(' : ')
} else {
g.writeln('else {')
}
}
2020-04-05 18:03:36 +02:00
} else {
2020-03-16 03:56:38 +01:00
if j > 0 {
2020-04-05 18:15:12 +02:00
if is_expr {
g.write(' : ')
} else {
g.write('else ')
}
}
if is_expr {
g.write('(')
} else {
g.write('if (')
2020-03-16 03:56:38 +01:00
}
for i, expr in branch.exprs {
if node.is_sum_type {
g.expr(node.cond)
g.write('.typ == ')
// g.write('${tmp}.typ == ')
2020-03-16 03:56:38 +01:00
// sum_type_str
2020-04-05 18:03:36 +02:00
} else if type_sym.kind == .string {
g.write('string_eq(')
2020-04-08 13:53:11 +02:00
//
g.expr(node.cond)
g.write(', ')
// g.write('string_eq($tmp, ')
2020-04-05 18:03:36 +02:00
} else {
g.expr(node.cond)
g.write(' == ')
// g.write('$tmp == ')
2020-03-16 03:56:38 +01:00
}
g.expr(expr)
if type_sym.kind == .string {
g.write(')')
}
if i < branch.exprs.len - 1 {
g.write(' || ')
}
}
2020-04-05 18:15:12 +02:00
if is_expr {
g.write(') ? ')
} else {
g.writeln(') {')
}
2020-03-16 03:56:38 +01:00
}
// g.writeln('/* M sum_type=$node.is_sum_type is_expr=$node.is_expr exp_type=${g.typ(node.expected_type)}*/')
if node.is_sum_type && branch.exprs.len > 0 && !node.is_expr {
2020-03-16 03:56:38 +01:00
// The first node in expr is an ast.Type
// Use it to generate `it` variable.
first_expr := branch.exprs[0]
match first_expr {
2020-03-16 03:56:38 +01:00
ast.Type {
it_type := g.typ(it.typ)
// g.writeln('$it_type* it = ($it_type*)${tmp}.obj; // ST it')
g.write('\t$it_type* it = ($it_type*)')
g.expr(node.cond)
g.writeln('.obj; // ST it')
2020-03-16 03:56:38 +01:00
}
else {
verror('match sum type')
}
2020-04-05 18:03:36 +02:00
}
2020-03-16 03:56:38 +01:00
}
g.stmts(branch.stmts)
2020-04-13 01:53:26 +02:00
if !g.inside_ternary && node.branches.len > 1 {
2020-04-14 01:03:31 +02:00
g.write('}')
}
2020-03-16 03:56:38 +01:00
}
2020-04-13 01:53:26 +02:00
g.inside_ternary = was_inside_ternary
2020-03-16 03:56:38 +01:00
}
fn (mut g Gen) ident(node ast.Ident) {
if node.name == 'lld' {
2020-03-20 20:46:42 +01:00
return
}
if node.name.starts_with('C.') {
g.write(node.name[2..].replace('.', '__'))
return
2020-03-13 05:57:51 +01:00
}
if node.kind == .constant && !node.name.starts_with('g_') {
// TODO globals hack
g.write('_const_')
}
name := c_name(node.name)
// TODO `is`
match node.info {
ast.IdentVar {
// x ?int
// `x = 10` => `x.data = 10` (g.right_is_opt == false)
// `x = new_opt()` => `x = new_opt()` (g.right_is_opt == true)
// `println(x)` => `println(*(int*)x.data)`
2020-03-31 10:11:47 +02:00
if it.is_optional && !(g.is_assign_lhs && g.right_is_opt) {
g.write('/*opt*/')
styp := g.typ(it.typ)[7..] // Option_int => int TODO perf?
g.write('(*($styp*)${name}.data)')
return
2020-03-13 05:57:51 +01:00
}
}
else {}
2020-03-13 05:57:51 +01:00
}
g.write(name)
2020-03-13 05:57:51 +01:00
}
fn (mut g Gen) if_expr(node ast.IfExpr) {
2020-03-21 11:17:17 +01:00
// println('if_expr pos=$node.pos.line_nr')
2020-03-18 16:47:37 +01:00
// g.writeln('/* if is_expr=$node.is_expr */')
2020-03-17 16:40:41 +01:00
// If expression? Assign the value to a temp var.
// Previously ?: was used, but it's too unreliable.
type_sym := g.table.get_type_symbol(node.typ)
mut tmp := ''
2020-03-17 16:40:41 +01:00
if type_sym.kind != .void {
tmp = g.new_tmp_var()
// g.writeln('$ti.name $tmp;')
}
// one line ?:
// TODO clean this up once `is` is supported
// TODO: make sure only one stmt in each branch
2020-04-07 18:51:39 +02:00
if node.is_expr && node.branches.len >= 2 && node.has_else && type_sym.kind != .void {
g.inside_ternary = true
g.write('(')
for i, branch in node.branches {
if i > 0 {
2020-03-17 16:40:41 +01:00
g.write(' : ')
}
if i < node.branches.len - 1 || !node.has_else {
g.expr(branch.cond)
g.write(' ? ')
}
g.stmts(branch.stmts)
}
g.write(')')
g.inside_ternary = false
2020-04-05 18:03:36 +02:00
} else {
guard_ok := g.new_tmp_var()
mut is_guard := false
for i, branch in node.branches {
if i == 0 {
match branch.cond {
ast.IfGuardExpr {
is_guard = true
g.writeln('bool $guard_ok;')
g.write('{ /* if guard */ ${g.typ(it.expr_type)} $it.var_name = ')
g.expr(it.expr)
g.writeln(';')
g.writeln('if (($guard_ok = ${it.var_name}.ok)) {')
}
else {
g.write('if (')
g.expr(branch.cond)
g.writeln(') {')
}
2020-04-05 18:03:36 +02:00
}
} else if i < node.branches.len - 1 || !node.has_else {
g.write('} else if (')
g.expr(branch.cond)
g.writeln(') {')
2020-04-05 18:03:36 +02:00
} else if i == node.branches.len - 1 && node.has_else {
2020-04-05 18:15:12 +02:00
if is_guard {
g.writeln('} if (!$guard_ok) { /* else */')
} else {
g.writeln('} else {')
}
2020-03-17 16:40:41 +01:00
}
// Assign ret value
// if i == node.stmts.len - 1 && type_sym.kind != .void {}
2020-03-17 16:40:41 +01:00
// g.writeln('$tmp =')
g.stmts(branch.stmts)
2020-03-17 16:40:41 +01:00
}
if is_guard {
g.write('}')
}
g.writeln('}')
}
}
fn (mut g Gen) index_expr(node ast.IndexExpr) {
2020-02-02 14:31:54 +01:00
// TODO else doesn't work with sum types
mut is_range := false
2020-02-02 14:31:54 +01:00
match node.index {
ast.RangeExpr {
sym := g.table.get_type_symbol(node.left_type)
2020-03-24 12:55:41 +01:00
is_range = true
if sym.kind == .string {
g.write('string_substr(')
2020-03-31 16:47:55 +02:00
g.expr(node.left)
2020-04-05 18:03:36 +02:00
} else if sym.kind == .array {
2020-03-24 12:55:41 +01:00
g.write('array_slice(')
2020-03-31 16:47:55 +02:00
g.expr(node.left)
2020-04-05 18:03:36 +02:00
} else if sym.kind == .array_fixed {
2020-03-31 16:47:55 +02:00
// Convert a fixed array to V array when doing `fixed_arr[start..end]`
2020-03-31 17:16:12 +02:00
g.write('array_slice(new_array_from_c_array(_ARR_LEN(')
2020-03-31 16:47:55 +02:00
g.expr(node.left)
2020-03-31 17:16:12 +02:00
g.write('), _ARR_LEN(')
2020-03-31 16:47:55 +02:00
g.expr(node.left)
g.write('), sizeof(')
g.expr(node.left)
g.write('[0]), ')
g.expr(node.left)
g.write(')')
2020-04-05 18:03:36 +02:00
} else {
2020-03-31 16:47:55 +02:00
g.expr(node.left)
2020-03-07 05:19:15 +01:00
}
2020-02-02 14:31:54 +01:00
g.write(', ')
2020-04-05 18:15:12 +02:00
if it.has_low {
g.expr(it.low)
} else {
g.write('0')
}
2020-02-02 14:31:54 +01:00
g.write(', ')
2020-03-06 22:24:39 +01:00
if it.has_high {
g.expr(it.high)
2020-04-05 18:03:36 +02:00
} else {
2020-03-06 22:24:39 +01:00
g.expr(node.left)
g.write('.len')
}
2020-02-02 14:31:54 +01:00
g.write(')')
2020-03-06 22:24:39 +01:00
return
2020-02-02 14:31:54 +01:00
}
else {}
}
2020-03-24 12:55:41 +01:00
if !is_range {
sym := g.table.get_type_symbol(node.left_type)
left_is_ptr := table.type_is_ptr(node.left_type)
if table.type_is(node.left_type, .variadic) {
2020-03-14 13:42:27 +01:00
g.expr(node.left)
g.write('.args')
g.write('[')
g.expr(node.index)
g.write(']')
2020-04-05 18:03:36 +02:00
} else if sym.kind == .array {
2020-03-11 21:11:27 +01:00
info := sym.info as table.Array
elem_type_str := g.typ(info.elem_type)
// `vals[i].field = x` is an exception and requires `array_get`:
// `(*(Val*)array_get(vals, i)).field = x;`
is_selector := node.left is ast.SelectorExpr
if g.is_assign_lhs && !is_selector && node.is_setter {
2020-03-07 16:39:15 +01:00
g.is_array_set = true
g.write('array_set(')
if !left_is_ptr {
g.write('&')
}
2020-03-07 16:39:15 +01:00
g.expr(node.left)
g.write(', ')
g.expr(node.index)
mut need_wrapper := true
2020-04-11 19:06:53 +02:00
/*
match node.right {
ast.EnumVal, ast.Ident {
// `&x` is enough for variables and enums
// `&(Foo[]){ ... }` is only needed for function calls and literals
need_wrapper = false
}
else {}
}
*/
if need_wrapper {
g.write(', &($elem_type_str[]) { ')
} else {
g.write(', &')
}
// `x[0] *= y`
2020-04-14 19:36:52 +02:00
if g.assign_op != .assign && g.assign_op in token.assign_tokens {
// TODO move this
g.write('*($elem_type_str*)array_get(')
2020-04-04 14:08:38 +02:00
if left_is_ptr {
g.write('*')
}
g.expr(node.left)
g.write(', ')
g.expr(node.index)
g.write(') ')
op := match g.assign_op {
.mult_assign { '*' }
.plus_assign { '+' }
.minus_assign { '-' }
.div_assign { '/' }
.xor_assign { '^' }
.mod_assign { '%' }
.or_assign { '|' }
.and_assign { '&' }
.left_shift_assign { '<<' }
.right_shift_assign { '>>' }
else { '' }
2020-04-05 18:03:36 +02:00
}
g.write(op)
}
2020-04-05 18:03:36 +02:00
} else {
2020-03-11 21:11:27 +01:00
g.write('(*($elem_type_str*)array_get(')
2020-04-04 14:08:38 +02:00
if left_is_ptr {
g.write('*')
}
2020-03-07 16:39:15 +01:00
g.expr(node.left)
g.write(', ')
g.expr(node.index)
2020-03-11 03:52:01 +01:00
g.write('))')
2020-03-07 16:39:15 +01:00
}
2020-04-05 18:03:36 +02:00
} else if sym.kind == .map {
2020-03-19 10:07:31 +01:00
info := sym.info as table.Map
elem_type_str := g.typ(info.value_type)
2020-04-15 02:42:00 +02:00
if g.is_assign_lhs && !g.is_array_set {
2020-03-19 10:07:31 +01:00
g.is_array_set = true
g.write('map_set(')
if !left_is_ptr {
g.write('&')
}
2020-03-19 10:07:31 +01:00
g.expr(node.left)
g.write(', ')
g.expr(node.index)
g.write(', &($elem_type_str[]) { ')
2020-04-05 18:03:36 +02:00
} else {
/*
2020-03-19 10:07:31 +01:00
g.write('(*($elem_type_str*)map_get2(')
2020-04-05 19:35:10 +02:00
g.expr(node.left)
g.write(', ')
g.expr(node.index)
g.write('))')
*/
zero := g.type_default(info.value_type)
g.write('(*($elem_type_str*)map_get3(')
g.expr(node.left)
g.write(', ')
g.expr(node.index)
g.write(', &($elem_type_str[]){ $zero }))')
2020-03-19 10:07:31 +01:00
}
2020-04-05 18:03:36 +02:00
} else if sym.kind == .string && !table.type_is_ptr(node.left_type) {
2020-03-06 22:24:39 +01:00
g.write('string_at(')
2020-03-06 20:22:58 +01:00
g.expr(node.left)
g.write(', ')
g.expr(node.index)
g.write(')')
2020-04-05 18:03:36 +02:00
} else {
2020-03-07 00:19:27 +01:00
g.expr(node.left)
g.write('[')
g.expr(node.index)
g.write(']')
}
2020-02-02 14:31:54 +01:00
}
}
fn (mut g Gen) return_statement(node ast.Return) {
2020-03-19 12:27:47 +01:00
g.write('return')
if g.fn_decl.name == 'main' {
2020-03-19 12:27:47 +01:00
g.writeln(' 0;')
return
}
fn_return_is_optional := table.type_is(g.fn_decl.return_type, .optional)
2020-03-13 05:57:51 +01:00
// multiple returns
if node.exprs.len > 1 {
2020-03-19 12:27:47 +01:00
g.write(' ')
2020-04-22 01:52:56 +02:00
// typ_sym := g.table.get_type_symbol(g.fn_decl.return_type)
// mr_info := typ_sym.info as table.MultiReturn
mut styp := g.typ(g.fn_decl.return_type)
if fn_return_is_optional { // && !table.type_is(node.types[0], .optional) && node.types[0] !=
styp = styp[7..] // remove 'Option_'
mut x := styp
if x.ends_with('_ptr') {
x = x.replace('_ptr', '*')
}
g.write('opt_ok(&($x/*X*/[]) { ')
2020-03-19 12:13:17 +01:00
}
g.write('($styp){')
for i, expr in node.exprs {
2020-03-13 05:57:51 +01:00
g.write('.arg$i=')
g.expr(expr)
if i < node.exprs.len - 1 {
2020-03-13 05:57:51 +01:00
g.write(',')
}
}
g.write('}')
2020-03-19 12:13:17 +01:00
if fn_return_is_optional {
2020-03-31 06:34:59 +02:00
g.write(' }, sizeof($styp))')
2020-03-19 12:13:17 +01:00
}
2020-04-05 18:03:36 +02:00
} else if node.exprs.len == 1 {
2020-04-05 02:08:10 +02:00
// normal return
2020-03-19 12:27:47 +01:00
g.write(' ')
return_sym := g.table.get_type_symbol(node.types[0])
2020-03-13 05:57:51 +01:00
// `return opt_ok(expr)` for functions that expect an optional
if fn_return_is_optional && !table.type_is(node.types[0], .optional) && return_sym.name !=
'Option' {
mut is_none := false
mut is_error := false
expr0 := node.exprs[0]
2020-03-18 12:23:32 +01:00
match expr0 {
2020-03-13 05:57:51 +01:00
ast.None {
is_none = true
}
ast.CallExpr {
if it.name == 'error' {
is_error = true // TODO check name 'error'
}
2020-03-13 05:57:51 +01:00
}
else {}
2020-04-05 18:03:36 +02:00
}
2020-03-13 05:57:51 +01:00
if !is_none && !is_error {
styp := g.typ(g.fn_decl.return_type)[7..] // remove 'Option_'
mut x := styp
if x.ends_with('_ptr') {
x = x.replace('_ptr', '*')
}
g.write('/*:)$return_sym.name*/opt_ok(&($x[]) { ')
g.expr(node.exprs[0])
g.writeln(' }, sizeof($x));')
2020-03-13 05:57:51 +01:00
return
}
// g.write('/*OPTIONAL*/')
}
if !table.type_is_ptr(g.fn_decl.return_type) && table.type_is_ptr(node.types[0]) {
// Automatic Dereference
g.write('*')
}
g.expr_with_cast(node.exprs[0], node.types[0], g.fn_decl.return_type)
2020-03-13 05:57:51 +01:00
}
g.writeln(';')
}
fn (mut g Gen) const_decl(node ast.ConstDecl) {
2020-03-06 14:03:35 +01:00
for i, field in node.fields {
name := c_name(field.name)
2020-03-21 09:29:16 +01:00
// TODO hack. Cut the generated value and paste it into definitions.
pos := g.out.len
g.expr(field.expr)
2020-03-21 09:29:16 +01:00
val := g.out.after(pos)
g.out.go_back(val.len)
/*
if field.typ == table.byte_type {
g.const_decl_simple_define(name, val)
return
}
*/
/*
if table.is_number(field.typ) {
g.const_decl_simple_define(name, val)
} else if field.typ == table.string_type {
g.definitions.writeln('string _const_$name; // a string literal, inited later')
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('\t_const_$name = $val;')
}
} else {
*/
match field.expr {
2020-04-04 22:06:47 +02:00
ast.CharLiteral {
2020-04-05 18:03:36 +02:00
g.const_decl_simple_define(name, val)
2020-04-04 22:06:47 +02:00
}
2020-04-16 19:43:39 +02:00
ast.FloatLiteral {
g.const_decl_simple_define(name, val)
}
2020-04-04 22:06:47 +02:00
ast.IntegerLiteral {
2020-04-05 18:03:36 +02:00
g.const_decl_simple_define(name, val)
2020-04-04 22:06:47 +02:00
}
ast.StringLiteral {
g.definitions.writeln('string _const_$name; // a string literal, inited later')
2020-04-10 18:11:43 +02:00
if g.pref.build_mode != .build_module {
g.stringliterals.writeln('\t_const_$name = $val;')
}
2020-03-06 14:03:35 +01:00
}
else {
// Initialize more complex consts in `void _vinit(){}`
2020-03-21 09:29:16 +01:00
// (C doesn't allow init expressions that can't be resolved at compile time).
2020-03-06 22:36:51 +01:00
styp := g.typ(field.typ)
2020-04-04 22:06:47 +02:00
g.definitions.writeln('$styp _const_$name; // inited later')
g.inits.writeln('\t_const_$name = $val;')
2020-03-06 14:03:35 +01:00
}
2020-04-05 18:03:36 +02:00
}
2020-03-06 14:03:35 +01:00
}
}
fn (mut g Gen) const_decl_simple_define(name, val string) {
2020-04-04 22:06:47 +02:00
// Simple expressions should use a #define
// so that we don't pollute the binary with unnecessary global vars
// Do not do this when building a module, otherwise the consts
// will not be accessible.
g.definitions.write('#define _const_$name ')
g.definitions.writeln(val)
}
fn (mut g Gen) struct_init(struct_init ast.StructInit) {
mut info := table.Struct{}
mut is_struct := false
sym := g.table.get_type_symbol(struct_init.typ)
if sym.kind == .struct_ {
is_struct = true
info = sym.info as table.Struct
}
// info := g.table.get_type_symbol(it.typ).info as table.Struct
2020-03-23 09:17:32 +01:00
// println(info.fields.len)
styp := g.typ(struct_init.typ)
2020-04-04 17:59:49 +02:00
is_amp := g.is_amp
if is_amp {
g.out.go_back(1) // delete the & already generated in `prefix_expr()
g.write('($styp*)memdup(&($styp){')
2020-04-05 18:03:36 +02:00
} else {
g.writeln('($styp){')
}
// var fields := []string
mut inited_fields := []string // TODO this is done in checker, move to ast node
/*
if struct_init.fields.len == 0 && struct_init.exprs.len > 0 {
// Get fields for {a,b} short syntax. Fields array wasn't set in the parser.
for f in info.fields {
fields << f.name
}
2020-04-05 18:03:36 +02:00
} else {
fields = struct_init.fields
}
*/
// User set fields
2020-04-22 01:52:56 +02:00
for _, field in struct_init.fields {
field_name := c_name(field.name)
inited_fields << field.name
g.write('\t.$field_name = ')
g.expr_with_cast(field.expr, field.typ, field.expected_type)
2020-03-23 11:57:54 +01:00
g.writeln(',')
}
// The rest of the fields are zeroed.
if is_struct {
for field in info.fields {
if field.name in inited_fields {
continue
}
2020-04-06 18:46:46 +02:00
if table.type_is(field.typ, .optional) {
// TODO handle/require optionals in inits
continue
}
field_name := c_name(field.name)
2020-04-19 04:44:39 +02:00
g.write('\t.$field_name = ')
if field.has_default_expr {
g.expr(field.default_expr)
} else {
2020-04-19 04:44:39 +02:00
g.write(g.type_default(field.typ))
}
2020-04-19 04:44:39 +02:00
g.writeln(',')
}
}
if struct_init.fields.len == 0 && info.fields.len == 0 {
g.write('0')
}
g.write('}')
2020-04-04 17:59:49 +02:00
if is_amp {
g.write(', sizeof($styp))')
}
}
2020-03-19 07:59:01 +01:00
// { user | name: 'new name' }
fn (mut g Gen) assoc(node ast.Assoc) {
2020-03-19 08:49:47 +01:00
g.writeln('// assoc')
2020-03-19 08:14:09 +01:00
if node.typ == 0 {
return
}
styp := g.typ(node.typ)
g.writeln('($styp){')
for i, field in node.fields {
field_name := c_name(field)
g.write('\t.$field_name = ')
2020-03-19 08:14:09 +01:00
g.expr(node.exprs[i])
g.writeln(', ')
}
// Copy the rest of the fields.
sym := g.table.get_type_symbol(node.typ)
info := sym.info as table.Struct
for field in info.fields {
if field.name in node.fields {
continue
}
field_name := c_name(field.name)
g.writeln('\t.$field_name = ${node.var_name}.$field_name,')
2020-03-19 08:14:09 +01:00
}
g.write('}')
if g.is_amp {
g.write(', sizeof($styp))')
}
}
2020-03-19 07:59:01 +01:00
fn (mut g Gen) generate_array_equality_fn(ptr_typ string, styp table.Type, sym &table.TypeSymbol) {
2020-04-09 03:55:37 +02:00
g.array_fn_definitions << ptr_typ
g.definitions.writeln('bool ${ptr_typ}_arr_eq(array_${ptr_typ} a, array_${ptr_typ} b) {')
g.definitions.writeln('\tif (a.len != b.len) {')
g.definitions.writeln('\t\treturn false;')
g.definitions.writeln('\t}')
g.definitions.writeln('\tfor (int i = 0; i < a.len; i++) {')
if styp == table.string_type_idx {
2020-04-11 17:25:25 +02:00
g.definitions.writeln('\t\tif (string_ne(*((${ptr_typ}*)((byte*)a.data+(i*a.element_size))), *((${ptr_typ}*)((byte*)b.data+(i*b.element_size))))) {')
2020-04-09 03:55:37 +02:00
} else if sym.kind == .struct_ {
2020-04-11 17:25:25 +02:00
g.definitions.writeln('\t\tif (memcmp((byte*)a.data+(i*a.element_size), (byte*)b.data+(i*b.element_size), a.element_size)) {')
2020-04-09 03:55:37 +02:00
} else {
2020-04-11 17:25:25 +02:00
g.definitions.writeln('\t\tif (*((${ptr_typ}*)((byte*)a.data+(i*a.element_size))) != *((${ptr_typ}*)((byte*)b.data+(i*b.element_size)))) {')
2020-04-09 03:55:37 +02:00
}
g.definitions.writeln('\t\t\treturn false;')
g.definitions.writeln('\t\t}')
g.definitions.writeln('\t}')
g.definitions.writeln('\treturn true;')
g.definitions.writeln('}')
}
fn verror(s string) {
util.verror('cgen error', s)
2019-12-24 18:54:43 +01:00
}
2020-03-10 23:21:26 +01:00
fn (mut g Gen) write_init_function() {
g.writeln('void _vinit() {')
2020-04-05 16:08:16 +02:00
g.writeln('\tbuiltin_init();')
2020-04-04 22:06:47 +02:00
g.writeln('\tvinit_string_literals();')
2020-03-21 10:22:16 +01:00
g.writeln(g.inits.str())
for mod_name in g.table.imports {
init_fn_name := '${mod_name}.init'
if _ := g.table.find_fn(init_fn_name) {
mod_c_name := mod_name.replace('.', '__')
init_fn_c_name := '${mod_c_name}__init'
g.writeln('\t${init_fn_c_name}();')
}
}
2020-03-21 09:29:16 +01:00
g.writeln('}')
2020-03-21 19:52:19 +01:00
if g.autofree {
g.writeln('void _vcleanup() {')
2020-03-31 20:26:15 +02:00
// g.writeln('puts("cleaning up...");')
if g.is_importing_os() {
g.writeln('free(_const_os__args.data);')
g.writeln('string_free(_const_os__wd_at_startup);')
}
g.writeln('free(_const_strconv__ftoa__powers_of_10.data);')
2020-03-21 19:52:19 +01:00
g.writeln('}')
}
2020-03-21 09:29:16 +01:00
}
fn (mut g Gen) write_str_fn_definitions() {
2020-03-21 07:10:53 +01:00
// _STR function can't be defined in vlib
g.writeln('
string _STR(const char *fmt, ...) {
va_list argptr;
va_start(argptr, fmt);
size_t len = vsnprintf(0, 0, fmt, argptr) + 1;
va_end(argptr);
byte* buf = malloc(len);
va_start(argptr, fmt);
vsprintf((char *)buf, fmt, argptr);
va_end(argptr);
#ifdef DEBUG_ALLOC
puts("_STR:");
puts(buf);
#endif
return tos2(buf);
}
string _STR_TMP(const char *fmt, ...) {
va_list argptr;
va_start(argptr, fmt);
//size_t len = vsnprintf(0, 0, fmt, argptr) + 1;
va_end(argptr);
va_start(argptr, fmt);
vsprintf((char *)g_str_buf, fmt, argptr);
va_end(argptr);
#ifdef DEBUG_ALLOC
//puts("_STR_TMP:");
//puts(g_str_buf);
#endif
return tos2(g_str_buf);
2020-03-21 11:47:23 +01:00
} // endof _STR_TMP
2020-03-21 07:10:53 +01:00
')
}
2020-03-10 23:21:26 +01:00
const (
builtins = ['string', 'array', 'KeyValue', 'DenseArray', 'map', 'Option']
2020-03-10 23:21:26 +01:00
)
fn (mut g Gen) write_builtin_types() {
mut builtin_types := []table.TypeSymbol // builtin types
2020-03-05 23:27:21 +01:00
// builtin types need to be on top
// everything except builtin will get sorted
2020-03-06 16:57:27 +01:00
for builtin_name in builtins {
builtin_types << g.table.types[g.table.type_idxs[builtin_name]]
}
2020-03-10 23:21:26 +01:00
g.write_types(builtin_types)
}
// C struct definitions, ordered
// Sort the types, make sure types that are referenced by other types
// are added before them.
fn (mut g Gen) write_sorted_types() {
mut types := []table.TypeSymbol // structs that need to be sorted
2020-03-06 12:01:56 +01:00
for typ in g.table.types {
2020-03-06 16:57:27 +01:00
if !(typ.name in builtins) {
types << typ
2020-03-05 23:27:21 +01:00
}
}
// sort structs
types_sorted := g.sort_structs(types)
// Generate C code
g.definitions.writeln('// builtin types:')
2020-03-06 20:22:58 +01:00
g.definitions.writeln('//------------------ #endbuiltin')
2020-03-05 23:27:21 +01:00
g.write_types(types_sorted)
}
fn (mut g Gen) write_types(types []table.TypeSymbol) {
for typ in types {
if typ.name.starts_with('C.') {
continue
}
2020-03-05 23:27:21 +01:00
// sym := g.table.get_type_symbol(typ)
name := typ.name.replace('.', '__')
2020-03-05 23:27:21 +01:00
match typ.info {
table.Struct {
info := typ.info as table.Struct
// g.definitions.writeln('typedef struct {')
2020-04-08 01:20:55 +02:00
if info.is_union {
g.definitions.writeln('union $name {')
} else {
g.definitions.writeln('struct $name {')
}
2020-04-05 18:15:12 +02:00
if info.fields.len > 0 {
for field in info.fields {
2020-04-05 12:31:25 +02:00
type_name := g.typ(field.typ)
field_name := c_name(field.name)
2020-04-05 18:15:12 +02:00
g.definitions.writeln('\t$type_name $field_name;')
}
} else {
g.definitions.writeln('EMPTY_STRUCT_DECLARATION;')
}
2020-03-05 23:27:21 +01:00
// g.definitions.writeln('} $name;\n')
2020-04-08 13:53:11 +02:00
//
2020-03-05 23:27:21 +01:00
g.definitions.writeln('};\n')
}
2020-04-05 02:08:10 +02:00
table.Alias {
// table.Alias, table.SumType { TODO
}
table.SumType {
g.definitions.writeln('// Sum type')
g.definitions.writeln('
typedef struct {
void* obj;
int typ;
} $name;')
}
table.ArrayFixed {
2020-04-05 18:03:36 +02:00
// .array_fixed {
styp := typ.name.replace('.', '__')
// array_fixed_char_300 => char x[300]
mut fixed := styp[12..]
len := styp.after('_')
fixed = fixed[..fixed.len - len.len - 1]
g.definitions.writeln('typedef $fixed $styp [$len];')
2020-04-05 18:03:36 +02:00
// }
}
else {}
2020-04-05 18:03:36 +02:00
}
2020-03-05 23:27:21 +01:00
}
}
// sort structs by dependant fields
2020-04-05 18:03:36 +02:00
fn (g Gen) sort_structs(typesa []table.TypeSymbol) []table.TypeSymbol {
mut dep_graph := depgraph.new_dep_graph()
2020-03-05 23:27:21 +01:00
// types name list
mut type_names := []string
for typ in typesa {
2020-03-05 23:27:21 +01:00
type_names << typ.name
}
// loop over types
for t in typesa {
2020-03-06 12:01:56 +01:00
// create list of deps
mut field_deps := []string
2020-03-05 23:27:21 +01:00
match t.info {
table.ArrayFixed {
dep := g.table.get_type_symbol(it.elem_type).name
if dep in type_names {
field_deps << dep
}
}
2020-03-05 23:27:21 +01:00
table.Struct {
info := t.info as table.Struct
for field in info.fields {
2020-03-06 12:01:56 +01:00
dep := g.table.get_type_symbol(field.typ).name
2020-03-05 23:27:21 +01:00
// skip if not in types list or already in deps
2020-03-06 20:22:58 +01:00
if !(dep in type_names) || dep in field_deps || table.type_is_ptr(field.typ) {
2020-03-06 12:01:56 +01:00
continue
}
field_deps << dep
2020-03-05 23:27:21 +01:00
}
}
// table.Interface {}
2020-03-05 23:27:21 +01:00
else {}
2020-04-05 18:03:36 +02:00
}
2020-03-06 12:01:56 +01:00
// add type and dependant types to graph
dep_graph.add(t.name, field_deps)
2020-03-05 23:27:21 +01:00
}
// sort graph
dep_graph_sorted := dep_graph.resolve()
if !dep_graph_sorted.acyclic {
verror('cgen.sort_structs(): the following structs form a dependency cycle:\n' + dep_graph_sorted.display_cycles() +
'\nyou can solve this by making one or both of the dependant struct fields references, eg: field &MyStruct' +
2020-04-05 18:03:36 +02:00
'\nif you feel this is an error, please create a new issue here: https://github.com/vlang/v/issues and tag @joe-conigliaro')
2020-03-05 23:27:21 +01:00
}
// sort types
mut types_sorted := []table.TypeSymbol
2020-03-05 23:27:21 +01:00
for node in dep_graph_sorted.nodes {
2020-03-06 16:57:27 +01:00
types_sorted << g.table.types[g.table.type_idxs[node.name]]
2020-03-05 23:27:21 +01:00
}
return types_sorted
}
fn (mut g Gen) string_inter_literal(node ast.StringInterLiteral) {
2020-03-21 07:01:06 +01:00
g.write('_STR("')
// Build the string with %
for i, val in node.vals {
escaped_val := val.replace_each(['"', '\\"', '\r\n', '\\n', '\n', '\\n', '%', '%%'])
2020-03-21 07:10:53 +01:00
g.write(escaped_val)
2020-03-21 07:01:06 +01:00
if i >= node.exprs.len {
continue
}
// TODO: fix match, sum type false positive
// match node.expr_types[i] {
2020-03-21 19:52:19 +01:00
// table.string_type {
// g.write('%.*s')
// }
// table.int_type {
// g.write('%d')
// }
// else {}
// }
2020-04-08 15:54:38 +02:00
sym := g.table.get_type_symbol(node.expr_types[i])
sfmt := node.expr_fmts[i]
if sfmt.len > 0 {
fspec := sfmt[sfmt.len - 1]
if fspec == `s` && node.expr_types[i] != table.string_type {
verror('only V strings can be formatted with a ${sfmt} format')
}
g.write('%' + sfmt[1..])
2020-04-14 19:32:23 +02:00
} else if node.expr_types[i] in [table.string_type, table.bool_type] || sym.kind in
[.enum_, .array, .array_fixed] {
g.write('%.*s')
2020-04-14 07:44:19 +02:00
} else if node.expr_types[i] in [table.f32_type, table.f64_type] {
g.write('%g')
2020-04-22 04:00:38 +02:00
} else if sym.kind in [.struct_, .map] && !sym.has_method('str') {
g.write('%.*s')
} else if node.expr_types[i] == table.i16_type {
g.write('%"PRId16"')
} else if node.expr_types[i] == table.u16_type {
g.write('%"PRIu16"')
} else if node.expr_types[i] == table.u32_type {
g.write('%"PRIu32"')
} else if node.expr_types[i] == table.i64_type {
g.write('%"PRId64"')
} else if node.expr_types[i] == table.u64_type {
g.write('%"PRIu64"')
2020-04-05 18:03:36 +02:00
} else {
g.write('%"PRId32"')
}
2020-03-21 07:01:06 +01:00
}
g.write('", ')
// Build args
for i, expr in node.exprs {
sfmt := node.expr_fmts[i]
if sfmt.len > 0 {
fspec := sfmt[sfmt.len - 1]
if fspec == `s` && node.expr_types[i] == table.string_type {
g.expr(expr)
g.write('.str')
} else {
g.expr(expr)
}
} else if node.expr_types[i] == table.string_type {
2020-03-21 07:01:06 +01:00
// `name.str, name.len,`
2020-03-21 07:04:53 +01:00
g.expr(expr)
2020-03-21 07:01:06 +01:00
g.write('.len, ')
2020-03-21 07:04:53 +01:00
g.expr(expr)
2020-03-21 07:01:06 +01:00
g.write('.str')
} else if node.expr_types[i] == table.bool_type {
g.expr(expr)
g.write(' ? 4 : 5, ')
g.expr(expr)
g.write(' ? "true" : "false"')
2020-04-14 07:44:19 +02:00
} else if node.expr_types[i] in [table.f32_type, table.f64_type] {
g.expr(expr)
} else {
2020-04-08 15:54:38 +02:00
sym := g.table.get_type_symbol(node.expr_types[i])
if sym.kind == .enum_ {
is_var := match node.exprs[i] {
2020-04-17 16:10:41 +02:00
ast.SelectorExpr { true }
ast.Ident { true }
else { false }
2020-04-08 15:54:38 +02:00
}
if is_var {
styp := g.typ(node.expr_types[i])
str_fn_name := styp_to_str_fn_name(styp)
g.gen_str_for_type(sym, styp, str_fn_name)
g.write('${str_fn_name}(')
2020-04-08 15:54:38 +02:00
g.enum_expr(expr)
g.write(')')
g.write('.len, ')
g.write('${str_fn_name}(')
2020-04-08 15:54:38 +02:00
g.enum_expr(expr)
g.write(').str')
} else {
g.write('tos3("')
g.enum_expr(expr)
g.write('")')
g.write('.len, ')
g.write('"')
g.enum_expr(expr)
g.write('"')
}
2020-04-14 07:44:19 +02:00
} else if sym.kind in [.array, .array_fixed] {
2020-04-13 19:18:22 +02:00
styp := g.typ(node.expr_types[i])
str_fn_name := styp_to_str_fn_name(styp)
g.gen_str_for_type(sym, styp, str_fn_name)
g.write('${str_fn_name}(')
2020-04-13 19:18:22 +02:00
g.expr(expr)
g.write(')')
g.write('.len, ')
g.write('${str_fn_name}(')
2020-04-13 19:18:22 +02:00
g.expr(expr)
g.write(').str')
2020-04-22 04:00:38 +02:00
} else if sym.kind == .map && !sym.has_method('str') {
styp := g.typ(node.expr_types[i])
str_fn_name := styp_to_str_fn_name(styp)
g.gen_str_for_type(sym, styp, str_fn_name)
g.write('${str_fn_name}(')
g.expr(expr)
g.write(')')
g.write('.len, ')
g.write('${str_fn_name}(')
g.expr(expr)
g.write(').str')
} else if sym.kind == .struct_ && !sym.has_method('str') {
styp := g.typ(node.expr_types[i])
str_fn_name := styp_to_str_fn_name(styp)
g.gen_str_for_type(sym, styp, str_fn_name)
g.write('${str_fn_name}(')
g.expr(expr)
g.write(',0)')
g.write('.len, ')
g.write('${str_fn_name}(')
g.expr(expr)
g.write(',0).str')
} else {
2020-04-08 15:54:38 +02:00
g.expr(expr)
}
2020-03-21 07:01:06 +01:00
}
if i < node.exprs.len - 1 {
g.write(', ')
}
}
g.write(')')
}
// `nums.filter(it % 2 == 0)`
fn (mut g Gen) gen_filter(node ast.CallExpr) {
2020-03-19 15:18:29 +01:00
tmp := g.new_tmp_var()
s := g.out.after(g.stmt_start_pos) // the already generated part of current statement
2020-03-19 15:18:29 +01:00
g.out.go_back(s.len)
// println('filter s="$s"')
sym := g.table.get_type_symbol(node.return_type)
if sym.kind != .array {
verror('filter() requires an array')
}
info := sym.info as table.Array
styp := g.typ(node.return_type)
elem_type_str := g.typ(info.elem_type)
g.write('\nint ${tmp}_len = ')
g.expr(node.left)
2020-03-19 15:18:29 +01:00
g.writeln('.len;')
g.writeln('$styp $tmp = new_array(0, ${tmp}_len, sizeof($elem_type_str));')
g.writeln('for (int i = 0; i < ${tmp}_len; i++) {')
g.write(' $elem_type_str it = (($elem_type_str*) ')
g.expr(node.left)
2020-03-19 15:18:29 +01:00
g.writeln('.data)[i];')
g.write('if (')
g.expr(node.args[0].expr) // the first arg is the filter condition
2020-03-19 15:18:29 +01:00
g.writeln(') array_push(&$tmp, &it); \n }')
g.write(s)
g.write(' ')
g.write(tmp)
}
fn (mut g Gen) insert_before(s string) {
cur_line := g.out.after(g.stmt_start_pos)
g.out.go_back(cur_line.len)
g.writeln(s)
g.write(cur_line)
}
2020-03-31 06:34:59 +02:00
// If user is accessing the return value eg. in assigment, pass the variable name.
// If the user is not using the optional return value. We need to pass a temp var
// to access its fields (`.ok`, `.error` etc)
// `os.cp(...)` => `Option bool tmp = os__cp(...); if (!tmp.ok) { ... }`
fn (mut g Gen) or_block(var_name string, stmts []ast.Stmt, return_type table.Type) {
mr_styp := g.typ(return_type)
mr_styp2 := mr_styp[7..] // remove Option_
g.writeln(';') // or')
2020-03-26 14:42:14 +01:00
g.writeln('if (!${var_name}.ok) {')
g.writeln('\tstring err = ${var_name}.v_error;')
g.writeln('\tint errcode = ${var_name}.ecode;')
2020-04-05 18:03:36 +02:00
last_type, type_of_last_expression := g.type_of_last_statement(stmts)
if last_type == 'v.ast.ExprStmt' && type_of_last_expression != 'void' {
g.indent++
for i, stmt in stmts {
2020-04-05 18:03:36 +02:00
if i == stmts.len - 1 {
g.indent--
g.write('\t*(${mr_styp2}*) ${var_name}.data = ')
}
g.stmt(stmt)
}
} else {
g.stmts(stmts)
}
2020-03-31 06:34:59 +02:00
g.write('}')
2020-03-26 14:42:14 +01:00
}
fn (mut g Gen) type_of_last_statement(stmts []ast.Stmt) (string, string) {
mut last_type := ''
mut last_expr_result_type := ''
if stmts.len > 0 {
2020-04-05 18:03:36 +02:00
last_stmt := stmts[stmts.len - 1]
last_type = typeof(last_stmt)
if last_type == 'v.ast.ExprStmt' {
match last_stmt {
ast.ExprStmt {
it_expr_type := typeof(it.expr)
if it_expr_type == 'v.ast.CallExpr' {
g.writeln('\t // typeof it_expr_type: $it_expr_type')
last_expr_result_type = g.type_of_call_expr(it.expr)
2020-04-05 18:03:36 +02:00
} else {
last_expr_result_type = it_expr_type
}
}
else {
last_expr_result_type = last_type
}
}
}
}
g.writeln('\t// last_type: $last_type')
g.writeln('\t// last_expr_result_type: $last_expr_result_type')
return last_type, last_expr_result_type
}
fn (mut g Gen) type_of_call_expr(node ast.Expr) string {
match node {
ast.CallExpr { return g.typ(it.return_type) }
else { return typeof(node) }
}
return ''
}
2020-03-19 16:12:46 +01:00
// `a in [1,2,3]` => `a == 1 || a == 2 || a == 3`
fn (mut g Gen) in_optimization(left ast.Expr, right ast.ArrayInit) {
2020-03-19 16:12:46 +01:00
is_str := right.elem_type == table.string_type
for i, array_expr in right.exprs {
if is_str {
g.write('string_eq(')
}
g.expr(left)
2020-04-05 18:15:12 +02:00
if is_str {
g.write(', ')
} else {
g.write(' == ')
}
2020-03-19 16:12:46 +01:00
g.expr(array_expr)
if is_str {
g.write(')')
}
if i < right.exprs.len - 1 {
g.write(' || ')
}
}
}
fn op_to_fn_name(name string) string {
return match name {
'+' { '_op_plus' }
'-' { '_op_minus' }
'*' { '_op_mul' }
'/' { '_op_div' }
'%' { '_op_mod' }
else { 'bad op $name' }
}
}
2020-03-22 13:55:39 +01:00
fn comp_if_to_ifdef(name string) string {
match name {
2020-04-11 11:41:48 +02:00
// platforms/os-es:
'windows' { return '_WIN32' }
'mac' { return '__APPLE__' }
'macos' { return '__APPLE__' }
'linux' { return '__linux__' }
'freebsd' { return '__FreeBSD__' }
'openbsd' { return '__OpenBSD__' }
'netbsd' { return '__NetBSD__' }
'dragonfly' { return '__DragonFly__' }
'msvc' { return '_MSC_VER' }
'android' { return '__ANDROID__' }
'solaris' { return '__sun' }
'haiku' { return '__haiku__' }
'linux_or_macos' { return '' }
2020-04-11 11:41:48 +02:00
//
'js' { return '_VJS' }
2020-04-11 11:41:48 +02:00
// compilers:
'tinyc' { return '__TINYC__' }
'clang' { return '__clang__' }
'mingw' { return '__MINGW32__' }
'msvc' { return '_MSC_VER' }
2020-04-11 11:41:48 +02:00
// other:
'debug' { return '_VDEBUG' }
'glibc' { return '__GLIBC__' }
'prealloc' { return 'VPREALLOC' }
'no_bounds_checking' { return 'NO_BOUNDS_CHECK' }
'x64' { return 'TARGET_IS_64BIT' }
'x32' { return 'TARGET_IS_32BIT' }
'little_endian' { return 'TARGET_ORDER_IS_LITTLE' }
'big_endian' { return 'TARGET_ORDER_IS_BIG' }
else { verror('bad os ifdef name "$name"') }
2020-03-22 13:55:39 +01:00
}
// verror('bad os ifdef name "$name"')
return ''
}
[inline]
fn c_name(name_ string) string {
name := name_.replace('.', '__')
if name in c_reserved {
return 'v_$name'
}
return name
}
2020-04-05 18:03:36 +02:00
fn (g Gen) type_default(typ table.Type) string {
sym := g.table.get_type_symbol(typ)
if sym.kind == .array {
2020-03-24 03:31:16 +01:00
elem_sym := g.table.get_type_symbol(sym.array_info().elem_type)
elem_type_str := elem_sym.name.replace('.', '__')
return 'new_array(0, 1, sizeof($elem_type_str))'
}
if sym.kind == .map {
2020-04-11 16:24:21 +02:00
value_type_str := g.typ(sym.map_info().value_type)
return 'new_map_1(sizeof($value_type_str))'
}
// Always set pointers to 0
if table.type_is_ptr(typ) {
return '0'
}
// User struct defined in another module.
// if typ.contains('__') {
if sym.kind == .struct_ {
return '{0}'
}
// if typ.ends_with('Fn') { // TODO
// return '0'
// }
// Default values for other types are not needed because of mandatory initialization
2020-03-23 09:17:32 +01:00
idx := int(typ)
if idx >= 1 && idx <= 17 {
return '0'
}
/*
match idx {
2020-04-05 19:35:10 +02:00
table.bool_type_idx {
return '0'
}
else {}
}
*/
2020-03-23 09:17:32 +01:00
match sym.name {
'string' { return 'tos3("")' }
'rune' { return '0' }
else {}
}
return '{0}'
// TODO this results in
// error: expected a field designator, such as '.field = 4'
// - Empty ee= (Empty) { . = {0} } ;
/*
return match typ {
2020-04-05 19:35:10 +02:00
'bool'{ '0'}
'string'{ 'tos3("")'}
'i8'{ '0'}
'i16'{ '0'}
'i64'{ '0'}
'u16'{ '0'}
'u32'{ '0'}
'u64'{ '0'}
'byte'{ '0'}
'int'{ '0'}
'rune'{ '0'}
'f32'{ '0.0'}
'f64'{ '0.0'}
'byteptr'{ '0'}
'voidptr'{ '0'}
else { '{0} '}
}
*/
}
pub fn (mut g Gen) write_tests_main() {
g.definitions.writeln('int g_test_oks = 0;')
g.definitions.writeln('int g_test_fails = 0;')
2020-04-07 12:32:09 +02:00
$if windows {
g.writeln('int wmain() {')
2020-04-07 18:51:39 +02:00
} $else {
2020-04-07 12:32:09 +02:00
g.writeln('int main() {')
}
2020-03-25 00:17:39 +01:00
g.writeln('\t_vinit();')
2020-03-30 17:21:32 +02:00
g.writeln('')
all_tfuncs := g.get_all_test_function_names()
if g.pref.is_stats {
g.writeln('\tBenchedTests bt = start_testing(${all_tfuncs.len}, tos3("$g.pref.path"));')
}
for t in all_tfuncs {
2020-03-31 19:58:44 +02:00
g.writeln('')
2020-03-30 17:21:32 +02:00
if g.pref.is_stats {
g.writeln('\tBenchedTests_testing_step_start(&bt, tos3("$t"));')
}
g.writeln('\t${t}();')
if g.pref.is_stats {
g.writeln('\tBenchedTests_testing_step_end(&bt);')
}
}
2020-03-31 19:58:44 +02:00
g.writeln('')
2020-03-30 17:21:32 +02:00
if g.pref.is_stats {
g.writeln('\tBenchedTests_end_testing(&bt);')
}
g.writeln('')
2020-04-02 09:18:45 +02:00
if g.autofree {
g.writeln('\t_vcleanup();')
}
2020-03-30 17:21:32 +02:00
g.writeln('\treturn g_test_fails > 0;')
g.writeln('}')
}
2020-04-05 18:03:36 +02:00
fn (g Gen) get_all_test_function_names() []string {
mut tfuncs := []string
mut tsuite_begin := ''
mut tsuite_end := ''
for _, f in g.table.fns {
if f.name == 'testsuite_begin' {
tsuite_begin = f.name
continue
}
if f.name == 'testsuite_end' {
tsuite_end = f.name
continue
}
if f.name.starts_with('test_') {
tfuncs << f.name
continue
}
// What follows is for internal module tests
// (they are part of a V module, NOT in main)
if f.name.contains('.test_') {
tfuncs << f.name
continue
}
if f.name.ends_with('.testsuite_begin') {
tsuite_begin = f.name
continue
}
if f.name.ends_with('.testsuite_end') {
tsuite_end = f.name
continue
}
}
mut all_tfuncs := []string
if tsuite_begin.len > 0 {
2020-03-30 17:21:32 +02:00
all_tfuncs << tsuite_begin
}
2020-03-30 17:21:32 +02:00
all_tfuncs << tfuncs
if tsuite_end.len > 0 {
2020-03-30 17:21:32 +02:00
all_tfuncs << tsuite_end
}
mut all_tfuncs_c := []string
for f in all_tfuncs {
all_tfuncs_c << f.replace('.', '__')
}
return all_tfuncs_c
}
2020-04-05 18:03:36 +02:00
fn (g Gen) is_importing_os() bool {
return 'os' in g.table.imports
}
2020-03-27 14:44:30 +01:00
fn (mut g Gen) comp_if(it ast.CompIf) {
2020-03-27 14:44:30 +01:00
ifdef := comp_if_to_ifdef(it.val)
if it.is_not {
g.writeln('\n#ifndef ' + ifdef)
g.writeln('// #if not $it.val')
2020-04-05 18:03:36 +02:00
} else {
2020-03-27 14:44:30 +01:00
g.writeln('\n#ifdef ' + ifdef)
g.writeln('// #if $it.val')
}
// NOTE: g.defer_ifdef is needed for defers called witin an ifdef
// in v1 this code would be completely excluded
2020-04-05 18:15:12 +02:00
g.defer_ifdef = if it.is_not {
2020-04-11 11:41:48 +02:00
'\n#ifndef ' + ifdef
2020-04-05 18:15:12 +02:00
} else {
2020-04-11 11:41:48 +02:00
'\n#ifdef ' + ifdef
2020-04-05 18:15:12 +02:00
}
2020-03-27 14:44:30 +01:00
// println('comp if stmts $g.file.path:$it.pos.line_nr')
g.stmts(it.stmts)
g.defer_ifdef = ''
if it.has_else {
2020-04-11 11:41:48 +02:00
g.writeln('\n#else')
2020-04-05 18:15:12 +02:00
g.defer_ifdef = if it.is_not {
2020-04-11 11:41:48 +02:00
'\n#ifdef ' + ifdef
2020-04-05 18:15:12 +02:00
} else {
2020-04-11 11:41:48 +02:00
'\n#ifndef ' + ifdef
2020-04-05 18:15:12 +02:00
}
2020-03-27 14:44:30 +01:00
g.stmts(it.else_stmts)
g.defer_ifdef = ''
}
2020-04-11 11:41:48 +02:00
g.writeln('\n#endif')
2020-03-27 14:44:30 +01:00
}
2020-04-03 15:18:17 +02:00
fn (mut g Gen) go_stmt(node ast.GoStmt) {
2020-04-03 15:18:17 +02:00
tmp := g.new_tmp_var()
// x := node.call_expr as ast.CallEpxr // TODO
match node.call_expr {
2020-04-05 18:03:36 +02:00
ast.CallExpr {
mut name := it.name.replace('.', '__')
2020-04-03 15:18:17 +02:00
if it.is_method {
receiver_sym := g.table.get_type_symbol(it.receiver_type)
name = receiver_sym.name + '_' + name
}
g.writeln('// go')
wrapper_struct_name := 'thread_arg_' + name
wrapper_fn_name := name + '_thread_wrapper'
arg_tmp_var := 'arg_' + tmp
g.writeln('$wrapper_struct_name *$arg_tmp_var = malloc(sizeof(thread_arg_$name));')
2020-04-03 15:18:17 +02:00
if it.is_method {
g.write('${arg_tmp_var}->arg0 = ')
2020-04-03 15:18:17 +02:00
g.expr(it.left)
g.writeln(';')
}
for i, arg in it.args {
g.write('${arg_tmp_var}->arg${i+1} = ')
2020-04-03 15:18:17 +02:00
g.expr(arg.expr)
g.writeln(';')
}
if g.pref.os == .windows {
g.writeln('CreateThread(0,0, (LPTHREAD_START_ROUTINE)$wrapper_fn_name, $arg_tmp_var, 0,0);')
} else {
g.writeln('pthread_t thread_$tmp;')
g.writeln('pthread_create(&thread_$tmp, NULL, (void*)$wrapper_fn_name, $arg_tmp_var);')
}
2020-04-03 15:18:17 +02:00
g.writeln('// endgo\n')
// Register the wrapper type and function
if name in g.threaded_fns {
return
}
g.definitions.writeln('\ntypedef struct $wrapper_struct_name {')
if it.is_method {
styp := g.typ(it.receiver_type)
g.definitions.writeln('\t$styp arg0;')
2020-04-03 15:18:17 +02:00
}
for i, arg in it.args {
styp := g.typ(arg.typ)
g.definitions.writeln('\t$styp arg${i+1};')
2020-04-03 15:18:17 +02:00
}
g.definitions.writeln('} $wrapper_struct_name;')
g.definitions.writeln('void* ${wrapper_fn_name}($wrapper_struct_name *arg);')
g.gowrappers.writeln('void* ${wrapper_fn_name}($wrapper_struct_name *arg) {')
g.gowrappers.write('\t${name}(')
2020-04-03 15:18:17 +02:00
if it.is_method {
g.gowrappers.write('arg->arg0')
2020-04-03 15:18:17 +02:00
if it.args.len > 0 {
g.gowrappers.write(', ')
2020-04-03 15:18:17 +02:00
}
}
2020-04-05 18:03:36 +02:00
for i in 0 .. it.args.len {
g.gowrappers.write('arg->arg${i+1}')
2020-04-03 15:18:17 +02:00
if i < it.args.len - 1 {
g.gowrappers.write(', ')
2020-04-03 15:18:17 +02:00
}
}
g.gowrappers.writeln(');')
g.gowrappers.writeln('\treturn 0;')
g.gowrappers.writeln('}')
2020-04-03 15:18:17 +02:00
g.threaded_fns << name
}
2020-04-05 18:03:36 +02:00
else {}
2020-04-03 15:18:17 +02:00
}
}
fn (mut g Gen) is_expr(node ast.InfixExpr) {
2020-04-16 15:32:11 +02:00
g.expr(node.left)
g.write('.typ == ')
g.expr(node.right)
}
fn styp_to_str_fn_name(styp string) string {
res := styp.replace('.', '__').replace('*','_ptr') + '_str'
return res
}
// already generated styp, reuse it
fn (mut g Gen) gen_str_for_type(sym table.TypeSymbol, styp string, str_fn_name string) {
already_generated_key := '${styp}:${str_fn_name}'
if sym.has_method('str') || already_generated_key in g.str_types {
2020-04-08 22:14:01 +02:00
return
}
g.str_types << already_generated_key
match sym.info {
table.Alias { g.gen_str_default(sym, styp, str_fn_name) }
table.Array { g.gen_str_for_array(it, styp, str_fn_name) }
table.Enum { g.gen_str_for_enum(it, styp, str_fn_name) }
table.Struct { g.gen_str_for_struct(it, styp, str_fn_name) }
2020-04-22 04:00:38 +02:00
table.Map { g.gen_str_for_map(it, styp, str_fn_name) }
else { verror("could not generate string method $str_fn_name for type \'${styp}\'") }
}
2020-04-08 15:54:38 +02:00
}
fn (mut g Gen) gen_str_default(sym table.TypeSymbol, styp string, str_fn_name string) {
mut convertor := ''
mut typename := ''
2020-04-13 20:07:25 +02:00
if sym.parent_idx in table.integer_type_idxs {
convertor = 'int'
typename = 'int'
2020-04-14 00:37:47 +02:00
} else if sym.parent_idx == table.f32_type_idx {
2020-04-13 20:07:25 +02:00
convertor = 'float'
typename = 'f32'
2020-04-14 00:37:47 +02:00
} else if sym.parent_idx == table.f64_type_idx {
2020-04-13 20:07:25 +02:00
convertor = 'double'
typename = 'f64'
2020-04-14 00:37:47 +02:00
} else if sym.parent_idx == table.bool_type_idx {
2020-04-13 20:07:25 +02:00
convertor = 'bool'
typename = 'bool'
2020-04-14 00:37:47 +02:00
} else {
verror("could not generate string method for type \'${styp}\'")
2020-04-13 20:07:25 +02:00
}
g.definitions.writeln('string ${str_fn_name}($styp it); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp it) {')
2020-04-13 20:07:25 +02:00
if convertor == 'bool' {
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(tos3("${styp}("), (${convertor})it ? tos3("true") : tos3("false"));')
2020-04-13 20:07:25 +02:00
} else {
g.auto_str_funcs.writeln('\tstring tmp1 = string_add(tos3("${styp}("), tos3(${typename}_str((${convertor})it).str));')
2020-04-13 20:07:25 +02:00
}
g.auto_str_funcs.writeln('\tstring tmp2 = string_add(tmp1, tos3(")"));')
g.auto_str_funcs.writeln('\tstring_free(tmp1);')
g.auto_str_funcs.writeln('\treturn tmp2;')
g.auto_str_funcs.writeln('}')
2020-04-13 20:07:25 +02:00
}
fn (mut g Gen) gen_str_for_enum(info table.Enum, styp string, str_fn_name string) {
2020-04-08 15:54:38 +02:00
s := styp.replace('.', '__')
g.definitions.writeln('string ${str_fn_name}($styp it); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp it) { /* gen_str_for_enum */')
g.auto_str_funcs.writeln('\tswitch(it) {')
2020-04-08 18:55:10 +02:00
for i, val in info.vals {
g.auto_str_funcs.writeln('\t\tcase ${s}_$val: return tos3("$val");')
2020-04-08 15:54:38 +02:00
}
g.auto_str_funcs.writeln('\t\tdefault: return tos3("unknown enum value");')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('}')
2020-04-08 15:54:38 +02:00
}
fn (mut g Gen) gen_str_for_struct(info table.Struct, styp string, str_fn_name string) {
2020-04-08 22:14:01 +02:00
// TODO: short it if possible
// generates all definitions of substructs
mut fnames2strfunc := map[string]string
2020-04-08 22:14:01 +02:00
for i, field in info.fields {
sym := g.table.get_type_symbol(field.typ)
2020-04-22 04:00:38 +02:00
if sym.kind in [.struct_, .array, .array_fixed, .map, .enum_] {
2020-04-08 22:14:01 +02:00
field_styp := g.typ(field.typ)
field_fn_name := styp_to_str_fn_name( field_styp )
fnames2strfunc[ field_styp ] = field_fn_name
g.gen_str_for_type(sym, field_styp, field_fn_name)
}
}
g.definitions.writeln('string ${str_fn_name}($styp x, int indent_count); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp x, int indent_count) {')
mut clean_struct_v_type_name := styp.replace('__','.')
if styp.ends_with('*') {
deref_typ := styp.replace('*', '')
g.auto_str_funcs.writeln('\t${deref_typ} *it = x;')
clean_struct_v_type_name = '&' + clean_struct_v_type_name.replace('*', '')
}else{
deref_typ := styp
g.auto_str_funcs.writeln('\t${deref_typ} *it = &x;')
2020-04-08 22:14:01 +02:00
}
// generate ident / indent length = 4 spaces
g.auto_str_funcs.writeln('\tstring indents = tos3("");')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < indent_count; i++) {')
g.auto_str_funcs.writeln('\t\tindents = string_add(indents, tos3(" "));')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\treturn _STR("${clean_struct_v_type_name} {\\n"')
for field in info.fields {
2020-04-08 22:14:01 +02:00
fmt := g.type_to_fmt(field.typ)
g.auto_str_funcs.writeln('\t\t"%.*s ' + '$field.name: $fmt\\n"')
}
g.auto_str_funcs.write('\t\t"%.*s}"')
2020-04-03 18:49:12 +02:00
if info.fields.len > 0 {
g.auto_str_funcs.write(',\n\t\t')
2020-04-08 22:14:01 +02:00
for i, field in info.fields {
sym := g.table.get_type_symbol(field.typ)
has_custom_str := sym.has_method('str')
second_str_param := if has_custom_str {''} else {', indent_count + 1'}
field_styp := g.typ(field.typ)
field_styp_fn_name := if has_custom_str {'${field_styp}_str'} else {fnames2strfunc[ field_styp ]}
if sym.kind == .enum_ {
g.auto_str_funcs.write('indents.len, indents.str, ')
g.auto_str_funcs.write('${field_styp_fn_name}( it->${field.name} ).len, ')
g.auto_str_funcs.write('${field_styp_fn_name}( it->${field.name} ).str ')
}else if sym.kind in [.struct_, .array, .array_fixed] {
g.auto_str_funcs.write('indents.len, indents.str, ')
g.auto_str_funcs.write('${field_styp_fn_name}( it->${field.name}${second_str_param} ).len, ')
g.auto_str_funcs.write('${field_styp_fn_name}( it->${field.name}${second_str_param} ).str ')
2020-04-08 22:14:01 +02:00
} else {
g.auto_str_funcs.write('indents.len, indents.str, it->${field.name}')
2020-04-08 22:14:01 +02:00
if field.typ == table.string_type {
g.auto_str_funcs.write('.len, it->${field.name}.str')
2020-04-08 22:14:01 +02:00
} else if field.typ == table.bool_type {
g.auto_str_funcs.write(' ? 4 : 5, it->${field.name} ? "true" : "false"')
2020-04-08 22:14:01 +02:00
}
}
if i < info.fields.len - 1 {
g.auto_str_funcs.write(',\n\t\t')
2020-04-08 22:14:01 +02:00
}
}
}
g.auto_str_funcs.writeln(',')
g.auto_str_funcs.writeln('\t\tindents.len, indents.str);')
g.auto_str_funcs.writeln('}')
}
fn (mut g Gen) gen_str_for_array(info table.Array, styp string, str_fn_name string) {
2020-04-17 16:10:41 +02:00
sym := g.table.get_type_symbol(info.elem_type)
2020-04-19 10:42:34 +02:00
field_styp := g.typ(info.elem_type)
2020-04-17 16:10:41 +02:00
if sym.kind == .struct_ && !sym.has_method('str') {
g.gen_str_for_type(sym, field_styp, styp_to_str_fn_name(field_styp) )
}
g.definitions.writeln('string ${str_fn_name}($styp a); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp a) {')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder(a.len * 10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos3("["));')
g.auto_str_funcs.writeln('\tfor (int i = 0; i < a.len; i++) {')
g.auto_str_funcs.writeln('\t\t${field_styp} it = (*(${field_styp}*)array_get(a, i));')
2020-04-19 10:42:34 +02:00
if sym.kind == .struct_ && !sym.has_method('str') {
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, ${field_styp}_str(it,0));')
2020-04-19 10:42:34 +02:00
} else if sym.kind in [.f32, .f64] {
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, _STR("%g", it));')
2020-04-19 10:42:34 +02:00
} else {
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, ${field_styp}_str(it));')
2020-04-19 10:42:34 +02:00
}
g.auto_str_funcs.writeln('\t\tif (i != a.len-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos3(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos3("]"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
2020-04-17 16:10:41 +02:00
}
2020-04-22 04:00:38 +02:00
fn (mut g Gen) gen_str_for_map(info table.Map, styp string, str_fn_name string) {
key_sym := g.table.get_type_symbol(info.key_type)
key_styp := g.typ(info.key_type)
if key_sym.kind == .struct_ && !key_sym.has_method('str') {
g.gen_str_for_type(key_sym, key_styp, styp_to_str_fn_name(key_styp))
}
val_sym := g.table.get_type_symbol(info.value_type)
val_styp := g.typ(info.value_type)
if val_sym.kind == .struct_ && !val_sym.has_method('str') {
g.gen_str_for_type(val_sym, val_styp, styp_to_str_fn_name(val_styp))
}
zero := g.type_default(info.value_type)
g.definitions.writeln('string ${str_fn_name}($styp m); // auto')
g.auto_str_funcs.writeln('string ${str_fn_name}($styp m) { /* gen_str_for_map */')
g.auto_str_funcs.writeln('\tstrings__Builder sb = strings__new_builder(m.key_values.size*10);')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos3("$styp"));')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos3("{"));')
g.auto_str_funcs.writeln('\tfor (unsigned int i = 0; i < m.key_values.size; i++) {')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, (*(string*)DenseArray_get(m.key_values, i)));')
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, tos3(": "));')
g.auto_str_funcs.write('\t$val_styp it = (*($val_styp*)map_get3(')
g.auto_str_funcs.write('m, (*(string*)DenseArray_get(m.key_values, i))')
g.auto_str_funcs.write(', ')
g.auto_str_funcs.writeln(' &($val_styp[]) { $zero }));')
if val_sym.kind == .string {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, it);')
} else if val_sym.kind == .struct_ && !val_sym.has_method('str') {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${val_styp}_str(it,0));')
} else if val_sym.kind in [.f32, .f64] {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, _STR("%g", it));')
} else {
g.auto_str_funcs.writeln('\t\tstrings__Builder_write(&sb, ${val_styp}_str(it));')
}
g.auto_str_funcs.writeln('\t\tif (i != m.key_values.size-1) {')
g.auto_str_funcs.writeln('\t\t\tstrings__Builder_write(&sb, tos3(", "));')
g.auto_str_funcs.writeln('\t\t}')
g.auto_str_funcs.writeln('\t}')
g.auto_str_funcs.writeln('\tstrings__Builder_write(&sb, tos3("}"));')
g.auto_str_funcs.writeln('\treturn strings__Builder_str(&sb);')
g.auto_str_funcs.writeln('}')
}
2020-04-08 22:14:01 +02:00
fn (g Gen) type_to_fmt(typ table.Type) string {
sym := g.table.get_type_symbol(typ)
2020-04-22 04:00:38 +02:00
if sym.kind in [.struct_, .array, .array_fixed, .map] {
return '%.*s'
2020-04-08 22:14:01 +02:00
} else if typ == table.string_type {
2020-04-08 00:46:16 +02:00
return "\'%.*s\'"
2020-04-08 22:14:01 +02:00
} else if typ == table.bool_type {
return '%.*s'
} else if sym.kind == .enum_ {
return '%.*s'
2020-04-08 22:14:01 +02:00
} else if typ in [table.f32_type, table.f64_type] {
return '%g' // g removes trailing zeros unlike %f
}
return '%d'
}