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

Lambdaexpr #123

Merged
merged 9 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -36,6 +36,7 @@
FunctionCall,
FunctionPrototype,
FunctionReturn,
LambdaExpr,
)
from astx.datatypes import (
Boolean,
Expand Down Expand Up @@ -173,6 +174,7 @@ def get_version() -> str:
"UInt32",
"UInt64",
"UInt128",
"LambdaExpr",
"Literal",
"LiteralBoolean",
"LiteralInt8",
Expand Down
2 changes: 2 additions & 0 deletions src/astx/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ class ASTKind(Enum):
ImportExprKind = -800
ImportFromExprKind = -801

LambdaExprKind = -807


class ASTMeta(type):
def __str__(cls) -> str:
Expand Down
34 changes: 34 additions & 0 deletions src/astx/callables.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,37 @@ def get_struct(self, simplified: bool = False) -> ReprStruct:

value: ReprStruct = {**args_struct, **body_struct}
return self._prepare_struct(key, value, simplified)


@public
class LambdaExpr(Expr):
"""AST class for lambda expressions."""

params: Arguments = Arguments()
body: Expr

def __init__(
self,
body: Expr,
params: Arguments = Arguments(),
loc: SourceLocation = NO_SOURCE_LOCATION,
parent: Optional[ASTNodes] = None,
) -> None:
super().__init__(loc=loc, parent=parent)
self.params = params
self.body = body
self.kind = ASTKind.LambdaExprKind

def __str__(self) -> str:
"""Return a string representation of the lambda expression."""
params_str = ", ".join(param.name for param in self.params) # type: ignore[attr-defined]
return f"lambda {params_str}: {self.body}"

def get_struct(self, simplified: bool = False) -> ReprStruct:
"""Return the AST structure of the lambda expression."""
key = "LambdaExpr"
value: ReprStruct = {
"params": self.params.get_struct(simplified),
"body": self.body.get_struct(simplified),
}
return self._prepare_struct(key, value, simplified)
6 changes: 6 additions & 0 deletions src/astx/transpilers/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ def visit(self, node: astx.FunctionReturn) -> str:
value = self.visit(node.value) if node.value else ""
return f"return {value}"

@dispatch # type: ignore[no-redef]
def visit(self, node: astx.LambdaExpr) -> str:
"""Handle LambdaExpr nodes."""
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.UnaryOp) -> str:
"""Handle UnaryOp nodes."""
Expand Down
24 changes: 24 additions & 0 deletions tests/test_callables.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
FunctionCall,
FunctionPrototype,
FunctionReturn,
LambdaExpr,
)
from astx.datatypes import Int32, LiteralInt32
from astx.modifiers import ScopeKind, VisibilityKind
from astx.operators import BinaryOp
from astx.variables import Variable
from astx.viz import visualize


Expand Down Expand Up @@ -91,3 +94,24 @@ def test_function_return() -> None:
assert str(fn_return)
assert fn_return.get_struct()
assert fn_return.get_struct(simplified=True)


def test_lambdaexpr() -> None:
"""Test the LambdaExpr class."""
params = Arguments(Argument(name="x", type_=Int32))
body = BinaryOp(op_code="+", lhs=Variable(name="x"), rhs=LiteralInt32(1))
lambda_expr = LambdaExpr(params=params, body=body)

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


def test_lambdaexpr_noparams() -> None:
"""Test the LambdaExpr class without params."""
body = LiteralInt32(1)
lambda_expr = LambdaExpr(body=body)

assert str(lambda_expr)
assert lambda_expr.get_struct()
assert lambda_expr.get_struct(simplified=True)
37 changes: 37 additions & 0 deletions tests/transpilers/test_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,43 @@ def test_transpiler_relative_import_from_expr() -> None:
assert generated_code == expected_code, "generated_code != expected_code"


def test_transpiler_lambdaexpr() -> None:
"""Test astx.LambdaExpr."""
params = astx.Arguments(astx.Argument(name="x", type_=astx.Int32))
body = astx.BinaryOp(
op_code="+", lhs=astx.Variable(name="x"), rhs=astx.LiteralInt32(1)
)

lambda_expr = astx.LambdaExpr(params=params, body=body)

# Initialize the generator
generator = astx2py.ASTxPythonTranspiler()

# Generate Python code
generated_code = generator.visit(lambda_expr)

expected_code = "lambda x: (x + 1)"

assert generated_code == expected_code, "generated_code != expected_code"


def test_transpiler_lambdaexpr_noparams() -> None:
"""Test astx.LambdaExpr without params."""
body = astx.LiteralInt32(1)

lambda_expr = astx.LambdaExpr(body=body)

# Initialize the generator
generator = astx2py.ASTxPythonTranspiler()

# Generate Python code
generated_code = generator.visit(lambda_expr)

expected_code = "lambda : 1"

assert generated_code == expected_code, "generated_code != expected_code"


def test_transpiler_function() -> None:
"""Test astx.Function."""
# Function parameters
Expand Down