astx.blocks: Contains the Block class for sequences of statements.
astx.modifiers: Contains enums for VisibilityKind, MutabilityKind, and ScopeKind.
astx.datatypes: Contains data type classes and operations.
astx.types: Contains type aliases and structures.
Conventions:
Statements: Classes representing statements inherit from StatementType.
Expressions: Classes representing expressions inherit from Expr.
AST Kinds: Node kinds are defined in ASTKind for downcasting.
Modifiers: Use VisibilityKind, MutabilityKind, and ScopeKind for attributes.
Designing the EnumDeclarationStmt Class
We need to design an EnumDeclarationStmt class that:
Inherits from StatementType since an enum declaration is a statement.
Contains the necessary attributes to represent an enum declaration.
Integrates with existing structures (e.g., modifiers, expressions, blocks).
Is added to the ASTKind enum.
Fits into the module structure, possibly in astx/classes.py or a new astx/enums.py.
Given that astx/classes.py is meant for class-related AST nodes, and enums are similar to classes in many languages, we can include EnumDeclarationStmt in astx/classes.py. Alternatively, if you prefer to separate them, we can create a new module astx/enums.py.
For consistency, we'll include it in astx/classes.py.
1. Updating ASTKind Enum
First, we need to add a new kind for the enum declaration.
In astx/base.py, add:
# astx/base.py
@public
class ASTKind(Enum):
"""The expression kind class used for downcasting."""
# ... existing kinds ...
# Class and Enum statements
ClassDeclarationKind = -700
ClassDefinitionKind = -701
EnumDeclarationKind = -702
# ... rest of the code ...
2. Defining EnumDeclarationStmt
In astx/classes.py, add the following:
# astx/classes.py
from typing import Dict, Union
from astx.variables import Variable
from astx.datatypes import Literal
# ... existing imports ...
@public
class EnumDeclarationStmt(StatementType):
"""AST class for enum declaration."""
name: str
values: Dict[str, Union[int, str, float, Literal]]
decorators: List[Expr]
visibility: VisibilityKind
def __init__(
self,
name: str,
values: Dict[str, Union[int, str, float, Literal]],
decorators: Optional[List[Expr]] = None,
visibility: VisibilityKind = VisibilityKind.public,
loc: SourceLocation = NO_SOURCE_LOCATION,
parent: Optional[ASTNodes] = None,
) -> None:
super().__init__(loc=loc, parent=parent)
self.name = name
self.values = values
self.decorators = decorators or []
self.visibility = visibility
self.kind = ASTKind.EnumDeclarationKind
def __str__(self) -> str:
decorators_str = "".join(f"@{decorator}\n" for decorator in self.decorators)
visibility_str = self.visibility.name.lower() if self.visibility != VisibilityKind.public else ""
enum_header = f"{visibility_str} enum {self.name}".strip()
values_str = ",\n ".join(f"{key} = {value}" for key, value in self.values.items())
return f"{decorators_str}{enum_header} {{\n {values_str}\n}}"
def get_struct(self, simplified: bool = False) -> ReprStruct:
key = f"EnumDeclaration[{self.name}]"
value = {
"visibility": self.visibility.name.lower(),
"values": {k: v if isinstance(v, (int, float, str)) else v.get_struct(simplified) for k, v in self.values.items()},
"decorators": [decorator.get_struct(simplified) for decorator in self.decorators],
}
return self._prepare_struct(key, value, simplified)
Explanation:
Inheritance: Inherits from StatementType since an enum declaration is a statement.
Attributes:
name: The enum name.
values: A dictionary mapping enum member names to their values.
decorators: List of decorators (Expr instances).
visibility: Access modifier from VisibilityKind.
Methods:
__str__: Provides a readable string representation.
get_struct: Returns a structured representation suitable for serialization.
Notes:
The values can be simple types (int, str, float) or Literal instances for consistency.
The decorators and visibility attributes are optional, with defaults.
3. Updating astx/__init__.py
Add the EnumDeclarationStmt to your package's __init__.py:
public enum Size {
SMALL = Literal[String]: S,
MEDIUM = Literal[String]: M,
LARGE = Literal[String]: L
}
Integration with Existing Structures
Modifiers: Uses VisibilityKind from astx.modifiers for access modifiers.
Expressions: Decorators are Expr instances, consistent with other parts of your codebase.
Literals: Enum values can be Literal instances from astx.datatypes.
Updating LiteralString Class
Since the LiteralString class was not previously defined in astx.datatypes, let's define it to represent string literals.
In astx/datatypes.py, add:
@public
class LiteralString(Literal):
"""LiteralString data type class."""
value: str
def __init__(
self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION
) -> None:
"""Initialize LiteralString."""
super().__init__(loc)
self.value = value
self.type_ = String
self.loc = loc
@public
class String(DataType):
"""String data type expression."""
Explanation:
String Class: Represents the string data type.
LiteralString Class: Represents string literals, inheriting from Literal.
Testing and Validation
Unit Tests: Write tests to create instances of EnumDeclarationStmt with various configurations.
Integration Tests: Ensure that EnumDeclarationStmt integrates correctly with the rest of the astx framework.
Visualization: Use astx.viz to visualize the AST of the enum declarations.
Documentation
Docstrings: Ensure all new classes and methods have clear docstrings.
Module Documentation: Update your module's documentation to include the new EnumDeclarationStmt class.
Conclusion
By creating the EnumDeclarationStmt class, we've extended your astx module to support enum declarations. This class fits naturally into your existing framework, utilizing existing components and following your established conventions.
Next Steps
Implement: Add the EnumDeclarationStmt class and any supporting classes to your codebase.
Test: Write tests to verify the functionality and integration.
Refine: Adjust the class as needed based on your specific requirements.
Full Code for astx/classes.py with EnumDeclarationStmt
Here's the complete code for astx/classes.py, including the EnumDeclarationStmt:
# astx/classes.py
from __future__ import annotations
from typing import Optional, List, Dict, Union
from public import public
from astx.base import (
NO_SOURCE_LOCATION,
ASTKind,
ASTNodes,
Expr,
SourceLocation,
StatementType,
)
from astx.types import ReprStruct
from astx.modifiers import VisibilityKind
from astx.blocks import Block
from astx.variables import Variable
from astx.datatypes import Literal
@public
class ClassDeclarationStmt(StatementType):
# ... existing code for ClassDeclarationStmt ...
@public
class ClassDefinitionStmt(ClassDeclarationStmt):
# ... existing code for ClassDefinitionStmt ...
@public
class EnumDeclarationStmt(StatementType):
"""AST class for enum declaration."""
name: str
values: Dict[str, Union[int, str, float, Literal]]
decorators: List[Expr]
visibility: VisibilityKind
def __init__(
self,
name: str,
values: Dict[str, Union[int, str, float, Literal]],
decorators: Optional[List[Expr]] = None,
visibility: VisibilityKind = VisibilityKind.public,
loc: SourceLocation = NO_SOURCE_LOCATION,
parent: Optional[ASTNodes] = None,
) -> None:
super().__init__(loc=loc, parent=parent)
self.name = name
self.values = values
self.decorators = decorators or []
self.visibility = visibility
self.kind = ASTKind.EnumDeclarationKind
def __str__(self) -> str:
decorators_str = "".join(f"@{decorator}\n" for decorator in self.decorators)
visibility_str = self.visibility.name.lower() if self.visibility != VisibilityKind.public else ""
enum_header = f"{visibility_str} enum {self.name}".strip()
values_str = ",\n ".join(f"{key} = {value}" for key, value in self.values.items())
return f"{decorators_str}{enum_header} {{\n {values_str}\n}}"
def get_struct(self, simplified: bool = False) -> ReprStruct:
key = f"EnumDeclaration[{self.name}]"
value = {
"visibility": self.visibility.name.lower(),
"values": {k: v if isinstance(v, (int, float, str)) else v.get_struct(simplified) for k, v in self.values.items()},
"decorators": [decorator.get_struct(simplified) for decorator in self.decorators],
}
return self._prepare_struct(key, value, simplified)
Implementing LiteralString and String in astx/datatypes.py
# astx/datatypes.py
# ... existing imports and classes ...
@public
class String(DataType):
"""String data type expression."""
@public
class LiteralString(Literal):
"""LiteralString data type class."""
value: str
def __init__(
self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION
) -> None:
"""Initialize LiteralString."""
super().__init__(loc)
self.value = value
self.type_ = String
self.loc = loc
Final Notes
Ensure that all necessary imports are included in each module.
Update any documentation or comments to reflect these additions.
Test the new classes thoroughly to ensure they behave as expected.
from gpt:
Understanding the Existing Structure
Based on the modules you've provided, here's a summary of key points relevant to creating the
EnumDeclarationStmt
class:Base Classes and Enums:
AST
: The root class for all AST nodes (astx/base.py
).StatementType
: Inherits fromAST
, used for statements.Expr
: Inherits fromAST
, used for expressions.ASTKind
: An enumeration of different AST node kinds.Modules:
astx.base
: Contains base classes and fundamental definitions.astx.callables
: Contains function-related classes.astx.variables
: Contains variable-related classes.astx.blocks
: Contains theBlock
class for sequences of statements.astx.modifiers
: Contains enums forVisibilityKind
,MutabilityKind
, andScopeKind
.astx.datatypes
: Contains data type classes and operations.astx.types
: Contains type aliases and structures.Conventions:
StatementType
.Expr
.ASTKind
for downcasting.VisibilityKind
,MutabilityKind
, andScopeKind
for attributes.Designing the
EnumDeclarationStmt
ClassWe need to design an
EnumDeclarationStmt
class that:StatementType
since an enum declaration is a statement.ASTKind
enum.astx/classes.py
or a newastx/enums.py
.Given that
astx/classes.py
is meant for class-related AST nodes, and enums are similar to classes in many languages, we can includeEnumDeclarationStmt
inastx/classes.py
. Alternatively, if you prefer to separate them, we can create a new moduleastx/enums.py
.For consistency, we'll include it in
astx/classes.py
.1. Updating
ASTKind
EnumFirst, we need to add a new kind for the enum declaration.
In
astx/base.py
, add:2. Defining
EnumDeclarationStmt
In
astx/classes.py
, add the following:Explanation:
StatementType
since an enum declaration is a statement.name
: The enum name.values
: A dictionary mapping enum member names to their values.decorators
: List of decorators (Expr
instances).visibility
: Access modifier fromVisibilityKind
.__str__
: Provides a readable string representation.get_struct
: Returns a structured representation suitable for serialization.values
can be simple types (int
,str
,float
) orLiteral
instances for consistency.decorators
andvisibility
attributes are optional, with defaults.3. Updating
astx/__init__.py
Add the
EnumDeclarationStmt
to your package's__init__.py
:Example Usage
1. Creating an Enum Declaration
Output:
2. Enum with String Values
Output:
Integration with Existing Structures
VisibilityKind
fromastx.modifiers
for access modifiers.Expr
instances, consistent with other parts of your codebase.Literal
instances fromastx.datatypes
.Updating
LiteralString
ClassSince the
LiteralString
class was not previously defined inastx.datatypes
, let's define it to represent string literals.In
astx/datatypes.py
, add:Explanation:
String
Class: Represents the string data type.LiteralString
Class: Represents string literals, inheriting fromLiteral
.Testing and Validation
EnumDeclarationStmt
with various configurations.EnumDeclarationStmt
integrates correctly with the rest of theastx
framework.astx.viz
to visualize the AST of the enum declarations.Documentation
EnumDeclarationStmt
class.Conclusion
By creating the
EnumDeclarationStmt
class, we've extended yourastx
module to support enum declarations. This class fits naturally into your existing framework, utilizing existing components and following your established conventions.Next Steps
EnumDeclarationStmt
class and any supporting classes to your codebase.Full Code for
astx/classes.py
withEnumDeclarationStmt
Here's the complete code for
astx/classes.py
, including theEnumDeclarationStmt
:Implementing
LiteralString
andString
inastx/datatypes.py
Final Notes