1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

builtin,cgen: rename Option to _option (#14317)

This commit is contained in:
Daniel Däschle 2022-05-06 18:25:54 +02:00 committed by GitHub
parent 45fe87c9e3
commit 76cdf75299
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 83 additions and 47 deletions

View File

@ -104,6 +104,22 @@ pub fn (o Option) str() string {
return 'Option{ error: "$o.err" }'
}
pub struct _option {
state u8
err IError = none__
}
// str returns the Option type: ok, none, or error
pub fn (o _option) str() string {
if o.state == 0 {
return 'Option{ ok }'
}
if o.state == 1 {
return 'Option{ none }'
}
return 'Option{ error: "$o.err" }'
}
// trace_error prints to stderr a string and a backtrace of the error
fn trace_error(x string) {
eprintln('> ${@FN} | $x')

View File

@ -121,6 +121,23 @@ fn opt_ok(data voidptr, mut option Option, size int) {
}
}
// option is the base of V's internal optional return system.
struct _option {
state u8
err IError = none__
// Data is trailing after err
// and is not included in here but in the
// derived _option_xxx types
}
fn opt_ok2(data voidptr, mut option _option, size int) {
unsafe {
*option = _option{}
// use err to get the end of OptionBase and then memcpy into it
vmemcpy(&u8(&option.err) + sizeof(IError), data, size)
}
}
struct _result {
is_error bool
err IError = none__

View File

@ -997,7 +997,7 @@ pub fn (t &Table) thread_cname(return_type Type) string {
}
return_type_sym := t.sym(return_type)
suffix := if return_type.is_ptr() { '_ptr' } else { '' }
prefix := if return_type.has_flag(.optional) { 'Option_' } else { '' }
prefix := if return_type.has_flag(.optional) { '_option_' } else { '' }
return '__v_thread_$prefix$return_type_sym.cname$suffix'
}

View File

@ -73,8 +73,8 @@ pub fn (mut c Checker) return_stmt(mut node ast.Return) {
}
}
}
// allow `none` & `error` return types for function that returns option or result
option_type_idx := c.table.type_idxs['Option']
// allow `none` & `error` return types for function that returns optional
option_type_idx := c.table.type_idxs['_option']
result_type_idx := c.table.type_idxs['_result']
got_types_0_idx := got_types[0].idx()
if (exp_is_optional

View File

@ -32,6 +32,7 @@ const (
// when operands are switched
cmp_rev = ['eq', 'ne', 'lt', 'gt', 'le', 'ge']
result_name = '_result'
option_name = '_option'
)
fn string_array_to_map(a []string) map[string]bool {
@ -972,7 +973,7 @@ fn (mut g Gen) expr_string_surround(prepend string, expr ast.Expr, append string
// if one location changes
fn (mut g Gen) optional_type_name(t ast.Type) (string, string) {
base := g.base_type(t)
mut styp := 'Option_$base'
mut styp := '_option_$base'
if t.is_ptr() {
styp = styp.replace('*', '_ptr')
}
@ -1187,11 +1188,11 @@ fn (mut g Gen) write_chan_push_optional_fns() {
done << styp
g.register_optional(ast.void_type.set_flag(.optional))
g.channel_definitions.writeln('
static inline Option_void __Option_${styp}_pushval($styp ch, $el_type e) {
static inline ${c.option_name}_void __Option_${styp}_pushval($styp ch, $el_type e) {
if (sync__Channel_try_push_priv(ch, &e, false)) {
return (Option_void){ .state = 2, .err = _v_error(_SLIT("channel closed")), .data = {EMPTY_STRUCT_INITIALIZATION} };
return (${c.option_name}_void){ .state = 2, .err = _v_error(_SLIT("channel closed")), .data = {EMPTY_STRUCT_INITIALIZATION} };
}
return (Option_void){0};
return (${c.option_name}_void){0};
}')
}
}
@ -1563,9 +1564,9 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) {
styp = 'f64'
}
}
g.write('opt_ok(&($styp[]) { ')
g.write('opt_ok2(&($styp[]) { ')
g.stmt(stmt)
g.writeln(' }, (Option*)(&$tmp_var), sizeof($styp));')
g.writeln(' }, ($c.option_name*)(&$tmp_var), sizeof($styp));')
}
}
} else {
@ -4011,11 +4012,11 @@ fn (mut g Gen) return_stmt(node ast.Return) {
ret_typ := g.typ(g.unwrap_generic(g.fn_decl.return_type))
mut use_tmp_var := g.defer_stmts.len > 0 || g.defer_profile_code.len > 0
|| g.cur_lock.lockeds.len > 0
// handle promoting none/error/function returning 'Option'
// handle promoting none/error/function returning _option'
if fn_return_is_optional {
optional_none := node.exprs[0] is ast.None
ftyp := g.typ(node.types[0])
mut is_regular_option := ftyp == 'Option'
mut is_regular_option := ftyp == '_option'
if optional_none || is_regular_option || node.types[0] == ast.error_type_idx {
if !isnil(g.fn_decl) && g.fn_decl.is_test {
test_error_var := g.new_tmp_var()
@ -4085,7 +4086,7 @@ fn (mut g Gen) return_stmt(node ast.Return) {
if fn_return_is_optional || fn_return_is_result {
g.writeln('$ret_typ $tmpvar;')
styp = g.base_type(g.fn_decl.return_type)
g.write('opt_ok(&($styp/*X*/[]) { ')
g.write('opt_ok2(&($styp/*X*/[]) { ')
} else {
if use_tmp_var {
g.write('$ret_typ $tmpvar = ')
@ -4154,7 +4155,7 @@ fn (mut g Gen) return_stmt(node ast.Return) {
}
g.write('}')
if fn_return_is_optional || fn_return_is_result {
g.writeln(' }, (Option*)(&$tmpvar), sizeof($styp));')
g.writeln(' }, ($c.option_name*)(&$tmpvar), sizeof($styp));')
g.write_defer_stmts_when_needed()
g.write('return $tmpvar')
}
@ -4187,10 +4188,10 @@ fn (mut g Gen) return_stmt(node ast.Return) {
node.types[0].has_flag(.optional)
}
}
if fn_return_is_optional && !expr_type_is_opt && return_sym.name != 'Option' {
if fn_return_is_optional && !expr_type_is_opt && return_sym.name != c.option_name {
styp := g.base_type(g.fn_decl.return_type)
g.writeln('$ret_typ $tmpvar;')
g.write('opt_ok(&($styp[]) { ')
g.write('opt_ok2(&($styp[]) { ')
if !g.fn_decl.return_type.is_ptr() && node.types[0].is_ptr() {
if !(node.exprs[0] is ast.Ident && !g.is_amp) {
g.write('*')
@ -4202,7 +4203,7 @@ fn (mut g Gen) return_stmt(node ast.Return) {
g.write(', ')
}
}
g.writeln(' }, (Option*)(&$tmpvar), sizeof($styp));')
g.writeln(' }, ($c.option_name*)(&$tmpvar), sizeof($styp));')
g.write_defer_stmts_when_needed()
g.autofree_scope_vars(node.pos.pos - 1, node.pos.line_nr, true)
g.writeln('return $tmpvar;')
@ -4734,7 +4735,7 @@ fn (mut g Gen) write_init_function() {
}
const (
builtins = ['string', 'array', 'DenseArray', 'map', 'Error', 'IError', 'Option', result_name]
builtins = ['string', 'array', 'DenseArray', 'map', 'Error', 'IError', option_name, result_name]
)
fn (mut g Gen) write_builtin_types() {

View File

@ -1282,7 +1282,7 @@ fn (mut g Gen) fn_call(node ast.CallExpr) {
g.call_args(node)
g.writeln(');')
tmp2 = g.new_tmp_var()
g.writeln('Option_$typ $tmp2 = ${fn_name}($json_obj);')
g.writeln('${option_name}_$typ $tmp2 = ${fn_name}($json_obj);')
}
if !g.is_autofree {
g.write('cJSON_Delete($json_obj); // del')
@ -1798,7 +1798,7 @@ fn (mut g Gen) go_expr(node ast.GoExpr) {
if node.call_expr.return_type == ast.void_type {
gohandle_name = if is_opt { '__v_thread_Option_void' } else { '__v_thread' }
} else {
opt := if is_opt { 'Option_' } else { '' }
opt := if is_opt { '${option_name}_' } else { '' }
gohandle_name = '__v_thread_$opt${g.table.sym(g.unwrap_generic(node.call_expr.return_type)).cname}'
}
if g.pref.os == .windows {

View File

@ -64,7 +64,7 @@ fn (mut g Gen) infix_expr_arrow_op(node ast.InfixExpr) {
if gen_or {
elem_styp := g.typ(elem_type)
g.register_chan_push_optional_fn(elem_styp, styp)
g.write('Option_void $tmp_opt = __Option_${styp}_pushval(')
g.write('${option_name}_void $tmp_opt = __Option_${styp}_pushval(')
} else {
g.write('__${styp}_pushval(')
}

View File

@ -45,7 +45,7 @@ fn (mut g Gen) gen_jsons() {
// cJSON_Parse(str) call is added by the compiler
// Code gen decoder
dec_fn_name := js_dec_name(styp)
dec_fn_dec := 'Option_$styp ${dec_fn_name}(cJSON* root)'
dec_fn_dec := '${option_name}_$styp ${dec_fn_name}(cJSON* root)'
mut init_styp := '$styp res'
if sym.kind == .struct_ {
@ -96,7 +96,7 @@ $dec_fn_dec {
int maxchars = vstrlen_char(prevline_ptr);
vmemcpy(buf, prevline_ptr, (maxchars < maxcontext_chars ? maxchars : maxcontext_chars));
}
return (Option_$styp){.state = 2,.err = _v_error(tos2(buf)),.data = {0}};
return (${option_name}_$styp){.state = 2,.err = _v_error(tos2(buf)),.data = {0}};
}
}
')
@ -157,8 +157,8 @@ $enc_fn_dec {
}
// cJSON_delete
// p.cgen.fns << '$dec return opt_ok(res); \n}'
dec.writeln('\tOption_$styp ret;')
dec.writeln('\topt_ok(&res, (Option*)&ret, sizeof(res));')
dec.writeln('\t${option_name}_$styp ret;')
dec.writeln('\topt_ok2(&res, ($option_name*)&ret, sizeof(res));')
dec.writeln('\treturn ret;\n}')
enc.writeln('\treturn o;\n}')
g.definitions.writeln(dec.str())
@ -255,9 +255,9 @@ fn (mut g Gen) gen_sumtype_enc_dec(sym ast.TypeSymbol, mut enc strings.Builder,
dec.writeln('\t\t\t}')
} else if !is_js_prim(variant_typ) && variant_sym.kind != .enum_ {
dec.writeln('\t\t\tif (strcmp("$unmangled_variant_name", $type_var) == 0) {')
dec.writeln('\t\t\t\tOption_$variant_typ $tmp = ${js_dec_name(variant_typ)}(root);')
dec.writeln('\t\t\t\t${option_name}_$variant_typ $tmp = ${js_dec_name(variant_typ)}(root);')
dec.writeln('\t\t\t\tif (${tmp}.state != 0) {')
dec.writeln('\t\t\t\t\treturn (Option_$sym.cname){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t\t\t\t\treturn (${option_name}_$sym.cname){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t\t\t\t}')
dec.writeln('\t\t\t\tres = ${variant_typ}_to_sumtype_${sym.cname}(($variant_typ*)${tmp}.data);')
dec.writeln('\t\t\t}')
@ -321,9 +321,9 @@ fn (mut g Gen) gen_sumtype_enc_dec(sym ast.TypeSymbol, mut enc strings.Builder,
'cJSON_IsNumber(root->child)'
}
dec.writeln('\t\tif (cJSON_IsArray(root) && $judge_elem_typ) {')
dec.writeln('\t\t\tOption_$var_t $tmp = ${js_dec_name(var_t)}(root);')
dec.writeln('\t\t\t${option_name}_$var_t $tmp = ${js_dec_name(var_t)}(root);')
dec.writeln('\t\t\tif (${tmp}.state != 0) {')
dec.writeln('\t\t\t\treturn (Option_$sym.cname){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t\t\t\treturn (${option_name}_$sym.cname){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t\t\t}')
dec.writeln('\t\t\tres = ${var_t}_to_sumtype_${sym.cname}(($var_t*)${tmp}.data);')
dec.writeln('\t\t}')
@ -456,16 +456,16 @@ fn gen_js_get(styp string, tmp string, name string, mut dec strings.Builder, is_
dec.writeln('\tcJSON *jsonroot_$tmp = js_get(root,"$name");')
if is_required {
dec.writeln('\tif(jsonroot_$tmp == 0) {')
dec.writeln('\t\treturn (Option_$styp){ .state = 2, .err = _v_error(_SLIT("expected field \'$name\' is missing")), .data = {0} };')
dec.writeln('\t\treturn (${option_name}_$styp){ .state = 2, .err = _v_error(_SLIT("expected field \'$name\' is missing")), .data = {0} };')
dec.writeln('\t}')
}
}
fn gen_js_get_opt(dec_name string, field_type string, styp string, tmp string, name string, mut dec strings.Builder, is_required bool) {
gen_js_get(styp, tmp, name, mut dec, is_required)
dec.writeln('\tOption_$field_type $tmp = $dec_name (jsonroot_$tmp);')
dec.writeln('\t${option_name}_$field_type $tmp = $dec_name (jsonroot_$tmp);')
dec.writeln('\tif(${tmp}.state != 0) {')
dec.writeln('\t\treturn (Option_$styp){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t\treturn (${option_name}_$styp){ .state = ${tmp}.state, .err = ${tmp}.err, .data = {0} };')
dec.writeln('\t}')
}
@ -493,10 +493,10 @@ fn (mut g Gen) decode_array(value_type ast.Type) string {
s = '$styp val = ${fn_name}((cJSON *)jsval); '
} else {
s = '
Option_$styp val2 = $fn_name ((cJSON *)jsval);
${option_name}_$styp val2 = $fn_name ((cJSON *)jsval);
if(val2.state != 0) {
array_free(&res);
return *(Option_Array_$styp*)&val2;
return *(${option_name}_Array_$styp*)&val2;
}
$styp val = *($styp*)val2.data;
'
@ -504,7 +504,7 @@ fn (mut g Gen) decode_array(value_type ast.Type) string {
noscan := g.check_noscan(value_type)
return '
if(root && !cJSON_IsArray(root) && !cJSON_IsNull(root)) {
return (Option_Array_$styp){.state = 2, .err = _v_error(string__plus(_SLIT("Json element is not an array: "), tos2((byteptr)cJSON_PrintUnformatted(root)))), .data = {0}};
return (${option_name}_Array_$styp){.state = 2, .err = _v_error(string__plus(_SLIT("Json element is not an array: "), tos2((byteptr)cJSON_PrintUnformatted(root)))), .data = {0}};
}
res = __new_array${noscan}(0, 0, sizeof($styp));
const cJSON *jsval = NULL;
@ -538,17 +538,17 @@ fn (mut g Gen) decode_map(key_type ast.Type, value_type ast.Type) string {
s = '$styp_v val = $fn_name_v (js_get(root, jsval->string));'
} else {
s = '
Option_$styp_v val2 = $fn_name_v (js_get(root, jsval->string));
${option_name}_$styp_v val2 = $fn_name_v (js_get(root, jsval->string));
if(val2.state != 0) {
map_free(&res);
return *(Option_Map_${styp}_$styp_v*)&val2;
return *(${option_name}_Map_${styp}_$styp_v*)&val2;
}
$styp_v val = *($styp_v*)val2.data;
'
}
return '
if(!cJSON_IsObject(root) && !cJSON_IsNull(root)) {
return (Option_Map_${styp}_$styp_v){ .state = 2, .err = _v_error(string__plus(_SLIT("Json element is not an object: "), tos2((byteptr)cJSON_PrintUnformatted(root)))), .data = {0}};
return (${option_name}_Map_${styp}_$styp_v){ .state = 2, .err = _v_error(string__plus(_SLIT("Json element is not an object: "), tos2((byteptr)cJSON_PrintUnformatted(root)))), .data = {0}};
}
res = new_map(sizeof($styp), sizeof($styp_v), $hash_fn, $key_eq_fn, $clone_fn, $free_fn);
cJSON *jsval = NULL;

View File

@ -77,11 +77,11 @@ fn (mut g Gen) sql_stmt_line(nd ast.SqlStmtLine, expr string) {
}
if node.kind == .create {
g.write('Option_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('${option_name}_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.sql_create_table(node, expr, table_name)
subs = true
} else if node.kind == .drop {
g.write('Option_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('${option_name}_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.writeln('drop(${expr}._object, _SLIT("$table_name"));')
subs = true
} else if node.kind == .insert {
@ -90,10 +90,10 @@ fn (mut g Gen) sql_stmt_line(nd ast.SqlStmtLine, expr string) {
g.sql_insert(node, expr, table_name, arr, res, '', false, '')
dcheck = true
} else if node.kind == .update {
g.write('Option_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('${option_name}_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.sql_update(node, expr, table_name)
} else if node.kind == .delete {
g.write('Option_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('${option_name}_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.sql_delete(node, expr, table_name)
}
if !dcheck {
@ -185,7 +185,7 @@ fn (mut g Gen) sql_insert(node ast.SqlStmtLine, expr string, table_name string,
g.writeln('array_push(&$last_ids_arr, _MOV((orm__Primitive[]){orm__Connection_name_table[${expr}._typ]._method_last_id(${expr}._object)}));')
}
g.write('Option_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('${option_name}_void $res = orm__Connection_name_table[${expr}._typ]._method_')
g.write('insert(${expr}._object, _SLIT("$table_name"), (orm__QueryData){')
g.write('.fields = new_array_from_c_array($fields.len, $fields.len, sizeof(string),')
@ -551,7 +551,7 @@ fn (mut g Gen) sql_select(node ast.SqlExpr, expr string, left string) {
res := g.new_tmp_var()
table_name := g.get_table_name(node.table_expr)
g.sql_table_name = g.table.sym(node.table_expr.typ).name
g.write('Option_Array_Array_orm__Primitive _o$res = orm__Connection_name_table[${expr}._typ]._method_select(${expr}._object, ')
g.write('${option_name}_Array_Array_orm__Primitive _o$res = orm__Connection_name_table[${expr}._typ]._method_select(${expr}._object, ')
g.write('(orm__SelectConfig){')
g.write('.table = _SLIT("$table_name"),')
g.write('.is_count = $node.is_count,')

View File

@ -3,7 +3,7 @@
{1, { .str=(byteptr)("embed.vv"), .len=8, .is_lit=1 }, { .str=(byteptr)("none"), .len=4, .is_lit=1 }, _v_embed_blob_1},
VV_LOCAL_SYMBOL void v__preludes__embed_file__zlib__init(void);
VV_LOCAL_SYMBOL Option_Array_u8 v__preludes__embed_file__zlib__ZLibDecoder_decompress(v__preludes__embed_file__zlib__ZLibDecoder _d1, Array_u8 data) {
VV_LOCAL_SYMBOL _option_Array_u8 v__preludes__embed_file__zlib__ZLibDecoder_decompress(v__preludes__embed_file__zlib__ZLibDecoder _d1, Array_u8 data) {
= compress__zlib__decompress(data);
res.compressed = v__embed_file__find_index_entry_by_path((voidptr)_v_embed_file_index, _SLIT("embed.vv"), _SLIT("zlib"))->data;

View File

@ -23,6 +23,7 @@ const (
'int_literal', 'float_literal', 'bool', 'string', 'map', 'array', 'rune', 'any', 'voidptr']
shallow_equatables = [ast.Kind.i8, .i16, .int, .i64, .u8, .u16, .u32, .u64, .f32, .f64,
.int_literal, .float_literal, .bool, .string]
option_name = '_option'
)
struct SourcemapHelper {
@ -899,7 +900,7 @@ fn (mut g JsGen) expr(node_ ast.Expr) {
// TODO
}
ast.CharLiteral {
if utf8_str_len(node.val) < node.val.len {
if node.val.len_utf8() < node.val.len {
g.write("new rune('$node.val'.charCodeAt())")
} else {
g.write("new u8('$node.val')")
@ -1870,7 +1871,7 @@ fn (mut g JsGen) gen_return_stmt(it ast.Return) {
if fn_return_is_optional {
optional_none := node.exprs[0] is ast.None
ftyp := g.typ(node.types[0])
mut is_regular_option := ftyp == 'Option'
mut is_regular_option := ftyp == js.option_name
if optional_none || is_regular_option || node.types[0] == ast.error_type_idx {
if !isnil(g.fn_decl) && g.fn_decl.is_test {
test_error_var := g.new_tmp_var()
@ -1895,7 +1896,7 @@ fn (mut g JsGen) gen_return_stmt(it ast.Return) {
tmp := g.new_tmp_var()
g.write('const $tmp = new ')
g.writeln('Option({});')
g.writeln('${js.option_name}({});')
g.write('${tmp}.state = new u8(0);')
g.write('${tmp}.data = ')
if it.exprs.len == 1 {

View File

@ -35,6 +35,7 @@ pub fn mark_used(mut table ast.Table, pref &pref.Preferences, ast_files []&ast.F
'tos3',
'isnil',
'opt_ok',
'opt_ok2',
'error',
// utf8_str_visible_length is used by c/str.v
'utf8_str_visible_length',