Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add TypeCastExpr class #130

Merged
merged 17 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/astx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
LiteralUInt128,
Number,
SignedInteger,
TypeCastExpr,
UInt8,
UInt16,
UInt32,
Expand Down Expand Up @@ -203,6 +204,7 @@ def get_version() -> str:
"StatementType",
"symbol_table",
"Target",
"TypeCastExpr",
"UnaryOp",
"Undefined",
"VariableAssignment",
Expand Down
1 change: 1 addition & 0 deletions src/astx/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ class ASTKind(Enum):
ImportFromExprKind = -801

LambdaExprKind = -807
TypeCastExprKind = -809


class ASTMeta(type):
Expand Down
39 changes: 38 additions & 1 deletion src/astx/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

from typing import Any
from typing import Any, Optional
from uuid import uuid4

from public import public
Expand All @@ -11,7 +11,9 @@
from astx.base import (
NO_SOURCE_LOCATION,
ASTKind,
ASTNodes,
DataType,
Expr,
ExprType,
ReprStruct,
SourceLocation,
Expand Down Expand Up @@ -679,3 +681,38 @@ def __init__(
"""Initialize LiteralComplex64."""
super().__init__(Complex64(real, imag), loc)
self.type_ = Complex64


@public
@typechecked
class TypeCastExpr(Expr):
"""AST class for type casting expressions."""

expr: Expr
target_type: DataType

def __init__(
self,
expr: Expr,
target_type: DataType,
loc: SourceLocation = SourceLocation(-1, -1),
parent: Optional[ASTNodes] = None,
) -> None:
super().__init__(loc=loc, parent=parent)
self.expr = expr
self.target_type = target_type
self.kind = ASTKind.TypeCastExprKind

def __str__(self) -> str:
"""Return a string representation of the TypeCast expression."""
return f"TypeCastExpr ({self.expr}, {self.target_type})"

def get_struct(self, simplified: bool = False) -> ReprStruct:
"""Return the AST structure of the TypeCast expression."""
key = "TypeCastExpr"
value: ReprStruct = {
"expression": self.expr.get_struct(),
"target_type": self.target_type.get_struct(),
}

return self._prepare_struct(key, value, simplified)
5 changes: 5 additions & 0 deletions src/astx/transpilers/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ def visit(self, node: astx.LambdaExpr) -> str:
params_str = ", ".join(param.name for param in node.params)
return f"lambda {params_str}: {self.visit(node.body)}"

@dispatch # type: ignore[no-redef]
def visit(self, node: astx.TypeCastExpr) -> str:
"""Handle TypeCastExpr nodes."""
return f"cast({node.target_type.__class__.__name__}, {node.expr.name})"
apkrelling marked this conversation as resolved.
Show resolved Hide resolved

@dispatch # type: ignore[no-redef]
def visit(self, node: astx.UnaryOp) -> str:
"""Handle UnaryOp nodes."""
Expand Down
2 changes: 1 addition & 1 deletion src/astx/viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
_AsciiGraphProxy,
)
from graphviz import Digraph
from IPython.display import Image, display
from IPython.display import Image, display # type: ignore[attr-defined]
from msgpack import dumps, loads

from astx.base import DictDataTypesStruct, ReprStruct
Expand Down
25 changes: 25 additions & 0 deletions tests/test_datatypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Tests for complex number data types."""

from __future__ import annotations

from astx.datatypes import Int32, TypeCastExpr
from astx.variables import Variable
from astx.viz import visualize


def test_typecastexpr() -> None:
"""Test TypeCastExpr."""
# Expression to cast
expr = Variable(name="x")

# Target type for casting
target_type = Int32()

# Create the TypeCastExpr
cast_expr = TypeCastExpr(expr=expr, target_type=target_type)

assert str(cast_expr)
assert cast_expr.get_struct()
assert cast_expr.get_struct(simplified=True)

visualize(cast_expr.get_struct())
21 changes: 21 additions & 0 deletions tests/transpilers/test_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,3 +371,24 @@ def test_literal_complex64() -> None:
assert (
generated_code == expected_code
), f"Expected '{expected_code}', but got '{generated_code}'"


def test_transpiler_typecastexpr() -> None:
"""Test astx.TypeCastExpr."""
# Expression to cast
expr = astx.Variable(name="x")
# Target type for casting
target_type = astx.Int32()
# Create the TypeCastExpr
cast_expr = astx.TypeCastExpr(expr=expr, target_type=target_type)

# Initialize the generator
generator = astx2py.ASTxPythonTranspiler()

# Generate Python code
generated_code = generator.visit(cast_expr)
expected_code = "cast(Int32, x)"
apkrelling marked this conversation as resolved.
Show resolved Hide resolved

assert (
generated_code == expected_code
), f"Expected '{expected_code}', but got '{generated_code}'"
Loading