From 2369a5c8c6e38d0619ab2b483ab92c58024e064a Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 14 May 2020 16:56:45 +0200 Subject: [PATCH] cgen: handle `is` for interfaces --- vlib/v/gen/cgen.v | 9 +++++++-- vlib/v/tests/interface_test.v | 13 ++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 1274e89b46..c30f3f3694 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -325,7 +325,7 @@ fn (g &Gen) base_type(t table.Type) string { fn (mut g Gen) register_optional(t table.Type, styp string) { // g.typedefs2.writeln('typedef Option $x;') - no_ptr := styp.replace('*','_ptr') + no_ptr := styp.replace('*', '_ptr') g.hotcode_definitions.writeln('typedef struct { $styp data; string error; @@ -3260,7 +3260,12 @@ fn (mut g Gen) is_expr(node ast.InfixExpr) { } else { g.write('.') } - g.write('typ == ') + sym := g.table.get_type_symbol(node.left_type) + if sym.kind == .interface_ { + g.write('_interface_idx == ') + } else if sym.kind == .sum_type { + g.write('typ == ') + } g.expr(node.right) } diff --git a/vlib/v/tests/interface_test.v b/vlib/v/tests/interface_test.v index 68391a7d2e..0480a8d4cc 100644 --- a/vlib/v/tests/interface_test.v +++ b/vlib/v/tests/interface_test.v @@ -26,7 +26,7 @@ fn (c Cat) name_detailed(pet_name string) string { return '$pet_name the ${typeof(c)}, breed:${c.breed}' } -fn (c mut Cat) set_breed(new string) { +fn (mut c Cat) set_breed(new string) { c.breed = new } @@ -49,12 +49,11 @@ fn (d Dog) name_detailed(pet_name string) string { return '$pet_name the ${typeof(d)}, breed:${d.breed}' } -fn (d mut Dog) set_breed(new string) { +fn (mut d Dog) set_breed(new string) { println('Nah') } // do not add to Dog the utility function 'str', so the default one will be used, as a sample - fn test_todo() { if true { } else { @@ -66,9 +65,9 @@ fn perform_speak(a Animal) { assert true name := a.name() assert name == 'Dog' || name == 'Cat' - // if a is Dog { - // assert name == 'Dog' - // } + if a is Dog { + assert name == 'Dog' + } println(a.name()) println('Got animal of type: ${typeof(a)}') // TODO: get implementation type (if possible) // assert a is Dog || a is Cat // TODO: enable when available @@ -151,7 +150,7 @@ fn test_perform_name_detailed() { perform_speak(cat_persian2) cat_persian2_str := cat_persian2.str() println("Persian Cat 2: '$cat_persian2_str' ...") - assert cat_persian2_str == "Custom string conversion for Cat: Persian" + assert cat_persian2_str == 'Custom string conversion for Cat: Persian' println('Test (dummy/empty) on array of animals ...') handle_animals([dog, cat]) handle_animals_mutable([dog, cat])