arxlang / astx

https://astx.arxlang.org/
Other
1 stars 4 forks source link

`LambdaExpr` - Represents a lambda or anonymous function expression. #104

Open xmnlab opened 1 month ago

xmnlab commented 1 month ago

from gpt:

1. Update ASTKind Enum in astx/base.py

Add the following line to your ASTKind enumeration to include the new LambdaExprKind:

@public
class ASTKind(Enum):
    # ... existing kinds ...

    LambdaExprKind = -807  # Add this line

2. Define LambdaExpr in astx/expressions.py

Add the following class definition to represent lambda expressions:

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

    params: Arguments  # You may need to import or define 'Arguments'
    body: Expr

    def __init__(
        self,
        params: Arguments,
        body: Expr,
        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

Notes:


3. Usage Example (Optional)

If you need to see how it might be used:

# Example usage (do not include in code if not needed)
from astx.expressions import LambdaExpr
from astx.callables import Arguments
from astx.datatypes import LiteralInt32

# Create parameters and body for the lambda
params = Arguments([Argument(name="x")])  # Assuming 'Argument' class exists
body = BinaryOp(op_code="+", lhs=Variable(name="x"), rhs=LiteralInt32(1))

# Create the LambdaExpr
lambda_expr = LambdaExpr(params=params, body=body)
xmnlab commented 5 days ago

just an idea for the get_struct and __str__ methods:


    def __str__(self) -> str:
        """Return a string representation of the lambda expression."""
        params_str = ", ".join(arg.name for arg in self.params.args)
        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)
xmnlab commented 4 days ago

Suggestion for the graphical/ascii representation:

       [LambdaExpr]
         |       | 
       params  body
        |        |
[Arguments (1)] [Expr]
      |
[Argument(myargname)] 

PS1: the final result could be different because it depends on the implementation. PS2: the values inside [] are ASTx nodes/classes

xmnlab commented 4 days ago

Examples of output for the python transpiler: