Skip to content

Commit 2c4c70d

Browse files
authored
Merge pull request #1916 from Smit-create/i-1914
ASR: Allow importing union
2 parents 4a87aab + 072712f commit 2c4c70d

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

integration_tests/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,8 @@ RUN(NAME enum_07 IMPORT_PATH ..
561561
RUN(NAME union_01 LABELS cpython llvm c)
562562
RUN(NAME union_02 LABELS llvm c)
563563
RUN(NAME union_03 LABELS cpython llvm c)
564+
RUN(NAME union_04 IMPORT_PATH ..
565+
LABELS cpython llvm c)
564566
RUN(NAME test_str_to_int LABELS cpython llvm c)
565567
RUN(NAME test_platform LABELS cpython llvm c)
566568
RUN(NAME test_vars_01 LABELS cpython llvm)

integration_tests/union_04.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from union_01 import u_type
2+
from lpython import f32, f64, i64
3+
4+
# Test taken from union_01.py but checks importing union
5+
6+
def test_union_04():
7+
unionobj: u_type = u_type()
8+
unionobj.integer32 = 1
9+
print(unionobj.integer32)
10+
assert unionobj.integer32 == 1
11+
12+
unionobj.real32 = f32(2.0)
13+
print(unionobj.real32)
14+
assert abs(f64(unionobj.real32) - 2.0) <= 1e-6
15+
16+
unionobj.real64 = 3.5
17+
print(unionobj.real64)
18+
assert abs(unionobj.real64 - 3.5) <= 1e-12
19+
20+
unionobj.integer64 = i64(4)
21+
print(unionobj.integer64)
22+
assert unionobj.integer64 == i64(4)
23+
24+
test_union_04()

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,20 @@ ASR::symbol_t* import_from_module(Allocator &al, ASR::Module_t *m, SymbolTable *
483483
ASR::accessType::Public
484484
);
485485
return ASR::down_cast<ASR::symbol_t>(est);
486+
} else if (ASR::is_a<ASR::UnionType_t>(*t)) {
487+
ASR::UnionType_t *ut = ASR::down_cast<ASR::UnionType_t>(t);
488+
Str name;
489+
name.from_str(al, new_sym_name);
490+
char *cname = name.c_str(al);
491+
ASR::asr_t *est = ASR::make_ExternalSymbol_t(
492+
al, loc,
493+
/* a_symtab */ current_scope,
494+
/* a_name */ cname,
495+
(ASR::symbol_t*)ut,
496+
m->m_name, nullptr, 0, ut->m_name,
497+
ASR::accessType::Public
498+
);
499+
return ASR::down_cast<ASR::symbol_t>(est);
486500
} else if (ASR::is_a<ASR::Variable_t>(*t)) {
487501
ASR::Variable_t *mv = ASR::down_cast<ASR::Variable_t>(t);
488502
// `mv` is the Variable in a module. Now we construct

0 commit comments

Comments
 (0)