arxlang / astx

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

`IfExpr` - Represents an if expression (e.g., in Rust). #93

Open xmnlab opened 2 days ago

xmnlab commented 2 days ago

suggestion from gpt:


# Add this code to src/astx/datatypes.py

from typing import Optional
from astx.base import (
    NO_SOURCE_LOCATION,
    ASTKind,
    DataTypeOps,
    ExprType,
    SourceLocation,
    ASTNodes,
)
from astx.types import ReprStruct
from public import public

@public
class IfExpr(DataTypeOps):
    """AST class for the 'if' expression."""

    condition: DataTypeOps
    then_expr: DataTypeOps
    else_expr: DataTypeOps
    type_: ExprType

    def __init__(
        self,
        condition: DataTypeOps,
        then_expr: DataTypeOps,
        else_expr: DataTypeOps,
        loc: SourceLocation = NO_SOURCE_LOCATION,
        parent: Optional[ASTNodes] = None,
    ) -> None:
        """Initialize the IfExpr instance."""
        super().__init__(loc=loc, parent=parent)
        self.condition = condition
        self.then_expr = then_expr
        self.else_expr = else_expr
        self.kind = ASTKind.IfExprKind  # We'll add this to ASTKind
        self.type_ = self._infer_type()
        self.loc = loc
        self.parent = parent

    def _infer_type(self) -> ExprType:
        """Infer the resulting type of the IfExpr."""
        if self.then_expr.type_ == self.else_expr.type_:
            return self.then_expr.type_
        else:
            # Implement logic to determine the resulting type
            # For simplicity, we can choose a common ancestor or promote types
            return AnyExpr

    def __str__(self) -> str:
        """Return a string that represents the object."""
        return f"IfExpr({self.condition}, {self.then_expr}, {self.else_expr})"

    def get_struct(self, simplified: bool = False) -> ReprStruct:
        """Return the AST structure of the object."""
        key = "IfExpr"
        value = {
            "condition": self.condition.get_struct(simplified),
            "then": self.then_expr.get_struct(simplified),
            "else": self.else_expr.get_struct(simplified),
        }
        return self._prepare_struct(key, value, simplified)
xmnlab commented 1 day ago

not sure about the usage of DataTypeOps .. but we can discuss that