Skip to content

Commit

Permalink
getting type from tuple
Browse files Browse the repository at this point in the history
  • Loading branch information
nucccc committed Mar 27, 2024
1 parent 5e21247 commit a22daa2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
17 changes: 17 additions & 0 deletions markarth/convert/collect/ast_to_typ/ast_to_typ.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ def ast_val_to_typ(
return typ_from_constant(val)
if type(val) == ast.BinOp:
return typ_from_bin_op(val, var_tracker)
if type(val) == ast.Tuple:
return typ_from_tuple(ast_tup = val, var_tracker = var_tracker)
if var_tracker is not None:
if type(val) == ast.Name:
supposed_typ = var_tracker.get_vartyp( val.id )
Expand Down Expand Up @@ -123,6 +125,7 @@ def typ_from_call(
return call_type
return typs.TypAny()


def typ_from_iter(iter_stat : ast.AST) -> typs.Typ:
'''
type_from_iter shall get the type of a variable "extracted"
Expand All @@ -139,3 +142,17 @@ def typ_from_iter(iter_stat : ast.AST) -> typs.Typ:
typs.TypAny()
])
return typs.TypAny()


def typ_from_tuple(
ast_tup : ast.Tuple,
var_tracker : VarTypTracker | None = None
) -> typs.TypTuple:
'''
typ_from_tuple returns a tuple typ from an ast tuple statement
'''
# for each of the tuple's elements i gather their typ
inner_typs = [
ast_val_to_typ(elt, var_tracker) for elt in ast_tup.elts
]
return typs.TypTuple(inner_typs = inner_typs)
36 changes: 34 additions & 2 deletions tests/test_ast_to_typ.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
typ_from_iter,
typ_from_call,
ast_val_to_typ,
eval_op_typ
eval_op_typ,
typ_from_tuple
)
from markarth.convert.collect.vartyp_tracker import VarTypTracker
from markarth.convert.typs import typs


Expand Down Expand Up @@ -226,4 +228,34 @@ def test_typ_from_call():
call = mod.body[0].value

call_typ = typ_from_call(call = call)
assert call_typ.is_any()
assert call_typ.is_any()


def test_typ_from_tuple():
code = 'a = (4, 5, 6.11)'
mod = ast.parse(code)
ast_tup = mod.body[0].value

typ = typ_from_tuple(ast_tup = ast_tup)

assert typ.is_tuple()
assert len(typ.inner_typs) == 3
assert typ.inner_typs[0].is_int()
assert typ.inner_typs[1].is_int()
assert typ.inner_typs[2].is_float()


def test_typ_from_tuple_with_vartracker():
code = 'a = (4, a, 6.11)'
mod = ast.parse(code)
ast_tup = mod.body[0].value
vartyp_tracker = VarTypTracker()
vartyp_tracker.add_local_typ('a', typs.TypPrimitive(typs.PrimitiveCod.BOOL))

typ = typ_from_tuple(ast_tup = ast_tup, var_tracker = vartyp_tracker)

assert typ.is_tuple()
assert len(typ.inner_typs) == 3
assert typ.inner_typs[0].is_int()
assert typ.inner_typs[1].is_bool()
assert typ.inner_typs[2].is_float()

0 comments on commit a22daa2

Please sign in to comment.