diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f916efba..c12a65c6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -49,6 +49,16 @@ repos: types: - python + - id: douki + name: douki + entry: douki sync + language: system + pass_filenames: true + require_serial: yes + files: "./" + types: + - python + - id: mypy name: mypy entry: mypy . diff --git a/libs/astx-transpilers/src/astx_transpilers/__init__.py b/libs/astx-transpilers/src/astx_transpilers/__init__.py index d4ef295e..b08cd6ac 100644 --- a/libs/astx-transpilers/src/astx_transpilers/__init__.py +++ b/libs/astx-transpilers/src/astx_transpilers/__init__.py @@ -1,10 +1,16 @@ -"""ASTx Transpilers.""" +""" +title: ASTx Transpilers. +""" from importlib import metadata as importlib_metadata def get_version() -> str: - """Return the program version.""" + """ + title: Return the program version. + returns: + type: str + """ try: return importlib_metadata.version(__name__) except importlib_metadata.PackageNotFoundError: # pragma: no cover diff --git a/libs/astx-transpilers/src/astx_transpilers/python_string.py b/libs/astx-transpilers/src/astx_transpilers/python_string.py index aad7d274..a2fb68b9 100644 --- a/libs/astx-transpilers/src/astx_transpilers/python_string.py +++ b/libs/astx-transpilers/src/astx_transpilers/python_string.py @@ -1,11 +1,11 @@ -"""ASTx to Python string transpiler (New Implementation).""" +""" +title: ASTx to Python string transpiler (New Implementation). +""" import ast import re import sys -from typing import Union - import astx from astx.tools.typing import typechecked @@ -16,19 +16,31 @@ @typechecked class ASTxPythonTranspiler: """ - Transpiler that converts ASTx nodes to Python source code strings. - - This transpiler uses the AST-based approach by first converting ASTx to - Python AST and then using ast.unparse() to generate the string - representation. + title: Transpiler that converts ASTx nodes to Python source code strings. + summary: |- + + This transpiler uses the AST-based approach by first converting ASTx to + Python AST and then using ast.unparse() to generate the string + representation. + attributes: + indent_level: + type: int + indent_str: + type: str + _ast_transpiler: + type: ASTxPythonASTTranspiler """ + indent_level: int + indent_str: str + _ast_transpiler: ASTxPythonASTTranspiler + def __init__(self) -> None: self.indent_level = 0 self.indent_str = " " self._ast_transpiler = ASTxPythonASTTranspiler() - def visit(self, node: Union[astx.AST, astx.ASTNodes]) -> str: # noqa: D102 + def visit(self, node: astx.AST | astx.ASTNodes) -> str: try: python_ast = self._ast_transpiler.visit(node) if sys.version_info >= (3, 9): @@ -65,7 +77,7 @@ def visit(self, node: Union[astx.AST, astx.ASTNodes]) -> str: # noqa: D102 except Exception as e: return f"# Error converting {type(node).__name__!s}: {e!s}" - def set_indent(self, level: int, indent_str: str = " ") -> None: # noqa: D102 + def set_indent(self, level: int, indent_str: str = " ") -> None: self.indent_level = level self.indent_str = indent_str diff --git a/libs/astx-transpilers/src/astx_transpilers/python_to_ast.py b/libs/astx-transpilers/src/astx_transpilers/python_to_ast.py index d6a089cf..5b868069 100644 --- a/libs/astx-transpilers/src/astx_transpilers/python_to_ast.py +++ b/libs/astx-transpilers/src/astx_transpilers/python_to_ast.py @@ -1,9 +1,11 @@ -"""ASTx to Python AST transpiler.""" +""" +title: ASTx to Python AST transpiler. +""" import ast import sys -from typing import Any, List, Optional, Union +from typing import Any, Optional import astx @@ -72,20 +74,36 @@ @typechecked class ASTxPythonASTTranspiler: """ - Transpiler that converts ASTx nodes to Python AST nodes. - - Notes - ----- - Please keep the visit method in alphabet order according to the node type. - The visit method for astx.AST should be the first one. + title: Transpiler that converts ASTx nodes to Python AST nodes. + summary: |- + + Notes + ----- + Please keep the visit method in alphabet order according to the node + type. + The visit method for astx.AST should be the first one. + attributes: + indent_level: + type: int """ + indent_level: int + def __init__(self) -> None: - """Initialize the transpiler.""" + """ + title: Initialize the transpiler. + """ self.indent_level = 0 def _convert_using_unparse(self, node: astx.AST) -> ast.AST: - """Convert an ASTx node to a Python AST node using fallback.""" + """ + title: Convert an ASTx node to a Python AST node using fallback. + parameters: + node: + type: astx.AST + returns: + type: ast.AST + """ try: # Simple fallback without circular import if hasattr(node, "value"): @@ -98,9 +116,16 @@ def _convert_using_unparse(self, node: astx.AST) -> ast.AST: return ast.Constant(value=f"<{type(node).__name__}>") def _convert_block( - self, block: Optional[Union[astx.ASTNodes, astx.Block]] - ) -> List[ast.stmt]: - """Convert a block of statements to Python AST nodes.""" + self, block: Optional[astx.ASTNodes | astx.Block] + ) -> list[ast.stmt]: + """ + title: Convert a block of statements to Python AST nodes. + parameters: + block: + type: Optional[astx.ASTNodes | astx.Block] + returns: + type: list[ast.stmt] + """ if not block: return [ast.Pass()] @@ -126,12 +151,26 @@ def _convert_block( @dispatch.abstract def visit(self, expr: astx.AST) -> ast.AST: - """Translate an ASTx node to a Python AST node.""" + """ + title: Translate an ASTx node to a Python AST node. + parameters: + expr: + type: astx.AST + returns: + type: ast.AST + """ raise Exception(f"Not implemented yet ({expr}).") @dispatch # type: ignore[no-redef] def visit(self, node: astx.AliasExpr) -> ast.alias: - """Handle AliasExpr nodes.""" + """ + title: Handle AliasExpr nodes. + parameters: + node: + type: astx.AliasExpr + returns: + type: ast.alias + """ if not hasattr(node, "name"): return ast.alias(name="", asname=None) return ast.alias( @@ -141,7 +180,14 @@ def visit(self, node: astx.AliasExpr) -> ast.alias: @dispatch # type: ignore[no-redef] def visit(self, node: astx.AndOp) -> ast.BoolOp: - """Handle AndOp nodes.""" + """ + title: Handle AndOp nodes. + parameters: + node: + type: astx.AndOp + returns: + type: ast.BoolOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) return ast.BoolOp( @@ -150,7 +196,14 @@ def visit(self, node: astx.AndOp) -> ast.BoolOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Argument) -> ast.arg: - """Handle Argument nodes.""" + """ + title: Handle Argument nodes. + parameters: + node: + type: astx.Argument + returns: + type: ast.arg + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) annotation = None @@ -160,7 +213,14 @@ def visit(self, node: astx.Argument) -> ast.arg: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Arguments) -> ast.arguments: - """Handle Arguments nodes.""" + """ + title: Handle Arguments nodes. + parameters: + node: + type: astx.Arguments + returns: + type: ast.arguments + """ if not hasattr(node, "nodes"): return self._convert_using_unparse(node) args = [self.visit(arg) for arg in node.nodes] @@ -176,7 +236,14 @@ def visit(self, node: astx.Arguments) -> ast.arguments: @dispatch # type: ignore[no-redef] def visit(self, node: astx.AssignmentExpr) -> ast.Assign: - """Handle AssignmentExpr nodes.""" + """ + title: Handle AssignmentExpr nodes. + parameters: + node: + type: astx.AssignmentExpr + returns: + type: ast.Assign + """ if not hasattr(node, "targets") or not node.targets: return self._convert_using_unparse(node) @@ -194,15 +261,29 @@ def visit(self, node: astx.AssignmentExpr) -> ast.Assign: return ast.Assign(targets=targets, value=value) @dispatch # type: ignore[no-redef] - def visit(self, node: astx.ASTNodes) -> List[ast.AST]: - """Handle ASTNodes nodes.""" + def visit(self, node: astx.ASTNodes) -> list[ast.AST]: + """ + title: Handle ASTNodes nodes. + parameters: + node: + type: astx.ASTNodes + returns: + type: list[ast.AST] + """ if not hasattr(node, "nodes"): return [self._convert_using_unparse(node)] return [self.visit(n) for n in node.nodes] @dispatch # type: ignore[no-redef] def visit(self, node: astx.AsyncForRangeLoopExpr) -> ast.ListComp: - """Handle AsyncForRangeLoopExpr nodes.""" + """ + title: Handle AsyncForRangeLoopExpr nodes. + parameters: + node: + type: astx.AsyncForRangeLoopExpr + returns: + type: ast.ListComp + """ if not hasattr(node, "variable") or not hasattr(node, "body"): return self._convert_using_unparse(node) target = ast.Name(id=node.variable.name, ctx=ast.Store()) @@ -235,7 +316,14 @@ def visit(self, node: astx.AsyncForRangeLoopExpr) -> ast.ListComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.AugAssign) -> ast.AugAssign: - """Handle AugAssign nodes.""" + """ + title: Handle AugAssign nodes. + parameters: + node: + type: astx.AugAssign + returns: + type: ast.AugAssign + """ if ( not hasattr(node, "target") or not hasattr(node, "value") @@ -256,15 +344,29 @@ def visit(self, node: astx.AugAssign) -> ast.AugAssign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.AwaitExpr) -> ast.Await: - """Handle AwaitExpr nodes.""" + """ + title: Handle AwaitExpr nodes. + parameters: + node: + type: astx.AwaitExpr + returns: + type: ast.Await + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) value = self.visit(node.value) return ast.Await(value=value) @dispatch # type: ignore[no-redef] - def visit(self, node: astx.BinaryOp) -> Union[ast.BinOp, ast.Call]: - """Handle BinaryOp nodes.""" + def visit(self, node: astx.BinaryOp) -> ast.BinOp | ast.Call: + """ + title: Handle BinaryOp nodes. + parameters: + node: + type: astx.BinaryOp + returns: + type: ast.BinOp | ast.Call + """ if ( not hasattr(node, "lhs") or not hasattr(node, "rhs") @@ -294,18 +396,39 @@ def visit(self, node: astx.BinaryOp) -> Union[ast.BinOp, ast.Call]: return binop @dispatch # type: ignore[no-redef] - def visit(self, node: astx.Block) -> List[ast.stmt]: - """Handle Block nodes.""" + def visit(self, node: astx.Block) -> list[ast.stmt]: + """ + title: Handle Block nodes. + parameters: + node: + type: astx.Block + returns: + type: list[ast.stmt] + """ return self._convert_block(node) @dispatch # type: ignore[no-redef] def visit(self, node: astx.BreakStmt) -> ast.Break: - """Handle BreakStmt nodes.""" + """ + title: Handle BreakStmt nodes. + parameters: + node: + type: astx.BreakStmt + returns: + type: ast.Break + """ return ast.Break() @dispatch # type: ignore[no-redef] def visit(self, node: astx.CaseStmt) -> Any: - """Handle CaseStmt nodes - Python 3.10+ only.""" + """ + title: Handle CaseStmt nodes - Python 3.10+ only. + parameters: + node: + type: astx.CaseStmt + returns: + type: Any + """ if sys.version_info < (3, 10): raise NotImplementedError( "CaseStmt requires Python 3.10 or higher" @@ -329,7 +452,14 @@ def visit(self, node: astx.CaseStmt) -> Any: @dispatch # type: ignore[no-redef] def visit(self, node: astx.CatchHandlerStmt) -> ast.ExceptHandler: - """Handle CatchHandlerStmt nodes.""" + """ + title: Handle CatchHandlerStmt nodes. + parameters: + node: + type: astx.CatchHandlerStmt + returns: + type: ast.ExceptHandler + """ type_ = None if hasattr(node, "types") and node.types: type_ = self.visit(node.types[0]) @@ -350,7 +480,14 @@ def visit(self, node: astx.CatchHandlerStmt) -> ast.ExceptHandler: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ClassDefStmt) -> ast.ClassDef: - """Handle ClassDefStmt nodes.""" + """ + title: Handle ClassDefStmt nodes. + parameters: + node: + type: astx.ClassDefStmt + returns: + type: ast.ClassDef + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) @@ -376,7 +513,14 @@ def visit(self, node: astx.ClassDefStmt) -> ast.ClassDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.CompareOp) -> ast.Compare: - """Handle CompareOp nodes.""" + """ + title: Handle CompareOp nodes. + parameters: + node: + type: astx.CompareOp + returns: + type: ast.Compare + """ if ( not hasattr(node, "left") or not hasattr(node, "ops") @@ -395,7 +539,14 @@ def visit(self, node: astx.CompareOp) -> ast.Compare: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ComprehensionClause) -> ast.comprehension: - """Handle ComprehensionClause nodes.""" + """ + title: Handle ComprehensionClause nodes. + parameters: + node: + type: astx.ComprehensionClause + returns: + type: ast.comprehension + """ if not hasattr(node, "target") or not hasattr(node, "iterable"): return self._convert_using_unparse(node) target = self.visit(node.target) @@ -413,48 +564,101 @@ def visit(self, node: astx.ComprehensionClause) -> ast.comprehension: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ContinueStmt) -> ast.Continue: - """Handle ContinueStmt nodes.""" + """ + title: Handle ContinueStmt nodes. + parameters: + node: + type: astx.ContinueStmt + returns: + type: ast.Continue + """ return ast.Continue() @dispatch # type: ignore[no-redef] def visit( - self, node: Union[astx.Int8, astx.Int16, astx.Int32, astx.Int64] + self, node: astx.Int8 | astx.Int16 | astx.Int32 | astx.Int64 ) -> ast.Name: - """Handle all integer type nodes.""" + """ + title: Handle all integer type nodes. + parameters: + node: + type: astx.Int8 | astx.Int16 | astx.Int32 | astx.Int64 + returns: + type: ast.Name + """ return ast.Name(id="int", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit( self, - node: Union[ - astx.UInt8, astx.UInt16, astx.UInt32, astx.UInt64, astx.UInt128 - ], + node: astx.UInt8 + | astx.UInt16 + | astx.UInt32 + | astx.UInt64 + | astx.UInt128, ) -> ast.Name: - """Handle all unsigned integer type nodes.""" + """ + title: Handle all unsigned integer type nodes. + parameters: + node: + type: >- + astx.UInt8 | astx.UInt16 | astx.UInt32 | astx.UInt64 | + astx.UInt128 + returns: + type: ast.Name + """ return ast.Name(id="int", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit( - self, node: Union[astx.Float16, astx.Float32, astx.Float64] + self, node: astx.Float16 | astx.Float32 | astx.Float64 ) -> ast.Name: - """Handle all float type nodes.""" + """ + title: Handle all float type nodes. + parameters: + node: + type: astx.Float16 | astx.Float32 | astx.Float64 + returns: + type: ast.Name + """ return ast.Name(id="float", ctx=ast.Load()) @dispatch # type: ignore[no-redef] - def visit(self, node: Union[astx.Complex32, astx.Complex64]) -> ast.Name: - """Handle all complex type nodes.""" + def visit(self, node: astx.Complex32 | astx.Complex64) -> ast.Name: + """ + title: Handle all complex type nodes. + parameters: + node: + type: astx.Complex32 | astx.Complex64 + returns: + type: ast.Name + """ return ast.Name(id="complex", ctx=ast.Load()) @dispatch # type: ignore[no-redef] - def visit(self, node: Union[astx.UTF8Char, astx.UTF8String]) -> ast.Name: - """Handle UTF8 string type nodes.""" + def visit(self, node: astx.UTF8Char | astx.UTF8String) -> ast.Name: + """ + title: Handle UTF8 string type nodes. + parameters: + node: + type: astx.UTF8Char | astx.UTF8String + returns: + type: ast.Name + """ return ast.Name(id="str", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit( - self, node: Union[astx.Date, astx.DateTime, astx.Time, astx.Timestamp] + self, node: astx.Date | astx.DateTime | astx.Time | astx.Timestamp ) -> ast.Name: - """Handle all datetime type nodes.""" + """ + title: Handle all datetime type nodes. + parameters: + node: + type: astx.Date | astx.DateTime | astx.Time | astx.Timestamp + returns: + type: ast.Name + """ type_mapping = { "Date": "date", "DateTime": "datetime", @@ -466,7 +670,14 @@ def visit( @dispatch # type: ignore[no-redef] def visit(self, node: astx.DataType) -> ast.Name: - """Handle DataType nodes.""" + """ + title: Handle DataType nodes. + parameters: + node: + type: astx.DataType + returns: + type: ast.Name + """ if hasattr(node, "id") and node.id: type_id = node.id else: @@ -475,7 +686,14 @@ def visit(self, node: astx.DataType) -> ast.Name: @dispatch # type: ignore[no-redef] def visit(self, node: astx.DeleteStmt) -> ast.Delete: - """Handle DeleteStmt nodes.""" + """ + title: Handle DeleteStmt nodes. + parameters: + node: + type: astx.DeleteStmt + returns: + type: ast.Delete + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) targets = [self.visit(target) for target in node.value] @@ -483,7 +701,14 @@ def visit(self, node: astx.DeleteStmt) -> ast.Delete: @dispatch # type: ignore[no-redef] def visit(self, node: astx.DoWhileExpr) -> ast.ListComp: - """Handle DoWhileExpr nodes.""" + """ + title: Handle DoWhileExpr nodes. + parameters: + node: + type: astx.DoWhileExpr + returns: + type: ast.ListComp + """ if not hasattr(node, "body") or not hasattr(node, "condition"): return self._convert_using_unparse(node) element = ( @@ -522,7 +747,14 @@ def visit(self, node: astx.DoWhileExpr) -> ast.ListComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.DoWhileStmt) -> ast.While: - """Handle DoWhileStmt nodes.""" + """ + title: Handle DoWhileStmt nodes. + parameters: + node: + type: astx.DoWhileStmt + returns: + type: ast.While + """ if not hasattr(node, "body") or not hasattr(node, "condition"): return self._convert_using_unparse(node) body = ( @@ -542,12 +774,26 @@ def visit(self, node: astx.DoWhileStmt) -> ast.While: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Ellipsis) -> ast.Constant: - """Handle Ellipsis nodes.""" + """ + title: Handle Ellipsis nodes. + parameters: + node: + type: astx.Ellipsis + returns: + type: ast.Constant + """ return ast.Constant(value=...) @dispatch # type: ignore[no-redef] def visit(self, node: astx.EnumDeclStmt) -> ast.ClassDef: - """Handle EnumDeclStmt nodes.""" + """ + title: Handle EnumDeclStmt nodes. + parameters: + node: + type: astx.EnumDeclStmt + returns: + type: ast.ClassDef + """ if not hasattr(node, "name") or not hasattr(node, "attributes"): return self._convert_using_unparse(node) body = [] @@ -586,7 +832,14 @@ def visit(self, node: astx.EnumDeclStmt) -> ast.ClassDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ExceptionHandlerStmt) -> ast.Try: - """Handle ExceptionHandlerStmt nodes.""" + """ + title: Handle ExceptionHandlerStmt nodes. + parameters: + node: + type: astx.ExceptionHandlerStmt + returns: + type: ast.Try + """ if not hasattr(node, "body"): return self._convert_using_unparse(node) @@ -607,7 +860,14 @@ def visit(self, node: astx.ExceptionHandlerStmt) -> ast.Try: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FinallyHandlerStmt) -> ast.Try: - """Handle FinallyHandlerStmt nodes.""" + """ + title: Handle FinallyHandlerStmt nodes. + parameters: + node: + type: astx.FinallyHandlerStmt + returns: + type: ast.Try + """ if not hasattr(node, "body"): return self._convert_using_unparse(node) @@ -619,7 +879,14 @@ def visit(self, node: astx.FinallyHandlerStmt) -> ast.Try: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ForCountLoopStmt) -> ast.For: - """Handle ForCountLoopStmt nodes.""" + """ + title: Handle ForCountLoopStmt nodes. + parameters: + node: + type: astx.ForCountLoopStmt + returns: + type: ast.For + """ if ( not hasattr(node, "initializer") or not hasattr(node, "condition") @@ -656,7 +923,14 @@ def visit(self, node: astx.ForCountLoopStmt) -> ast.For: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ForRangeLoopExpr) -> ast.ListComp: - """Handle ForRangeLoopExpr nodes.""" + """ + title: Handle ForRangeLoopExpr nodes. + parameters: + node: + type: astx.ForRangeLoopExpr + returns: + type: ast.ListComp + """ if not hasattr(node, "variable") or not hasattr(node, "body"): return self._convert_using_unparse(node) target = ast.Name(id=node.variable.name, ctx=ast.Store()) @@ -689,7 +963,14 @@ def visit(self, node: astx.ForRangeLoopExpr) -> ast.ListComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ForRangeLoopStmt) -> ast.For: - """Handle ForRangeLoopStmt nodes.""" + """ + title: Handle ForRangeLoopStmt nodes. + parameters: + node: + type: astx.ForRangeLoopStmt + returns: + type: ast.For + """ if not hasattr(node, "variable") or not hasattr(node, "start"): return self._convert_using_unparse(node) target = ast.Name(id=node.variable.name, ctx=ast.Store()) @@ -713,7 +994,14 @@ def visit(self, node: astx.ForRangeLoopStmt) -> ast.For: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FunctionAsyncDef) -> ast.AsyncFunctionDef: - """Handle FunctionAsyncDef nodes.""" + """ + title: Handle FunctionAsyncDef nodes. + parameters: + node: + type: astx.FunctionAsyncDef + returns: + type: ast.AsyncFunctionDef + """ if ( not hasattr(node, "name") or not hasattr(node, "prototype") @@ -760,7 +1048,14 @@ def visit(self, node: astx.FunctionAsyncDef) -> ast.AsyncFunctionDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FunctionCall) -> ast.Call: - """Handle FunctionCall nodes.""" + """ + title: Handle FunctionCall nodes. + parameters: + node: + type: astx.FunctionCall + returns: + type: ast.Call + """ if not hasattr(node, "fn"): return ast.Call( func=ast.Name(id="unknown_function", ctx=ast.Load()), @@ -794,7 +1089,14 @@ def visit(self, node: astx.FunctionCall) -> ast.Call: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FunctionDef) -> ast.FunctionDef: - """Handle FunctionDef nodes.""" + """ + title: Handle FunctionDef nodes. + parameters: + node: + type: astx.FunctionDef + returns: + type: ast.FunctionDef + """ if not hasattr(node, "prototype"): return self._convert_using_unparse(node) @@ -833,7 +1135,14 @@ def visit(self, node: astx.FunctionDef) -> ast.FunctionDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FunctionPrototype) -> ast.FunctionDef: - """Handle FunctionPrototype nodes.""" + """ + title: Handle FunctionPrototype nodes. + parameters: + node: + type: astx.FunctionPrototype + returns: + type: ast.FunctionDef + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) args_nodes = [] @@ -863,7 +1172,14 @@ def visit(self, node: astx.FunctionPrototype) -> ast.FunctionDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.FunctionReturn) -> ast.Return: - """Handle FunctionReturn nodes.""" + """ + title: Handle FunctionReturn nodes. + parameters: + node: + type: astx.FunctionReturn + returns: + type: ast.Return + """ value = None if hasattr(node, "value") and node.value: value = self.visit(node.value) @@ -871,7 +1187,14 @@ def visit(self, node: astx.FunctionReturn) -> ast.Return: @dispatch # type: ignore[no-redef] def visit(self, node: astx.GeneratorExpr) -> ast.GeneratorExp: - """Handle GeneratorExpr nodes.""" + """ + title: Handle GeneratorExpr nodes. + parameters: + node: + type: astx.GeneratorExpr + returns: + type: ast.GeneratorExp + """ if not hasattr(node, "element") or not hasattr(node, "generators"): return self._convert_using_unparse(node) element = self.visit(node.element) @@ -880,7 +1203,14 @@ def visit(self, node: astx.GeneratorExpr) -> ast.GeneratorExp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Identifier) -> ast.Name: - """Handle Identifier nodes.""" + """ + title: Handle Identifier nodes. + parameters: + node: + type: astx.Identifier + returns: + type: ast.Name + """ # Get the identifier name from the node if hasattr(node, "name"): identifier_name = node.name @@ -900,7 +1230,14 @@ def visit(self, node: astx.Identifier) -> ast.Name: @dispatch # type: ignore[no-redef] def visit(self, node: astx.IfExpr) -> ast.IfExp: - """Handle IfExpr nodes.""" + """ + title: Handle IfExpr nodes. + parameters: + node: + type: astx.IfExpr + returns: + type: ast.IfExp + """ if not hasattr(node, "condition"): return self._convert_using_unparse(node) then_value = None @@ -926,7 +1263,14 @@ def visit(self, node: astx.IfExpr) -> ast.IfExp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.IfStmt) -> ast.If: - """Handle IfStmt nodes.""" + """ + title: Handle IfStmt nodes. + parameters: + node: + type: astx.IfStmt + returns: + type: ast.If + """ if not hasattr(node, "condition"): return self._convert_using_unparse(node) then_body = ( @@ -945,7 +1289,14 @@ def visit(self, node: astx.IfStmt) -> ast.If: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ImportExpr) -> ast.Assign: - """Handle ImportExpr nodes.""" + """ + title: Handle ImportExpr nodes. + parameters: + node: + type: astx.ImportExpr + returns: + type: ast.Assign + """ if not hasattr(node, "names"): return self._convert_using_unparse(node) import_calls = [] @@ -974,7 +1325,14 @@ def visit(self, node: astx.ImportExpr) -> ast.Assign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ImportFromExpr) -> ast.Assign: - """Handle ImportFromExpr nodes.""" + """ + title: Handle ImportFromExpr nodes. + parameters: + node: + type: astx.ImportFromExpr + returns: + type: ast.Assign + """ if not hasattr(node, "names") or not hasattr(node, "module"): return self._convert_using_unparse(node) import_calls = [] @@ -1020,7 +1378,14 @@ def visit(self, node: astx.ImportFromExpr) -> ast.Assign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ImportFromStmt) -> ast.ImportFrom: - """Handle ImportFromStmt nodes.""" + """ + title: Handle ImportFromStmt nodes. + parameters: + node: + type: astx.ImportFromStmt + returns: + type: ast.ImportFrom + """ if not hasattr(node, "names") or not hasattr(node, "module"): return self._convert_using_unparse(node) names = [self.visit(name) for name in node.names] @@ -1029,7 +1394,14 @@ def visit(self, node: astx.ImportFromStmt) -> ast.ImportFrom: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ImportStmt) -> ast.Import: - """Handle ImportStmt nodes.""" + """ + title: Handle ImportStmt nodes. + parameters: + node: + type: astx.ImportStmt + returns: + type: ast.Import + """ if not hasattr(node, "names"): return ast.Import(names=[ast.alias(name="", asname=None)]) names = [self.visit(name) for name in node.names] @@ -1037,7 +1409,14 @@ def visit(self, node: astx.ImportStmt) -> ast.Import: @dispatch # type: ignore[no-redef] def visit(self, node: astx.InlineVariableDeclaration) -> ast.AnnAssign: - """Handle InlineVariableDeclaration nodes.""" + """ + title: Handle InlineVariableDeclaration nodes. + parameters: + node: + type: astx.InlineVariableDeclaration + returns: + type: ast.AnnAssign + """ if not hasattr(node, "name") or not hasattr(node, "type_"): return self._convert_using_unparse(node) target = ast.Name(id=node.name, ctx=ast.Store()) @@ -1056,7 +1435,14 @@ def visit(self, node: astx.InlineVariableDeclaration) -> ast.AnnAssign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LambdaExpr) -> ast.Lambda: - """Handle LambdaExpr nodes.""" + """ + title: Handle LambdaExpr nodes. + parameters: + node: + type: astx.LambdaExpr + returns: + type: ast.Lambda + """ if not hasattr(node, "body"): return self._convert_using_unparse(node) args = [] @@ -1079,7 +1465,14 @@ def visit(self, node: astx.LambdaExpr) -> ast.Lambda: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ListComprehension) -> ast.ListComp: - """Handle ListComprehension nodes.""" + """ + title: Handle ListComprehension nodes. + parameters: + node: + type: astx.ListComprehension + returns: + type: ast.ListComp + """ if not hasattr(node, "element") or not hasattr(node, "generators"): return self._convert_using_unparse(node) element = self.visit(node.element) @@ -1088,7 +1481,14 @@ def visit(self, node: astx.ListComprehension) -> ast.ListComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralBoolean) -> ast.Constant: - """Handle LiteralBoolean nodes.""" + """ + title: Handle LiteralBoolean nodes. + parameters: + node: + type: astx.LiteralBoolean + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value=False) return ast.Constant(value=node.value) @@ -1096,15 +1496,22 @@ def visit(self, node: astx.LiteralBoolean) -> ast.Constant: @dispatch # type: ignore[no-redef] def visit( self, - node: Union[ - astx.LiteralInt8, - astx.LiteralInt16, - astx.LiteralInt32, - astx.LiteralInt64, - astx.LiteralInt128, - ], + node: astx.LiteralInt8 + | astx.LiteralInt16 + | astx.LiteralInt32 + | astx.LiteralInt64 + | astx.LiteralInt128, ) -> ast.Constant: - """Handle all integer literal nodes.""" + """ + title: Handle all integer literal nodes. + parameters: + node: + type: >- + astx.LiteralInt8 | astx.LiteralInt16 | astx.LiteralInt32 | + astx.LiteralInt64 | astx.LiteralInt128 + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value=0) return ast.Constant(value=node.value) @@ -1112,15 +1519,22 @@ def visit( @dispatch # type: ignore[no-redef] def visit( self, - node: Union[ - astx.LiteralUInt8, - astx.LiteralUInt16, - astx.LiteralUInt32, - astx.LiteralUInt64, - astx.LiteralUInt128, - ], + node: astx.LiteralUInt8 + | astx.LiteralUInt16 + | astx.LiteralUInt32 + | astx.LiteralUInt64 + | astx.LiteralUInt128, ) -> ast.Constant: - """Handle all unsigned integer literal nodes.""" + """ + title: Handle all unsigned integer literal nodes. + parameters: + node: + type: >- + astx.LiteralUInt8 | astx.LiteralUInt16 | astx.LiteralUInt32 | + astx.LiteralUInt64 | astx.LiteralUInt128 + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value=0) return ast.Constant(value=node.value) @@ -1128,20 +1542,33 @@ def visit( @dispatch # type: ignore[no-redef] def visit( self, - node: Union[ - astx.LiteralFloat16, astx.LiteralFloat32, astx.LiteralFloat64 - ], + node: astx.LiteralFloat16 | astx.LiteralFloat32 | astx.LiteralFloat64, ) -> ast.Constant: - """Handle all float literal nodes.""" + """ + title: Handle all float literal nodes. + parameters: + node: + type: >- + astx.LiteralFloat16 | astx.LiteralFloat32 | astx.LiteralFloat64 + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value=0.0) return ast.Constant(value=node.value) @dispatch # type: ignore[no-redef] def visit( - self, node: Union[astx.LiteralComplex32, astx.LiteralComplex64] + self, node: astx.LiteralComplex32 | astx.LiteralComplex64 ) -> ast.Call: - """Handle all complex literal nodes.""" + """ + title: Handle all complex literal nodes. + parameters: + node: + type: astx.LiteralComplex32 | astx.LiteralComplex64 + returns: + type: ast.Call + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) real = ast.Constant(value=node.value[0]) @@ -1154,16 +1581,30 @@ def visit( @dispatch # type: ignore[no-redef] def visit( - self, node: Union[astx.LiteralUTF8Char, astx.LiteralUTF8String] + self, node: astx.LiteralUTF8Char | astx.LiteralUTF8String ) -> ast.Constant: - """Handle UTF8 string literal nodes.""" + """ + title: Handle UTF8 string literal nodes. + parameters: + node: + type: astx.LiteralUTF8Char | astx.LiteralUTF8String + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value="") return ast.Constant(value=str(node.value)) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralDate) -> ast.Call: - """Handle LiteralDate nodes.""" + """ + title: Handle LiteralDate nodes. + parameters: + node: + type: astx.LiteralDate + returns: + type: ast.Call + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) return ast.Call( @@ -1189,27 +1630,62 @@ def visit(self, node: astx.LiteralDate) -> ast.Call: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralDateTime) -> ast.Name: - """Handle LiteralDateTime nodes.""" + """ + title: Handle LiteralDateTime nodes. + parameters: + node: + type: astx.LiteralDateTime + returns: + type: ast.Name + """ return ast.Name(id="datetime", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralTime) -> ast.Name: - """Handle LiteralTime nodes.""" + """ + title: Handle LiteralTime nodes. + parameters: + node: + type: astx.LiteralTime + returns: + type: ast.Name + """ return ast.Name(id="time", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralTimestamp) -> ast.Name: - """Handle LiteralTimestamp nodes.""" + """ + title: Handle LiteralTimestamp nodes. + parameters: + node: + type: astx.LiteralTimestamp + returns: + type: ast.Name + """ return ast.Name(id="timestamp", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralComplex) -> ast.Name: - """Handle LiteralComplex nodes.""" + """ + title: Handle LiteralComplex nodes. + parameters: + node: + type: astx.LiteralComplex + returns: + type: ast.Name + """ return ast.Name(id="complex", ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralDict) -> ast.Dict: - """Handle LiteralDict nodes.""" + """ + title: Handle LiteralDict nodes. + parameters: + node: + type: astx.LiteralDict + returns: + type: ast.Dict + """ if not hasattr(node, "elements"): return ast.Dict(keys=[], values=[]) keys = [self.visit(key) for key in node.elements.keys()] @@ -1218,7 +1694,14 @@ def visit(self, node: astx.LiteralDict) -> ast.Dict: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralList) -> ast.List: - """Handle LiteralList nodes.""" + """ + title: Handle LiteralList nodes. + parameters: + node: + type: astx.LiteralList + returns: + type: ast.List + """ if not hasattr(node, "elements"): return ast.List(elts=[], ctx=ast.Load()) elements = [self.visit(element) for element in node.elements] @@ -1226,12 +1709,26 @@ def visit(self, node: astx.LiteralList) -> ast.List: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralNone) -> ast.Constant: - """Handle LiteralNone nodes.""" + """ + title: Handle LiteralNone nodes. + parameters: + node: + type: astx.LiteralNone + returns: + type: ast.Constant + """ return ast.Constant(value=None) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralSet) -> ast.Set: - """Handle LiteralSet nodes.""" + """ + title: Handle LiteralSet nodes. + parameters: + node: + type: astx.LiteralSet + returns: + type: ast.Set + """ if not hasattr(node, "elements"): return ast.Set(elts=[]) elements = [self.visit(element) for element in node.elements] @@ -1239,14 +1736,28 @@ def visit(self, node: astx.LiteralSet) -> ast.Set: @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralString) -> ast.Constant: - """Handle LiteralString nodes.""" + """ + title: Handle LiteralString nodes. + parameters: + node: + type: astx.LiteralString + returns: + type: ast.Constant + """ if not hasattr(node, "value"): return ast.Constant(value="") return ast.Constant(value=node.value) @dispatch # type: ignore[no-redef] def visit(self, node: astx.LiteralTuple) -> ast.Tuple: - """Handle LiteralTuple nodes.""" + """ + title: Handle LiteralTuple nodes. + parameters: + node: + type: astx.LiteralTuple + returns: + type: ast.Tuple + """ if not hasattr(node, "elements"): return ast.Tuple(elts=[], ctx=ast.Load()) elements = [self.visit(element) for element in node.elements] @@ -1254,7 +1765,14 @@ def visit(self, node: astx.LiteralTuple) -> ast.Tuple: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Module) -> ast.Module: - """Handle Module nodes.""" + """ + title: Handle Module nodes. + parameters: + node: + type: astx.Module + returns: + type: ast.Module + """ if not hasattr(node, "body"): return ast.Module(body=[ast.Pass()], type_ignores=[]) @@ -1263,7 +1781,14 @@ def visit(self, node: astx.Module) -> ast.Module: @dispatch # type: ignore[no-redef] def visit(self, node: astx.NandOp) -> ast.UnaryOp: - """Handle NandOp nodes.""" + """ + title: Handle NandOp nodes. + parameters: + node: + type: astx.NandOp + returns: + type: ast.UnaryOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) lhs = self.visit(node.lhs) @@ -1274,7 +1799,14 @@ def visit(self, node: astx.NandOp) -> ast.UnaryOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.NorOp) -> ast.UnaryOp: - """Handle NorOp nodes.""" + """ + title: Handle NorOp nodes. + parameters: + node: + type: astx.NorOp + returns: + type: ast.UnaryOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) lhs = self.visit(node.lhs) @@ -1285,7 +1817,14 @@ def visit(self, node: astx.NorOp) -> ast.UnaryOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.NotOp) -> ast.UnaryOp: - """Handle NotOp nodes.""" + """ + title: Handle NotOp nodes. + parameters: + node: + type: astx.NotOp + returns: + type: ast.UnaryOp + """ if not hasattr(node, "operand"): return self._convert_using_unparse(node) @@ -1294,7 +1833,14 @@ def visit(self, node: astx.NotOp) -> ast.UnaryOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.OrOp) -> ast.BoolOp: - """Handle OrOp nodes.""" + """ + title: Handle OrOp nodes. + parameters: + node: + type: astx.OrOp + returns: + type: ast.BoolOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) return ast.BoolOp( @@ -1303,14 +1849,28 @@ def visit(self, node: astx.OrOp) -> ast.BoolOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ParenthesizedExpr) -> ast.AST: - """Handle ParenthesizedExpr nodes.""" + """ + title: Handle ParenthesizedExpr nodes. + parameters: + node: + type: astx.ParenthesizedExpr + returns: + type: ast.AST + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) return self.visit(node.value) @dispatch # type: ignore[no-redef] def visit(self, node: astx.SetComprehension) -> ast.SetComp: - """Handle SetComprehension nodes.""" + """ + title: Handle SetComprehension nodes. + parameters: + node: + type: astx.SetComprehension + returns: + type: ast.SetComp + """ if not hasattr(node, "element") or not hasattr(node, "generators"): return self._convert_using_unparse(node) element = self.visit(node.element) @@ -1319,7 +1879,14 @@ def visit(self, node: astx.SetComprehension) -> ast.SetComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Starred) -> ast.Starred: - """Handle Starred nodes.""" + """ + title: Handle Starred nodes. + parameters: + node: + type: astx.Starred + returns: + type: ast.Starred + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) @@ -1328,7 +1895,14 @@ def visit(self, node: astx.Starred) -> ast.Starred: @dispatch # type: ignore[no-redef] def visit(self, node: astx.StructDeclStmt) -> ast.ClassDef: - """Handle StructDeclStmt nodes.""" + """ + title: Handle StructDeclStmt nodes. + parameters: + node: + type: astx.StructDeclStmt + returns: + type: ast.ClassDef + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) decorators = [ast.Name(id="dataclass", ctx=ast.Load())] @@ -1348,7 +1922,14 @@ def visit(self, node: astx.StructDeclStmt) -> ast.ClassDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.StructDefStmt) -> ast.ClassDef: - """Handle StructDefStmt nodes.""" + """ + title: Handle StructDefStmt nodes. + parameters: + node: + type: astx.StructDefStmt + returns: + type: ast.ClassDef + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) decorators = [ast.Name(id="dataclass", ctx=ast.Load())] @@ -1369,7 +1950,14 @@ def visit(self, node: astx.StructDefStmt) -> ast.ClassDef: @dispatch # type: ignore[no-redef] def visit(self, node: astx.SwitchStmt) -> Any: - """Handle SwitchStmt nodes - Python 3.10+ only.""" + """ + title: Handle SwitchStmt nodes - Python 3.10+ only. + parameters: + node: + type: astx.SwitchStmt + returns: + type: Any + """ if sys.version_info < (3, 10): raise NotImplementedError( "SwitchStmt requires Python 3.10 or higher" @@ -1389,7 +1977,14 @@ def visit(self, node: astx.SwitchStmt) -> Any: @dispatch # type: ignore[no-redef] def visit(self, node: astx.SubscriptExpr) -> ast.Subscript: - """Handle SubscriptExpr nodes.""" + """ + title: Handle SubscriptExpr nodes. + parameters: + node: + type: astx.SubscriptExpr + returns: + type: ast.Subscript + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) value = self.visit(node.value) @@ -1418,7 +2013,14 @@ def visit(self, node: astx.SubscriptExpr) -> ast.Subscript: @dispatch # type: ignore[no-redef] def visit(self, node: astx.ThrowStmt) -> ast.Raise: - """Handle ThrowStmt nodes.""" + """ + title: Handle ThrowStmt nodes. + parameters: + node: + type: astx.ThrowStmt + returns: + type: ast.Raise + """ exc = None if hasattr(node, "exception") and node.exception: try: @@ -1492,7 +2094,14 @@ def visit(self, node: astx.ThrowStmt) -> ast.Raise: @dispatch # type: ignore[no-redef] def visit(self, node: astx.TypeCastExpr) -> ast.Call: - """Handle TypeCastExpr nodes.""" + """ + title: Handle TypeCastExpr nodes. + parameters: + node: + type: astx.TypeCastExpr + returns: + type: ast.Call + """ if not hasattr(node, "target_type") or not hasattr(node, "expr"): return self._convert_using_unparse(node) target_type = self.visit(node.target_type) @@ -1505,7 +2114,14 @@ def visit(self, node: astx.TypeCastExpr) -> ast.Call: @dispatch # type: ignore[no-redef] def visit(self, node: astx.UnaryOp) -> ast.UnaryOp: - """Handle UnaryOp nodes.""" + """ + title: Handle UnaryOp nodes. + parameters: + node: + type: astx.UnaryOp + returns: + type: ast.UnaryOp + """ if not hasattr(node, "op_code") or not hasattr(node, "operand"): return self._convert_using_unparse(node) if node.op_code not in UNARY_OP_MAP: @@ -1515,14 +2131,28 @@ def visit(self, node: astx.UnaryOp) -> ast.UnaryOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.Variable) -> ast.Name: - """Handle Variable nodes.""" + """ + title: Handle Variable nodes. + parameters: + node: + type: astx.Variable + returns: + type: ast.Name + """ if not hasattr(node, "name"): return ast.Name(id="undefined", ctx=ast.Load()) return ast.Name(id=node.name, ctx=ast.Load()) @dispatch # type: ignore[no-redef] def visit(self, node: astx.VariableAssignment) -> ast.Assign: - """Handle VariableAssignment nodes.""" + """ + title: Handle VariableAssignment nodes. + parameters: + node: + type: astx.VariableAssignment + returns: + type: ast.Assign + """ if not hasattr(node, "name") or not hasattr(node, "value"): return self._convert_using_unparse(node) target = ast.Name(id=node.name, ctx=ast.Store()) @@ -1531,7 +2161,14 @@ def visit(self, node: astx.VariableAssignment) -> ast.Assign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.VariableDeclaration) -> ast.AnnAssign: - """Handle VariableDeclaration nodes.""" + """ + title: Handle VariableDeclaration nodes. + parameters: + node: + type: astx.VariableDeclaration + returns: + type: ast.AnnAssign + """ if not hasattr(node, "name"): return self._convert_using_unparse(node) @@ -1562,7 +2199,14 @@ def visit(self, node: astx.VariableDeclaration) -> ast.AnnAssign: @dispatch # type: ignore[no-redef] def visit(self, node: astx.WalrusOp) -> ast.NamedExpr: - """Handle WalrusOp nodes.""" + """ + title: Handle WalrusOp nodes. + parameters: + node: + type: astx.WalrusOp + returns: + type: ast.NamedExpr + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) target = self.visit(node.lhs) @@ -1573,7 +2217,14 @@ def visit(self, node: astx.WalrusOp) -> ast.NamedExpr: @dispatch # type: ignore[no-redef] def visit(self, node: astx.WhileExpr) -> ast.ListComp: - """Handle WhileExpr nodes.""" + """ + title: Handle WhileExpr nodes. + parameters: + node: + type: astx.WhileExpr + returns: + type: ast.ListComp + """ if not hasattr(node, "condition") or not hasattr(node, "body"): return self._convert_using_unparse(node) element = ( @@ -1611,7 +2262,14 @@ def visit(self, node: astx.WhileExpr) -> ast.ListComp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.WhileStmt) -> ast.While: - """Handle WhileStmt nodes.""" + """ + title: Handle WhileStmt nodes. + parameters: + node: + type: astx.WhileStmt + returns: + type: ast.While + """ if not hasattr(node, "condition"): return self._convert_using_unparse(node) @@ -1626,7 +2284,14 @@ def visit(self, node: astx.WhileStmt) -> ast.While: @dispatch # type: ignore[no-redef] def visit(self, node: astx.XnorOp) -> ast.UnaryOp: - """Handle XnorOp nodes.""" + """ + title: Handle XnorOp nodes. + parameters: + node: + type: astx.XnorOp + returns: + type: ast.UnaryOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) lhs = self.visit(node.lhs) @@ -1636,7 +2301,14 @@ def visit(self, node: astx.XnorOp) -> ast.UnaryOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.XorOp) -> ast.BinOp: - """Handle XorOp nodes.""" + """ + title: Handle XorOp nodes. + parameters: + node: + type: astx.XorOp + returns: + type: ast.BinOp + """ if not hasattr(node, "lhs") or not hasattr(node, "rhs"): return self._convert_using_unparse(node) lhs = self.visit(node.lhs) @@ -1645,7 +2317,14 @@ def visit(self, node: astx.XorOp) -> ast.BinOp: @dispatch # type: ignore[no-redef] def visit(self, node: astx.YieldExpr) -> ast.Yield: - """Handle YieldExpr nodes.""" + """ + title: Handle YieldExpr nodes. + parameters: + node: + type: astx.YieldExpr + returns: + type: ast.Yield + """ value = None if hasattr(node, "value") and node.value: value = self.visit(node.value) @@ -1653,7 +2332,14 @@ def visit(self, node: astx.YieldExpr) -> ast.Yield: @dispatch # type: ignore[no-redef] def visit(self, node: astx.YieldFromExpr) -> ast.YieldFrom: - """Handle YieldFromExpr nodes.""" + """ + title: Handle YieldFromExpr nodes. + parameters: + node: + type: astx.YieldFromExpr + returns: + type: ast.YieldFrom + """ if not hasattr(node, "value"): return self._convert_using_unparse(node) value = self.visit(node.value) @@ -1661,7 +2347,14 @@ def visit(self, node: astx.YieldFromExpr) -> ast.YieldFrom: @dispatch # type: ignore[no-redef] def visit(self, node: astx.YieldStmt) -> ast.Expr: - """Handle YieldStmt nodes.""" + """ + title: Handle YieldStmt nodes. + parameters: + node: + type: astx.YieldStmt + returns: + type: ast.Expr + """ value = None if hasattr(node, "value") and node.value: value = self.visit(node.value) diff --git a/libs/astx-transpilers/tests/test_python_string.py b/libs/astx-transpilers/tests/test_python_string.py index 1f40855b..8e4f3d6a 100644 --- a/libs/astx-transpilers/tests/test_python_string.py +++ b/libs/astx-transpilers/tests/test_python_string.py @@ -1,4 +1,6 @@ -"""Test Python Transpiler.""" +""" +title: Test Python Transpiler. +""" import ast import sys @@ -12,19 +14,33 @@ def translate(node: astx.AST) -> str: - """Translate from ASTx to Python source.""" + """ + title: Translate from ASTx to Python source. + parameters: + node: + type: astx.AST + returns: + type: str + """ code = str(transpiler.visit(node)) ast.parse(code) return code def check_transpilation(code: str) -> None: - """Check Transpilation with Python ast lib.""" + """ + title: Check Transpilation with Python ast lib. + parameters: + code: + type: str + """ ast.parse(code) def test_transpiler_multiple_imports_stmt() -> None: - """Test astx.ImportStmt multiple imports.""" + """ + title: Test astx.ImportStmt multiple imports. + """ alias1 = astx.AliasExpr(name="math") alias2 = astx.AliasExpr(name="matplotlib", asname="mtlb") @@ -40,7 +56,9 @@ def test_transpiler_multiple_imports_stmt() -> None: def test_transpiler_import_from_stmt() -> None: - """Test astx.ImportFromStmt importing from module.""" + """ + title: Test astx.ImportFromStmt importing from module. + """ alias = astx.AliasExpr(name="pyplot", asname="plt") import_from_stmt = astx.ImportFromStmt( @@ -56,7 +74,9 @@ def test_transpiler_import_from_stmt() -> None: def test_transpiler_wildcard_import_from_stmt() -> None: - """Test astx.ImportFromStmt wildcard import from module.""" + """ + title: Test astx.ImportFromStmt wildcard import from module. + """ alias = astx.AliasExpr(name="*") import_from_stmt = astx.ImportFromStmt(module="matplotlib", names=[alias]) @@ -70,7 +90,9 @@ def test_transpiler_wildcard_import_from_stmt() -> None: def test_transpiler_future_import_from_stmt() -> None: - """Test astx.ImportFromStmt from future import.""" + """ + title: Test astx.ImportFromStmt from future import. + """ alias = astx.AliasExpr(name="division") import_from_stmt = astx.ImportFromStmt(module="__future__", names=[alias]) @@ -84,7 +106,9 @@ def test_transpiler_future_import_from_stmt() -> None: def test_transpiler_multiple_imports_expr() -> None: - """Test astx.ImportExpr multiple imports.""" + """ + title: Test astx.ImportExpr multiple imports. + """ alias1 = astx.AliasExpr(name="sqrt", asname="square_root") alias2 = astx.AliasExpr(name="pi") @@ -102,7 +126,9 @@ def test_transpiler_multiple_imports_expr() -> None: def test_transpiler_import_from_expr() -> None: - """Test astx.ImportFromExpr importing from module.""" + """ + title: Test astx.ImportFromExpr importing from module. + """ alias1 = astx.AliasExpr(name="sqrt", asname="square_root") import_from_expr = astx.ImportFromExpr(module="math", names=[alias1]) @@ -119,7 +145,9 @@ def test_transpiler_import_from_expr() -> None: def test_transpiler_wildcard_import_from_expr() -> None: - """Test astx.ImportFromExpr wildcard import from module.""" + """ + title: Test astx.ImportFromExpr wildcard import from module. + """ alias1 = astx.AliasExpr(name="*") import_from_expr = astx.ImportFromExpr(module="math", names=[alias1]) @@ -136,7 +164,9 @@ def test_transpiler_wildcard_import_from_expr() -> None: def test_transpiler_future_import_from_expr() -> None: - """Test astx.ImportFromExpr from future import.""" + """ + title: Test astx.ImportFromExpr from future import. + """ alias1 = astx.AliasExpr(name="division") import_from_expr = astx.ImportFromExpr(module="__future__", names=[alias1]) @@ -153,7 +183,9 @@ def test_transpiler_future_import_from_expr() -> None: def test_transpiler_relative_import_from_expr() -> None: - """Test astx.ImportFromExpr relative imports.""" + """ + title: Test astx.ImportFromExpr relative imports. + """ alias1 = astx.AliasExpr(name="division") alias2 = astx.AliasExpr(name="matplotlib", asname="mtlb") @@ -171,7 +203,9 @@ def test_transpiler_relative_import_from_expr() -> None: def test_transpiler_lambdaexpr() -> None: - """Test astx.LambdaExpr.""" + """ + title: 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) @@ -188,7 +222,9 @@ def test_transpiler_lambdaexpr() -> None: def test_transpiler_lambdaexpr_noparams() -> None: - """Test astx.LambdaExpr without params.""" + """ + title: Test astx.LambdaExpr without params. + """ body = astx.LiteralInt32(1) lambda_expr = astx.LambdaExpr(body=body) @@ -204,7 +240,9 @@ def test_transpiler_lambdaexpr_noparams() -> None: def test_transpiler_functiondef() -> None: - """Test astx.FunctionDef.""" + """ + title: Test astx.FunctionDef. + """ # Function parameters args = astx.Arguments( astx.Argument(name="x", type_=astx.Int32()), @@ -254,7 +292,9 @@ def test_transpiler_functiondef() -> None: def test_literal_int32() -> None: - """Test astx.LiteralInt32.""" + """ + title: Test astx.LiteralInt32. + """ # Create a LiteralInt32 node literal_int32_node = astx.LiteralInt32(value=42) @@ -266,7 +306,9 @@ def test_literal_int32() -> None: def test_literal_float16() -> None: - """Test astx.LiteralFloat16.""" + """ + title: Test astx.LiteralFloat16. + """ # Create a LiteralFloat16 node literal_float16_node = astx.LiteralFloat16(value=3.14) @@ -278,7 +320,9 @@ def test_literal_float16() -> None: def test_literal_float32() -> None: - """Test astx.LiteralFloat32.""" + """ + title: Test astx.LiteralFloat32. + """ # Create a LiteralFloat32 node literal_float32_node = astx.LiteralFloat32(value=2.718) @@ -290,7 +334,9 @@ def test_literal_float32() -> None: def test_literal_float64() -> None: - """Test astx.LiteralFloat64.""" + """ + title: Test astx.LiteralFloat64. + """ # Create a LiteralFloat64 node literal_float64_node = astx.LiteralFloat64(value=1.414) @@ -302,7 +348,9 @@ def test_literal_float64() -> None: def test_literal_complex32() -> None: - """Test astx.LiteralComplex32.""" + """ + title: Test astx.LiteralComplex32. + """ # Create a LiteralComplex32 node literal_complex32_node = astx.LiteralComplex32(real=1, imag=2.8) @@ -316,7 +364,9 @@ def test_literal_complex32() -> None: def test_literal_complex64() -> None: - """Test astx.LiteralComplex64.""" + """ + title: Test astx.LiteralComplex64. + """ # Create a LiteralComplex64 node literal_complex64_node = astx.LiteralComplex64(real=3.5, imag=4) @@ -330,7 +380,9 @@ def test_literal_complex64() -> None: def test_transpiler_typecastexpr() -> None: - """Test astx.TypeCastExpr.""" + """ + title: Test astx.TypeCastExpr. + """ # Expression to cast expr = astx.Variable(name="x") # Target type for casting @@ -347,7 +399,9 @@ def test_transpiler_typecastexpr() -> None: def test_transpiler_utf8_char() -> None: - """Test astx.Utf8Char.""" + """ + title: Test astx.Utf8Char. + """ # Create a Utf8Char node utf8_char_node = astx.LiteralUTF8Char(value="c") @@ -361,7 +415,9 @@ def test_transpiler_utf8_char() -> None: def test_transpiler_utf8_string() -> None: - """Test astx.Utf8String.""" + """ + title: Test astx.Utf8String. + """ # Create a Utf8String node utf8_string_node = astx.LiteralUTF8String(value="hello") @@ -375,7 +431,9 @@ def test_transpiler_utf8_string() -> None: def test_transpiler_literal_utf8_char() -> None: - """Test astx.LiteralUtf8Char.""" + """ + title: Test astx.LiteralUtf8Char. + """ # Create a LiteralUtf8Char node literal_utf8_char_node = astx.LiteralUTF8Char(value="a") @@ -389,7 +447,9 @@ def test_transpiler_literal_utf8_char() -> None: def test_transpiler_literal_utf8_string() -> None: - """Test astx.LiteralUtf8String.""" + """ + title: Test astx.LiteralUtf8String. + """ # Create a LiteralUtf8String node literal_utf8_string_node = astx.LiteralUTF8String(value="world") @@ -403,7 +463,9 @@ def test_transpiler_literal_utf8_string() -> None: def test_transpiler_for_range_loop_expr() -> None: - """Test `For Range Loop` expression`.""" + """ + title: Test `For Range Loop` expression`. + """ decl_a = astx.InlineVariableDeclaration( "a", type_=astx.Int32(), value=astx.LiteralInt32(-1) ) @@ -426,7 +488,9 @@ def test_transpiler_for_range_loop_expr() -> None: def test_transpiler_async_for_range_loop_expr() -> None: - """Test `Async For Range Loop` expression`.""" + """ + title: Test `Async For Range Loop` expression`. + """ decl_a = astx.InlineVariableDeclaration( "a", type_=astx.Int32(), value=astx.LiteralInt32(-1) ) @@ -449,7 +513,9 @@ def test_transpiler_async_for_range_loop_expr() -> None: def test_transpiler_break_stmt() -> None: - """Test astx.BreakStmt transpilation.""" + """ + title: Test astx.BreakStmt transpilation. + """ # Create a simple loop structure (e.g., WhileStmt) x_var = astx.Variable(name="x") condition = astx.BinaryOp(op_code="<", lhs=x_var, rhs=astx.LiteralInt32(5)) @@ -472,7 +538,9 @@ def test_transpiler_break_stmt() -> None: def test_transpiler_continue_stmt() -> None: - """Test astx.ContinueStmt transpilation.""" + """ + title: Test astx.ContinueStmt transpilation. + """ # Create a simple loop structure (e.g., WhileStmt) x_var = astx.Variable(name="x") condition = astx.BinaryOp(op_code="<", lhs=x_var, rhs=astx.LiteralInt32(5)) @@ -495,7 +563,9 @@ def test_transpiler_continue_stmt() -> None: def test_transpiler_binary_op() -> None: - """Test astx.BinaryOp for addition operation.""" + """ + title: Test astx.BinaryOp for addition operation. + """ # Create a BinaryOp node for the expression "x + y" lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") @@ -513,7 +583,9 @@ def test_transpiler_binary_op() -> None: def test_transpiler_while_stmt() -> None: - """Test astx.WhileStmt.""" + """ + title: Test astx.WhileStmt. + """ # Define a condition: x < 5 x_var = astx.Variable(name="x") condition = astx.BinaryOp( @@ -560,7 +632,9 @@ def test_transpiler_while_stmt() -> None: def test_transpiler_ifexpr_with_else() -> None: - """Test astx.IfExpr with else block.""" + """ + title: Test astx.IfExpr with else block. + """ # determine condition cond = astx.BinaryOp( op_code=">", lhs=astx.LiteralInt32(1), rhs=astx.LiteralInt32(2) @@ -591,7 +665,9 @@ def test_transpiler_ifexpr_with_else() -> None: def test_transpiler_while_expr() -> None: - """Test astx.WhileExpr.""" + """ + title: Test astx.WhileExpr. + """ # Define a condition: x < 5 x_var = astx.Variable(name="x") condition = astx.BinaryOp( @@ -637,7 +713,9 @@ def test_transpiler_while_expr() -> None: def test_transpiler_ifexpr_without_else() -> None: - """Test astx.IfExpr without else block.""" + """ + title: Test astx.IfExpr without else block. + """ # determine condition cond = astx.BinaryOp( op_code=">", lhs=astx.LiteralInt32(1), rhs=astx.LiteralInt32(2) @@ -665,7 +743,9 @@ def test_transpiler_ifexpr_without_else() -> None: def test_transpiler_ifstmt_with_else() -> None: - """Test astx.IfStmt with else block.""" + """ + title: Test astx.IfStmt with else block. + """ # determine condition cond = astx.BinaryOp( op_code=">", lhs=astx.LiteralInt32(1), rhs=astx.LiteralInt32(2) @@ -702,7 +782,9 @@ def test_transpiler_ifstmt_with_else() -> None: def test_transpiler_ifstmt_without_else() -> None: - """Test astx.IfStmt without else block.""" + """ + title: Test astx.IfStmt without else block. + """ # determine condition cond = astx.BinaryOp( op_code=">", lhs=astx.LiteralInt32(1), rhs=astx.LiteralInt32(2) @@ -736,7 +818,9 @@ def test_transpiler_ifstmt_without_else() -> None: def test_transpiler_date_type() -> None: - """Test Type[astx.Date].""" + """ + title: Test Type[astx.Date]. + """ # Generate Python code for the type generated_code = translate(astx.Date()) expected_code = "date" @@ -747,7 +831,9 @@ def test_transpiler_date_type() -> None: def test_transpiler_time_type() -> None: - """Test Type[astx.Time].""" + """ + title: Test Type[astx.Time]. + """ # Generate Python code for the type generated_code = translate(astx.Time()) expected_code = "time" @@ -758,7 +844,9 @@ def test_transpiler_time_type() -> None: def test_transpiler_timestamp_type() -> None: - """Test Type[astx.Timestamp].""" + """ + title: Test Type[astx.Timestamp]. + """ # Generate Python code for the type generated_code = translate(astx.Timestamp()) expected_code = "timestamp" @@ -769,7 +857,9 @@ def test_transpiler_timestamp_type() -> None: def test_transpiler_datetime_type() -> None: - """Test Type[astx.DateTime].""" + """ + title: Test Type[astx.DateTime]. + """ # Generate Python code for the type generated_code = translate(astx.DateTime()) expected_code = "datetime" @@ -780,7 +870,9 @@ def test_transpiler_datetime_type() -> None: def test_transpiler_literal_date() -> None: - """Test astx.LiteralDate.""" + """ + title: Test astx.LiteralDate. + """ # Create a LiteralDate node literal_date_node = astx.LiteralDate(value="2024-11-24") @@ -794,7 +886,9 @@ def test_transpiler_literal_date() -> None: def test_transpiler_literal_time() -> None: - """Test astx.LiteralTime.""" + """ + title: Test astx.LiteralTime. + """ # Create a LiteralTime node literal_time_node = astx.LiteralTime(value="14:30:00") @@ -808,7 +902,9 @@ def test_transpiler_literal_time() -> None: def test_transpiler_literal_timestamp() -> None: - """Test astx.LiteralTimestamp.""" + """ + title: Test astx.LiteralTimestamp. + """ literal_timestamp_node = astx.LiteralTimestamp(value="2024-11-24 14:30:00") generated_code = translate(literal_timestamp_node) expected_code = "timestamp" @@ -819,7 +915,9 @@ def test_transpiler_literal_timestamp() -> None: def test_transpiler_literal_datetime() -> None: - """Test astx.LiteralDateTime.""" + """ + title: Test astx.LiteralDateTime. + """ literal_datetime_node = astx.LiteralDateTime(value="2024-11-24T14:30:00") generated_code = translate(literal_datetime_node) @@ -831,7 +929,9 @@ def test_transpiler_literal_datetime() -> None: def test_transpiler_classdefstmt() -> None: - """Test astx.ClassDefStmt.""" + """ + title: Test astx.ClassDefStmt. + """ class_body = astx.Block(name="MyClass_body") var1 = astx.Variable(name="var1") class_body.append(var1) @@ -849,7 +949,9 @@ def test_transpiler_classdefstmt() -> None: def test_transpiler_enumdeclstmt() -> None: - """Test astx.ClassDeclStmt.""" + """ + title: Test astx.ClassDeclStmt. + """ var_r = astx.VariableDeclaration( name="RED", type_=astx.DataType(), @@ -880,7 +982,9 @@ def test_transpiler_enumdeclstmt() -> None: def test_transpiler_variabledeclaration() -> None: - """Test astx.VariableDeclaration.""" + """ + title: Test astx.VariableDeclaration. + """ var_r = astx.VariableDeclaration( name="RED", type_=astx.DataType(), @@ -897,7 +1001,9 @@ def test_transpiler_variabledeclaration() -> None: def test_transpiler_structdeclstmt() -> None: - """Test astx.StructDeclStmt.""" + """ + title: Test astx.StructDeclStmt. + """ # Define struct attributes attr1 = astx.VariableDeclaration( name="id", @@ -933,7 +1039,9 @@ def test_transpiler_structdeclstmt() -> None: def test_transpiler_structdefstmt() -> None: - """Test astx.StructDefStmt.""" + """ + title: Test astx.StructDefStmt. + """ attr1 = astx.VariableDeclaration( name="id", type_=astx.DataType(), @@ -963,7 +1071,9 @@ def test_transpiler_structdefstmt() -> None: def test_transpiler_subscriptexpr_upper_lower() -> None: - """Test astx.SubscriptExpr (slice).""" + """ + title: Test astx.SubscriptExpr (slice). + """ a_var = astx.Variable(name="a") subscr_expr = astx.SubscriptExpr( value=a_var, @@ -980,7 +1090,9 @@ def test_transpiler_subscriptexpr_upper_lower() -> None: def test_transpiler_subscriptexpr_index() -> None: - """Test astx.SubscriptExpr (index).""" + """ + title: Test astx.SubscriptExpr (index). + """ a_var = astx.Variable(name="a") subscr_expr = astx.SubscriptExpr( value=a_var, @@ -997,7 +1109,14 @@ def test_transpiler_subscriptexpr_index() -> None: def fn_print( arg: astx.LiteralString, ) -> astx.FunctionCall: - """Return a FunctionCall to print a string.""" + """ + title: Return a FunctionCall to print a string. + parameters: + arg: + type: astx.LiteralString + returns: + type: astx.FunctionCall + """ proto = astx.FunctionPrototype( name="print", args=astx.Arguments(astx.Argument("_", type_=astx.String())), @@ -1012,7 +1131,9 @@ def fn_print( @pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python>=3.10") def test_transpiler_switchstmt() -> None: - """Test astx.SwitchStmt (2 cases + default).""" + """ + title: Test astx.SwitchStmt (2 cases + default). + """ value_expr = astx.Variable(name="x") condition1 = astx.LiteralInt32(value=1) body1 = astx.Block() @@ -1048,7 +1169,9 @@ def test_transpiler_switchstmt() -> None: def test_transpiler_yieldexpr_whilestmt() -> None: - """Test astx.YieldExpr (using WhileStmt).""" + """ + title: Test astx.YieldExpr (using WhileStmt). + """ while_cond = astx.LiteralBoolean(True) while_body = astx.Block() yield_expr = astx.YieldExpr(value=astx.LiteralInt32(1)) @@ -1067,7 +1190,9 @@ def test_transpiler_yieldexpr_whilestmt() -> None: def test_transpiler_yieldstmt_whilestmt() -> None: - """Test astx.YieldStmt (using WhileStmt).""" + """ + title: Test astx.YieldStmt (using WhileStmt). + """ while_cond = astx.LiteralBoolean(True) while_body = astx.Block() yield_stmt = astx.YieldExpr(value=astx.LiteralInt32(1)) @@ -1085,7 +1210,9 @@ def test_transpiler_yieldstmt_whilestmt() -> None: def test_transpiler_yieldfromexpr_whilestmt() -> None: - """Test astx.YieldFromExpr (using WhileStmt).""" + """ + title: Test astx.YieldFromExpr (using WhileStmt). + """ while_cond = astx.LiteralBoolean(True) while_body = astx.Block() yieldfrom_expr = astx.YieldFromExpr(value=astx.Variable("x")) @@ -1104,7 +1231,9 @@ def test_transpiler_yieldfromexpr_whilestmt() -> None: def test_transpiler_assignmentexpr() -> None: - """Test astx.AssignmentExpr.""" + """ + title: Test astx.AssignmentExpr. + """ var_a = astx.Variable(name="a") var_b = astx.Variable(name="b") assign_expr = astx.AssignmentExpr( @@ -1122,7 +1251,9 @@ def test_transpiler_assignmentexpr() -> None: def test_transpiler_delete_stmt() -> None: - """Test astx.DeleteStmt transpilation.""" + """ + title: Test astx.DeleteStmt transpilation. + """ var1 = astx.Variable(name="x") var2 = astx.Variable(name="y") delete_stmt = astx.DeleteStmt(value=[var1, var2]) @@ -1142,7 +1273,9 @@ def test_transpiler_delete_stmt() -> None: def test_transpiler_throwstmt() -> None: - """Test astx.ThrowStmt.""" + """ + title: Test astx.ThrowStmt. + """ throw_stmt = astx.ThrowStmt() generated_code = translate(throw_stmt) expected_code = "raise" @@ -1153,7 +1286,9 @@ def test_transpiler_throwstmt() -> None: def test_transpiler_exception_handler_stmt() -> None: - """Test astx.ExceptionHandlerStmt.""" + """ + title: Test astx.ExceptionHandlerStmt. + """ try_body = astx.Block() try_body.append(fn_print(astx.LiteralString(value="passed"))) exception_types = [astx.Identifier("A")] @@ -1179,7 +1314,9 @@ def test_transpiler_exception_handler_stmt() -> None: def test_transpiler_exception_handler_stmt_with_finally() -> None: - """Test astx.ExceptionHandlerStmt with FinallyHandler.""" + """ + title: Test astx.ExceptionHandlerStmt with FinallyHandler. + """ try_body = astx.Block() try_body.append(fn_print(astx.LiteralString(value="passed"))) @@ -1221,7 +1358,9 @@ def test_transpiler_exception_handler_stmt_with_finally() -> None: def test_transpiler_and_op() -> None: - """Test transpiler for AndOp.""" + """ + title: Test transpiler for AndOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.AndOp(lhs=lhs, rhs=rhs) @@ -1236,7 +1375,9 @@ def test_transpiler_and_op() -> None: def test_transpiler_or_op() -> None: - """Test transpiler for OrOp.""" + """ + title: Test transpiler for OrOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.OrOp(lhs=lhs, rhs=rhs) @@ -1250,7 +1391,9 @@ def test_transpiler_or_op() -> None: def test_transpiler_xor_op() -> None: - """Test transpiler for XorOp.""" + """ + title: Test transpiler for XorOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.XorOp(lhs=lhs, rhs=rhs) @@ -1264,7 +1407,9 @@ def test_transpiler_xor_op() -> None: def test_transpiler_nand_op() -> None: - """Test transpiler for NandOp.""" + """ + title: Test transpiler for NandOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.NandOp(lhs=lhs, rhs=rhs) @@ -1278,7 +1423,9 @@ def test_transpiler_nand_op() -> None: def test_transpiler_nor_op() -> None: - """Test transpiler for NorOp.""" + """ + title: Test transpiler for NorOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.NorOp(lhs=lhs, rhs=rhs) @@ -1290,7 +1437,9 @@ def test_transpiler_nor_op() -> None: def test_transpiler_xnor_op() -> None: - """Test transpiler for XnorOp.""" + """ + title: Test transpiler for XnorOp. + """ lhs = astx.Variable(name="x") rhs = astx.Variable(name="y") op = astx.XnorOp(lhs=lhs, rhs=rhs) @@ -1302,7 +1451,9 @@ def test_transpiler_xnor_op() -> None: def test_group_expr() -> None: - """Test struct representation.""" + """ + title: Test struct representation. + """ grp = astx.ParenthesizedExpr( astx.AndOp(astx.LiteralBoolean(True), astx.LiteralBoolean(False)) ) @@ -1314,7 +1465,9 @@ def test_group_expr() -> None: def test_transpiler_functionasyncdef() -> None: - """Test astx.FunctionAsyncDef.""" + """ + title: Test astx.FunctionAsyncDef. + """ arg_a = astx.Argument( "a", type_=astx.Int32(), default=astx.LiteralInt32(1) ) @@ -1339,7 +1492,9 @@ def test_transpiler_functionasyncdef() -> None: def test_transpiler_await_expr_() -> None: - """Test astx.AwaitExpr.""" + """ + title: Test astx.AwaitExpr. + """ var_a = astx.Variable("a") await_expr = astx.AwaitExpr(value=var_a) generated_code = translate(await_expr) @@ -1350,7 +1505,9 @@ def test_transpiler_await_expr_() -> None: def test_transpiler_literal_list() -> None: - """Test astx.LiteralList.""" + """ + title: Test astx.LiteralList. + """ lit_list = astx.LiteralList( [astx.LiteralInt32(1), astx.LiteralInt32(2), astx.LiteralInt32(3)] ) @@ -1362,7 +1519,9 @@ def test_transpiler_literal_list() -> None: def test_transpiler_literal_tuple() -> None: - """Test astx.LiteralTuple.""" + """ + title: Test astx.LiteralTuple. + """ lit_tuple = astx.LiteralTuple((astx.LiteralInt32(1), astx.LiteralInt32(2))) generated_code = transpiler.visit(lit_tuple) @@ -1373,7 +1532,9 @@ def test_transpiler_literal_tuple() -> None: def test_transpiler_literal_set() -> None: - """Test astx.LiteralSet.""" + """ + title: Test astx.LiteralSet. + """ lit_set = astx.LiteralSet( {astx.LiteralInt32(1), astx.LiteralInt32(2), astx.LiteralInt32(3)} ) @@ -1388,7 +1549,9 @@ def test_transpiler_literal_set() -> None: def test_transpiler_literal_dict() -> None: - """Test astx.LiteralDict.""" + """ + title: Test astx.LiteralDict. + """ lit_dict = astx.LiteralDict( { astx.LiteralInt32(1): astx.LiteralInt32(10), @@ -1405,7 +1568,9 @@ def test_transpiler_literal_dict() -> None: def test_transpiler_do_while_stmt() -> None: - """Test astx.DoWhileStmt.""" + """ + title: Test astx.DoWhileStmt. + """ x_var = astx.Variable(name="x") condition = astx.BinaryOp( op_code="<", @@ -1443,7 +1608,9 @@ def test_transpiler_do_while_stmt() -> None: def test_transpiler_do_while_expr() -> None: - """Test astx.DoWhileExpr.""" + """ + title: Test astx.DoWhileExpr. + """ x_var = astx.Variable(name="x") condition = astx.BinaryOp( op_code="<", @@ -1481,7 +1648,9 @@ def test_transpiler_do_while_expr() -> None: def test_transpiler_generator_expr() -> None: - """Test astx.GeneratorExpr.""" + """ + title: Test astx.GeneratorExpr. + """ comp_1 = astx.ComprehensionClause( target=astx.Variable("x"), iterable=astx.Variable("list_1"), @@ -1531,7 +1700,9 @@ def test_transpiler_generator_expr() -> None: def test_transpiler_list_comprehension() -> None: - """Test ListComprehension.""" + """ + title: Test ListComprehension. + """ gen_expr = astx.ListComprehension( element=astx.BinaryOp( op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("x") @@ -1566,7 +1737,9 @@ def test_transpiler_list_comprehension() -> None: def test_transpiler_set_comprehension() -> None: - """Test SetComprehension code generation.""" + """ + title: Test SetComprehension code generation. + """ set_comp = astx.SetComprehension( element=astx.BinaryOp( op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("x") @@ -1601,7 +1774,9 @@ def test_transpiler_set_comprehension() -> None: def test_transpiler_set_comprehension_no_conditions() -> None: - """Test SetComprehension without conditions.""" + """ + title: Test SetComprehension without conditions. + """ set_comp = astx.SetComprehension( element=astx.Variable("x"), generators=[ @@ -1620,7 +1795,9 @@ def test_transpiler_set_comprehension_no_conditions() -> None: def test_transpiler_nested_set_comprehension() -> None: - """Test nested SetComprehension.""" + """ + title: Test nested SetComprehension. + """ set_comp = astx.SetComprehension( element=astx.BinaryOp( op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("y") @@ -1645,7 +1822,9 @@ def test_transpiler_nested_set_comprehension() -> None: def test_transpiler_set_comprehension_with_multiple_conditions() -> None: - """Test SetComprehension with multiple conditions.""" + """ + title: Test SetComprehension with multiple conditions. + """ set_comp = astx.SetComprehension( element=astx.Variable("x"), generators=[ @@ -1676,7 +1855,9 @@ def test_transpiler_set_comprehension_with_multiple_conditions() -> None: def test_transpiler_ellipsis() -> None: - """Test transpilation of Ellipsis nodes.""" + """ + title: Test transpilation of Ellipsis nodes. + """ ellipsis = astx.Ellipsis() generated_code = transpiler.visit(ellipsis) @@ -1688,7 +1869,9 @@ def test_transpiler_ellipsis() -> None: def test_transpiler_ellipsis_in_context() -> None: - """Test Ellipsis transpilation within expressions.""" + """ + title: Test Ellipsis transpilation within expressions. + """ ellipsis = astx.Ellipsis() simple_code = transpiler.visit(ellipsis) assert simple_code == "..." @@ -1699,7 +1882,9 @@ def test_transpiler_ellipsis_in_context() -> None: def test_transpiler_starred_simple() -> None: - """Test simple starred expression transpilation.""" + """ + title: Test simple starred expression transpilation. + """ var = astx.Variable(name="args") starred = astx.Starred(value=var) generated_code = translate(starred) @@ -1708,7 +1893,9 @@ def test_transpiler_starred_simple() -> None: def test_transpiler_starred_in_list() -> None: - """Test starred expression within a list literal transpilation.""" + """ + title: Test starred expression within a list literal transpilation. + """ var = astx.Variable(name="items") starred = astx.Starred(value=var) lit_1 = astx.LiteralInt32(1) @@ -1721,7 +1908,9 @@ def test_transpiler_starred_in_list() -> None: def test_transpiler_multiple_starred() -> None: - """Test multiple starred expressions transpilation.""" + """ + title: Test multiple starred expressions transpilation. + """ var1 = astx.Variable(name="args1") var2 = astx.Variable(name="args2") starred1 = astx.Starred(value=var1) diff --git a/libs/astx-transpilers/tests/test_python_to_ast.py b/libs/astx-transpilers/tests/test_python_to_ast.py index e2800168..0bd66b2f 100644 --- a/libs/astx-transpilers/tests/test_python_to_ast.py +++ b/libs/astx-transpilers/tests/test_python_to_ast.py @@ -1,4 +1,6 @@ -"""ASTx Python AST transpiler implementation.""" +""" +title: ASTx Python AST transpiler implementation. +""" import ast import sys @@ -16,14 +18,20 @@ class TestAdditionalControlFlowNodes: - """Test additional control flow node types.""" + """ + title: Test additional control flow node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() def test_subscript_expr_index(self) -> None: - """Test astx.SubscriptExpr with index.""" + """ + title: Test astx.SubscriptExpr with index. + """ value = astx.Variable(name="arr") index = astx.LiteralInt32(value=0) node = astx.SubscriptExpr(value=value, index=index) @@ -33,7 +41,9 @@ def test_subscript_expr_index(self) -> None: assert result.value.id == "arr" def test_subscript_expr_slice(self) -> None: - """Test astx.SubscriptExpr with slice.""" + """ + title: Test astx.SubscriptExpr with slice. + """ value = astx.Variable(name="arr") lower = astx.LiteralInt32(value=1) upper = astx.LiteralInt32(value=5) @@ -43,7 +53,9 @@ def test_subscript_expr_slice(self) -> None: assert isinstance(result.slice, ast.Slice) def test_do_while_stmt_simple(self) -> None: - """Test astx.DoWhileStmt with condition and body.""" + """ + title: Test astx.DoWhileStmt with condition and body. + """ condition = astx.LiteralBoolean(value=True) body_stmt = astx.Variable(name="result") body = astx.Block() @@ -54,15 +66,21 @@ def test_do_while_stmt_simple(self) -> None: class TestAdditionalFunctionNodes: - """Test additional function-related node types.""" + """ + title: Test additional function-related node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_42 = 42 def test_function_return_none(self) -> None: - """Test astx.FunctionReturn with None value.""" + """ + title: Test astx.FunctionReturn with None value. + """ value = astx.LiteralNone() node = astx.FunctionReturn(value=value) result = self.transpiler.visit(node) @@ -71,7 +89,9 @@ def test_function_return_none(self) -> None: assert result.value.value is None def test_function_return_simple(self) -> None: - """Test astx.FunctionReturn with value.""" + """ + title: Test astx.FunctionReturn with value. + """ value = astx.LiteralInt32(value=self.Variable_42) node = astx.FunctionReturn(value=value) result = self.transpiler.visit(node) @@ -81,10 +101,14 @@ def test_function_return_simple(self) -> None: class TestAdditionalLiteralNodes: - """Test additional literal node types.""" + """ + title: Test additional literal node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_42 = 42 self.Variable_1024 = 1024 @@ -95,20 +119,26 @@ def setup_method(self) -> None: self.Variable_9223372036854775807 = 9223372036854775807 def test_literal_date_simple(self) -> None: - """Test astx.LiteralDate with date string.""" + """ + title: Test astx.LiteralDate with date string. + """ node = astx.LiteralDate(value="2023-12-25") result = self.transpiler.visit(node) assert isinstance(result, ast.Call) def test_literal_datetime_simple(self) -> None: - """Test astx.LiteralDateTime with simple value.""" + """ + title: Test astx.LiteralDateTime with simple value. + """ node = astx.LiteralDateTime(value="2023-01-01T00:00:00") result = self.transpiler.visit(node) assert isinstance(result, ast.Name) assert result.id == "datetime" def test_literal_dict_simple(self) -> None: - """Test astx.LiteralDict with key-value pairs.""" + """ + title: Test astx.LiteralDict with key-value pairs. + """ elements: Any = { astx.LiteralString(value="key1"): astx.LiteralInt32( value=self.Variable_1 @@ -124,42 +154,54 @@ def test_literal_dict_simple(self) -> None: assert len(result.values) == self.Variable_2 def test_literal_float32_simple(self) -> None: - """Test astx.LiteralFloat32 with simple value.""" + """ + title: Test astx.LiteralFloat32 with simple value. + """ node = astx.LiteralFloat32(value=self.Variable_3_14) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == self.Variable_3_14 def test_literal_float64_simple(self) -> None: - """Test astx.LiteralFloat64 with simple value.""" + """ + title: Test astx.LiteralFloat64 with simple value. + """ node = astx.LiteralFloat64(value=self.Variable_2_718281828) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == self.Variable_2_718281828 def test_literal_int16_simple(self) -> None: - """Test astx.LiteralInt16 with simple value.""" + """ + title: Test astx.LiteralInt16 with simple value. + """ node = astx.LiteralInt16(value=self.Variable_1024) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == self.Variable_1024 def test_literal_int64_simple(self) -> None: - """Test astx.LiteralInt64 with simple value.""" + """ + title: Test astx.LiteralInt64 with simple value. + """ node = astx.LiteralInt64(value=self.Variable_9223372036854775807) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == self.Variable_9223372036854775807 def test_literal_int8_simple(self) -> None: - """Test astx.LiteralInt8 with simple value.""" + """ + title: Test astx.LiteralInt8 with simple value. + """ node = astx.LiteralInt8(value=self.Variable_42) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == self.Variable_42 def test_literal_list_simple(self) -> None: - """Test astx.LiteralList with elements.""" + """ + title: Test astx.LiteralList with elements. + """ elements: Any = [ astx.LiteralInt32(value=self.Variable_1), astx.LiteralInt32(value=self.Variable_2), @@ -172,14 +214,18 @@ def test_literal_list_simple(self) -> None: assert result.elts[0].value == self.Variable_1 def test_literal_none_simple(self) -> None: - """Test astx.LiteralNone.""" + """ + title: Test astx.LiteralNone. + """ node = astx.LiteralNone() result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value is None def test_literal_set_simple(self) -> None: - """Test astx.LiteralSet with elements.""" + """ + title: Test astx.LiteralSet with elements. + """ elements: Any = { astx.LiteralInt32(value=self.Variable_1), astx.LiteralInt32(value=self.Variable_2), @@ -190,21 +236,27 @@ def test_literal_set_simple(self) -> None: assert len(result.elts) == self.Variable_2 def test_literal_time_simple(self) -> None: - """Test astx.LiteralTime with simple value.""" + """ + title: Test astx.LiteralTime with simple value. + """ node = astx.LiteralTime(value="12:00:00") result = self.transpiler.visit(node) assert isinstance(result, ast.Name) assert result.id == "time" def test_literal_timestamp_simple(self) -> None: - """Test astx.LiteralTimestamp with simple value.""" + """ + title: Test astx.LiteralTimestamp with simple value. + """ node = astx.LiteralTimestamp(value="2023-01-01T00:00:00Z") result = self.transpiler.visit(node) assert isinstance(result, ast.Name) assert result.id == "timestamp" def test_literal_tuple_simple(self) -> None: - """Test astx.LiteralTuple with elements.""" + """ + title: Test astx.LiteralTuple with elements. + """ elements = ( astx.LiteralInt32(value=self.Variable_1), astx.LiteralInt32(value=self.Variable_2), @@ -216,15 +268,21 @@ def test_literal_tuple_simple(self) -> None: class TestAdditionalOperatorNodes: - """Test additional operator node types.""" + """ + title: Test additional operator node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_2 = 2 def test_not_op_simple(self) -> None: - """Test astx.NotOp with simple operand.""" + """ + title: Test astx.NotOp with simple operand. + """ operand = astx.LiteralBoolean(value=True) node = astx.NotOp(operand=operand) result = self.transpiler.visit(node) @@ -232,7 +290,9 @@ def test_not_op_simple(self) -> None: assert isinstance(result.op, ast.Not) def test_or_op_simple(self) -> None: - """Test astx.OrOp with two operands.""" + """ + title: Test astx.OrOp with two operands. + """ lhs = astx.LiteralBoolean(value=True) rhs = astx.LiteralBoolean(value=False) node = astx.OrOp(lhs=lhs, rhs=rhs) @@ -242,7 +302,9 @@ def test_or_op_simple(self) -> None: assert len(result.values) == self.Variable_2 def test_unary_op_negation(self) -> None: - """Test astx.UnaryOp with negation.""" + """ + title: Test astx.UnaryOp with negation. + """ operand = astx.LiteralInt32(value=5) node = astx.UnaryOp(op_code="-", operand=operand) result = self.transpiler.visit(node) @@ -250,7 +312,9 @@ def test_unary_op_negation(self) -> None: assert isinstance(result.op, ast.USub) def test_unary_op_not(self) -> None: - """Test astx.UnaryOp with not operator.""" + """ + title: Test astx.UnaryOp with not operator. + """ operand = astx.LiteralBoolean(value=True) node = astx.UnaryOp(op_code="not", operand=operand) result = self.transpiler.visit(node) @@ -258,7 +322,9 @@ def test_unary_op_not(self) -> None: assert isinstance(result.op, ast.Not) def test_walrus_op_simple(self) -> None: - """Test astx.WalrusOp (assignment expression).""" + """ + title: Test astx.WalrusOp (assignment expression). + """ lhs = astx.Variable(name="x") rhs = astx.LiteralInt32(value=42) node = astx.WalrusOp(lhs=lhs, rhs=rhs) @@ -269,14 +335,20 @@ def test_walrus_op_simple(self) -> None: class TestAdditionalVariableNodes: - """Test additional variable-related node types.""" + """ + title: Test additional variable-related node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() def test_variable_assignment_simple(self) -> None: - """Test astx.VariableAssignment with simple assignment.""" + """ + title: Test astx.VariableAssignment with simple assignment. + """ value = astx.LiteralInt32(value=42) node = astx.VariableAssignment(name="x", value=value) result = self.transpiler.visit(node) @@ -286,7 +358,9 @@ def test_variable_assignment_simple(self) -> None: assert result.targets[0].id == "x" def test_variable_declaration_simple(self) -> None: - """Test astx.VariableDeclaration with simple type.""" + """ + title: Test astx.VariableDeclaration with simple type. + """ node = astx.VariableDeclaration( name="x", type_=astx.Int32(), value=astx.LiteralInt32(value=42) ) @@ -302,14 +376,20 @@ def test_variable_declaration_simple(self) -> None: class TestComprehensionNodes: - """Test cases for comprehension node transpilation.""" + """ + title: Test cases for comprehension node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() def test_comprehension_clause_simple(self) -> None: - """Test astx.ComprehensionClause with simple iteration.""" + """ + title: Test astx.ComprehensionClause with simple iteration. + """ target = astx.Variable(name="x") iterable = astx.Variable(name="items") node = astx.ComprehensionClause(target=target, iterable=iterable) @@ -323,7 +403,9 @@ def test_comprehension_clause_simple(self) -> None: assert result.is_async == 0 def test_generator_expr_simple(self) -> None: - """Test astx.GeneratorExpr with generator expression.""" + """ + title: Test astx.GeneratorExpr with generator expression. + """ element = astx.Variable(name="x") target = astx.Variable(name="x") iterable = astx.Variable(name="items") @@ -336,7 +418,9 @@ def test_generator_expr_simple(self) -> None: assert len(result.generators) == 1 def test_list_comprehension_simple(self) -> None: - """Test astx.ListComprehension with element and generator.""" + """ + title: Test astx.ListComprehension with element and generator. + """ element = astx.Variable(name="x") target = astx.Variable(name="x") iterable = astx.Variable(name="items") @@ -349,7 +433,9 @@ def test_list_comprehension_simple(self) -> None: assert len(result.generators) == 1 def test_set_comprehension_simple(self) -> None: - """Test astx.SetComprehension with element and generator.""" + """ + title: Test astx.SetComprehension with element and generator. + """ element = astx.Variable(name="x") target = astx.Variable(name="x") iterable = astx.Variable(name="items") @@ -363,16 +449,22 @@ def test_set_comprehension_simple(self) -> None: class TestControlFlowNodes: - """Test cases for control flow node transpilation.""" + """ + title: Test cases for control flow node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_2 = 2 self.Variable_42 = 42 def test_async_for_range_loop_expr_simple(self) -> None: - """Test astx.AsyncForRangeLoopExpr with range.""" + """ + title: Test astx.AsyncForRangeLoopExpr with range. + """ variable = astx.InlineVariableDeclaration(name="i", type_=astx.Int32()) start = astx.LiteralInt32(value=0) end = astx.LiteralInt32(value=10) @@ -387,7 +479,9 @@ def test_async_for_range_loop_expr_simple(self) -> None: assert isinstance(result, ast.ListComp) def test_break_stmt(self) -> None: - """Test astx.BreakStmt conversion.""" + """ + title: Test astx.BreakStmt conversion. + """ node = astx.BreakStmt() result = self.transpiler.visit(node) assert isinstance(result, ast.Break) @@ -395,7 +489,9 @@ def test_break_stmt(self) -> None: assert code == "break" def test_continue_stmt(self) -> None: - """Test astx.ContinueStmt conversion.""" + """ + title: Test astx.ContinueStmt conversion. + """ node = astx.ContinueStmt() result = self.transpiler.visit(node) assert isinstance(result, ast.Continue) @@ -403,7 +499,9 @@ def test_continue_stmt(self) -> None: assert code == "continue" def test_do_while_stmt_simple(self) -> None: - """Test astx.DoWhileStmt with condition and body.""" + """ + title: Test astx.DoWhileStmt with condition and body. + """ condition = astx.LiteralBoolean(value=True) body_stmt = astx.Variable(name="result") body = astx.Block() @@ -413,7 +511,9 @@ def test_do_while_stmt_simple(self) -> None: assert isinstance(result, ast.While) def test_for_count_loop_stmt_simple(self) -> None: - """Test astx.ForCountLoopStmt with range.""" + """ + title: Test astx.ForCountLoopStmt with range. + """ initializer = astx.InlineVariableDeclaration( name="i", type_=astx.DataType(), value=astx.LiteralInt32(value=0) ) @@ -456,7 +556,9 @@ def test_for_count_loop_stmt_simple(self) -> None: assert isinstance(result.body[0], ast.Break) def test_for_range_loop_expr_simple(self) -> None: - """Test astx.ForRangeLoopExpr with range expression.""" + """ + title: Test astx.ForRangeLoopExpr with range expression. + """ variable = astx.InlineVariableDeclaration(name="i", type_=astx.Int32()) start = astx.LiteralInt32(value=0) end = astx.LiteralInt32(value=10) @@ -474,7 +576,9 @@ def test_for_range_loop_expr_simple(self) -> None: assert result.generators[0].target.id == "i" def test_for_range_loop_stmt_simple(self) -> None: - """Test astx.ForRangeLoopStmt with target and iter.""" + """ + title: Test astx.ForRangeLoopStmt with target and iter. + """ variable = astx.InlineVariableDeclaration( name="item", type_=astx.DataType(), @@ -501,7 +605,9 @@ def test_for_range_loop_stmt_simple(self) -> None: assert isinstance(result.body[0], ast.Break) def test_if_expr_simple(self) -> None: - """Test astx.IfExpr with condition and branches.""" + """ + title: Test astx.IfExpr with condition and branches. + """ condition = astx.LiteralBoolean(value=True) then_expr = astx.LiteralInt32(value=1) else_expr = astx.LiteralInt32(value=2) @@ -518,7 +624,9 @@ def test_if_expr_simple(self) -> None: assert result.test.value is True def test_if_stmt_simple(self) -> None: - """Test astx.IfStmt with condition and body.""" + """ + title: Test astx.IfStmt with condition and body. + """ condition = astx.LiteralBoolean(value=True) then_stmt = astx.BreakStmt() then_body = astx.Block() @@ -530,7 +638,9 @@ def test_if_stmt_simple(self) -> None: assert result.test.value is True def test_while_expr_simple(self) -> None: - """Test astx.WhileExpr with condition and body.""" + """ + title: Test astx.WhileExpr with condition and body. + """ condition = astx.LiteralBoolean(value=True) body_expr = astx.Variable(name="result") body = astx.Block() @@ -543,7 +653,9 @@ def test_while_expr_simple(self) -> None: assert isinstance(result.elt, ast.Name) def test_while_stmt_simple(self) -> None: - """Test astx.WhileStmt with condition and body.""" + """ + title: Test astx.WhileStmt with condition and body. + """ condition = astx.LiteralBoolean(value=True) body_stmt = astx.BreakStmt() body = astx.Block() @@ -556,14 +668,20 @@ def test_while_stmt_simple(self) -> None: class TestEnumNodes: - """Test enum-related node types.""" + """ + title: Test enum-related node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() def test_enum_decl_stmt_simple(self) -> None: - """Test astx.EnumDeclStmt with simple enum.""" + """ + title: Test astx.EnumDeclStmt with simple enum. + """ attr1 = astx.VariableDeclaration(name="RED", type_=astx.DataType()) attr2 = astx.VariableDeclaration(name="BLUE", type_=astx.DataType()) node = astx.EnumDeclStmt(name="Color", attributes=[attr1, attr2]) @@ -577,14 +695,20 @@ def test_enum_decl_stmt_simple(self) -> None: class TestExceptionNodes: - """Test cases for exception handling node transpilation.""" + """ + title: Test cases for exception handling node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() def test_catch_handler_stmt_simple(self) -> None: - """Test astx.CatchHandlerStmt with exception type.""" + """ + title: Test astx.CatchHandlerStmt with exception type. + """ exception_type = astx.Identifier("Exception") body_stmt = astx.BreakStmt() body = astx.Block() @@ -597,7 +721,9 @@ def test_catch_handler_stmt_simple(self) -> None: self.transpiler.visit(node) def test_exception_handler_stmt_simple(self) -> None: - """Test astx.ExceptionHandlerStmt with try-except.""" + """ + title: Test astx.ExceptionHandlerStmt with try-except. + """ body_stmt = astx.BreakStmt() body = astx.Block() body.append(body_stmt) @@ -610,7 +736,9 @@ def test_exception_handler_stmt_simple(self) -> None: self.transpiler.visit(node) def test_finally_handler_stmt_simple(self) -> None: - """Test astx.FinallyHandlerStmt with finally block.""" + """ + title: Test astx.FinallyHandlerStmt with finally block. + """ body_stmt = astx.BreakStmt() body = astx.Block() body.append(body_stmt) @@ -621,7 +749,9 @@ def test_finally_handler_stmt_simple(self) -> None: assert isinstance(result.finalbody[0], ast.Break) def test_throw_stmt_simple(self) -> None: - """Test astx.ThrowStmt with exception.""" + """ + title: Test astx.ThrowStmt with exception. + """ args = astx.Arguments() prototype = astx.FunctionPrototype( name="ValueError", args=args, return_type=astx.Int32() @@ -642,15 +772,21 @@ def test_throw_stmt_simple(self) -> None: class TestFunctionNodes: - """Test cases for function-related node transpilation.""" + """ + title: Test cases for function-related node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_2 = 2 def test_argument_simple(self) -> None: - """Test astx.Argument with simple name.""" + """ + title: Test astx.Argument with simple name. + """ node = astx.Argument(name="param", type_=astx.DataType()) result = self.transpiler.visit(node) assert isinstance(result, ast.arg) @@ -658,7 +794,9 @@ def test_argument_simple(self) -> None: assert result.annotation is not None def test_argument_with_type(self) -> None: - """Test astx.Argument with type annotation.""" + """ + title: Test astx.Argument with type annotation. + """ type_annotation = astx.DataType() node = astx.Argument(name="param", type_=type_annotation) result = self.transpiler.visit(node) @@ -667,7 +805,9 @@ def test_argument_with_type(self) -> None: assert isinstance(result.annotation, ast.Name) def test_arguments_empty(self) -> None: - """Test astx.Arguments with empty args.""" + """ + title: Test astx.Arguments with empty args. + """ node = astx.Arguments() result = self.transpiler.visit(node) assert isinstance(result, ast.arguments) @@ -676,7 +816,9 @@ def test_arguments_empty(self) -> None: assert len(result.kwonlyargs) == 0 def test_arguments_with_args(self) -> None: - """Test astx.Arguments with arguments.""" + """ + title: Test astx.Arguments with arguments. + """ arg1 = astx.Argument(name="x", type_=astx.DataType()) arg2 = astx.Argument(name="y", type_=astx.DataType()) node = astx.Arguments(arg1, arg2) @@ -687,7 +829,9 @@ def test_arguments_with_args(self) -> None: assert result.args[1].arg == "y" def test_function_async_def_simple(self) -> None: - """Test astx.FunctionAsyncDef with simple async function.""" + """ + title: Test astx.FunctionAsyncDef with simple async function. + """ args = astx.Arguments() prototype = astx.FunctionPrototype( name="async_func", args=args, return_type=astx.Int32() @@ -701,7 +845,9 @@ def test_function_async_def_simple(self) -> None: assert result.name == "async_func" def test_function_call_simple(self) -> None: - """Test astx.FunctionCall with simple function call.""" + """ + title: Test astx.FunctionCall with simple function call. + """ args = astx.Arguments() prototype = astx.FunctionPrototype( name="print", args=args, return_type=astx.Int32() @@ -719,7 +865,9 @@ def test_function_call_simple(self) -> None: assert result.func.id == "print" def test_function_def_simple(self) -> None: - """Test astx.FunctionDef with simple function.""" + """ + title: Test astx.FunctionDef with simple function. + """ args = astx.Arguments() prototype = astx.FunctionPrototype( name="my_func", args=args, return_type=astx.Int32() @@ -733,7 +881,9 @@ def test_function_def_simple(self) -> None: assert result.name == "my_func" def test_function_prototype_simple(self) -> None: - """Test astx.FunctionPrototype with simple prototype.""" + """ + title: Test astx.FunctionPrototype with simple prototype. + """ args = astx.Arguments() node = astx.FunctionPrototype( name="proto_func", args=args, return_type=astx.Int32() @@ -743,7 +893,9 @@ def test_function_prototype_simple(self) -> None: assert result.name == "proto_func" def test_lambda_expr_simple(self) -> None: - """Test astx.LambdaExpr with simple lambda.""" + """ + title: Test astx.LambdaExpr with simple lambda. + """ param = astx.Argument(name="x", type_=astx.DataType()) params = astx.Arguments(param) body = astx.BinaryOp( @@ -760,28 +912,38 @@ def test_lambda_expr_simple(self) -> None: class TestImportNodes: - """Test import-related node types.""" + """ + title: Test import-related node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() def test_import_expr_simple(self) -> None: - """Test astx.ImportExpr with single module.""" + """ + title: Test astx.ImportExpr with single module. + """ alias = astx.AliasExpr(name="os") node = astx.ImportExpr(names=[alias]) result = self.transpiler.visit(node) assert isinstance(result, ast.Assign) def test_import_from_expr_simple(self) -> None: - """Test astx.ImportFromExpr with module and names.""" + """ + title: Test astx.ImportFromExpr with module and names. + """ alias = astx.AliasExpr(name="path") node = astx.ImportFromExpr(module="os", names=[alias]) result = self.transpiler.visit(node) assert isinstance(result, ast.Assign) def test_import_from_stmt_simple(self) -> None: - """Test astx.ImportFromStmt with module and names.""" + """ + title: Test astx.ImportFromStmt with module and names. + """ alias = astx.AliasExpr(name="sqrt") node = astx.ImportFromStmt(module="math", names=[alias]) result = self.transpiler.visit(node) @@ -790,7 +952,9 @@ def test_import_from_stmt_simple(self) -> None: assert len(result.names) == 1 def test_import_stmt_simple(self) -> None: - """Test astx.ImportStmt with single module.""" + """ + title: Test astx.ImportStmt with single module. + """ alias = astx.AliasExpr(name="math") node = astx.ImportStmt(names=[alias]) result = self.transpiler.visit(node) @@ -800,17 +964,23 @@ def test_import_stmt_simple(self) -> None: class TestLiteralNodes: - """Test cases for literal node transpilation.""" + """ + title: Test cases for literal node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_2 = 2 self.Variable_42 = 42 self.Variable_3_14 = 3.14 def test_literal_boolean_false(self) -> None: - """Test astx.LiteralBoolean with False value.""" + """ + title: Test astx.LiteralBoolean with False value. + """ node = astx.LiteralBoolean(value=False) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -819,7 +989,9 @@ def test_literal_boolean_false(self) -> None: assert code == "False" def test_literal_boolean_true(self) -> None: - """Test astx.LiteralBoolean with True value.""" + """ + title: Test astx.LiteralBoolean with True value. + """ node = astx.LiteralBoolean(value=True) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -828,7 +1000,9 @@ def test_literal_boolean_true(self) -> None: assert code == "True" def test_literal_complex32_simple(self) -> None: - """Test astx.LiteralComplex32 with complex value.""" + """ + title: Test astx.LiteralComplex32 with complex value. + """ node = astx.LiteralComplex32(real=3.0, imag=4.0) result = self.transpiler.visit(node) assert isinstance(result, ast.Call) @@ -837,7 +1011,9 @@ def test_literal_complex32_simple(self) -> None: assert len(result.args) == self.Variable_2 def test_literal_complex64_simple(self) -> None: - """Test astx.LiteralComplex64 with complex value.""" + """ + title: Test astx.LiteralComplex64 with complex value. + """ node = astx.LiteralComplex64(real=3.0, imag=4.0) result = self.transpiler.visit(node) assert isinstance(result, ast.Call) @@ -846,14 +1022,18 @@ def test_literal_complex64_simple(self) -> None: assert len(result.args) == self.Variable_2 def test_literal_complex_simple(self) -> None: - """Test astx.LiteralComplex with simple value.""" + """ + title: Test astx.LiteralComplex with simple value. + """ node = astx.LiteralComplex(real=3.0, imag=4.0) result = self.transpiler.visit(node) assert isinstance(result, ast.Name) assert result.id == "complex" def test_literal_float16_simple(self) -> None: - """Test astx.LiteralFloat16 with float value.""" + """ + title: Test astx.LiteralFloat16 with float value. + """ node = astx.LiteralFloat16(value=3.14) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -861,7 +1041,9 @@ def test_literal_float16_simple(self) -> None: assert result.value == LITERAL_FLOAT16_VALUE def test_literal_int32_negative(self) -> None: - """Test astx.LiteralInt32 with negative value.""" + """ + title: Test astx.LiteralInt32 with negative value. + """ NEGATIVE_INT = -15 node = astx.LiteralInt32(value=NEGATIVE_INT) result = self.transpiler.visit(node) @@ -871,7 +1053,9 @@ def test_literal_int32_negative(self) -> None: assert code == str(NEGATIVE_INT) def test_literal_int32_positive(self) -> None: - """Test astx.LiteralInt32 with positive value.""" + """ + title: Test astx.LiteralInt32 with positive value. + """ POSITIVE_INT = 42 node = astx.LiteralInt32(value=POSITIVE_INT) result = self.transpiler.visit(node) @@ -881,7 +1065,9 @@ def test_literal_int32_positive(self) -> None: assert code == str(POSITIVE_INT) def test_literal_int32_zero(self) -> None: - """Test astx.LiteralInt32 with zero value.""" + """ + title: Test astx.LiteralInt32 with zero value. + """ node = astx.LiteralInt32(value=0) result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -890,7 +1076,9 @@ def test_literal_int32_zero(self) -> None: assert code == "0" def test_literal_string_empty(self) -> None: - """Test astx.LiteralString with empty string.""" + """ + title: Test astx.LiteralString with empty string. + """ node = astx.LiteralString(value="") result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -899,7 +1087,9 @@ def test_literal_string_empty(self) -> None: assert code == "''" def test_literal_string_simple(self) -> None: - """Test astx.LiteralString with simple string.""" + """ + title: Test astx.LiteralString with simple string. + """ test_string = "Hello, World!" node = astx.LiteralString(value=test_string) result = self.transpiler.visit(node) @@ -909,14 +1099,18 @@ def test_literal_string_simple(self) -> None: assert code == "'Hello, World!'" def test_literal_utf8_char_simple(self) -> None: - """Test astx.LiteralUTF8Char with character value.""" + """ + title: Test astx.LiteralUTF8Char with character value. + """ node = astx.LiteralUTF8Char(value="A") result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) assert result.value == "A" def test_literal_utf8_string_simple(self) -> None: - """Test astx.LiteralUTF8String with string value.""" + """ + title: Test astx.LiteralUTF8String with string value. + """ node = astx.LiteralUTF8String(value="Hello UTF8") result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -924,15 +1118,21 @@ def test_literal_utf8_string_simple(self) -> None: class TestOperatorNodes: - """Test cases for operator node transpilation.""" + """ + title: Test cases for operator node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.OR_OP_NUM_VALUES = 2 def test_and_op_simple(self) -> None: - """Test astx.AndOp with boolean operands.""" + """ + title: Test astx.AndOp with boolean operands. + """ left = astx.LiteralBoolean(value=True) right = astx.LiteralBoolean(value=False) node = astx.AndOp(lhs=left, rhs=right) @@ -951,7 +1151,9 @@ def test_and_op_simple(self) -> None: assert code == "True and False" def test_aug_assign_add(self) -> None: - """Test astx.AugAssign with addition.""" + """ + title: Test astx.AugAssign with addition. + """ target = astx.Identifier("x") # Replace value with name value = astx.LiteralInt32(value=5) node = astx.AugAssign(target=target, value=value, op_code="+=") @@ -968,7 +1170,9 @@ def test_aug_assign_add(self) -> None: assert code == "x += 5" def test_binary_op_addition(self) -> None: - """Test astx.BinaryOp with addition operation.""" + """ + title: Test astx.BinaryOp with addition operation. + """ LEFT_VALUE = 5 RIGHT_VALUE = 3 left = astx.LiteralInt32(value=LEFT_VALUE) @@ -985,7 +1189,9 @@ def test_binary_op_addition(self) -> None: assert code == f"{LEFT_VALUE} + {RIGHT_VALUE}" def test_binary_op_multiplication(self) -> None: - """Test astx.BinaryOp with multiplication operation.""" + """ + title: Test astx.BinaryOp with multiplication operation. + """ LEFT_VALUE = 4 RIGHT_VALUE = 7 left = astx.LiteralInt32(value=LEFT_VALUE) @@ -1000,7 +1206,9 @@ def test_binary_op_multiplication(self) -> None: assert result.right.value == RIGHT_VALUE def test_compare_op_equal(self) -> None: - """Test astx.CompareOp with equality.""" + """ + title: Test astx.CompareOp with equality. + """ TEST_INT = 5 left = astx.LiteralInt32(value=TEST_INT) right = astx.LiteralInt32(value=TEST_INT) @@ -1018,7 +1226,9 @@ def test_compare_op_equal(self) -> None: assert code == f"{TEST_INT} == {TEST_INT}" def test_nand_op_simple(self) -> None: - """Test astx.NandOp with boolean operands.""" + """ + title: Test astx.NandOp with boolean operands. + """ left = astx.LiteralBoolean(value=True) right = astx.LiteralBoolean(value=False) node = astx.NandOp(lhs=left, rhs=right) @@ -1029,7 +1239,9 @@ def test_nand_op_simple(self) -> None: assert isinstance(result.operand.op, ast.And) def test_nor_op_simple(self) -> None: - """Test astx.NorOp with boolean operands.""" + """ + title: Test astx.NorOp with boolean operands. + """ left = astx.LiteralBoolean(value=True) right = astx.LiteralBoolean(value=False) node = astx.NorOp(lhs=left, rhs=right) @@ -1040,7 +1252,9 @@ def test_nor_op_simple(self) -> None: assert isinstance(result.operand.op, ast.Or) def test_xnor_op_simple(self) -> None: - """Test astx.XnorOp with boolean operands.""" + """ + title: Test astx.XnorOp with boolean operands. + """ left = astx.LiteralBoolean(value=True) right = astx.LiteralBoolean(value=False) node = astx.XnorOp(lhs=left, rhs=right) @@ -1051,7 +1265,9 @@ def test_xnor_op_simple(self) -> None: assert isinstance(result.operand.op, ast.BitXor) def test_xor_op_simple(self) -> None: - """Test astx.XorOp with boolean operands.""" + """ + title: Test astx.XorOp with boolean operands. + """ left = astx.LiteralBoolean(value=True) right = astx.LiteralBoolean(value=False) node = astx.XorOp(lhs=left, rhs=right) @@ -1063,16 +1279,22 @@ def test_xor_op_simple(self) -> None: class TestSpecialNodes: - """Test cases for special and miscellaneous node transpilation.""" + """ + title: Test cases for special and miscellaneous node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_2 = 2 self.Variable_42 = 42 def test_alias_expr_no_asname(self) -> None: - """Test astx.AliasExpr without asname.""" + """ + title: Test astx.AliasExpr without asname. + """ node = astx.AliasExpr(name="os", asname="") result = self.transpiler.visit(node) assert isinstance(result, ast.alias) @@ -1080,7 +1302,9 @@ def test_alias_expr_no_asname(self) -> None: assert result.asname == "" def test_alias_expr_simple(self) -> None: - """Test astx.AliasExpr with simple alias.""" + """ + title: Test astx.AliasExpr with simple alias. + """ node = astx.AliasExpr(name="numpy", asname="np") result = self.transpiler.visit(node) assert isinstance(result, ast.alias) @@ -1088,7 +1312,9 @@ def test_alias_expr_simple(self) -> None: assert result.asname == "np" def test_ast_nodes_list(self) -> None: - """Test astx.ASTNodes with multiple nodes.""" + """ + title: Test astx.ASTNodes with multiple nodes. + """ node1 = astx.LiteralInt32(value=1) node2 = astx.LiteralInt32(value=2) node = astx.ASTNodes() @@ -1102,7 +1328,9 @@ def test_ast_nodes_list(self) -> None: assert result[1].value == self.Variable_2 def test_await_expr_simple(self) -> None: - """Test astx.AwaitExpr with simple value.""" + """ + title: Test astx.AwaitExpr with simple value. + """ value = astx.Variable(name="async_func") node = astx.AwaitExpr(value=value) result = self.transpiler.visit(node) @@ -1113,7 +1341,9 @@ def test_await_expr_simple(self) -> None: assert code == "await async_func" def test_block_simple(self) -> None: - """Test astx.Block with statements.""" + """ + title: Test astx.Block with statements. + """ stmt1 = astx.BreakStmt() stmt2 = astx.ContinueStmt() node = astx.Block() @@ -1126,7 +1356,9 @@ def test_block_simple(self) -> None: assert isinstance(result[1], ast.Continue) def test_delete_stmt_simple(self) -> None: - """Test astx.DeleteStmt with variable.""" + """ + title: Test astx.DeleteStmt with variable. + """ target = astx.Variable(name="x") node = astx.DeleteStmt(value=[target]) result = self.transpiler.visit(node) @@ -1138,7 +1370,9 @@ def test_delete_stmt_simple(self) -> None: assert code == "del x" def test_ellipsis_simple(self) -> None: - """Test astx.Ellipsis conversion.""" + """ + title: Test astx.Ellipsis conversion. + """ node = astx.Ellipsis() result = self.transpiler.visit(node) assert isinstance(result, ast.Constant) @@ -1147,14 +1381,18 @@ def test_ellipsis_simple(self) -> None: assert code == "..." def test_identifier_simple(self) -> None: - """Test astx.Variable with simple value.""" + """ + title: Test astx.Variable with simple value. + """ node = astx.Variable(name="my_id") result = self.transpiler.visit(node) assert isinstance(result, ast.Name) assert result.id == "my_id" def test_module_simple(self) -> None: - """Test astx.Module with body.""" + """ + title: Test astx.Module with body. + """ stmt = astx.BreakStmt() body = astx.Block() body.append(stmt) @@ -1164,7 +1402,9 @@ def test_module_simple(self) -> None: assert isinstance(result, ast.Module) def test_parenthesized_expr_simple(self) -> None: - """Test astx.ParenthesizedExpr with inner value.""" + """ + title: Test astx.ParenthesizedExpr with inner value. + """ inner_value = astx.LiteralInt32(value=42) node = astx.ParenthesizedExpr(value=inner_value) result = self.transpiler.visit(node) @@ -1172,7 +1412,9 @@ def test_parenthesized_expr_simple(self) -> None: assert result.value == self.Variable_42 def test_starred_simple(self) -> None: - """Test astx.Starred with value.""" + """ + title: Test astx.Starred with value. + """ value = astx.Variable(name="args") node = astx.Starred(value=value) result = self.transpiler.visit(node) @@ -1183,14 +1425,20 @@ def test_starred_simple(self) -> None: class TestTypeDataNodes: - """Test cases for type and data node transpilation.""" + """ + title: Test cases for type and data node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() def test_complex32_simple(self) -> None: - """Test astx.Complex32 type.""" + """ + title: Test astx.Complex32 type. + """ node = astx.Complex32() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1198,7 +1446,9 @@ def test_complex32_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_complex64_simple(self) -> None: - """Test astx.Complex64 type.""" + """ + title: Test astx.Complex64 type. + """ node = astx.Complex64() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1206,7 +1456,9 @@ def test_complex64_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_data_type_simple(self) -> None: - """Test astx.DataType with simple type.""" + """ + title: Test astx.DataType with simple type. + """ node = astx.DataType() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1214,7 +1466,9 @@ def test_data_type_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_date_simple(self) -> None: - """Test astx.Date type.""" + """ + title: Test astx.Date type. + """ node = astx.Date() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1222,7 +1476,9 @@ def test_date_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_datetime_simple(self) -> None: - """Test astx.DateTime type.""" + """ + title: Test astx.DateTime type. + """ node = astx.DateTime() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1230,7 +1486,9 @@ def test_datetime_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_float16_simple(self) -> None: - """Test astx.Float16 type.""" + """ + title: Test astx.Float16 type. + """ node = astx.Float16() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1238,7 +1496,9 @@ def test_float16_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_float32_simple(self) -> None: - """Test astx.Float32 type.""" + """ + title: Test astx.Float32 type. + """ node = astx.Float32() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1246,7 +1506,9 @@ def test_float32_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_float64_simple(self) -> None: - """Test astx.Float64 type.""" + """ + title: Test astx.Float64 type. + """ node = astx.Float64() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1254,7 +1516,9 @@ def test_float64_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_int32_simple(self) -> None: - """Test astx.Int32 type.""" + """ + title: Test astx.Int32 type. + """ node = astx.Int32() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1262,7 +1526,9 @@ def test_int32_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_time_simple(self) -> None: - """Test astx.Time type.""" + """ + title: Test astx.Time type. + """ node = astx.Time() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1270,7 +1536,9 @@ def test_time_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_timestamp_simple(self) -> None: - """Test astx.Timestamp type.""" + """ + title: Test astx.Timestamp type. + """ node = astx.Timestamp() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1278,7 +1546,9 @@ def test_timestamp_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_type_cast_expr_simple(self) -> None: - """Test astx.TypeCastExpr with cast.""" + """ + title: Test astx.TypeCastExpr with cast. + """ target_type = astx.DataType() expr = astx.LiteralFloat32(value=3.14) node = astx.TypeCastExpr(target_type=target_type, expr=expr) @@ -1287,7 +1557,9 @@ def test_type_cast_expr_simple(self) -> None: assert isinstance(result.func, ast.Name) def test_utf8_char_simple(self) -> None: - """Test astx.UTF8Char type.""" + """ + title: Test astx.UTF8Char type. + """ node = astx.UTF8Char() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1295,7 +1567,9 @@ def test_utf8_char_simple(self) -> None: assert isinstance(result.ctx, ast.Load) def test_utf8_string_simple(self) -> None: - """Test astx.UTF8String type.""" + """ + title: Test astx.UTF8String type. + """ node = astx.UTF8String() result = self.transpiler.visit(node) assert isinstance(result, ast.Name) @@ -1304,15 +1578,21 @@ def test_utf8_string_simple(self) -> None: class TestVariableAssignmentNodes: - """Test cases for variable and assignment node transpilation.""" + """ + title: Test cases for variable and assignment node transpilation. + """ def setup_method(self) -> None: - """Set up test fixtures before each test method.""" + """ + title: Set up test fixtures before each test method. + """ self.transpiler = ASTxPythonASTTranspiler() self.Variable_42 = 42 def test_assignment_expr_single_target(self) -> None: - """Test astx.AssignmentExpr with single target.""" + """ + title: Test astx.AssignmentExpr with single target. + """ target = astx.Variable(name="x") value = astx.LiteralInt32(value=42) node = astx.AssignmentExpr(targets=[target], value=value) @@ -1326,7 +1606,9 @@ def test_assignment_expr_single_target(self) -> None: assert result.value.value == VARIABLE_42 def test_inline_variable_declaration_simple(self) -> None: - """Test astx.InlineVariableDeclaration with type annotation.""" + """ + title: Test astx.InlineVariableDeclaration with type annotation. + """ var_type = astx.DataType() value = astx.LiteralInt32(value=42) node = astx.InlineVariableDeclaration( @@ -1338,7 +1620,9 @@ def test_inline_variable_declaration_simple(self) -> None: assert result.target.id == "x" def test_variable_declaration_simple(self) -> None: - """Test astx.VariableDeclaration with simple type.""" + """ + title: Test astx.VariableDeclaration with simple type. + """ node = astx.VariableDeclaration( name="x", type_=astx.Int32(), value=astx.LiteralInt32(value=42) ) @@ -1353,7 +1637,9 @@ def test_variable_declaration_simple(self) -> None: assert result.value.value == VARIABLE_42 def test_variable_simple_name(self) -> None: - """Test astx.Variable with simple identifier.""" + """ + title: Test astx.Variable with simple identifier. + """ variable_name = "my_variable" node = astx.Variable(name=variable_name) result = self.transpiler.visit(node) @@ -1364,7 +1650,9 @@ def test_variable_simple_name(self) -> None: assert code == "my_variable" def test_variable_underscore_name(self) -> None: - """Test astx.Variable with underscore identifier.""" + """ + title: Test astx.Variable with underscore identifier. + """ variable_name = "_private_var" node = astx.Variable(name=variable_name) result = self.transpiler.visit(node) @@ -1376,14 +1664,20 @@ def test_variable_underscore_name(self) -> None: class TestYieldNodes: - """Test yield-related node types.""" + """ + title: Test yield-related node types. + """ def setup_method(self) -> None: - """Set up test fixtures.""" + """ + title: Set up test fixtures. + """ self.transpiler = ASTxPythonASTTranspiler() def test_yield_expr_simple(self) -> None: - """Test astx.YieldExpr with value.""" + """ + title: Test astx.YieldExpr with value. + """ value = astx.LiteralInt32(value=1) node = astx.YieldExpr(value=value) result = self.transpiler.visit(node) @@ -1391,7 +1685,9 @@ def test_yield_expr_simple(self) -> None: assert isinstance(result.value, ast.Constant) def test_yield_from_expr_simple(self) -> None: - """Test astx.YieldFromExpr with iterator.""" + """ + title: Test astx.YieldFromExpr with iterator. + """ value = astx.Variable(name="iterator") node = astx.YieldFromExpr(value=value) result = self.transpiler.visit(node) @@ -1399,7 +1695,9 @@ def test_yield_from_expr_simple(self) -> None: assert isinstance(result.value, ast.Name) def test_yield_stmt_simple(self) -> None: - """Test astx.YieldStmt with value.""" + """ + title: Test astx.YieldStmt with value. + """ value = astx.LiteralInt32(value=1) node = astx.YieldStmt(value=value) result = self.transpiler.visit(node) diff --git a/libs/astx/src/astx/__init__.py b/libs/astx/src/astx/__init__.py index 196dedf0..fd527896 100644 --- a/libs/astx/src/astx/__init__.py +++ b/libs/astx/src/astx/__init__.py @@ -1,5 +1,7 @@ # mypy: disable-error-code="attr-defined" -"""ASTx.""" +""" +title: ASTx. +""" from importlib import metadata as importlib_metadata @@ -206,7 +208,11 @@ def get_version() -> str: - """Return the program version.""" + """ + title: Return the program version. + returns: + type: str + """ try: return importlib_metadata.version(__name__) except importlib_metadata.PackageNotFoundError: # pragma: no cover diff --git a/libs/astx/src/astx/base.py b/libs/astx/src/astx/base.py index 11762a75..89fc62e1 100644 --- a/libs/astx/src/astx/base.py +++ b/libs/astx/src/astx/base.py @@ -1,4 +1,6 @@ -"""AST classes and functions.""" +""" +title: AST classes and functions. +""" from __future__ import annotations @@ -39,7 +41,11 @@ def is_using_jupyter_notebook() -> bool: - """Check if it is executed in a jupyter notebook.""" + """ + title: Check if it is executed in a jupyter notebook. + returns: + type: bool + """ try: from IPython import get_ipython # type: ignore @@ -73,7 +79,9 @@ def __repr__(self) -> str: @public @typechecked class ASTKind(Enum): - """The expression kind class used for downcasting.""" + """ + title: The expression kind class used for downcasting. + """ GenericKind = -100 ModuleKind = -101 @@ -201,14 +209,31 @@ class ASTKind(Enum): class ASTMeta(type): def __str__(cls) -> str: - """Return an string that represents the object.""" + """ + title: Return an string that represents the object. + returns: + type: str + """ return cls.__name__ @public @typechecked class AST(metaclass=ASTMeta): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + """ loc: SourceLocation kind: ASTKind @@ -221,7 +246,14 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ self.kind = ASTKind.GenericKind self.loc = loc self.ref = "" @@ -234,11 +266,19 @@ def __hash__(self) -> int: return int.from_bytes(value, "big") def __str__(self) -> str: - """Return an string that represents the object.""" + """ + title: Return an string that represents the object. + returns: + type: str + """ return f"{self.__class__.__name__}" def __repr__(self) -> str: - """Return an string that represents the object.""" + """ + title: Return an string that represents the object. + returns: + type: str + """ if is_using_jupyter_notebook(): return "" @@ -250,10 +290,11 @@ def __repr__(self) -> str: def _repr_png_(self) -> None: """ - Return PNG representation of the Graphviz object. + title: Return PNG representation of the Graphviz object. + summary: |- - This method is specially recognized by Jupyter Notebook to display - a Graphviz diagram inline. + This method is specially recognized by Jupyter Notebook to display + a Graphviz diagram inline. """ # importing it here in order to avoid cyclic import issue from astx.viz import visualize_image @@ -261,12 +302,18 @@ def _repr_png_(self) -> None: visualize_image(self.get_struct(simplified=False)) def _update_parent(self) -> None: - """Update the parent node.""" + """ + title: Update the parent node. + """ if self.parent is not None: self.parent.append(self) def _get_metadata(self) -> ReprStruct: - """Return the metadata for the requested AST.""" + """ + title: Return the metadata for the requested AST. + returns: + type: ReprStruct + """ metadata = { "loc": {"line": self.loc.line, "col": self.loc.col}, "comment": self.comment, @@ -278,7 +325,7 @@ def _get_metadata(self) -> ReprStruct: def _prepare_struct( self, key: str, - value: Union[PrimitivesStruct, ReprStruct], + value: PrimitivesStruct | ReprStruct, simplified: bool, ) -> ReprStruct: struct: ReprStruct = ( @@ -295,23 +342,63 @@ def _prepare_struct( @abstractmethod def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a structure that represents the node object.""" + """ + title: Return a structure that represents the node object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ def to_yaml(self, simplified: bool = False) -> str: - """Return an yaml string that represents the object.""" + """ + title: Return an yaml string that represents the object. + parameters: + simplified: + type: bool + returns: + type: str + """ return str( yaml.dump(self.get_struct(simplified=simplified), sort_keys=False) ) def to_json(self, simplified: bool = False) -> str: - """Return an json string that represents the object.""" + """ + title: Return an json string that represents the object. + parameters: + simplified: + type: bool + returns: + type: str + """ return json.dumps(self.get_struct(simplified=simplified), indent=2) @public @typechecked class ASTNodes(Generic[ASTType], AST): - """AST with a list of nodes, supporting type-specific elements.""" + """ + title: AST with a list of nodes, supporting type-specific elements. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + name: + type: str + nodes: + type: list[ASTType] + position: + type: int + """ name: str nodes: list[ASTType] @@ -323,19 +410,36 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + name: + type: str + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name self.nodes: list[ASTType] = [] self.position: int = 0 def __iter__(self) -> Iterator[ASTType]: - """Overload `iter` magic function.""" + """ + title: Overload `iter` magic function. + returns: + type: Iterator[ASTType] + """ self.position = 0 # Reset position for fresh iteration return self def __next__(self) -> ASTType: - """Overload `next` magic function.""" + """ + title: Overload `next` magic function. + returns: + type: ASTType + """ if self.position >= len(self.nodes): self.position = 0 raise StopIteration() @@ -345,19 +449,42 @@ def __next__(self) -> ASTType: return self.nodes[i] def append(self, value: ASTType) -> None: - """Append a new node to the stack.""" + """ + title: Append a new node to the stack. + parameters: + value: + type: ASTType + """ self.nodes.append(value) def __getitem__(self, index: int) -> ASTType: - """Support subscripting to get nodes by index.""" + """ + title: Support subscripting to get nodes by index. + parameters: + index: + type: int + returns: + type: ASTType + """ return self.nodes[index] def __len__(self) -> int: - """Return the number of nodes, supports len function.""" + """ + title: Return the number of nodes, supports len function. + returns: + type: int + """ return len(self.nodes) def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ args_nodes = [] for node in self.nodes: @@ -371,7 +498,22 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Expr(AST): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + """ nbytes: int = 0 @@ -379,22 +521,66 @@ class Expr(AST): @public @typechecked class ExprType(Expr): - """ExprType expression class.""" + """ + title: ExprType expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + """ nbytes: int = 0 def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a structure that represents the node object.""" + """ + title: Return a structure that represents the node object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ return {"Type": self.__class__.__name__} @public @typechecked class Undefined(Expr): - """Undefined expression class.""" + """ + title: Undefined expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + """ def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a simple structure that represents the object.""" + """ + title: Return a simple structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ value = "UNDEFINED" key = "UNDEFINED" return self._prepare_struct(key, value, simplified) @@ -408,7 +594,9 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: Undefined, ] DataTypesStruct: TypeAlias = Union[ - PrimitivesStruct, Dict[str, "DataTypesStruct"], List["DataTypesStruct"] + PrimitivesStruct, + Dict[str, "DataTypesStruct"], + List["DataTypesStruct"], ] DictDataTypesStruct: TypeAlias = Dict[str, DataTypesStruct] ReprStruct: TypeAlias = Union[ @@ -421,7 +609,28 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class DataType(ExprType): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + type_: + type: ExprType + name: + type: str + _tmp_id: + type: ClassVar[int] + """ type_: ExprType name: str @@ -439,11 +648,22 @@ def __init__( self.type_: ExprType = ExprType() def __str__(self) -> str: - """Return an string that represents the object.""" + """ + title: Return an string that represents the object. + returns: + type: str + """ return f"{self.__class__.__name__}: {self.name}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a simple structure that represents the object.""" + """ + title: Return a simple structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"DATA-TYPE[{self.__class__.__name__}]" value = self.name return self._prepare_struct(key, value, simplified) @@ -452,19 +672,79 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class OperatorType(DataType): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + type_: + type: ExprType + name: + type: str + _tmp_id: + type: ClassVar[int] + """ @public @typechecked class StatementType(AST): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + """ @public @typechecked class ParenthesizedExpr(DataType): - """AST class for explicitly grouped expressions (parentheses retained).""" + """ + title: AST class for explicitly grouped expressions (parentheses retained). + attributes: + loc: + type: SourceLocation + comment: + type: str + parent: + type: Optional[ASTNodes] + ref: + type: str + nbytes: + type: int + name: + type: str + _tmp_id: + type: ClassVar[int] + type_: + type: DataType + kind: + type: ASTKind + value: + type: Expr + """ + + type_: DataType + kind: ASTKind value: Expr @@ -474,18 +754,38 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ParenthesizedExpr instance.""" + """ + title: Initialize the ParenthesizedExpr instance. + parameters: + value: + type: Expr + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.type_ = getattr(value, "type_", DataType()) self.value = value self.kind = ASTKind.ParenthesizedExprKind def __str__(self) -> str: - """Return a string representation of the object with parentheses.""" + """ + title: Return a string representation of the object with parentheses. + returns: + type: str + """ return f"ParenthesizedExpr({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "PARENTHESIZED-EXPR" value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) diff --git a/libs/astx/src/astx/blocks.py b/libs/astx/src/astx/blocks.py index 4de6d16b..8c2550a7 100644 --- a/libs/astx/src/astx/blocks.py +++ b/libs/astx/src/astx/blocks.py @@ -1,4 +1,6 @@ -"""Module for different kind of ASTx blocks.""" +""" +title: Module for different kind of ASTx blocks. +""" from __future__ import annotations @@ -17,10 +19,19 @@ @public @typechecked class Block(ASTNodes[ASTType]): - """The AST tree.""" + """ + title: The AST tree. + """ def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ block_nodes = [] for node in self.nodes: diff --git a/libs/astx/src/astx/callables.py b/libs/astx/src/astx/callables.py index 99acaded..d4f4b503 100644 --- a/libs/astx/src/astx/callables.py +++ b/libs/astx/src/astx/callables.py @@ -1,4 +1,6 @@ -"""Module for callable ASTx.""" +""" +title: Module for callable ASTx. +""" from __future__ import annotations @@ -29,7 +31,22 @@ @public @typechecked class Argument(Variable): - """AST class for argument definition.""" + """ + title: AST class for argument definition. + attributes: + kind: + type: ASTKind + mutability: + type: MutabilityKind + name: + type: str + type_: + type: DataType + default: + type: Expr + """ + + kind: ASTKind mutability: MutabilityKind name: str @@ -45,7 +62,22 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the VarExprAST instance.""" + """ + title: Initialize the VarExprAST instance. + parameters: + name: + type: str + type_: + type: DataType + mutability: + type: MutabilityKind + default: + type: Expr + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(name=name, loc=loc, parent=parent) self.mutability = mutability self.type_ = type_ @@ -53,12 +85,23 @@ def __init__( self.kind = ASTKind.ArgumentKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ type_ = self.type_.__class__.__name__ return f"Argument[{self.name}, {type_}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"Argument[{self.name}, {self.type_}] = {self.default}" value = self.default.get_struct() return self._prepare_struct(key, value, simplified) @@ -67,7 +110,9 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Arguments(ASTNodes[Argument]): - """AST class for argument definition.""" + """ + title: AST class for argument definition. + """ def __init__(self, *args: Argument, **kwargs: Any) -> None: super().__init__(**kwargs) @@ -75,11 +120,22 @@ def __init__(self, *args: Argument, **kwargs: Any) -> None: self.append(arg) def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"Arguments({len(self.nodes)})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ args_nodes = [] for node in self.nodes: @@ -93,7 +149,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class FunctionCall(DataType): - """AST class for function call.""" + """ + title: AST class for function call. + attributes: + kind: + type: ASTKind + fn: + type: str + args: + type: Iterable[DataType] + type_: + type: DataType + """ + + kind: ASTKind fn: str args: Iterable[DataType] @@ -107,7 +176,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Call instance.""" + """ + title: Initialize the Call instance. + parameters: + fn: + type: FunctionDef | str + args: + type: Iterable[DataType] + type_: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.fn = fn if not isinstance(fn, FunctionDef) else fn.name self.args = args @@ -115,12 +197,23 @@ def __init__( self.type_ = type_ def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ args = [str(arg) for arg in self.args] return f"Call[{self.fn}: {', '.join(args)}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ call_params = [] for node in self.args: @@ -143,7 +236,27 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class FunctionPrototype(StatementType): - """AST class for function prototype declaration.""" + """ + title: AST class for function prototype declaration. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + name: + type: str + args: + type: Arguments + return_type: + type: AnyType + scope: + type: ScopeKind + visibility: + type: VisibilityKind + """ + + loc: SourceLocation + kind: ASTKind name: str args: Arguments @@ -161,7 +274,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the FunctionPrototype instance.""" + """ + title: Initialize the FunctionPrototype instance. + parameters: + name: + type: str + args: + type: Arguments + return_type: + type: AnyType + scope: + type: ScopeKind + visibility: + type: VisibilityKind + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name self.args = args @@ -172,14 +302,30 @@ def __init__( self.visibility = visibility def get_struct(self, simplified: bool = False) -> ReprStruct: - """Get the AST structure that represent the object.""" + """ + title: Get the AST structure that represent the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ raise Exception("Visitor method not necessary") @public @typechecked class FunctionReturn(StatementType): - """AST class for function `return` statement.""" + """ + title: AST class for function `return` statement. + attributes: + kind: + type: ASTKind + value: + type: DataType + """ + + kind: ASTKind value: DataType @@ -189,17 +335,37 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Return instance.""" + """ + title: Initialize the Return instance. + parameters: + value: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.ReturnKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"Return[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "RETURN" value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -208,7 +374,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class FunctionDef(StatementType): - """AST class for function definition.""" + """ + title: AST class for function definition. + attributes: + kind: + type: ASTKind + prototype: + type: FunctionPrototype + body: + type: Block + """ + + kind: ASTKind prototype: FunctionPrototype body: Block @@ -220,7 +397,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Function instance.""" + """ + title: Initialize the Function instance. + parameters: + prototype: + type: FunctionPrototype + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.prototype = prototype self.body = body @@ -228,11 +416,19 @@ def __init__( @property def name(self) -> str: - """Return the function prototype name.""" + """ + title: Return the function prototype name. + returns: + type: str + """ return self.prototype.name def __str__(self) -> str: - """Return a string that represent the object.""" + """ + title: Return a string that represent the object. + returns: + type: str + """ return f"FunctionDef[{self.name}]" def __call__( @@ -241,11 +437,29 @@ def __call__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> FunctionCall: - """Initialize the Call instance.""" + """ + title: Initialize the Call instance. + parameters: + args: + type: tuple[DataType, Ellipsis] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + returns: + type: FunctionCall + """ return FunctionCall(fn=self, args=args, loc=loc, parent=parent) def get_struct(self, simplified: bool = False) -> ReprStruct: - """Get the AST structure that represent the object.""" + """ + title: Get the AST structure that represent the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ fn_args = self.prototype.args.get_struct(simplified) fn_body = self.body.get_struct(simplified) @@ -260,7 +474,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LambdaExpr(Expr): - """AST class for lambda expressions.""" + """ + title: AST class for lambda expressions. + attributes: + kind: + type: ASTKind + params: + type: Arguments + body: + type: Expr + """ + + kind: ASTKind params: Arguments = Arguments() body: Expr @@ -278,12 +503,23 @@ def __init__( self.kind = ASTKind.LambdaExprKind def __str__(self) -> str: - """Return a string representation of the lambda expression.""" + """ + title: Return a string representation of the lambda expression. + returns: + type: str + """ params_str = ", ".join(param.name for param in self.params) return f"lambda {params_str}: {self.body}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the lambda expression.""" + """ + title: Return the AST structure of the lambda expression. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "LambdaExpr" value: ReprStruct = { "params": self.params.get_struct(simplified), @@ -295,7 +531,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class FunctionAsyncDef(FunctionDef): - """AST class for async function definition.""" + """ + title: AST class for async function definition. + attributes: + kind: + type: ASTKind + prototype: + type: FunctionPrototype + body: + type: Block + """ + + kind: ASTKind prototype: FunctionPrototype body: Block @@ -307,18 +554,40 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the FunctionAsync instance.""" + """ + title: Initialize the FunctionAsync instance. + parameters: + prototype: + type: FunctionPrototype + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( loc=loc, parent=parent, body=body, prototype=prototype ) self.kind = ASTKind.FunctionAsyncDefKind def __str__(self) -> str: - """Return a string that represent the object.""" + """ + title: Return a string that represent the object. + returns: + type: str + """ return f"FunctionAsyncDef[{self.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Get the AST structure that represent the object.""" + """ + title: Get the AST structure that represent the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ fn_args = self.prototype.args.get_struct(simplified) fn_body = self.body.get_struct(simplified) @@ -333,7 +602,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AwaitExpr(Expr): - """AST class for AwaitExpr.""" + """ + title: AST class for AwaitExpr. + attributes: + kind: + type: ASTKind + value: + type: Optional[Expr] + """ + + kind: ASTKind value: Optional[Expr] @@ -343,17 +621,37 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the AwaitExpr instance.""" + """ + title: Initialize the AwaitExpr instance. + parameters: + value: + type: Optional[Expr] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.AwaitExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"AwaitExpr[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "AWAIT-EXPR" value = {} if self.value is None else self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -362,7 +660,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class YieldExpr(Expr): - """AST class for YieldExpr.""" + """ + title: AST class for YieldExpr. + attributes: + kind: + type: ASTKind + value: + type: Optional[Expr] + """ + + kind: ASTKind value: Optional[Expr] @@ -372,17 +679,37 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the YieldExpr instance.""" + """ + title: Initialize the YieldExpr instance. + parameters: + value: + type: Optional[Expr] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.YieldExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"YieldExpr[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "YIELD-EXPR" value = {} if self.value is None else self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -391,7 +718,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class YieldStmt(StatementType): - """AST class for yield statement.""" + """ + title: AST class for yield statement. + attributes: + kind: + type: ASTKind + value: + type: Optional[Expr] + """ + + kind: ASTKind value: Optional[Expr] @@ -401,19 +737,31 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the YieldStmt instance. - - Args: - value: The expression to yield (optional) - loc: Source location of the statement - parent: Parent AST node + """ + title: Initialize the YieldStmt instance. + summary: |- + + value: The expression to yield (optional) + loc: Source location of the statement + parent: Parent AST node + parameters: + value: + type: Optional[Expr] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.YieldStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return ( f"YieldStmt[{self.value}]" if self.value is not None @@ -421,7 +769,14 @@ def __str__(self) -> str: ) def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"YIELD-STMT[{id(self)}]" if simplified else "YIELD-STMT" value = ( self.value.get_struct(simplified) if self.value is not None else {} @@ -432,7 +787,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class YieldFromExpr(Expr): - """AST class for YieldFromExpr.""" + """ + title: AST class for YieldFromExpr. + attributes: + kind: + type: ASTKind + value: + type: Expr + """ + + kind: ASTKind value: Expr @@ -442,17 +806,37 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the YieldFromExpr instance.""" + """ + title: Initialize the YieldFromExpr instance. + parameters: + value: + type: Expr + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.YieldFromExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"YieldFromExpr[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "YIELDFROM-EXPR" value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) diff --git a/libs/astx/src/astx/classes.py b/libs/astx/src/astx/classes.py index 49372e24..a5056f50 100644 --- a/libs/astx/src/astx/classes.py +++ b/libs/astx/src/astx/classes.py @@ -1,4 +1,6 @@ -"""Module for classes definitions/declarations.""" +""" +title: Module for classes definitions/declarations. +""" from __future__ import annotations @@ -28,7 +30,30 @@ @public @typechecked class ClassDeclStmt(StatementType): - """AST class for class declaration.""" + """ + title: AST class for class declaration. + attributes: + kind: + type: ASTKind + name: + type: str + bases: + type: ASTNodes[Expr] + decorators: + type: ASTNodes[Expr] + visibility: + type: VisibilityKind + is_abstract: + type: bool + metaclass: + type: Optional[Expr] + attributes: + type: ASTNodes[VariableDeclaration] + methods: + type: ASTNodes[FunctionDef] + """ + + kind: ASTKind name: str bases: ASTNodes[Expr] @@ -53,7 +78,30 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize ClassDeclStmt instance.""" + """ + title: Initialize ClassDeclStmt instance. + parameters: + name: + type: str + bases: + type: Iterable[Expr] | ASTNodes[Expr] + decorators: + type: Iterable[Expr] | ASTNodes[Expr] + visibility: + type: VisibilityKind + is_abstract: + type: bool + metaclass: + type: Optional[Expr] + attributes: + type: Iterable[VariableDeclaration] | ASTNodes[VariableDeclaration] + methods: + type: Iterable[FunctionDef] | ASTNodes[FunctionDef] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name @@ -91,7 +139,11 @@ def __init__( self.kind = ASTKind.ClassDeclStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ modifiers = [] if self.visibility != VisibilityKind.public: modifiers.append(self.visibility.name) @@ -114,7 +166,14 @@ def __str__(self) -> str: return f"{decorators_str}{modifiers_str} {class_str}".strip() def _get_struct_wrapper(self, simplified: bool) -> DictDataTypesStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: DictDataTypesStruct + """ bases_dict: ReprStruct = {} decors_dict: ReprStruct = {} metaclass_dict: ReprStruct = {} @@ -150,7 +209,14 @@ def _get_struct_wrapper(self, simplified: bool) -> DictDataTypesStruct: return value def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ vis = dict(zip(("public", "private", "protected"), ("+", "-", "#"))) abstract = ", abstract" if self.is_abstract else "" @@ -166,7 +232,32 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ClassDefStmt(ClassDeclStmt): - """AST class for class definition, including attributes and methods.""" + """ + title: AST class for class definition, including attributes and methods. + attributes: + name: + type: str + bases: + type: ASTNodes[Expr] + decorators: + type: ASTNodes[Expr] + visibility: + type: VisibilityKind + is_abstract: + type: bool + metaclass: + type: Optional[Expr] + attributes: + type: ASTNodes[VariableDeclaration] + methods: + type: ASTNodes[FunctionDef] + kind: + type: ASTKind + body: + type: Block + """ + + kind: ASTKind body: Block @@ -185,7 +276,32 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize ClassDefStmt instance.""" + """ + title: Initialize ClassDefStmt instance. + parameters: + name: + type: str + bases: + type: Iterable[Expr] | ASTNodes[Expr] + decorators: + type: Iterable[Expr] | ASTNodes[Expr] + body: + type: Block + visibility: + type: VisibilityKind + is_abstract: + type: bool + metaclass: + type: Optional[Expr] + attributes: + type: Iterable[VariableDeclaration] | ASTNodes[VariableDeclaration] + methods: + type: Iterable[FunctionDef] | ASTNodes[FunctionDef] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( name=name, bases=bases, @@ -207,7 +323,11 @@ def __init__( self.kind = ASTKind.ClassDefStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ class_decl_str = super().__str__() if not self.body.nodes: body_str = " pass" @@ -216,7 +336,14 @@ def __str__(self) -> str: return f"{class_decl_str}:\n {body_str}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ vis = dict(zip(("public", "private", "protected"), ("+", "-", "#"))) abstract = ", abstract" if self.is_abstract else "" @@ -232,7 +359,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class EnumDeclStmt(StatementType): - """AST class for enum declaration.""" + """ + title: AST class for enum declaration. + attributes: + kind: + type: ASTKind + name: + type: str + attributes: + type: ASTNodes[VariableDeclaration] + visibility: + type: VisibilityKind + """ + + kind: ASTKind name: str attributes: ASTNodes[VariableDeclaration] @@ -247,7 +387,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize EnumDeclStmt instance.""" + """ + title: Initialize EnumDeclStmt instance. + parameters: + name: + type: str + attributes: + type: Iterable[VariableDeclaration] | ASTNodes[VariableDeclaration] + visibility: + type: VisibilityKind + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name @@ -262,7 +415,11 @@ def __init__( self.kind = ASTKind.EnumDeclStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ visibility_str = ( self.visibility.name.lower() if self.visibility != VisibilityKind.public @@ -274,7 +431,14 @@ def __str__(self) -> str: return f"{enum_header} {{\n {attrs_str}\n}}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ vis = dict(zip(("public", "private", "protected"), ("+", "-", "#"))) key = f"ENUM-DECL[{vis[self.visibility.name]}{self.name}]" @@ -291,7 +455,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class StructDeclStmt(StatementType): - """AST class for struct declaration.""" + """ + title: AST class for struct declaration. + attributes: + kind: + type: ASTKind + name: + type: str + attributes: + type: ASTNodes[VariableDeclaration] + visibility: + type: VisibilityKind + decorators: + type: ASTNodes[Expr] + methods: + type: ASTNodes[FunctionDef] + """ + + kind: ASTKind name: str attributes: ASTNodes[VariableDeclaration] @@ -310,7 +491,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize StructDeclStmt instance.""" + """ + title: Initialize StructDeclStmt instance. + parameters: + name: + type: str + attributes: + type: Iterable[VariableDeclaration] | ASTNodes[VariableDeclaration] + decorators: + type: Iterable[Expr] | ASTNodes[Expr] + methods: + type: Iterable[FunctionDef] | ASTNodes[FunctionDef] + visibility: + type: VisibilityKind + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name @@ -339,7 +537,11 @@ def __init__( self.kind = ASTKind.StructDeclStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ decorators_str = "".join( f"@{decorator}\n" for decorator in self.decorators ) @@ -353,7 +555,14 @@ def __str__(self) -> str: return f"{decorators_str}{struct_header} {{\n {attributes_str}\n}}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ vis = dict(zip(("public", "private", "protected"), ("+", "-", "#"))) key = f"STRUCT-DECL[{vis[self.visibility.name]}{self.name}]" @@ -383,7 +592,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class StructDefStmt(StructDeclStmt): - """AST class for struct definition.""" + """ + title: AST class for struct definition. + attributes: + name: + type: str + attributes: + type: ASTNodes[VariableDeclaration] + visibility: + type: VisibilityKind + decorators: + type: ASTNodes[Expr] + methods: + type: ASTNodes[FunctionDef] + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -396,7 +622,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize StructDefStmt instance.""" + """ + title: Initialize StructDefStmt instance. + parameters: + name: + type: str + attributes: + type: Iterable[VariableDeclaration] | ASTNodes[VariableDeclaration] + decorators: + type: Iterable[Expr] | ASTNodes[Expr] + methods: + type: Iterable[FunctionDef] | ASTNodes[FunctionDef] + visibility: + type: VisibilityKind + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( name=name, attributes=attributes, @@ -409,7 +652,11 @@ def __init__( self.kind = ASTKind.StructDefStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ decorators_str = "".join( f"@{decorator}\n" for decorator in self.decorators ) @@ -423,7 +670,14 @@ def __str__(self) -> str: return f"{decorators_str}{struct_header} {{\n {attributes_str}\n}}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ vis = dict(zip(("public", "private", "protected"), ("+", "-", "#"))) key = f"STRUCT-DEF[{vis[self.visibility.name]}{self.name}]" diff --git a/libs/astx/src/astx/comprehensions.py b/libs/astx/src/astx/comprehensions.py index f48c59d1..c2c444d3 100644 --- a/libs/astx/src/astx/comprehensions.py +++ b/libs/astx/src/astx/comprehensions.py @@ -1,4 +1,6 @@ -"""AST comprehension classes and functions.""" +""" +title: AST comprehension classes and functions. +""" from __future__ import annotations @@ -24,7 +26,22 @@ @public @typechecked class ComprehensionClause(Expr): - """AST node for generic comprehensions.""" + """ + title: AST node for generic comprehensions. + attributes: + kind: + type: ASTKind + target: + type: Expr + iterable: + type: Expr + conditions: + type: ASTNodes[Expr] + is_async: + type: bool + """ + + kind: ASTKind target: Expr iterable: Expr @@ -56,11 +73,22 @@ def __init__( self.conditions = ASTNodes[Expr]() def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"COMPREHENSION[is_async={self.is_async}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ conditions = ( {"conditions": self.conditions.get_struct(simplified)} if self.conditions.nodes @@ -80,7 +108,12 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Comprehension(Expr): - """AST Comprehension class.""" + """ + title: AST Comprehension class. + attributes: + generators: + type: ASTNodes[ComprehensionClause] + """ generators: ASTNodes[ComprehensionClause] @@ -103,7 +136,14 @@ def __init__( @abstractmethod def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ value: ReprStruct = { "generators": self.generators.get_struct(simplified), } @@ -114,7 +154,14 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ListComprehension(Comprehension): - """ListComprehension class.""" + """ + title: ListComprehension class. + attributes: + generators: + type: ASTNodes[ComprehensionClause] + element: + type: Expr + """ element: Expr @@ -126,12 +173,30 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the GeneratorExpr instance.""" + """ + title: Initialize the GeneratorExpr instance. + parameters: + element: + type: Expr + generators: + type: ASTNodes[ComprehensionClause] | Iterable[ComprehensionClause] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(generators=generators, loc=loc, parent=parent) self.element = element def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"{self}" key += f"#{id(self)}" if simplified else "" @@ -151,7 +216,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class SetComprehension(Comprehension): - """AST node representing set comprehension expressions.""" + """ + title: AST node representing set comprehension expressions. + attributes: + generators: + type: ASTNodes[ComprehensionClause] + kind: + type: ASTKind + element: + type: Expr + """ + + kind: ASTKind element: Expr @@ -163,17 +239,39 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the SetComprehension instance.""" + """ + title: Initialize the SetComprehension instance. + parameters: + element: + type: Expr + generators: + type: ASTNodes[ComprehensionClause] | Iterable[ComprehensionClause] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(generators=generators, loc=loc, parent=parent) self.element = element self.kind = ASTKind.SetComprehensionKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return "SET-COMPREHENSION" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ generators = ( {"generators": self.generators.get_struct(simplified)} if self.generators.nodes @@ -191,7 +289,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class GeneratorExpr(Comprehension): - """AST class for generator expressions.""" + """ + title: AST class for generator expressions. + attributes: + generators: + type: ASTNodes[ComprehensionClause] + kind: + type: ASTKind + element: + type: Expr + """ + + kind: ASTKind element: Expr @@ -203,13 +312,31 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the GeneratorExpr instance.""" + """ + title: Initialize the GeneratorExpr instance. + parameters: + element: + type: Expr + generators: + type: Iterable[ComprehensionClause] | ASTNodes[ComprehensionClause] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(generators=generators, loc=loc, parent=parent) self.element = element self.kind = ASTKind.GeneratorExprKind def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"GENERATOR-EXPR#{id(self)}" if simplified else "GENERATOR-EXPR" value: ReprStruct = { "element": self.element.get_struct(simplified), diff --git a/libs/astx/src/astx/context_manager.py b/libs/astx/src/astx/context_manager.py index 2713f7d3..65efd842 100644 --- a/libs/astx/src/astx/context_manager.py +++ b/libs/astx/src/astx/context_manager.py @@ -1,8 +1,10 @@ -"""ASTx class for With Statement (Context Manager).""" +""" +title: ASTx class for With Statement (Context Manager). +""" from __future__ import annotations -from typing import Dict, List, Optional, cast +from typing import Optional, cast from public import public @@ -22,31 +24,70 @@ @public class WithItem: - """AST class representing an item inside a `with` statement.""" + """ + title: AST class representing an item inside a `with` statement. + attributes: + context_expr: + type: Expr + instance_name: + type: Optional[Identifier] + """ + + context_expr: Expr + instance_name: Optional[Identifier] def __init__( self, context_expr: Expr, instance_name: Optional[Identifier] = None ) -> None: - """Initialize a WithItem instance.""" + """ + title: Initialize a WithItem instance. + parameters: + context_expr: + type: Expr + instance_name: + type: Optional[Identifier] + """ self.context_expr = context_expr self.instance_name = instance_name def __str__(self) -> str: - """Return string representation of the WithItem.""" + """ + title: Return string representation of the WithItem. + returns: + type: str + """ if self.instance_name: return f"{self.context_expr} as {self.instance_name}" return str(self.context_expr) def _prepare_struct( self, key: str, value: DataTypesStruct, simplified: bool = False - ) -> Dict[str, DataTypesStruct]: - """Prepare structural representation.""" + ) -> dict[str, DataTypesStruct]: + """ + title: Prepare structural representation. + parameters: + key: + type: str + value: + type: DataTypesStruct + simplified: + type: bool + returns: + type: dict[str, DataTypesStruct] + """ return {key: value} if simplified else {"WithItem": {key: value}} def get_struct( self, simplified: bool = False - ) -> Dict[str, DataTypesStruct]: - """Get structural representation of the WithItem.""" + ) -> dict[str, DataTypesStruct]: + """ + title: Get structural representation of the WithItem. + parameters: + simplified: + type: bool + returns: + type: dict[str, DataTypesStruct] + """ key = ( "CONTEXT" if not self.instance_name @@ -57,29 +98,64 @@ def get_struct( class WithStmt(StatementType): - """AST class for the `with` statement (context manager).""" + """ + title: AST class for the `with` statement (context manager). + attributes: + items: + type: list[WithItem] + body: + type: Block + kind: + type: ASTKind + """ + + items: list[WithItem] + body: Block + kind: ASTKind def __init__( self, - items: List[WithItem], + items: list[WithItem], body: Block, loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize WithStmt instance.""" + """ + title: Initialize WithStmt instance. + parameters: + items: + type: list[WithItem] + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.items = items self.body = body self.kind = ASTKind.WithStmtKind def __str__(self) -> str: - """Return string representation of the WithStmt.""" + """ + title: Return string representation of the WithStmt. + returns: + type: str + """ items_str = ", ".join(str(item) for item in self.items) return f"WithStmt[{items_str}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Get structural representation of the WithStmt.""" - items_structs: List[Dict[str, DataTypesStruct]] = [ + """ + title: Get structural representation of the WithStmt. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ + items_structs: list[dict[str, DataTypesStruct]] = [ item.get_struct(simplified) for item in self.items ] diff --git a/libs/astx/src/astx/data.py b/libs/astx/src/astx/data.py index 094e0d47..19f4dd5d 100644 --- a/libs/astx/src/astx/data.py +++ b/libs/astx/src/astx/data.py @@ -1,4 +1,6 @@ -"""Module for Variables.""" +""" +title: Module for Variables. +""" from __future__ import annotations @@ -28,7 +30,26 @@ @public @typechecked class VariableDeclaration(StatementType): - """AST class for variable declaration.""" + """ + title: AST class for variable declaration. + attributes: + kind: + type: ASTKind + mutability: + type: MutabilityKind + visibility: + type: VisibilityKind + scope: + type: ScopeKind + name: + type: str + type_: + type: DataType + value: + type: Expr + """ + + kind: ASTKind mutability: MutabilityKind visibility: VisibilityKind @@ -48,7 +69,26 @@ def __init__( parent: Optional[ASTNodes] = None, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the VarExprAST instance.""" + """ + title: Initialize the VarExprAST instance. + parameters: + name: + type: str + type_: + type: DataType + mutability: + type: MutabilityKind + visibility: + type: VisibilityKind + scope: + type: ScopeKind + value: + type: Expr + parent: + type: Optional[ASTNodes] + loc: + type: SourceLocation + """ super().__init__(loc=loc, parent=parent) self.mutability = mutability self.scope = scope @@ -59,12 +99,23 @@ def __init__( self.kind = ASTKind.VarDeclKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ type_ = self.type_.__class__.__name__ return f"VariableDeclaration[{self.name}, {type_}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = str(self) value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -74,11 +125,31 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @typechecked class InlineVariableDeclaration(Expr): """ - AST class for inline variable declaration expression. - - Can be used in expressions like for loops. + title: AST class for inline variable declaration expression. + summary: |- + + Can be used in expressions like for loops. + attributes: + scope: + type: ScopeKind + visibility: + type: VisibilityKind + kind: + type: ASTKind + mutability: + type: MutabilityKind + name: + type: str + type_: + type: DataType + value: + type: Expr """ + scope: ScopeKind + visibility: VisibilityKind + kind: ASTKind + mutability: MutabilityKind name: str type_: DataType @@ -95,7 +166,26 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the VarExprAST instance.""" + """ + title: Initialize the VarExprAST instance. + parameters: + name: + type: str + type_: + type: DataType + mutability: + type: MutabilityKind + visibility: + type: VisibilityKind + scope: + type: ScopeKind + value: + type: Expr + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.mutability = mutability self.scope = scope @@ -106,12 +196,23 @@ def __init__( self.kind = ASTKind.VarDeclKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ type_ = self.type_.__class__.__name__ return f"InlineVariableDeclaration[{self.name}, {type_}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = str(self) value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -120,7 +221,14 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Identifier(DataTypeOps): - """AST class for identifiers.""" + """ + title: AST class for identifiers. + attributes: + name: + type: str + type_: + type: DataType + """ name: str type_: DataType = AnyType() @@ -131,18 +239,38 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Identifier instance.""" + """ + title: Initialize the Identifier instance. + parameters: + name: + type: str + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.name = name # note: necessary for data operations self.type_ = AnyType() def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"{self.__class__.__name__}[{self.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return a structure that represents the Identifier object.""" + """ + title: Return a structure that represents the Identifier object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"{self.__class__.__name__.upper()}[{self.name}]" return self._prepare_struct(key, self.name, simplified) @@ -150,7 +278,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Variable(Identifier): - """AST class for the variable usage.""" + """ + title: AST class for the variable usage. + attributes: + name: + type: str + type_: + type: DataType + """ + + type_: DataType def __init__( self, @@ -159,13 +296,33 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Variable instance.""" + """ + title: Initialize the Variable instance. + parameters: + name: + type: str + type_: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(name=name, loc=loc, parent=parent) self.type_ = type_ class DeleteStmt(StatementType): - """AST class for 'del' statements.""" + """ + title: AST class for 'del' statements. + attributes: + kind: + type: ASTKind + value: + type: Iterable[Identifier] + """ + + kind: ASTKind value: Iterable[Identifier] @@ -175,18 +332,38 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the DeleteStmt instance.""" + """ + title: Initialize the DeleteStmt instance. + parameters: + value: + type: Iterable[Identifier] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value self.kind = ASTKind.DeleteStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ value_str = ", ".join(str(value) for value in self.value) return f"DeleteStmt[{value_str}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "DELETE" value: ReprStruct = { diff --git a/libs/astx/src/astx/exceptions.py b/libs/astx/src/astx/exceptions.py index 9d788d1c..1ec448d5 100644 --- a/libs/astx/src/astx/exceptions.py +++ b/libs/astx/src/astx/exceptions.py @@ -1,4 +1,6 @@ -"""Module for Exceptions.""" +""" +title: Module for Exceptions. +""" from __future__ import annotations @@ -25,7 +27,16 @@ @public @typechecked class ThrowStmt(StatementType): - """AST class for throw statements.""" + """ + title: AST class for throw statements. + attributes: + kind: + type: ASTKind + exception: + type: Optional[Expr] + """ + + kind: ASTKind exception: Optional[Expr] @@ -35,20 +46,40 @@ def __init__( parent: Optional[ASTNodes] = None, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the instance.""" + """ + title: Initialize the instance. + parameters: + exception: + type: Optional[Expr] + parent: + type: Optional[ASTNodes] + loc: + type: SourceLocation + """ super().__init__(loc=loc, parent=parent) self.exception = exception self.kind = ASTKind.ThrowStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ throw_str = ( f"ThrowStmt[{self.exception}]" if self.exception else "ThrowStmt" ) return throw_str def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"THROW-STMT[{id(self)}]" if simplified else "THROW-STMT" value = self.exception.get_struct(simplified) if self.exception else "" return self._prepare_struct(key, value, simplified) @@ -57,7 +88,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class CatchHandlerStmt(StatementType): - """AST class for catch statements.""" + """ + title: AST class for catch statements. + attributes: + kind: + type: ASTKind + body: + type: Block[AST] + name: + type: Optional[Identifier] + types: + type: Optional[ASTNodes[Identifier]] + """ + + kind: ASTKind body: Block[AST] name: Optional[Identifier] @@ -71,7 +115,20 @@ def __init__( parent: Optional[ASTNodes] = None, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the instance.""" + """ + title: Initialize the instance. + parameters: + body: + type: Block[AST] + name: + type: Optional[Identifier] + types: + type: Optional[Iterable[Identifier] | ASTNodes[Identifier]] + parent: + type: Optional[ASTNodes] + loc: + type: SourceLocation + """ super().__init__(loc=loc, parent=parent) self.body = body self.name = name @@ -89,11 +146,22 @@ def __init__( self.kind = ASTKind.CatchHandlerStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"CatchHandlerStmt[{self.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = ( f"CATCH-HANDLER-STMT[{id(self)}]" if simplified @@ -118,7 +186,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ExceptionHandlerStmt(StatementType): - """AST class for try statements.""" + """ + title: AST class for try statements. + attributes: + kind: + type: ASTKind + body: + type: Block[AST] + handlers: + type: ASTNodes[CatchHandlerStmt] + finally_handler: + type: Optional[FinallyHandlerStmt] + """ + + kind: ASTKind body: Block[AST] handlers: ASTNodes[CatchHandlerStmt] @@ -132,7 +213,20 @@ def __init__( parent: Optional[ASTNodes] = None, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the instance.""" + """ + title: Initialize the instance. + parameters: + body: + type: Block[AST] + handlers: + type: Iterable[CatchHandlerStmt] | ASTNodes[CatchHandlerStmt] + finally_handler: + type: Optional[FinallyHandlerStmt] + parent: + type: Optional[ASTNodes] + loc: + type: SourceLocation + """ super().__init__(loc=loc, parent=parent) self.body = body @@ -148,11 +242,22 @@ def __init__( self.kind = ASTKind.ExceptionHandlerStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return "ExceptionHandlerStmt" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = ( f"EXCEPTION-HANDLER-STMT[{id(self)}]" if simplified @@ -178,7 +283,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class FinallyHandlerStmt(StatementType): - """AST class for finally statements.""" + """ + title: AST class for finally statements. + attributes: + kind: + type: ASTKind + body: + type: Block[AST] + """ + + kind: ASTKind body: Block[AST] @@ -188,17 +302,37 @@ def __init__( parent: Optional[ASTNodes] = None, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the instance.""" + """ + title: Initialize the instance. + parameters: + body: + type: Block[AST] + parent: + type: Optional[ASTNodes] + loc: + type: SourceLocation + """ super().__init__(loc=loc, parent=parent) self.body = body self.kind = ASTKind.FinallyHandlerStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return "FinallyStmt" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"FINALLY-STMT[{id(self)}]" if simplified else "FINALLY-STMT" value: DictDataTypesStruct = {"body": self.body.get_struct(simplified)} diff --git a/libs/astx/src/astx/flows.py b/libs/astx/src/astx/flows.py index ef454852..1fbfb6d5 100644 --- a/libs/astx/src/astx/flows.py +++ b/libs/astx/src/astx/flows.py @@ -1,4 +1,6 @@ -"""Module for controle flow AST.""" +""" +title: Module for controle flow AST. +""" from __future__ import annotations @@ -24,7 +26,23 @@ @public @typechecked class IfStmt(StatementType): - """AST class for `if` statement.""" + """ + title: AST class for `if` statement. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + condition: + type: Expr + then: + type: Block + else_: + type: Optional[Block] + """ + + loc: SourceLocation + kind: ASTKind condition: Expr then: Block @@ -38,7 +56,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the IfStmt instance.""" + """ + title: Initialize the IfStmt instance. + parameters: + condition: + type: Expr + then: + type: Block + else_: + type: Optional[Block] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.loc = loc self.condition = condition @@ -47,11 +78,22 @@ def __init__( self.kind = ASTKind.IfStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"IfStmt[{self.condition}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ if_condition = {"condition": self.condition.get_struct(simplified)} if_then = {"then-block": self.then.get_struct(simplified)} if_else: ReprStruct = {} @@ -72,7 +114,23 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class IfExpr(Expr): - """AST class for `if` expression.""" + """ + title: AST class for `if` expression. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + condition: + type: Expr + then: + type: Block + else_: + type: Optional[Block] + """ + + loc: SourceLocation + kind: ASTKind condition: Expr then: Block @@ -86,7 +144,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the IfExpr instance.""" + """ + title: Initialize the IfExpr instance. + parameters: + condition: + type: Expr + then: + type: Block + else_: + type: Optional[Block] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.loc = loc self.condition = condition @@ -95,11 +166,22 @@ def __init__( self.kind = ASTKind.IfExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"IfExpr[{self.condition}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ if_condition = {"condition": self.condition.get_struct(simplified)} if_then = {"then-block": self.then.get_struct(simplified)} if_else: ReprStruct = {} @@ -120,7 +202,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ForRangeLoopStmt(StatementType): - """AST class for `For` Range Statement.""" + """ + title: AST class for `For` Range Statement. + attributes: + kind: + type: ASTKind + variable: + type: InlineVariableDeclaration + start: + type: Expr + end: + type: Expr + step: + type: Expr + body: + type: Block + """ + + kind: ASTKind variable: InlineVariableDeclaration start: Expr @@ -138,7 +237,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ForRangeLoopStmt instance.""" + """ + title: Initialize the ForRangeLoopStmt instance. + parameters: + variable: + type: InlineVariableDeclaration + start: + type: Expr + end: + type: Expr + step: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.variable = variable self.start = start @@ -148,7 +264,11 @@ def __init__( self.kind = ASTKind.ForRangeLoopStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ start = self.start end = self.end step = self.step @@ -156,7 +276,14 @@ def __str__(self) -> str: return f"ForRangeLoopStmt({var_name}=[{start}:{end}:{step}])" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_start = {"start": self.start.get_struct(simplified)} for_end = {"end": self.end.get_struct(simplified)} for_step = {"step": self.step.get_struct(simplified)} @@ -179,7 +306,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ForRangeLoopExpr(Expr): - """AST class for `For` Range Expression.""" + """ + title: AST class for `For` Range Expression. + attributes: + kind: + type: ASTKind + variable: + type: InlineVariableDeclaration + start: + type: Expr + end: + type: Expr + step: + type: Expr + body: + type: Block + """ + + kind: ASTKind variable: InlineVariableDeclaration start: Expr @@ -197,7 +341,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ForRangeLoopExpr instance.""" + """ + title: Initialize the ForRangeLoopExpr instance. + parameters: + variable: + type: InlineVariableDeclaration + start: + type: Expr + end: + type: Expr + step: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.variable = variable self.start = start @@ -208,7 +369,11 @@ def __init__( # self.step = step if step is not None else LiteralInt32(1) def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ var_name = self.variable.name # note: it would be nice to have the following structure # ForRangeLoopExpr({var_name}=[{start}:{end}:{step}]) @@ -217,7 +382,14 @@ def __str__(self) -> str: return f"ForRangeLoopExpr[{var_name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_var = {"var": self.variable.get_struct(simplified)} for_start = {"start": self.start.get_struct(simplified)} for_end = {"end": self.end.get_struct(simplified)} @@ -239,11 +411,25 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @typechecked class ForCountLoopStmt(StatementType): """ - AST class for a simple Count-Controlled `For` Loop statement. - - This is a very basic `for` loop, used by languages like C or C++. + title: AST class for a simple Count-Controlled `For` Loop statement. + summary: |- + + This is a very basic `for` loop, used by languages like C or C++. + attributes: + kind: + type: ASTKind + initializer: + type: InlineVariableDeclaration + condition: + type: Expr + update: + type: Expr + body: + type: Block """ + kind: ASTKind + initializer: InlineVariableDeclaration condition: Expr update: Expr @@ -258,7 +444,22 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ForCountLoopStmt instance.""" + """ + title: Initialize the ForCountLoopStmt instance. + parameters: + initializer: + type: InlineVariableDeclaration + condition: + type: Expr + update: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.initializer = initializer self.condition = condition @@ -267,14 +468,25 @@ def __init__( self.kind = ASTKind.ForCountLoopStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ init = self.initializer cond = self.condition update = self.update return f"ForCountLoopStmt({init};{cond};{update})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_init = {"initialization": self.initializer.get_struct(simplified)} for_cond = {"condition": self.condition.get_struct(simplified)} for_update = {"update": self.update.get_struct(simplified)} @@ -295,11 +507,25 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @typechecked class ForCountLoopExpr(Expr): """ - AST class for a simple Count-Controlled `For` Loop expression. - - This is a very basic `for` loop, used by languages like C or C++. + title: AST class for a simple Count-Controlled `For` Loop expression. + summary: |- + + This is a very basic `for` loop, used by languages like C or C++. + attributes: + kind: + type: ASTKind + initializer: + type: InlineVariableDeclaration + condition: + type: Expr + update: + type: Expr + body: + type: Block """ + kind: ASTKind + initializer: InlineVariableDeclaration condition: Expr update: Expr @@ -314,7 +540,22 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ForLoopCountExpr instance.""" + """ + title: Initialize the ForLoopCountExpr instance. + parameters: + initializer: + type: InlineVariableDeclaration + condition: + type: Expr + update: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.initializer = initializer self.condition = condition @@ -323,14 +564,25 @@ def __init__( self.kind = ASTKind.ForCountLoopExprKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ init = self.initializer cond = self.condition update = self.update return f"ForCountLoopExpr({init};{cond};{update})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_init = {"initialization": self.initializer.get_struct(simplified)} for_cond = {"condition": self.condition.get_struct(simplified)} for_update = {"update": self.update.get_struct(simplified)} @@ -349,7 +601,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AsyncForRangeLoopStmt(StatementType): - """AST class for asynchronous `For` Range Statement.""" + """ + title: AST class for asynchronous `For` Range Statement. + attributes: + kind: + type: ASTKind + variable: + type: InlineVariableDeclaration + start: + type: Optional[Expr] + end: + type: Expr + step: + type: Optional[Expr] + body: + type: Block + """ + + kind: ASTKind variable: InlineVariableDeclaration start: Optional[Expr] @@ -367,7 +636,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the AsyncForRangeLoopStmt instance.""" + """ + title: Initialize the AsyncForRangeLoopStmt instance. + parameters: + variable: + type: InlineVariableDeclaration + start: + type: Optional[Expr] + end: + type: Expr + step: + type: Optional[Expr] + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.variable = variable self.start = start @@ -377,7 +663,11 @@ def __init__( self.kind = ASTKind.AsyncRangeLoopStmtKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ start = self.start end = self.end step = self.step @@ -385,7 +675,14 @@ def __str__(self) -> str: return f"AsyncForRangeLoopStmt({var_name}=[{start}:{end}:{step}])" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_start = { "start": {} if self.start is None @@ -412,7 +709,24 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AsyncForRangeLoopExpr(Expr): - """AST class for asynchronous `For` Range Expression.""" + """ + title: AST class for asynchronous `For` Range Expression. + attributes: + kind: + type: ASTKind + variable: + type: InlineVariableDeclaration + start: + type: Optional[Expr] + end: + type: Expr + step: + type: Optional[Expr] + body: + type: Block + """ + + kind: ASTKind variable: InlineVariableDeclaration start: Optional[Expr] @@ -430,7 +744,24 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the AsyncForRangeLoopExpr instance.""" + """ + title: Initialize the AsyncForRangeLoopExpr instance. + parameters: + variable: + type: InlineVariableDeclaration + start: + type: Optional[Expr] + end: + type: Expr + step: + type: Optional[Expr] + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.variable = variable self.start = start @@ -440,12 +771,23 @@ def __init__( self.kind = ASTKind.AsyncRangeLoopExprKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ var_name = self.variable.name return f"AsyncForRangeLoopExpr[{var_name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ for_var = {"var": self.variable.get_struct(simplified)} for_start = { "start": {} @@ -474,23 +816,48 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class BreakStmt(StatementType): - """AST class for break statement.""" + """ + title: AST class for break statement. + attributes: + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the BreakStmt instance.""" + """ + title: Initialize the BreakStmt instance. + parameters: + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.kind = ASTKind.BreakStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return "BreakStmt" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "BREAK-STMT" value: DictDataTypesStruct = {} return self._prepare_struct(key, value, simplified) @@ -499,23 +866,48 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ContinueStmt(StatementType): - """AST class for continue statement.""" + """ + title: AST class for continue statement. + attributes: + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the ContinueStmt instance.""" + """ + title: Initialize the ContinueStmt instance. + parameters: + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.kind = ASTKind.ContinueStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return "ContinueStmt" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "CONTINUE-STMT" value: DictDataTypesStruct = {} return self._prepare_struct(key, value, simplified) @@ -524,7 +916,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class WhileStmt(StatementType): - """AST class for `while` statement.""" + """ + title: AST class for `while` statement. + attributes: + kind: + type: ASTKind + condition: + type: Expr + body: + type: Block + """ + + kind: ASTKind condition: Expr body: Block @@ -536,18 +939,40 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the WhileStmt instance.""" + """ + title: Initialize the WhileStmt instance. + parameters: + condition: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.condition = condition self.body = body self.kind = ASTKind.WhileStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"WhileStmt[{self.condition}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ while_condition = self.condition.get_struct(simplified) while_body = self.body.get_struct(simplified) @@ -563,7 +988,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class WhileExpr(Expr): - """AST class for `while` expression.""" + """ + title: AST class for `while` expression. + attributes: + kind: + type: ASTKind + condition: + type: Expr + body: + type: Block + """ + + kind: ASTKind condition: Expr body: Block @@ -575,18 +1011,40 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the WhileExpr instance.""" + """ + title: Initialize the WhileExpr instance. + parameters: + condition: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.condition = condition self.body = body self.kind = ASTKind.WhileExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"WhileExpr[{self.condition}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ while_condition = self.condition.get_struct(simplified) while_body = self.body.get_struct(simplified) @@ -602,7 +1060,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class CaseStmt(StatementType): - """AST class for a case in a Switch statement.""" + """ + title: AST class for a case in a Switch statement. + attributes: + kind: + type: ASTKind + condition: + type: Optional[Expr] + body: + type: Block + default: + type: bool + """ + + kind: ASTKind condition: Optional[Expr] = None body: Block @@ -616,7 +1087,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the CaseStmt instance.""" + """ + title: Initialize the CaseStmt instance. + parameters: + body: + type: Block + condition: + type: Optional[Expr] + default: + type: bool + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.condition = condition self.body = body @@ -634,7 +1118,11 @@ def __init__( ) def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return ( f"CaseStmt[{self.condition}]" if self.condition @@ -642,7 +1130,14 @@ def __str__(self) -> str: ) def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ default_case = "default" if self.condition is None else "" default_only = "[default]" if self.condition is None else "" id_str = f"{id(self)}" if simplified else "" @@ -670,7 +1165,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class SwitchStmt(StatementType): - """AST class for Switch statements based on Rust's match syntax.""" + """ + title: AST class for Switch statements based on Rust's match syntax. + attributes: + kind: + type: ASTKind + value: + type: Expr + cases: + type: ASTNodes[CaseStmt] + """ + + kind: ASTKind value: Expr cases: ASTNodes[CaseStmt] @@ -682,7 +1188,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the SwitchStmt instance.""" + """ + title: Initialize the SwitchStmt instance. + parameters: + value: + type: Expr + cases: + type: list[CaseStmt] | ASTNodes[CaseStmt] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.value = value @@ -696,11 +1213,22 @@ def __init__( self.kind = ASTKind.SwitchStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"SwitchStmt[{len(self.cases)}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"SWITCH-STMT[{id(self)}]" if simplified else "SWITCH-STMT" case_dict = {} for d in range(len(self.cases)): @@ -716,7 +1244,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class GotoStmt(StatementType): - """AST class for function `Goto` statement.""" + """ + title: AST class for function `Goto` statement. + attributes: + kind: + type: ASTKind + label: + type: Identifier + """ + + kind: ASTKind label: Identifier @@ -726,17 +1263,37 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the Return instance.""" + """ + title: Initialize the Return instance. + parameters: + label: + type: Identifier + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.label = label self.kind = ASTKind.GotoStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"Goto[{self.label.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"GOTO-STMT[{self.label.name}]" value: DictDataTypesStruct = {} return self._prepare_struct(key, value, simplified) @@ -745,7 +1302,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class DoWhileStmt(WhileStmt): - """AST class for `do-while` statement.""" + """ + title: AST class for `do-while` statement. + attributes: + condition: + type: Expr + body: + type: Block + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -754,21 +1322,47 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the DoWhileStmt instance.""" + """ + title: Initialize the DoWhileStmt instance. + parameters: + condition: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( condition=condition, body=body, loc=loc, parent=parent ) self.kind = ASTKind.DoWhileStmtKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"DoWhileStmt[{self.condition}]" @public @typechecked class DoWhileExpr(WhileExpr): - """AST class for `do-while` expression.""" + """ + title: AST class for `do-while` expression. + attributes: + condition: + type: Expr + body: + type: Block + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -777,12 +1371,27 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the DoWhileExpr instance.""" + """ + title: Initialize the DoWhileExpr instance. + parameters: + condition: + type: Expr + body: + type: Block + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( condition=condition, body=body, loc=loc, parent=parent ) self.kind = ASTKind.DoWhileExprKind def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"DoWhileExpr[{self.condition}]" diff --git a/libs/astx/src/astx/literals/__init__.py b/libs/astx/src/astx/literals/__init__.py index 7e98ffa4..38bd138e 100644 --- a/libs/astx/src/astx/literals/__init__.py +++ b/libs/astx/src/astx/literals/__init__.py @@ -1,4 +1,6 @@ -"""AST nodes for literals.""" +""" +title: AST nodes for literals. +""" from astx.literals.base import ( Literal, diff --git a/libs/astx/src/astx/literals/base.py b/libs/astx/src/astx/literals/base.py index f7bda6cb..6f08a2ea 100644 --- a/libs/astx/src/astx/literals/base.py +++ b/libs/astx/src/astx/literals/base.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -21,7 +23,20 @@ @public @typechecked class Literal(DataTypeOps): - """Literal Data type.""" + """ + title: Literal Data type. + attributes: + ref: + type: str + type_: + type: ExprType + loc: + type: SourceLocation + value: + type: Any + """ + + ref: str type_: ExprType loc: SourceLocation @@ -32,12 +47,23 @@ def __init__(self, *args, **kwargs) -> None: # type: ignore self.ref = uuid4().hex def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ class_name = self.__class__.__name__ return f"{class_name}({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST representation for the object.""" + """ + title: Return the AST representation for the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"Literal[{self.type_}]: {self.value}" value = self.value return self._prepare_struct(key, value, simplified) @@ -46,13 +72,32 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralNone(Literal): - """LiteralNone data type.""" + """ + title: LiteralNone data type. + attributes: + loc: + type: SourceLocation + ref: + type: str + value: + type: None + type_: + type: NoneType + """ + + ref: str + value: None type_: NoneType value = None def __init__(self, loc: SourceLocation = NO_SOURCE_LOCATION) -> None: - """Initialize LiteralNone.""" + """ + title: Initialize LiteralNone. + parameters: + loc: + type: SourceLocation + """ super().__init__(loc) self.value = None self.type_ = NoneType() diff --git a/libs/astx/src/astx/literals/boolean.py b/libs/astx/src/astx/literals/boolean.py index cc910ca4..897b9a1f 100644 --- a/libs/astx/src/astx/literals/boolean.py +++ b/libs/astx/src/astx/literals/boolean.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -16,14 +18,33 @@ @public @typechecked class LiteralBoolean(Literal): - """LiteralBoolean data type class.""" + """ + title: LiteralBoolean data type class. + attributes: + type_: + type: Boolean + loc: + type: SourceLocation + value: + type: bool + """ + + type_: Boolean + loc: SourceLocation value: bool def __init__( self, value: bool, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralBoolean.""" + """ + title: Initialize LiteralBoolean. + parameters: + value: + type: bool + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Boolean() diff --git a/libs/astx/src/astx/literals/collections.py b/libs/astx/src/astx/literals/collections.py index 2b05ee39..f953340f 100644 --- a/libs/astx/src/astx/literals/collections.py +++ b/libs/astx/src/astx/literals/collections.py @@ -1,9 +1,9 @@ -"""ASTx Collection Literals.""" +""" +title: ASTx Collection Literals. +""" from __future__ import annotations -from typing import Dict, List, Set, Tuple - from public import public from astx.base import NO_SOURCE_LOCATION, SourceLocation @@ -16,14 +16,33 @@ @public @typechecked class LiteralList(Literal): - """Literal representation of a List.""" - - elements: List[Literal] + """ + title: Literal representation of a List. + attributes: + type_: + type: ListType + loc: + type: SourceLocation + elements: + type: list[Literal] + """ + + type_: ListType + loc: SourceLocation + + elements: list[Literal] def __init__( - self, elements: List[Literal], loc: SourceLocation = NO_SOURCE_LOCATION + self, elements: list[Literal], loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralList.""" + """ + title: Initialize LiteralList. + parameters: + elements: + type: list[Literal] + loc: + type: SourceLocation + """ super().__init__(loc) self.elements = list(elements) # Ensure correct type unique_types = {type(elem.type_) for elem in elements} @@ -34,16 +53,35 @@ def __init__( @public @typechecked class LiteralTuple(Literal): - """Literal representation of a Tuple.""" - - elements: Tuple[Literal, ...] + """ + title: Literal representation of a Tuple. + attributes: + type_: + type: TupleType + loc: + type: SourceLocation + elements: + type: tuple[Literal, Ellipsis] + """ + + type_: TupleType + loc: SourceLocation + + elements: tuple[Literal, ...] def __init__( self, - elements: Tuple[Literal, ...], + elements: tuple[Literal, ...], loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize LiteralTuple.""" + """ + title: Initialize LiteralTuple. + parameters: + elements: + type: tuple[Literal, Ellipsis] + loc: + type: SourceLocation + """ super().__init__(loc) self.elements = elements self.type_ = TupleType([elem.type_ for elem in elements]) @@ -53,14 +91,33 @@ def __init__( @public @typechecked class LiteralSet(Literal): - """Literal representation of a Set.""" - - elements: Set[Literal] + """ + title: Literal representation of a Set. + attributes: + type_: + type: SetType + loc: + type: SourceLocation + elements: + type: set[Literal] + """ + + type_: SetType + loc: SourceLocation + + elements: set[Literal] def __init__( - self, elements: Set[Literal], loc: SourceLocation = NO_SOURCE_LOCATION + self, elements: set[Literal], loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralSet.""" + """ + title: Initialize LiteralSet. + parameters: + elements: + type: set[Literal] + loc: + type: SourceLocation + """ super().__init__(loc) self.elements = set(elements) unique_types = {type(elem.type_) for elem in elements} @@ -73,16 +130,35 @@ def __init__( @public @typechecked class LiteralDict(Literal): - """Literal representation of a Dictionary.""" - - elements: Dict[Literal, Literal] + """ + title: Literal representation of a Dictionary. + attributes: + type_: + type: DictType + loc: + type: SourceLocation + elements: + type: dict[Literal, Literal] + """ + + type_: DictType + loc: SourceLocation + + elements: dict[Literal, Literal] def __init__( self, - elements: Dict[Literal, Literal], + elements: dict[Literal, Literal], loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize LiteralDict.""" + """ + title: Initialize LiteralDict. + parameters: + elements: + type: dict[Literal, Literal] + loc: + type: SourceLocation + """ super().__init__(loc) self.elements = dict(elements) key_types = {type(k.type_) for k in elements.keys()} diff --git a/libs/astx/src/astx/literals/numeric.py b/libs/astx/src/astx/literals/numeric.py index 913c52f2..574dce97 100644 --- a/libs/astx/src/astx/literals/numeric.py +++ b/libs/astx/src/astx/literals/numeric.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -34,14 +36,33 @@ @public @typechecked class LiteralInt8(Literal): - """LiteralInt8 data type class.""" + """ + title: LiteralInt8 data type class. + attributes: + type_: + type: Int8 + loc: + type: SourceLocation + value: + type: int + """ + + type_: Int8 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralInt8.""" + """ + title: Initialize LiteralInt8. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Int8() @@ -51,14 +72,33 @@ def __init__( @public @typechecked class LiteralInt16(Literal): - """LiteralInt16 data type class.""" + """ + title: LiteralInt16 data type class. + attributes: + type_: + type: Int16 + loc: + type: SourceLocation + value: + type: int + """ + + type_: Int16 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralInt16.""" + """ + title: Initialize LiteralInt16. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Int16() @@ -68,14 +108,33 @@ def __init__( @public @typechecked class LiteralInt32(Literal): - """LiteralInt32 data type class.""" + """ + title: LiteralInt32 data type class. + attributes: + type_: + type: Int32 + loc: + type: SourceLocation + value: + type: int + """ + + type_: Int32 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralInt32.""" + """ + title: Initialize LiteralInt32. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Int32() @@ -85,14 +144,33 @@ def __init__( @public @typechecked class LiteralInt64(Literal): - """LiteralInt64 data type class.""" + """ + title: LiteralInt64 data type class. + attributes: + type_: + type: Int64 + loc: + type: SourceLocation + value: + type: int + """ + + type_: Int64 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralInt64.""" + """ + title: Initialize LiteralInt64. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Int64() @@ -102,14 +180,33 @@ def __init__( @public @typechecked class LiteralInt128(Literal): - """LiteralInt128 data type class.""" + """ + title: LiteralInt128 data type class. + attributes: + type_: + type: Int128 + loc: + type: SourceLocation + value: + type: int + """ + + type_: Int128 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralInt128.""" + """ + title: Initialize LiteralInt128. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Int128() @@ -119,14 +216,33 @@ def __init__( @public @typechecked class LiteralUInt8(Literal): - """LiteralUInt8 data type class.""" + """ + title: LiteralUInt8 data type class. + attributes: + type_: + type: UInt8 + loc: + type: SourceLocation + value: + type: int + """ + + type_: UInt8 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralUInt8.""" + """ + title: Initialize LiteralUInt8. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = UInt8() @@ -136,14 +252,33 @@ def __init__( @public @typechecked class LiteralUInt16(Literal): - """LiteralUInt16 data type class.""" + """ + title: LiteralUInt16 data type class. + attributes: + type_: + type: UInt16 + loc: + type: SourceLocation + value: + type: int + """ + + type_: UInt16 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralUInt16.""" + """ + title: Initialize LiteralUInt16. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = UInt16() @@ -153,14 +288,33 @@ def __init__( @public @typechecked class LiteralUInt32(Literal): - """LiteralUInt32 data type class.""" + """ + title: LiteralUInt32 data type class. + attributes: + type_: + type: UInt32 + loc: + type: SourceLocation + value: + type: int + """ + + type_: UInt32 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralUInt32.""" + """ + title: Initialize LiteralUInt32. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = UInt32() @@ -170,14 +324,33 @@ def __init__( @public @typechecked class LiteralUInt64(Literal): - """LiteralUInt64 data type class.""" + """ + title: LiteralUInt64 data type class. + attributes: + type_: + type: UInt64 + loc: + type: SourceLocation + value: + type: int + """ + + type_: UInt64 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralUInt64.""" + """ + title: Initialize LiteralUInt64. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = UInt64() @@ -187,14 +360,33 @@ def __init__( @public @typechecked class LiteralUInt128(Literal): - """LiteralUInt128 data type class.""" + """ + title: LiteralUInt128 data type class. + attributes: + type_: + type: UInt128 + loc: + type: SourceLocation + value: + type: int + """ + + type_: UInt128 + loc: SourceLocation value: int def __init__( self, value: int, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralUInt128.""" + """ + title: Initialize LiteralUInt128. + parameters: + value: + type: int + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = UInt128() @@ -204,14 +396,33 @@ def __init__( @public @typechecked class LiteralFloat16(Literal): - """LiteralFloat16 data type class.""" + """ + title: LiteralFloat16 data type class. + attributes: + type_: + type: Float16 + loc: + type: SourceLocation + value: + type: float + """ + + type_: Float16 + loc: SourceLocation value: float def __init__( self, value: float, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralFloat16.""" + """ + title: Initialize LiteralFloat16. + parameters: + value: + type: float + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Float16() @@ -221,14 +432,33 @@ def __init__( @public @typechecked class LiteralFloat32(Literal): - """LiteralFloat32 data type class.""" + """ + title: LiteralFloat32 data type class. + attributes: + type_: + type: Float32 + loc: + type: SourceLocation + value: + type: float + """ + + type_: Float32 + loc: SourceLocation value: float def __init__( self, value: float, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralFloat32.""" + """ + title: Initialize LiteralFloat32. + parameters: + value: + type: float + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Float32() @@ -238,14 +468,33 @@ def __init__( @public @typechecked class LiteralFloat64(Literal): - """LiteralFloat64 data type class.""" + """ + title: LiteralFloat64 data type class. + attributes: + type_: + type: Float64 + loc: + type: SourceLocation + value: + type: float + """ + + type_: Float64 + loc: SourceLocation value: float def __init__( self, value: float, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralFloat64.""" + """ + title: Initialize LiteralFloat64. + parameters: + value: + type: float + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Float64() @@ -255,7 +504,14 @@ def __init__( @public @typechecked class LiteralComplex(Literal): - """Base class for literal complex numbers.""" + """ + title: Base class for literal complex numbers. + attributes: + type_: + type: Complex + value: + type: tuple[float, float] + """ type_: Complex value: tuple[float, float] @@ -266,16 +522,36 @@ def __init__( imag: float, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize a generic complex number.""" + """ + title: Initialize a generic complex number. + parameters: + real: + type: float + imag: + type: float + loc: + type: SourceLocation + """ super().__init__(loc) self.value = real, imag def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"LiteralComplex({self.value[0]} + {self.value[1]}j)" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST representation for the complex literal.""" + """ + title: Return the AST representation for the complex literal. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"{self.__class__.__name__}: {self.value}" value: ReprStruct = { "real": self.value[0], @@ -287,7 +563,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralComplex32(LiteralComplex): - """LiteralComplex32 data type class.""" + """ + title: LiteralComplex32 data type class. + attributes: + value: + type: tuple[float, float] + type_: + type: Complex32 + """ + + type_: Complex32 def __init__( self, @@ -295,7 +580,16 @@ def __init__( imag: float, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize LiteralComplex32.""" + """ + title: Initialize LiteralComplex32. + parameters: + real: + type: float + imag: + type: float + loc: + type: SourceLocation + """ super().__init__(real, imag, loc) self.type_ = Complex32() @@ -303,7 +597,16 @@ def __init__( @public @typechecked class LiteralComplex64(LiteralComplex): - """LiteralComplex64 data type class.""" + """ + title: LiteralComplex64 data type class. + attributes: + value: + type: tuple[float, float] + type_: + type: Complex64 + """ + + type_: Complex64 def __init__( self, @@ -311,6 +614,15 @@ def __init__( imag: float, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize LiteralComplex64.""" + """ + title: Initialize LiteralComplex64. + parameters: + real: + type: float + imag: + type: float + loc: + type: SourceLocation + """ super().__init__(real, imag, loc) self.type_ = Complex64() diff --git a/libs/astx/src/astx/literals/string.py b/libs/astx/src/astx/literals/string.py index f44ac4fe..1a341966 100644 --- a/libs/astx/src/astx/literals/string.py +++ b/libs/astx/src/astx/literals/string.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -17,25 +19,55 @@ @public @typechecked class LiteralString(Literal): - """LiteralString data type class.""" + """ + title: LiteralString data type class. + attributes: + type_: + type: String + loc: + type: SourceLocation + value: + type: str + """ + + type_: String + loc: SourceLocation value: str def __init__( self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralString.""" + """ + title: Initialize LiteralString. + parameters: + value: + type: str + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = String() self.loc = loc def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"LiteralString({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralString: {self.value}" value = self.value return self._prepare_struct(key, value, simplified) @@ -44,7 +76,19 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralUTF8String(LiteralString): - """Literal class for UTF-8 strings.""" + """ + title: Literal class for UTF-8 strings. + attributes: + loc: + type: SourceLocation + type_: + type: UTF8String + value: + type: str + """ + + loc: SourceLocation + type_: UTF8String value: str @@ -55,11 +99,22 @@ def __init__( self.type_ = UTF8String() def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"LiteralUTF8String({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the object in a simplified.""" + """ + title: Return the structure of the object in a simplified. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralUTF8String: {self.value}" value = self.value return self._prepare_struct(key, value, simplified) @@ -68,7 +123,19 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralUTF8Char(LiteralString): - """Literal class for UTF-8 characters.""" + """ + title: Literal class for UTF-8 characters. + attributes: + loc: + type: SourceLocation + type_: + type: UTF8Char + value: + type: str + """ + + loc: SourceLocation + type_: UTF8Char value: str @@ -79,11 +146,22 @@ def __init__( self.type_ = UTF8Char() def __str__(self) -> str: - """Return a string representation of the object.""" + """ + title: Return a string representation of the object. + returns: + type: str + """ return f"LiteralUTF8Char({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the object in a simplified.""" + """ + title: Return the structure of the object in a simplified. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralUTF8Char: {self.value}" value = self.value return self._prepare_struct(key, value, simplified) diff --git a/libs/astx/src/astx/literals/temporal.py b/libs/astx/src/astx/literals/temporal.py index c36e6909..d8b4d2aa 100644 --- a/libs/astx/src/astx/literals/temporal.py +++ b/libs/astx/src/astx/literals/temporal.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -22,23 +24,54 @@ @public @typechecked class LiteralDate(Literal): - """LiteralDate data type class.""" + """ + title: LiteralDate data type class. + attributes: + value: + type: str + type_: + type: Date + loc: + type: SourceLocation + """ + + value: str + type_: Date + loc: SourceLocation def __init__( self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralDate.""" + """ + title: Initialize LiteralDate. + parameters: + value: + type: str + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Date() self.loc = loc def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"LiteralDate[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the LiteralDate object.""" + """ + title: Return the structure of the LiteralDate object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralDate: {self.value}" return self._prepare_struct(key, self.value, simplified) @@ -46,23 +79,54 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralTime(Literal): - """LiteralTime data type class.""" + """ + title: LiteralTime data type class. + attributes: + value: + type: str + type_: + type: Time + loc: + type: SourceLocation + """ + + value: str + type_: Time + loc: SourceLocation def __init__( self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralTime.""" + """ + title: Initialize LiteralTime. + parameters: + value: + type: str + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Time() self.loc = loc def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"LiteralTime[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the LiteralTime object.""" + """ + title: Return the structure of the LiteralTime object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralTime: {self.value}" return self._prepare_struct(key, self.value, simplified) @@ -70,23 +134,54 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralTimestamp(Literal): - """LiteralTimestamp data type class.""" + """ + title: LiteralTimestamp data type class. + attributes: + value: + type: str + type_: + type: Timestamp + loc: + type: SourceLocation + """ + + value: str + type_: Timestamp + loc: SourceLocation def __init__( self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralTimestamp.""" + """ + title: Initialize LiteralTimestamp. + parameters: + value: + type: str + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = Timestamp() self.loc = loc def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"LiteralTimestamp[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the LiteralTimestamp object.""" + """ + title: Return the structure of the LiteralTimestamp object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralTimestamp: {self.value}" return self._prepare_struct(key, self.value, simplified) @@ -94,22 +189,53 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class LiteralDateTime(Literal): - """LiteralDateTime data type class.""" + """ + title: LiteralDateTime data type class. + attributes: + value: + type: str + type_: + type: DateTime + loc: + type: SourceLocation + """ + + value: str + type_: DateTime + loc: SourceLocation def __init__( self, value: str, loc: SourceLocation = NO_SOURCE_LOCATION ) -> None: - """Initialize LiteralDateTime.""" + """ + title: Initialize LiteralDateTime. + parameters: + value: + type: str + loc: + type: SourceLocation + """ super().__init__(loc) self.value = value self.type_ = DateTime() self.loc = loc def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"LiteralDateTime[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the structure of the LiteralDateTime object.""" + """ + title: Return the structure of the LiteralDateTime object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"LiteralDateTime: {self.value}" return self._prepare_struct(key, self.value, simplified) diff --git a/libs/astx/src/astx/mixes.py b/libs/astx/src/astx/mixes.py index a4fbd860..fe289fe0 100644 --- a/libs/astx/src/astx/mixes.py +++ b/libs/astx/src/astx/mixes.py @@ -1,6 +1,8 @@ -"""Module for mixing ASTx types from different modules.""" +""" +title: Module for mixing ASTx types from different modules. +""" -from typing import TypeAlias, Union +from typing import TypeAlias from astx.base import DataType from astx.callables import FunctionDef @@ -8,4 +10,4 @@ __all__ = ["NamedExpr"] -NamedExpr: TypeAlias = Union[DataType, FunctionDef, Variable] +NamedExpr: TypeAlias = DataType | FunctionDef | Variable diff --git a/libs/astx/src/astx/modifiers.py b/libs/astx/src/astx/modifiers.py index 7c457cae..51e29b30 100644 --- a/libs/astx/src/astx/modifiers.py +++ b/libs/astx/src/astx/modifiers.py @@ -1,4 +1,6 @@ -"""Modifications for ASTx, such as visibility, scope, etc.""" +""" +title: Modifications for ASTx, such as visibility, scope, etc. +""" from enum import Enum @@ -7,7 +9,9 @@ @public class VisibilityKind(Enum): - """Definition of different kind of visibility.""" + """ + title: Definition of different kind of visibility. + """ public = 1 private = 2 @@ -16,7 +20,9 @@ class VisibilityKind(Enum): @public class ScopeKind(Enum): - """Definition for different kind of scopes.""" + """ + title: Definition for different kind of scopes. + """ global_ = 1 local = 2 @@ -24,7 +30,9 @@ class ScopeKind(Enum): @public class MutabilityKind(Enum): - """Definition for different kind of mutability.""" + """ + title: Definition for different kind of mutability. + """ constant = 1 mutable = 2 diff --git a/libs/astx/src/astx/operators.py b/libs/astx/src/astx/operators.py index 01b63656..613c6ee6 100644 --- a/libs/astx/src/astx/operators.py +++ b/libs/astx/src/astx/operators.py @@ -1,4 +1,6 @@ -"""ASTx classes for the operators.""" +""" +title: ASTx classes for the operators. +""" from __future__ import annotations @@ -28,7 +30,20 @@ @public @typechecked class WalrusOp(DataType): - """AST class for the Walrus (assignment expression) operator.""" + """ + title: AST class for the Walrus (assignment expression) operator. + attributes: + lhs: + type: Variable + rhs: + type: DataType + kind: + type: ASTKind + """ + + lhs: Variable + rhs: DataType + kind: ASTKind def __init__( self, @@ -36,18 +51,38 @@ def __init__( rhs: DataType, loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the WalrusOp instance.""" + """ + title: Initialize the WalrusOp instance. + parameters: + lhs: + type: Variable + rhs: + type: DataType + loc: + type: SourceLocation + """ super().__init__(loc=loc) self.lhs = lhs self.rhs = rhs self.kind = ASTKind.WalrusOpKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"WalrusOp[:=]({self.lhs} := {self.rhs})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "WALRUS[:=]" lhs = {"lhs": self.lhs.get_struct(simplified)} rhs = {"rhs": self.rhs.get_struct(simplified)} @@ -59,7 +94,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AssignmentExpr(Expr): - """AST class for assignment expressions.""" + """ + title: AST class for assignment expressions. + attributes: + kind: + type: ASTKind + targets: + type: ASTNodes[Expr] + value: + type: Expr + """ + + kind: ASTKind targets: ASTNodes[Expr] value: Expr @@ -84,11 +130,22 @@ def __init__( self.kind = ASTKind.AssignmentExprKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"AssignmentExpr[{self.value}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "ASSIGNMENT-EXPR" targets_dict = {"targets": self.targets.get_struct(simplified)} value_dict = {"value": self.value.get_struct(simplified)} @@ -104,7 +161,21 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class VariableAssignment(StatementType): - """AST class for variable declaration.""" + """ + title: AST class for variable declaration. + attributes: + loc: + type: SourceLocation + kind: + type: ASTKind + name: + type: str + value: + type: Expr + """ + + loc: SourceLocation + kind: ASTKind name: str value: Expr @@ -116,7 +187,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the VarExprAST instance.""" + """ + title: Initialize the VarExprAST instance. + parameters: + name: + type: str + value: + type: Expr + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.loc = loc self.name = name @@ -124,11 +206,22 @@ def __init__( self.kind = ASTKind.VariableAssignmentKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"VariableAssignment[{self.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = str(self) value = self.value.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -153,7 +246,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AugAssign(DataType): - """AST class for augmented assignment.""" + """ + title: AST class for augmented assignment. + attributes: + kind: + type: ASTKind + target: + type: Identifier + op_code: + type: OpCodeAugAssign + value: + type: DataType + """ + + kind: ASTKind target: Identifier op_code: OpCodeAugAssign @@ -173,11 +279,22 @@ def __init__( self.kind = ASTKind.AugmentedAssignKind def __str__(self) -> str: - """Return a string that represents the augmented assignment object.""" + """ + title: Return a string that represents the augmented assignment object. + returns: + type: str + """ return f"AugAssign[{self.op_code}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = str(self) value: ReprStruct = { "target": self.target.get_struct(simplified), @@ -189,7 +306,23 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class CompareOp(DataType): - """AST class for comparison operators acting as properties.""" + """ + title: AST class for comparison operators acting as properties. + attributes: + ops: + type: list[Literal[==, !=, <, >, <=, >=]] + comparators: + type: list[DataType] + left: + type: DataType + kind: + type: ASTKind + """ + + ops: list[Literal["==", "!=", "<", ">", "<=", ">="]] + comparators: list[DataType] + left: DataType + kind: ASTKind def __init__( self, @@ -198,7 +331,18 @@ def __init__( comparators: Iterable[DataType], loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the CompareOp instance.""" + """ + title: Initialize the CompareOp instance. + parameters: + left: + type: DataType + ops: + type: Iterable[Literal[==, !=, <, >, <=, >=]] + comparators: + type: Iterable[DataType] + loc: + type: SourceLocation + """ super().__init__(loc=loc) self.ops = list(ops) self.comparators = list(comparators) @@ -213,12 +357,23 @@ def __init__( self.kind = ASTKind.CompareOpKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ ops_str = ", ".join(self.ops) return f"Compare[{ops_str}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ ops_str = ", ".join(self.ops) key = f"COMPARE[{ops_str}]" content: ReprStruct = { @@ -233,7 +388,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Starred(Expr): - """AST class for starred expressions (*expr).""" + """ + title: AST class for starred expressions (*expr). + attributes: + kind: + type: ASTKind + value: + type: Expr + """ + + kind: ASTKind value: Expr @@ -248,11 +412,22 @@ def __init__( self.kind = ASTKind.StarredKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"Starred[*]({self.value})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "STARRED[*]" content: ReprStruct = {"value": self.value.get_struct(simplified)} return self._prepare_struct(key, content, simplified) diff --git a/libs/astx/src/astx/packages.py b/libs/astx/src/astx/packages.py index 6c4943c0..f464e4ad 100644 --- a/libs/astx/src/astx/packages.py +++ b/libs/astx/src/astx/packages.py @@ -1,4 +1,6 @@ -"""Define ASTx for more broader scope.""" +""" +title: Define ASTx for more broader scope. +""" from __future__ import annotations @@ -25,19 +27,40 @@ @public @typechecked class Target(Expr): - """Define the Architecture target for the program.""" + """ + title: Define the Architecture target for the program. + attributes: + datalayout: + type: str + triple: + type: str + """ datalayout: str triple: str def __init__(self, datalayout: str, triple: str) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + datalayout: + type: str + triple: + type: str + """ super().__init__() self.datalayout = datalayout self.triple = triple def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "TARGET" value = f"{self.datalayout}, {self.triple}" return self._prepare_struct(key, value, simplified) @@ -46,7 +69,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Module(Block): - """AST main expression class.""" + """ + title: AST main expression class. + attributes: + kind: + type: ASTKind + name: + type: str + """ + + kind: ASTKind name: str @@ -55,21 +87,43 @@ def __init__( name: str = "main", loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + name: + type: str + loc: + type: SourceLocation + """ super().__init__(name=name, loc=loc) self.kind = ASTKind.ModuleKind def __str__(self) -> str: - """Return the string representation of the object.""" + """ + title: Return the string representation of the object. + returns: + type: str + """ return f"Module[{self.name}]" @property def block(self) -> list[AST]: - """Define an alias for self.nodes.""" + """ + title: Define an alias for self.nodes. + returns: + type: list[AST] + """ return self.nodes def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ block_node = [] for node in self.nodes: @@ -84,7 +138,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Package(ASTNodes): - """AST class for Package.""" + """ + title: AST class for Package. + attributes: + name: + type: str + modules: + type: list[Module] + packages: + type: list[Package] + """ name: str modules: list[Module] @@ -97,18 +160,40 @@ def __init__( packages: list[Package] = [], loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + name: + type: str + modules: + type: list[Module] + packages: + type: list[Package] + loc: + type: SourceLocation + """ super().__init__(loc=loc) self.name = name self.modules = copy.deepcopy(modules) self.packages = copy.deepcopy(packages) def __str__(self) -> str: - """Return the string representation of the object.""" + """ + title: Return the string representation of the object. + returns: + type: str + """ return f"PACKAGE[{self.name}]" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ packages = [] modules = [] @@ -133,7 +218,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Program(Package): - """AST class for Program.""" + """ + title: AST class for Program. + attributes: + name: + type: str + modules: + type: list[Module] + packages: + type: list[Package] + target: + type: Target + """ target: Target @@ -145,21 +241,49 @@ def __init__( packages: list[Package] = [], loc: SourceLocation = NO_SOURCE_LOCATION, ) -> None: - """Initialize the AST instance.""" + """ + title: Initialize the AST instance. + parameters: + name: + type: str + target: + type: Target + modules: + type: list[Module] + packages: + type: list[Package] + loc: + type: SourceLocation + """ super().__init__( name=name, modules=modules, packages=packages, loc=loc ) self.target = copy.deepcopy(target) def __str__(self) -> str: - """Return the string representation of the object.""" + """ + title: Return the string representation of the object. + returns: + type: str + """ return f"PROGRAM[{self.name}]" @public @typechecked class AliasExpr(Expr): - """Represents an alias in an import statement.""" + """ + title: Represents an alias in an import statement. + attributes: + kind: + type: ASTKind + name: + type: str + asname: + type: str + """ + + kind: ASTKind name: str asname: str @@ -177,14 +301,25 @@ def __init__( self.kind = ASTKind.AliasExprKind def __str__(self) -> str: - """Return a string representation of the alias.""" + """ + title: Return a string representation of the alias. + returns: + type: str + """ if self.asname: return f"{self.name} as {self.asname}" else: return self.name def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the alias.""" + """ + title: Return the AST structure of the alias. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ str_asname = f", {self.asname}" if self.asname else "" str_name_asname = f"[{self.name}{str_asname}]" key = f"Alias {str_name_asname}" @@ -196,7 +331,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ImportStmt(StatementType): - """Represents an import statement.""" + """ + title: Represents an import statement. + attributes: + kind: + type: ASTKind + names: + type: list[AliasExpr] + """ + + kind: ASTKind names: list[AliasExpr] @@ -211,12 +355,23 @@ def __init__( self.kind = ASTKind.ImportStmtKind def __str__(self) -> str: - """Return a string representation of the import statement.""" + """ + title: Return a string representation of the import statement. + returns: + type: str + """ names_str = ", ".join(str(name) for name in self.names) return f"import {names_str}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the import statement.""" + """ + title: Return the AST structure of the import statement. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "ImportStmt" value = cast( ReprStruct, [name.get_struct(simplified) for name in self.names] @@ -227,7 +382,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ImportFromStmt(StatementType): - """Represents an import-from statement.""" + """ + title: Represents an import-from statement. + attributes: + kind: + type: ASTKind + module: + type: Optional[str] + names: + type: list[AliasExpr] + level: + type: int + """ + + kind: ASTKind module: Optional[str] names: list[AliasExpr] @@ -248,7 +416,11 @@ def __init__( self.kind = ASTKind.ImportFromStmtKind def __str__(self) -> str: - """Return a string representation of the import-from statement.""" + """ + title: Return a string representation of the import-from statement. + returns: + type: str + """ level_dots = "." * self.level module_str = ( f"{level_dots}{self.module}" if self.module else level_dots @@ -257,7 +429,14 @@ def __str__(self) -> str: return f"from {module_str} import {names_str}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the import-from statement.""" + """ + title: Return the AST structure of the import-from statement. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ level_dots = "." * self.level module_str = ( f"{level_dots}{self.module}" if self.module else level_dots @@ -274,7 +453,16 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ImportExpr(Expr): - """Represents an import operation as an expression.""" + """ + title: Represents an import operation as an expression. + attributes: + kind: + type: ASTKind + names: + type: list[AliasExpr] + """ + + kind: ASTKind names: list[AliasExpr] @@ -289,12 +477,23 @@ def __init__( self.kind = ASTKind.ImportExprKind def __str__(self) -> str: - """Return a string representation of the import expression.""" + """ + title: Return a string representation of the import expression. + returns: + type: str + """ names_str = ", ".join(str(name) for name in self.names) return f"import {names_str}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the import expression.""" + """ + title: Return the AST structure of the import expression. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "ImportExpr" value = cast( ReprStruct, [name.get_struct(simplified) for name in self.names] @@ -305,7 +504,20 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class ImportFromExpr(Expr): - """Represents a 'from ... import ...' operation as an expression.""" + """ + title: Represents a 'from ... import ...' operation as an expression. + attributes: + kind: + type: ASTKind + module: + type: str + names: + type: list[AliasExpr] + level: + type: int + """ + + kind: ASTKind module: str names: list[AliasExpr] @@ -326,7 +538,11 @@ def __init__( self.kind = ASTKind.ImportFromExprKind def __str__(self) -> str: - """Return a string representation of the import-from expression.""" + """ + title: Return a string representation of the import-from expression. + returns: + type: str + """ level_dots = "." * self.level module_str = ( f"{level_dots}{self.module}" if self.module else level_dots @@ -336,7 +552,14 @@ def __str__(self) -> str: return f"from {module_str} import {names_str}" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the import-from expression.""" + """ + title: Return the AST structure of the import-from expression. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ level_dots = "." * self.level module_str = ( f"{level_dots}{self.module}" if self.module else level_dots diff --git a/libs/astx/src/astx/subscript.py b/libs/astx/src/astx/subscript.py index ac3baf40..b112c8c0 100644 --- a/libs/astx/src/astx/subscript.py +++ b/libs/astx/src/astx/subscript.py @@ -1,4 +1,6 @@ -"""Module for subscripts definitions/declarations.""" +""" +title: Module for subscripts definitions/declarations. +""" from typing import Optional, cast @@ -20,7 +22,24 @@ @public @typechecked class SubscriptExpr(Expr): - """AST class for subscript expressions.""" + """ + title: AST class for subscript expressions. + attributes: + kind: + type: ASTKind + value: + type: Expr + index: + type: Expr + lower: + type: Expr + upper: + type: Expr + step: + type: Expr + """ + + kind: ASTKind value: Expr index: Expr @@ -39,25 +58,41 @@ def __init__( parent: Optional[ASTNodes] = None, ) -> None: """ - Initialize the SubscriptExpr instance. - - Parameters - ---------- - value: Expr - The expression representing the object being indexed (e.g., - an array or list). - index (optional): Expr - The index of the variable. - lower (optional): Expr - The lower bound of the slice (inclusive). - upper (optional): Expr - The upper bound of the slice (exclusive). - step (optional): Expr - The step size for the slice. - loc: SourceLocation - The source location of the expression. - parent (optional): ASTNodes - The parent AST node. + title: Initialize the SubscriptExpr instance. + summary: |- + + Parameters + ---------- + value: Expr + The expression representing the object being indexed (e.g., + an array or list). + index (optional): Expr + The index of the variable. + lower (optional): Expr + The lower bound of the slice (inclusive). + upper (optional): Expr + The upper bound of the slice (exclusive). + step (optional): Expr + The step size for the slice. + loc: SourceLocation + The source location of the expression. + parent (optional): ASTNodes + The parent AST node. + parameters: + value: + type: Expr + index: + type: Optional[Expr] + lower: + type: Optional[Expr] + upper: + type: Optional[Expr] + step: + type: Optional[Expr] + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] """ super().__init__(loc=loc, parent=parent) self.value: Expr = value if value is not None else LiteralNone() @@ -68,7 +103,11 @@ def __init__( self.kind = ASTKind.SubscriptExprKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ lower_str = ( str(self.lower) if not isinstance(self.lower, LiteralNone) @@ -88,7 +127,14 @@ def __str__(self) -> str: return f"SubscriptExpr({self.value}[{lower_str}{upper_str}{step_str}])" def _get_struct_wrapper(self, simplified: bool) -> DictDataTypesStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: DictDataTypesStruct + """ value_dict: ReprStruct = {"indexed": self.value.get_struct(simplified)} lower_key = "index" if isinstance(self.lower, LiteralNone) else "lower" @@ -116,7 +162,14 @@ def _get_struct_wrapper(self, simplified: bool) -> DictDataTypesStruct: return value def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "SubscriptExpr" value = self._get_struct_wrapper(simplified) @@ -126,7 +179,14 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class Ellipsis(Expr): - """AST class for Ellipsis expressions.""" + """ + title: AST class for Ellipsis expressions. + attributes: + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -137,7 +197,14 @@ def __init__( self.kind = ASTKind.EllipsisKind def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = str(self) value: DictDataTypesStruct = {} return self._prepare_struct(key, value, simplified) diff --git a/libs/astx/src/astx/symbol_table.py b/libs/astx/src/astx/symbol_table.py index c52806ae..8a35fb7f 100644 --- a/libs/astx/src/astx/symbol_table.py +++ b/libs/astx/src/astx/symbol_table.py @@ -1,15 +1,15 @@ """ -Symbol Table module for ASTx. - -The `SymbolTable` class offered here allows the definition -of scopes, so the variable or function would be available in -specifics scopes. +title: Symbol Table module for ASTx. +summary: |- + The `SymbolTable` class offered here allows the definition + of scopes, so the variable or function would be available in + specifics scopes. """ from __future__ import annotations -from typing import Optional, Type +from typing import Optional from public import public @@ -20,7 +20,18 @@ @public @typechecked class ScopeNodeBase: - """ScopeNodeBase is the base used for the nodes (levels) in the scope.""" + """ + title: ScopeNodeBase is the base used for the nodes (levels) in the scope. + attributes: + name: + type: str + parent: + type: Optional[ScopeNodeBase] + default_parent: + type: Optional[ScopeNodeBase] + named_expr: + type: dict[str, NamedExpr] + """ name: str parent: Optional[ScopeNodeBase] @@ -30,7 +41,14 @@ class ScopeNodeBase: def __init__( self, name: str, parent: Optional[ScopeNodeBase] = None ) -> None: - """Initialize ScopeNodeBase.""" + """ + title: Initialize ScopeNodeBase. + parameters: + name: + type: str + parent: + type: Optional[ScopeNodeBase] + """ self.parent: Optional[ScopeNodeBase] = ( parent or ScopeNodeBase.default_parent ) @@ -41,7 +59,18 @@ def __init__( @public @typechecked class ScopeNode(ScopeNodeBase): - """Scope node organize the scope in different levels in the stack.""" + """ + title: Scope node organize the scope in different levels in the stack. + attributes: + name: + type: str + parent: + type: Optional[ScopeNodeBase] + default_parent: + type: Optional[ScopeNodeBase] + named_expr: + type: dict[str, NamedExpr] + """ ... @@ -49,18 +78,34 @@ class ScopeNode(ScopeNodeBase): @public @typechecked class Scope: - """Organize the ASTx objects according to the scope.""" + """ + title: Organize the ASTx objects according to the scope. + attributes: + nodes: + type: dict[int, ScopeNodeBase] + current: + type: Optional[ScopeNodeBase] + previous: + type: Optional[ScopeNodeBase] + scope_node_class: + type: type[ScopeNodeBase] + """ nodes: dict[int, ScopeNodeBase] current: Optional[ScopeNodeBase] previous: Optional[ScopeNodeBase] - scope_node_class: Type[ScopeNodeBase] + scope_node_class: type[ScopeNodeBase] def __init__( self, - scope_node_class: Type[ScopeNodeBase] = ScopeNode, + scope_node_class: type[ScopeNodeBase] = ScopeNode, ) -> None: - """Initialize the scope.""" + """ + title: Initialize the scope. + parameters: + scope_node_class: + type: type[ScopeNodeBase] + """ self.nodes: dict[int, ScopeNodeBase] = {} self.current = None self.previous = None @@ -76,7 +121,18 @@ def add( parent: Optional[ScopeNodeBase] = None, change_current: bool = True, ) -> ScopeNodeBase: - """Add a new node in the scope.""" + """ + title: Add a new node in the scope. + parameters: + name: + type: str + parent: + type: Optional[ScopeNodeBase] + change_current: + type: bool + returns: + type: ScopeNodeBase + """ node = self.scope_node_class(name, parent) # The use of id(node) as keys in the nodes dictionary is generally @@ -93,30 +149,53 @@ def add( return node def get_first(self) -> ScopeNodeBase: - """Get the first node in the scope.""" + """ + title: Get the first node in the scope. + returns: + type: ScopeNodeBase + """ node_id = next(iter(self.nodes.keys())) return self.nodes[node_id] def get_last(self) -> ScopeNodeBase: - """Get the latest node in the scope.""" + """ + title: Get the latest node in the scope. + returns: + type: ScopeNodeBase + """ node_id = list(self.nodes.keys())[-1] return self.nodes[node_id] def destroy(self, node: ScopeNodeBase) -> None: - """Destroy the current scope.""" + """ + title: Destroy the current scope. + parameters: + node: + type: ScopeNodeBase + """ del self.nodes[id(node)] self.current = self.previous self.previous = None def set_default_parent(self, node: ScopeNodeBase) -> None: - """Set default parent for the current scope.""" + """ + title: Set default parent for the current scope. + parameters: + node: + type: ScopeNodeBase + """ self.scope_node_class.default_parent = node @public @typechecked class SymbolTable: - """Symbol Table for ASTx.""" + """ + title: Symbol Table for ASTx. + attributes: + scopes: + type: Scope + """ scopes: Scope @@ -124,16 +203,25 @@ def __init__(self) -> None: self.scopes = Scope() def define(self, expr: NamedExpr) -> None: - """Define a new named expression inside the scoped stack.""" + """ + title: Define a new named expression inside the scoped stack. + parameters: + expr: + type: NamedExpr + """ if not self.scopes.current: raise Exception("SymbolTable: No scope active.") self.scopes.current.named_expr[expr.name] = expr def update(self, expr: NamedExpr) -> None: """ - Update the expression on the SymbolTable. + title: Update the expression on the SymbolTable. + summary: |- - It is useful mainly for updating the comment of the expression. + It is useful mainly for updating the comment of the expression. + parameters: + expr: + type: NamedExpr """ if not self.scopes.current: raise Exception("SymbolTable: No scope active.") @@ -142,7 +230,14 @@ def update(self, expr: NamedExpr) -> None: self.scopes.current.named_expr[expr.name] = expr def lookup(self, name: str) -> NamedExpr: - """Get a named expression from the scope stack.""" + """ + title: Get a named expression from the scope stack. + parameters: + name: + type: str + returns: + type: NamedExpr + """ scope = self.scopes.current while scope is not None: if name in scope.named_expr: diff --git a/libs/astx/src/astx/tools/__init__.py b/libs/astx/src/astx/tools/__init__.py index 0844da0d..ae3253d3 100644 --- a/libs/astx/src/astx/tools/__init__.py +++ b/libs/astx/src/astx/tools/__init__.py @@ -1 +1,3 @@ -"""Package for astx helper tools.""" +""" +title: Package for astx helper tools. +""" diff --git a/libs/astx/src/astx/tools/typing.py b/libs/astx/src/astx/tools/typing.py index aabebaff..f5d7c881 100644 --- a/libs/astx/src/astx/tools/typing.py +++ b/libs/astx/src/astx/tools/typing.py @@ -1,4 +1,6 @@ -"""Tools for typing support helper.""" +""" +title: Tools for typing support helper. +""" from typing import Any, Callable, TypeVar @@ -20,7 +22,16 @@ @public def skip_unused(*args: Any, **kwargs: Any) -> None: - """Referencing variables to pacify static analyzers.""" + """ + title: Referencing variables to pacify static analyzers. + parameters: + args: + type: Any + variadic: positional + kwargs: + type: Any + variadic: keyword + """ for arg in args: pass for key in kwargs: @@ -29,7 +40,14 @@ def skip_unused(*args: Any, **kwargs: Any) -> None: @public def copy_type(f: _T) -> Callable[[Any], _T]: - """Copy types for args, kwargs from parent class.""" + """ + title: Copy types for args, kwargs from parent class. + parameters: + f: + type: _T + returns: + type: Callable[[Any], _T] + """ skip_unused(f) return lambda x: x diff --git a/libs/astx/src/astx/types/__init__.py b/libs/astx/src/astx/types/__init__.py index 531561bb..6fd01f85 100644 --- a/libs/astx/src/astx/types/__init__.py +++ b/libs/astx/src/astx/types/__init__.py @@ -1,4 +1,6 @@ -"""Collection of ASTx nodes used for types.""" +""" +title: Collection of ASTx nodes used for types. +""" from astx.types.base import ( AnyType, diff --git a/libs/astx/src/astx/types/base.py b/libs/astx/src/astx/types/base.py index 2ae2d1ca..93db0fa6 100644 --- a/libs/astx/src/astx/types/base.py +++ b/libs/astx/src/astx/types/base.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -13,10 +15,14 @@ @public @typechecked class AnyType(DataType): - """Generic data type expression.""" + """ + title: Generic data type expression. + """ @public @typechecked class NoneType(AnyType): - """NoneType data type expression.""" + """ + title: NoneType data type expression. + """ diff --git a/libs/astx/src/astx/types/boolean.py b/libs/astx/src/astx/types/boolean.py index 6178719c..42e6c4a4 100644 --- a/libs/astx/src/astx/types/boolean.py +++ b/libs/astx/src/astx/types/boolean.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -11,4 +13,6 @@ @public @typechecked class Boolean(AnyType): - """Boolean data type expression.""" + """ + title: Boolean data type expression. + """ diff --git a/libs/astx/src/astx/types/casting.py b/libs/astx/src/astx/types/casting.py index 773a6794..27616e9c 100644 --- a/libs/astx/src/astx/types/casting.py +++ b/libs/astx/src/astx/types/casting.py @@ -1,4 +1,6 @@ -"""AST types module.""" +""" +title: AST types module. +""" from __future__ import annotations @@ -21,7 +23,18 @@ @public @typechecked class TypeCastExpr(Expr): - """AST class for type casting expressions.""" + """ + title: AST class for type casting expressions. + attributes: + kind: + type: ASTKind + expr: + type: Expr + target_type: + type: DataType + """ + + kind: ASTKind expr: Expr target_type: DataType @@ -39,11 +52,22 @@ def __init__( self.kind = ASTKind.TypeCastExprKind def __str__(self) -> str: - """Return a string representation of the TypeCast expression.""" + """ + title: Return a string representation of the TypeCast expression. + returns: + type: str + """ return f"TypeCastExpr ({self.expr}, {self.target_type})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the TypeCast expression.""" + """ + title: Return the AST structure of the TypeCast expression. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = "TypeCastExpr" value: ReprStruct = { "expression": self.expr.get_struct(simplified), diff --git a/libs/astx/src/astx/types/collections.py b/libs/astx/src/astx/types/collections.py index f3f1180b..8762b311 100644 --- a/libs/astx/src/astx/types/collections.py +++ b/libs/astx/src/astx/types/collections.py @@ -1,9 +1,9 @@ -"""ASTx Collection Data Types.""" +""" +title: ASTx Collection Data Types. +""" from __future__ import annotations -from typing import List - from public import public from astx.base import ExprType @@ -14,20 +14,38 @@ @public @typechecked class CollectionType(AnyType): - """Base class for collection data types.""" + """ + title: Base class for collection data types. + """ @public @typechecked class ListType(CollectionType): - """List data type expression.""" - - def __init__(self, element_types: List[ExprType]) -> None: - """Initialize ListType with an element type.""" + """ + title: List data type expression. + attributes: + element_types: + type: list[ExprType] + """ + + element_types: list[ExprType] + + def __init__(self, element_types: list[ExprType]) -> None: + """ + title: Initialize ListType with an element type. + parameters: + element_types: + type: list[ExprType] + """ self.element_types = element_types def __str__(self) -> str: - """Return string representation of ListType.""" + """ + title: Return string representation of ListType. + returns: + type: str + """ types_str = ", ".join(str(t) for t in self.element_types) return f"ListType[{types_str}]" @@ -35,42 +53,95 @@ def __str__(self) -> str: @public @typechecked class SetType(CollectionType): - """Set data type expression.""" + """ + title: Set data type expression. + attributes: + element_type: + type: ExprType + """ + + element_type: ExprType def __init__(self, element_type: ExprType) -> None: - """Initialize SetType with an element type.""" + """ + title: Initialize SetType with an element type. + parameters: + element_type: + type: ExprType + """ self.element_type = element_type def __str__(self) -> str: - """Return string representation of SetType.""" + """ + title: Return string representation of SetType. + returns: + type: str + """ return f"SetType[{self.element_type}]" @public @typechecked class DictType(CollectionType): - """Dictionary data type expression.""" + """ + title: Dictionary data type expression. + attributes: + key_type: + type: ExprType + value_type: + type: ExprType + """ + + key_type: ExprType + value_type: ExprType def __init__(self, key_type: ExprType, value_type: ExprType) -> None: - """Initialize DictType with key-value types.""" + """ + title: Initialize DictType with key-value types. + parameters: + key_type: + type: ExprType + value_type: + type: ExprType + """ self.key_type = key_type self.value_type = value_type def __str__(self) -> str: - """Return string representation of DictType.""" + """ + title: Return string representation of DictType. + returns: + type: str + """ return f"DictType[{self.key_type}, {self.value_type}]" @public @typechecked class TupleType(CollectionType): - """Tuple data type expression.""" - - def __init__(self, element_types: List[ExprType]) -> None: - """Initialize TupleType with multiple element types.""" + """ + title: Tuple data type expression. + attributes: + element_types: + type: list[ExprType] + """ + + element_types: list[ExprType] + + def __init__(self, element_types: list[ExprType]) -> None: + """ + title: Initialize TupleType with multiple element types. + parameters: + element_types: + type: list[ExprType] + """ self.element_types = element_types def __str__(self) -> str: - """Return string representation of TupleType.""" + """ + title: Return string representation of TupleType. + returns: + type: str + """ types_str = ", ".join(str(t) for t in self.element_types) return f"TupleType[{types_str}]" diff --git a/libs/astx/src/astx/types/numeric.py b/libs/astx/src/astx/types/numeric.py index 84a3f57b..c1653048 100644 --- a/libs/astx/src/astx/types/numeric.py +++ b/libs/astx/src/astx/types/numeric.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -11,31 +13,44 @@ @public @typechecked class Number(AnyType): - """Number data type expression.""" + """ + title: Number data type expression. + """ @public @typechecked class Integer(AnyType): - """Integer number data type expression.""" + """ + title: Integer number data type expression. + """ @public @typechecked class UnsignedInteger(Integer): - """Unsigned integer number data type expression.""" + """ + title: Unsigned integer number data type expression. + """ @public @typechecked class SignedInteger(Integer): - """Signed integer number data type expression.""" + """ + title: Signed integer number data type expression. + """ @public @typechecked class Int8(SignedInteger): - """Int8 data type expression.""" + """ + title: Int8 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 1 @@ -43,7 +58,12 @@ class Int8(SignedInteger): @public @typechecked class Int16(SignedInteger): - """Int16 data type expression.""" + """ + title: Int16 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 2 @@ -51,7 +71,12 @@ class Int16(SignedInteger): @public @typechecked class Int32(SignedInteger): - """Int32 data type expression.""" + """ + title: Int32 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 4 @@ -59,7 +84,12 @@ class Int32(SignedInteger): @public @typechecked class Int64(SignedInteger): - """Int64 data type expression.""" + """ + title: Int64 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 8 @@ -67,7 +97,12 @@ class Int64(SignedInteger): @public @typechecked class Int128(SignedInteger): - """Int128 data type expression.""" + """ + title: Int128 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 16 @@ -75,7 +110,12 @@ class Int128(SignedInteger): @public @typechecked class UInt8(UnsignedInteger): - """UInt8 data type expression.""" + """ + title: UInt8 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 1 @@ -83,7 +123,12 @@ class UInt8(UnsignedInteger): @public @typechecked class UInt16(UnsignedInteger): - """UInt16 data type expression.""" + """ + title: UInt16 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 2 @@ -91,7 +136,12 @@ class UInt16(UnsignedInteger): @public @typechecked class UInt32(UnsignedInteger): - """UInt32 data type expression.""" + """ + title: UInt32 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 4 @@ -99,7 +149,12 @@ class UInt32(UnsignedInteger): @public @typechecked class UInt64(UnsignedInteger): - """UInt64 data type expression.""" + """ + title: UInt64 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 8 @@ -107,7 +162,12 @@ class UInt64(UnsignedInteger): @public @typechecked class UInt128(UnsignedInteger): - """UInt128 data type expression.""" + """ + title: UInt128 data type expression. + attributes: + nbytes: + type: int + """ nbytes: int = 16 @@ -115,37 +175,52 @@ class UInt128(UnsignedInteger): @public @typechecked class Floating(Number): - """AST for the literal float number.""" + """ + title: AST for the literal float number. + """ @public @typechecked class Float16(Floating): - """Float16 data type expression.""" + """ + title: Float16 data type expression. + """ @public @typechecked class Float32(Floating): - """Float32 data type expression.""" + """ + title: Float32 data type expression. + """ @public @typechecked class Float64(Floating): - """Float64 data type expression.""" + """ + title: Float64 data type expression. + """ @public @typechecked class Complex(Number): - """Base class for complex numbers.""" + """ + title: Base class for complex numbers. + """ @public @typechecked class Complex32(Complex): - """Complex32 data type class.""" + """ + title: Complex32 data type class. + attributes: + nbytes: + type: int + """ nbytes: int = 8 @@ -153,6 +228,11 @@ class Complex32(Complex): @public @typechecked class Complex64(Complex): - """Complex64 data type class.""" + """ + title: Complex64 data type class. + attributes: + nbytes: + type: int + """ nbytes: int = 16 diff --git a/libs/astx/src/astx/types/operators.py b/libs/astx/src/astx/types/operators.py index 6612f277..f015c40e 100644 --- a/libs/astx/src/astx/types/operators.py +++ b/libs/astx/src/astx/types/operators.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -21,93 +23,234 @@ @public @typechecked class DataTypeOps(DataType): - """Overload some magic functions used for the main operations.""" + """ + title: Overload some magic functions used for the main operations. + """ def __hash__(self) -> int: - """Ensure that the hash method is not None.""" + """ + title: Ensure that the hash method is not None. + returns: + type: int + """ return super().__hash__() def __add__(self, other: DataType) -> BinaryOp: - """Overload the magic `add` method.""" + """ + title: Overload the magic `add` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("+", self, other) def __eq__(self, other: DataType) -> BinaryOp: # type: ignore - """Overload the magic `eq` method.""" + """ + title: Overload the magic `eq` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("==", self, other) def __floordiv__(self, other: DataType) -> BinaryOp: - """Overload the magic `floordiv` method.""" + """ + title: Overload the magic `floordiv` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("//", self, other) def __ge__(self, other: DataType) -> BinaryOp: - """Overload the magic `ge` method.""" + """ + title: Overload the magic `ge` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp(">=", self, other) def __gt__(self, other: DataType) -> BinaryOp: - """Overload the magic `gt` method.""" + """ + title: Overload the magic `gt` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp(">", self, other) def __le__(self, other: DataType) -> BinaryOp: - """Overload the magic `le` method.""" + """ + title: Overload the magic `le` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("<=", self, other) def __lt__(self, other: DataType) -> BinaryOp: - """Overload the magic `lt` method.""" + """ + title: Overload the magic `lt` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("<", self, other) def __mod__(self, other: DataType) -> BinaryOp: - """Overload the magic `mod` method.""" + """ + title: Overload the magic `mod` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("%", self, other) def __mul__(self, other: DataType) -> BinaryOp: - """Overload the magic `mul` method.""" + """ + title: Overload the magic `mul` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("*", self, other) def __ne__(self, other: DataType) -> BinaryOp: # type: ignore - """Overload the magic `ne` method.""" + """ + title: Overload the magic `ne` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("!=", self, other) def __neg__(self) -> UnaryOp: - """Overload the magic `neg` method.""" + """ + title: Overload the magic `neg` method. + returns: + type: UnaryOp + """ return UnaryOp("-", self) def __pos__(self) -> UnaryOp: - """Overload the magic `pos` method.""" + """ + title: Overload the magic `pos` method. + returns: + type: UnaryOp + """ return UnaryOp("+", self) def __pow__(self, other: DataType) -> BinaryOp: - """Overload the magic `pow` method.""" + """ + title: Overload the magic `pow` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("^", self, other) def __sub__(self, other: DataType) -> BinaryOp: - """Overload the magic `sub` method.""" + """ + title: Overload the magic `sub` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("-", self, other) def __truediv__(self, other: DataType) -> BinaryOp: - """Overload the magic `truediv` method.""" + """ + title: Overload the magic `truediv` method. + parameters: + other: + type: DataType + returns: + type: BinaryOp + """ return BinaryOp("/", self, other) def __and__(self, other: DataType) -> AndOp: - """Overload the magic 'and' method.""" + """ + title: Overload the magic 'and' method. + parameters: + other: + type: DataType + returns: + type: AndOp + """ return AndOp(self, other) def __or__(self, other: DataType) -> OrOp: - """Overload the magic 'or' method.""" + """ + title: Overload the magic 'or' method. + parameters: + other: + type: DataType + returns: + type: OrOp + """ return OrOp(self, other) def __xor__(self, other: DataType) -> XorOp: - """Overload the magic 'xor' method.""" + """ + title: Overload the magic 'xor' method. + parameters: + other: + type: DataType + returns: + type: XorOp + """ return XorOp(self, other) def __invert__(self) -> NotOp: - """Overload the magic 'not' method.""" + """ + title: Overload the magic 'not' method. + returns: + type: NotOp + """ return NotOp(self) @public @typechecked class UnaryOp(DataTypeOps): - """AST class for the unary operator.""" + """ + title: AST class for the unary operator. + attributes: + kind: + type: ASTKind + op_code: + type: str + operand: + type: DataType + """ + + kind: ASTKind op_code: str operand: DataType @@ -119,18 +262,40 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the UnaryOp instance.""" + """ + title: Initialize the UnaryOp instance. + parameters: + op_code: + type: str + operand: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.op_code = op_code self.operand = operand self.kind = ASTKind.UnaryOpKind def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"UnaryOp[{self.op_code}]({self.operand})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure of the object.""" + """ + title: Return the AST structure of the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"UNARY[{self.op_code}]" value = self.operand.get_struct(simplified) return self._prepare_struct(key, value, simplified) @@ -139,7 +304,22 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class BinaryOp(DataTypeOps): - """AST class for the binary operator.""" + """ + title: AST class for the binary operator. + attributes: + kind: + type: ASTKind + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + """ + + kind: ASTKind type_: ExprType lhs: DataType @@ -154,7 +334,20 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Initialize the BinaryOp instance.""" + """ + title: Initialize the BinaryOp instance. + parameters: + op_code: + type: str + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__(loc=loc, parent=parent) self.op_code = op_code @@ -177,11 +370,22 @@ def __init__( self.type_ = max([lhs.type_, rhs.type_], key=lambda v: v.nbytes) def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"BinaryOp[{self.op_code}]({self.lhs},{self.rhs})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"BINARY[{self.op_code}]" lhs = {"lhs": self.lhs.get_struct(simplified)} rhs = {"rhs": self.rhs.get_struct(simplified)} @@ -193,7 +397,22 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class BoolBinaryOp(BinaryOp): - """Base AST class for boolean binary operations.""" + """ + title: Base AST class for boolean binary operations. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -212,11 +431,22 @@ def __init__( ) def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"({self.lhs} {self.op_code} {self.rhs})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"BOOL_BINARY_OP[{self.__class__.__name__}]" value: ReprStruct = { "lhs": self.lhs.get_struct(simplified), @@ -228,7 +458,18 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class BoolUnaryOp(UnaryOp): - """Base AST class for boolean unary operations.""" + """ + title: Base AST class for boolean unary operations. + attributes: + op_code: + type: str + operand: + type: DataType + kind: + type: ASTKind + """ + + kind: ASTKind def __init__( self, @@ -245,11 +486,22 @@ def __init__( ) def __str__(self) -> str: - """Return a string that represents the object.""" + """ + title: Return a string that represents the object. + returns: + type: str + """ return f"({self.op_code} {self.operand})" def get_struct(self, simplified: bool = False) -> ReprStruct: - """Return the AST structure that represents the object.""" + """ + title: Return the AST structure that represents the object. + parameters: + simplified: + type: bool + returns: + type: ReprStruct + """ key = f"BOOL_UNARY_OP[{self.__class__.__name__}]" value: ReprStruct = {"operand": self.operand.get_struct(simplified)} return self._prepare_struct(key, value, simplified) @@ -258,7 +510,22 @@ def get_struct(self, simplified: bool = False) -> ReprStruct: @public @typechecked class AndOp(BoolBinaryOp): - """AST class for logical AND operation.""" + """ + title: AST class for logical AND operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.AndOpKind op_code = "and" @@ -270,7 +537,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical AND operation.""" + """ + title: Instantiate AST class for logical AND operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -283,7 +561,22 @@ def __init__( @public @typechecked class OrOp(BoolBinaryOp): - """AST class for logical OR operation.""" + """ + title: AST class for logical OR operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.OrOpKind op_code = "or" @@ -295,7 +588,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical OR operation.""" + """ + title: Instantiate AST class for logical OR operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -308,7 +612,22 @@ def __init__( @public @typechecked class XorOp(BoolBinaryOp): - """AST class for logical XOR operation.""" + """ + title: AST class for logical XOR operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.XorOpKind op_code = "xor" @@ -320,7 +639,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical XOR operation.""" + """ + title: Instantiate AST class for logical XOR operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -333,7 +663,22 @@ def __init__( @public @typechecked class NandOp(BoolBinaryOp): - """AST class for logical NAND operation.""" + """ + title: AST class for logical NAND operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.NandOpKind op_code = "nand" @@ -345,7 +690,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical NAND operation.""" + """ + title: Instantiate AST class for logical NAND operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -358,7 +714,22 @@ def __init__( @public @typechecked class NorOp(BoolBinaryOp): - """AST class for logical NOR operation.""" + """ + title: AST class for logical NOR operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.NorOpKind op_code = "nor" @@ -370,7 +741,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical NOR operation.""" + """ + title: Instantiate AST class for logical NOR operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -383,7 +765,22 @@ def __init__( @public @typechecked class XnorOp(BoolBinaryOp): - """AST class for logical XNOR operation.""" + """ + title: AST class for logical XNOR operation. + attributes: + type_: + type: ExprType + lhs: + type: DataType + rhs: + type: DataType + op_code: + type: str + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.XnorOpKind op_code = "xnor" @@ -395,7 +792,18 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical XNOR operation.""" + """ + title: Instantiate AST class for logical XNOR operation. + parameters: + lhs: + type: DataType + rhs: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, lhs=lhs, @@ -408,7 +816,18 @@ def __init__( @public @typechecked class NotOp(BoolUnaryOp): - """AST class for logical NOT operation.""" + """ + title: AST class for logical NOT operation. + attributes: + op_code: + type: str + operand: + type: DataType + kind: + type: ASTKind + """ + + kind: ASTKind kind = ASTKind.NotOpKind op_code = "not" @@ -419,7 +838,16 @@ def __init__( loc: SourceLocation = NO_SOURCE_LOCATION, parent: Optional[ASTNodes] = None, ) -> None: - """Instantiate AST class for logical NOT operation.""" + """ + title: Instantiate AST class for logical NOT operation. + parameters: + operand: + type: DataType + loc: + type: SourceLocation + parent: + type: Optional[ASTNodes] + """ super().__init__( op_code=self.op_code, operand=operand, diff --git a/libs/astx/src/astx/types/string.py b/libs/astx/src/astx/types/string.py index bca54ca5..25d77201 100644 --- a/libs/astx/src/astx/types/string.py +++ b/libs/astx/src/astx/types/string.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -11,16 +13,22 @@ @public @typechecked class String(AnyType): - """Base class for strings.""" + """ + title: Base class for strings. + """ @public @typechecked -class UTF8String(AnyType): - """Class for UTF-8 encoded strings.""" +class UTF8String(String): + """ + title: Class for UTF-8 encoded strings. + """ @public @typechecked -class UTF8Char(AnyType): - """Class for UTF-8 encoded characters.""" +class UTF8Char(String): + """ + title: Class for UTF-8 encoded characters. + """ diff --git a/libs/astx/src/astx/types/temporal.py b/libs/astx/src/astx/types/temporal.py index 3d835404..1a29b679 100644 --- a/libs/astx/src/astx/types/temporal.py +++ b/libs/astx/src/astx/types/temporal.py @@ -1,4 +1,6 @@ -"""ASTx Data Types module.""" +""" +title: ASTx Data Types module. +""" from __future__ import annotations @@ -11,28 +13,39 @@ @public @typechecked class Temporal(AnyType): - """Base class for temporal data types (date, time, timestamp, datetime).""" + """ + title: >- + Base class for temporal data types (date, time, timestamp, datetime). + """ @public @typechecked class Date(Temporal): - """Date data type expression.""" + """ + title: Date data type expression. + """ @public @typechecked class Time(Temporal): - """Time data type expression.""" + """ + title: Time data type expression. + """ @public @typechecked class Timestamp(Temporal): - """Timestamp data type expression.""" + """ + title: Timestamp data type expression. + """ @public @typechecked class DateTime(Temporal): - """DateTime data type expression.""" + """ + title: DateTime data type expression. + """ diff --git a/libs/astx/src/astx/types/ttypes.py b/libs/astx/src/astx/types/ttypes.py index 2066cea1..f83f7ccc 100644 --- a/libs/astx/src/astx/types/ttypes.py +++ b/libs/astx/src/astx/types/ttypes.py @@ -1,4 +1,6 @@ -"""Constant objects.""" +""" +title: Constant objects. +""" from __future__ import annotations diff --git a/libs/astx/src/astx/viz.py b/libs/astx/src/astx/viz.py index 63b59d8d..f1649f52 100644 --- a/libs/astx/src/astx/viz.py +++ b/libs/astx/src/astx/viz.py @@ -1,9 +1,9 @@ """ -AST graphic representation Module. - -This module provides utilities for converting an Abstract Syntax Tree (AST) -to Mermaid for inline display in Jupyter (Lab ≥4.1 / NB ≥7.1) and to ASCII -via the `mermaid-ascii` CLI. +title: AST graphic representation Module. +summary: >- + This module provides utilities for converting an Abstract Syntax Tree (AST) + to Mermaid for inline display in Jupyter (Lab ≥4.1 / NB ≥7.1) and to ASCII + via the `mermaid-ascii` CLI. """ from __future__ import annotations @@ -22,7 +22,18 @@ def _stable_id(label: str, ref: str, content: object) -> str: - """Build a stable-ish node id from label/ref/content.""" + """ + title: Build a stable-ish node id from label/ref/content. + parameters: + label: + type: str + ref: + type: str + content: + type: object + returns: + type: str + """ h = hashlib.md5( f"{label}|{ref}|{type(content).__name__}|{content!r}".encode(), usedforsecurity=False, @@ -31,7 +42,14 @@ def _stable_id(label: str, ref: str, content: object) -> str: def _esc_mermaid_label(s: str) -> str: - """Escape quotes for Mermaid labels (image/Jupyter path).""" + """ + title: Escape quotes for Mermaid labels (image/Jupyter path). + parameters: + s: + type: str + returns: + type: str + """ return str(s).replace('"', r"\"") @@ -42,16 +60,26 @@ def _traverse_ast_to_mermaid( named_items: bool = True, ) -> str: """ - Convert AST to Mermaid. - - Parameters - ---------- - direction : "TD" | "LR" - Layout direction. - named_items : bool - If True, emit `ID["Label"]` node declarations and quoted edge labels - (best for Jupyter/image). If False, emit plain identifiers and pipe - edge labels (compatible with mermaid-ascii). + title: Convert AST to Mermaid. + summary: |- + + Parameters + ---------- + direction : "TD" | "LR" + Layout direction. + named_items : bool + If True, emit `ID["Label"]` node declarations and quoted edge labels + (best for Jupyter/image). If False, emit plain identifiers and pipe + edge labels (compatible with mermaid-ascii). + parameters: + ast: + type: ReprStruct + direction: + type: Direction + named_items: + type: bool + returns: + type: str """ if direction not in ("TD", "LR"): raise ValueError('direction must be "TD" or "LR"') @@ -121,19 +149,45 @@ def walk( def ast_to_mermaid(ast: ReprStruct, direction: Direction = "TD") -> str: - """Mermaid for Jupyter/image (uses named items).""" + """ + title: Mermaid for Jupyter/image (uses named items). + parameters: + ast: + type: ReprStruct + direction: + type: Direction + returns: + type: str + """ return _traverse_ast_to_mermaid(ast, direction=direction, named_items=True) def ast_to_mermaid_ascii(ast: ReprStruct, direction: Direction = "TD") -> str: - """Mermaid tailored for mermaid-ascii, no named items, pipe edge labels.""" + """ + title: >- + Mermaid tailored for mermaid-ascii, no named items, pipe edge labels. + parameters: + ast: + type: ReprStruct + direction: + type: Direction + returns: + type: str + """ return _traverse_ast_to_mermaid( ast, direction=direction, named_items=False ) def visualize_image(ast: ReprStruct, direction: Direction = "TD") -> None: - """Display the AST as Mermaid inline in Jupyter (Lab ≥4.1 / NB ≥7.1).""" + """ + title: Display the AST as Mermaid inline in Jupyter (Lab ≥4.1 / NB ≥7.1). + parameters: + ast: + type: ReprStruct + direction: + type: Direction + """ _display( # type: ignore {"text/vnd.mermaid": ast_to_mermaid(ast, direction=direction)}, raw=True, @@ -141,7 +195,11 @@ def visualize_image(ast: ReprStruct, direction: Direction = "TD") -> None: def _find_mermaid_ascii() -> Optional[str]: - """Resolve the `mermaid-ascii` CLI path or return None.""" + """ + title: Resolve the `mermaid-ascii` CLI path or return None. + returns: + type: Optional[str] + """ return shutil.which("mermaid-ascii") or shutil.which("mermaid-ascii.exe") @@ -156,11 +214,31 @@ def visualize_ascii( ascii_only: bool = False, ) -> str: """ - Render the AST to ASCII using the `mermaid-ascii` CLI. - - For maximum compatibility, this uses an ASCII-friendly Mermaid form: - - no named items (node text is the identifier) - - pipe-labeled edges (--> |label| ...) + title: Render the AST to ASCII using the `mermaid-ascii` CLI. + summary: |- + + For maximum compatibility, this uses an ASCII-friendly Mermaid form: + - no named items (node text is the identifier) + - pipe-labeled edges (--> |label| ...) + parameters: + ast: + type: ReprStruct + timeout: + type: int + direction: + type: Direction + width: + type: Optional[int] + border_padding: + type: Optional[int] + padding_x: + type: Optional[int] + padding_y: + type: Optional[int] + ascii_only: + type: bool + returns: + type: str """ exe = _find_mermaid_ascii() if exe is None: diff --git a/libs/astx/tests/__init__.py b/libs/astx/tests/__init__.py index 1e9d4d09..bfe17588 100644 --- a/libs/astx/tests/__init__.py +++ b/libs/astx/tests/__init__.py @@ -1 +1,3 @@ -"""Unit test package for astx.""" +""" +title: Unit test package for astx. +""" diff --git a/libs/astx/tests/datatypes/__init__.py b/libs/astx/tests/datatypes/__init__.py index ce2de761..f00095ac 100644 --- a/libs/astx/tests/datatypes/__init__.py +++ b/libs/astx/tests/datatypes/__init__.py @@ -1 +1,3 @@ -"""Unit test package for astx types and literals.""" +""" +title: Unit test package for astx types and literals. +""" diff --git a/libs/astx/tests/datatypes/test_boolean.py b/libs/astx/tests/datatypes/test_boolean.py index 84ab579e..872d13fc 100644 --- a/libs/astx/tests/datatypes/test_boolean.py +++ b/libs/astx/tests/datatypes/test_boolean.py @@ -1,4 +1,6 @@ -"""Tests for Boolean data type.""" +""" +title: Tests for Boolean data type. +""" from astx.data import VariableDeclaration from astx.literals.boolean import LiteralBoolean @@ -6,7 +8,9 @@ def test_variable_boolean() -> None: - """Test variable boolean.""" + """ + title: Test variable boolean. + """ decl_a = VariableDeclaration( name="a", type_=Boolean(), value=LiteralBoolean(value=True) ) @@ -15,7 +19,9 @@ def test_variable_boolean() -> None: def test_literal_boolean() -> None: - """Test literal boolean.""" + """ + title: Test literal boolean. + """ lit_a = LiteralBoolean(value=True) assert isinstance(lit_a, LiteralBoolean) assert lit_a.get_struct() diff --git a/libs/astx/tests/datatypes/test_char_string.py b/libs/astx/tests/datatypes/test_char_string.py index 3204439b..ed27f9c5 100644 --- a/libs/astx/tests/datatypes/test_char_string.py +++ b/libs/astx/tests/datatypes/test_char_string.py @@ -1,8 +1,10 @@ -"""Tests for UTF-8 character and string data types.""" +""" +title: Tests for UTF-8 character and string data types. +""" from __future__ import annotations -from typing import Callable, Type +from typing import Callable import astx import pytest @@ -22,7 +24,9 @@ def test_variable() -> None: - """Test variable UTF-8 character and string.""" + """ + title: Test variable UTF-8 character and string. + """ var_a = Variable("a") var_b = Variable("b") @@ -30,16 +34,26 @@ def test_variable() -> None: @pytest.mark.parametrize("literal_class", UTF8_CHAR_LITERAL_CLASSES) -def test_utf8_char_literal(literal_class: Type[astx.Literal]) -> None: - """Test UTF-8 character literals.""" +def test_utf8_char_literal(literal_class: type[astx.Literal]) -> None: + """ + title: Test UTF-8 character literals. + parameters: + literal_class: + type: type[astx.Literal] + """ lit_a = literal_class("A") lit_b = literal_class("B") BinaryOp(op_code="+", lhs=lit_a, rhs=lit_b) @pytest.mark.parametrize("literal_class", UTF8_STRING_LITERAL_CLASSES) -def test_utf8_string_literal(literal_class: Type[astx.Literal]) -> None: - """Test UTF-8 string literals.""" +def test_utf8_string_literal(literal_class: type[astx.Literal]) -> None: + """ + title: Test UTF-8 string literals. + parameters: + literal_class: + type: type[astx.Literal] + """ lit_a = literal_class("Hello") lit_b = literal_class("World") BinaryOp(op_code="+", lhs=lit_a, rhs=lit_b) @@ -55,11 +69,20 @@ def test_utf8_string_literal(literal_class: Type[astx.Literal]) -> None: ) @pytest.mark.parametrize("literal_class", UTF8_CHAR_LITERAL_CLASSES) def test_bin_ops_char( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations on UTF-8 characters.""" + """ + title: Test binary operations on UTF-8 characters. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -78,11 +101,20 @@ def test_bin_ops_char( ) @pytest.mark.parametrize("literal_class", UTF8_STRING_LITERAL_CLASSES) def test_bin_ops_string( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations on UTF-8 strings.""" + """ + title: Test binary operations on UTF-8 strings. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -99,11 +131,20 @@ def test_bin_ops_string( ) @pytest.mark.parametrize("literal_class", UTF8_CHAR_LITERAL_CLASSES) def test_unary_ops_char( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations on UTF-8 characters.""" + """ + title: Test unary operations on UTF-8 characters. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" @@ -120,11 +161,20 @@ def test_unary_ops_char( ) @pytest.mark.parametrize("literal_class", UTF8_STRING_LITERAL_CLASSES) def test_unary_ops_string( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations on UTF-8 strings.""" + """ + title: Test unary operations on UTF-8 strings. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" diff --git a/libs/astx/tests/datatypes/test_collections.py b/libs/astx/tests/datatypes/test_collections.py index 8ae934ea..b7993242 100644 --- a/libs/astx/tests/datatypes/test_collections.py +++ b/libs/astx/tests/datatypes/test_collections.py @@ -1,9 +1,9 @@ -"""Test cases for collection data types.""" +""" +title: Test cases for collection data types. +""" from __future__ import annotations -from typing import Dict, List, Set, Tuple - from astx.literals.base import Literal from astx.literals.collections import ( LiteralDict, @@ -17,8 +17,10 @@ def test_literal_list_creation() -> None: - """Test creation of LiteralList.""" - elements: List[Literal] = [ + """ + title: Test creation of LiteralList. + """ + elements: list[Literal] = [ LiteralInt32(1), LiteralInt32(2), LiteralInt32(3), @@ -30,8 +32,10 @@ def test_literal_list_creation() -> None: def test_literal_tuple_creation() -> None: - """Test creation of LiteralTuple.""" - elements: Tuple[Literal, ...] = ( + """ + title: Test creation of LiteralTuple. + """ + elements: tuple[Literal, ...] = ( LiteralInt32(1), LiteralInt32(2), LiteralInt32(3), @@ -43,8 +47,10 @@ def test_literal_tuple_creation() -> None: def test_literal_set_creation() -> None: - """Test creation of LiteralSet.""" - elements: Set[Literal] = { + """ + title: Test creation of LiteralSet. + """ + elements: set[Literal] = { LiteralInt32(1), LiteralInt32(2), LiteralInt32(3), @@ -56,8 +62,10 @@ def test_literal_set_creation() -> None: def test_literal_dict_creation() -> None: - """Test creation of LiteralDict.""" - elements: Dict[Literal, Literal] = { + """ + title: Test creation of LiteralDict. + """ + elements: dict[Literal, Literal] = { LiteralInt32(1): LiteralInt32(10), LiteralInt32(2): LiteralInt32(20), } @@ -68,9 +76,11 @@ def test_literal_dict_creation() -> None: def test_literal_list_binary_addition() -> None: - """Test binary addition operation on LiteralList.""" - elements1: List[Literal] = [LiteralInt32(1), LiteralInt32(2)] - elements2: List[Literal] = [LiteralInt32(3), LiteralInt32(4)] + """ + title: Test binary addition operation on LiteralList. + """ + elements1: list[Literal] = [LiteralInt32(1), LiteralInt32(2)] + elements2: list[Literal] = [LiteralInt32(3), LiteralInt32(4)] lit_list1 = LiteralList(elements1) lit_list2 = LiteralList(elements2) combined = BinaryOp("+", lit_list1, lit_list2) @@ -81,8 +91,10 @@ def test_literal_list_binary_addition() -> None: def test_literal_list_unary_negation() -> None: - """Test unary negation operation on LiteralList.""" - elements: List[Literal] = [ + """ + title: Test unary negation operation on LiteralList. + """ + elements: list[Literal] = [ LiteralInt32(1), LiteralInt32(2), LiteralInt32(3), @@ -95,9 +107,11 @@ def test_literal_list_unary_negation() -> None: def test_literal_set_binary_union() -> None: - """Test binary union operation on LiteralSet.""" - elements1: Set[Literal] = {LiteralInt32(1), LiteralInt32(2)} - elements2: Set[Literal] = {LiteralInt32(3), LiteralInt32(4)} + """ + title: Test binary union operation on LiteralSet. + """ + elements1: set[Literal] = {LiteralInt32(1), LiteralInt32(2)} + elements2: set[Literal] = {LiteralInt32(3), LiteralInt32(4)} lit_set1 = LiteralSet(elements1) lit_set2 = LiteralSet(elements2) union_set = BinaryOp("|", lit_set1, lit_set2) @@ -108,9 +122,11 @@ def test_literal_set_binary_union() -> None: def test_literal_dict_binary_merge() -> None: - """Test binary merge operation on LiteralDict.""" - elements1: Dict[Literal, Literal] = {LiteralInt32(1): LiteralInt32(10)} - elements2: Dict[Literal, Literal] = {LiteralInt32(2): LiteralInt32(20)} + """ + title: Test binary merge operation on LiteralDict. + """ + elements1: dict[Literal, Literal] = {LiteralInt32(1): LiteralInt32(10)} + elements2: dict[Literal, Literal] = {LiteralInt32(2): LiteralInt32(20)} lit_dict1 = LiteralDict(elements1) lit_dict2 = LiteralDict(elements2) merged_dict = BinaryOp("**", lit_dict1, lit_dict2) diff --git a/libs/astx/tests/datatypes/test_complex.py b/libs/astx/tests/datatypes/test_complex.py index 4dabf0fa..ff57b9d6 100644 --- a/libs/astx/tests/datatypes/test_complex.py +++ b/libs/astx/tests/datatypes/test_complex.py @@ -1,8 +1,10 @@ -"""Tests for complex number data types.""" +""" +title: Tests for complex number data types. +""" from __future__ import annotations -from typing import Callable, Type +from typing import Callable import astx import pytest @@ -19,7 +21,9 @@ def test_variable() -> None: - """Test variable complex.""" + """ + title: Test variable complex. + """ var_a = Variable("a") var_b = Variable("b") @@ -27,8 +31,13 @@ def test_variable() -> None: @pytest.mark.parametrize("literal_class", COMPLEX_LITERAL_CLASSES) -def test_literal(literal_class: Type[astx.Literal]) -> None: - """Test complex literals.""" +def test_literal(literal_class: type[astx.Literal]) -> None: + """ + title: Test complex literals. + parameters: + literal_class: + type: type[astx.Literal] + """ lit_a = literal_class(1.5, 2.5) lit_b = literal_class(3.0, -4.0) BinaryOp(op_code="+", lhs=lit_a, rhs=lit_b) @@ -47,11 +56,20 @@ def test_literal(literal_class: Type[astx.Literal]) -> None: ) @pytest.mark.parametrize("literal_class", COMPLEX_LITERAL_CLASSES) def test_bin_ops( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations on complex numbers.""" + """ + title: Test binary operations on complex numbers. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -69,11 +87,20 @@ def test_bin_ops( ) @pytest.mark.parametrize("literal_class", COMPLEX_LITERAL_CLASSES) def test_unary_ops( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations on complex numbers.""" + """ + title: Test unary operations on complex numbers. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" diff --git a/libs/astx/tests/datatypes/test_date_time.py b/libs/astx/tests/datatypes/test_date_time.py index a1777fd2..e7995a79 100644 --- a/libs/astx/tests/datatypes/test_date_time.py +++ b/libs/astx/tests/datatypes/test_date_time.py @@ -1,8 +1,10 @@ -"""Tests for Date, Time, Timestamp, and DateTime data types.""" +""" +title: Tests for Date, Time, Timestamp, and DateTime data types. +""" from __future__ import annotations -from typing import Callable, Type +from typing import Callable import astx import pytest @@ -27,15 +29,22 @@ def test_variable_date() -> None: - """Test variable declaration with date types.""" + """ + title: Test variable declaration with date types. + """ var_date = Variable("date_var") var_time = Variable("time_var") BinaryOp(op_code="+", lhs=var_date, rhs=var_time) @pytest.mark.parametrize("literal_class", DATE_LITERAL_CLASSES) -def test_literal_initialization(literal_class: Type[astx.Literal]) -> None: - """Test date and time literals.""" +def test_literal_initialization(literal_class: type[astx.Literal]) -> None: + """ + title: Test date and time literals. + parameters: + literal_class: + type: type[astx.Literal] + """ literal_instance = literal_class("2023-10-31") assert str(literal_instance) != "" assert repr(literal_instance) != "" @@ -57,11 +66,20 @@ def test_literal_initialization(literal_class: Type[astx.Literal]) -> None: ) @pytest.mark.parametrize("literal_class", DATE_LITERAL_CLASSES) def test_binary_operations( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations on date and time literals.""" + """ + title: Test binary operations on date and time literals. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -79,11 +97,20 @@ def test_binary_operations( ) @pytest.mark.parametrize("literal_class", DATE_LITERAL_CLASSES) def test_unary_operations( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations on date and time literals.""" + """ + title: Test unary operations on date and time literals. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" @@ -93,28 +120,36 @@ def test_unary_operations( def test_literal_date_format() -> None: - """Test LiteralDate format.""" + """ + title: Test LiteralDate format. + """ literal_date = LiteralDate("2023-10-31") assert literal_date.value == "2023-10-31" assert isinstance(literal_date, LiteralDate) def test_literal_time_format() -> None: - """Test LiteralTime format.""" + """ + title: Test LiteralTime format. + """ literal_time = LiteralTime("12:00:00") assert literal_time.value == "12:00:00" assert isinstance(literal_time, LiteralTime) def test_literal_timestamp_format() -> None: - """Test LiteralTimestamp format.""" + """ + title: Test LiteralTimestamp format. + """ literal_timestamp = LiteralTimestamp("2023-10-31 12:00:00") assert literal_timestamp.value == "2023-10-31 12:00:00" assert isinstance(literal_timestamp, LiteralTimestamp) def test_literal_datetime_format() -> None: - """Test LiteralDateTime format.""" + """ + title: Test LiteralDateTime format. + """ literal_datetime = LiteralDateTime("2023-10-31 12:00:00.123456") assert literal_datetime.value == "2023-10-31 12:00:00.123456" assert isinstance(literal_datetime, LiteralDateTime) diff --git a/libs/astx/tests/datatypes/test_float.py b/libs/astx/tests/datatypes/test_float.py index a8b1dcb1..7babb6f1 100644 --- a/libs/astx/tests/datatypes/test_float.py +++ b/libs/astx/tests/datatypes/test_float.py @@ -1,8 +1,10 @@ -"""Tests for float data types.""" +""" +title: Tests for float data types. +""" from __future__ import annotations -from typing import Callable, Type +from typing import Callable import astx import pytest @@ -20,7 +22,9 @@ def test_variable() -> None: - """Test variable float.""" + """ + title: Test variable float. + """ var_a = Variable("a") var_b = Variable("b") @@ -28,8 +32,13 @@ def test_variable() -> None: @pytest.mark.parametrize("literal_class", FLOAT_LITERAL_CLASSES) -def test_literal(literal_class: Type[astx.Literal]) -> None: - """Test float literals.""" +def test_literal(literal_class: type[astx.Literal]) -> None: + """ + title: Test float literals. + parameters: + literal_class: + type: type[astx.Literal] + """ lit_a = literal_class(1.23) lit_b = literal_class(4.56) BinaryOp(op_code="+", lhs=lit_a, rhs=lit_b) @@ -55,11 +64,20 @@ def test_literal(literal_class: Type[astx.Literal]) -> None: ) @pytest.mark.parametrize("literal_class", FLOAT_LITERAL_CLASSES) def test_bin_ops( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations.""" + """ + title: Test binary operations. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -77,11 +95,20 @@ def test_bin_ops( ) @pytest.mark.parametrize("literal_class", FLOAT_LITERAL_CLASSES) def test_unary_ops( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations.""" + """ + title: Test unary operations. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" diff --git a/libs/astx/tests/datatypes/test_integer.py b/libs/astx/tests/datatypes/test_integer.py index c12b2e94..30b95151 100644 --- a/libs/astx/tests/datatypes/test_integer.py +++ b/libs/astx/tests/datatypes/test_integer.py @@ -1,8 +1,10 @@ -"""Tests for i32 data type.""" +""" +title: Tests for i32 data type. +""" from __future__ import annotations -from typing import Callable, Type +from typing import Callable import astx import pytest @@ -27,7 +29,9 @@ def test_variable() -> None: - """Test variable i32.""" + """ + title: Test variable i32. + """ var_a = Variable("a") var_b = Variable("b") @@ -35,8 +39,13 @@ def test_variable() -> None: @pytest.mark.parametrize("literal_class", LITERAL_CLASSES) -def test_literal(literal_class: Type[astx.Literal]) -> None: - """Test integer literals.""" +def test_literal(literal_class: type[astx.Literal]) -> None: + """ + title: Test integer literals. + parameters: + literal_class: + type: type[astx.Literal] + """ lit_a = literal_class(1) lit_b = literal_class(2) BinaryOp(op_code="+", lhs=lit_a, rhs=lit_b) @@ -62,11 +71,20 @@ def test_literal(literal_class: Type[astx.Literal]) -> None: ) @pytest.mark.parametrize("literal_class", LITERAL_CLASSES) def test_bin_ops( - literal_class: Type[astx.Literal], - fn_bin_op: Callable[[Type[astx.Literal]], BinaryOp], + literal_class: type[astx.Literal], + fn_bin_op: Callable[[type[astx.Literal]], BinaryOp], op_code: str, ) -> None: - """Test binary operations.""" + """ + title: Test binary operations. + parameters: + literal_class: + type: type[astx.Literal] + fn_bin_op: + type: Callable[[type[astx.Literal]], BinaryOp] + op_code: + type: str + """ bin_op = fn_bin_op(literal_class) assert bin_op.op_code == op_code assert str(bin_op) != "" @@ -84,11 +102,20 @@ def test_bin_ops( ) @pytest.mark.parametrize("literal_class", LITERAL_CLASSES) def test_unary_ops( - literal_class: Type[astx.Literal], - fn_unary_op: Callable[[Type[astx.Literal]], UnaryOp], + literal_class: type[astx.Literal], + fn_unary_op: Callable[[type[astx.Literal]], UnaryOp], op_code: str, ) -> None: - """Test unary operations.""" + """ + title: Test unary operations. + parameters: + literal_class: + type: type[astx.Literal] + fn_unary_op: + type: Callable[[type[astx.Literal]], UnaryOp] + op_code: + type: str + """ unary_op = fn_unary_op(literal_class) assert unary_op.op_code == op_code assert str(unary_op) != "" diff --git a/libs/astx/tests/datatypes/test_operators.py b/libs/astx/tests/datatypes/test_operators.py index 710f821b..526e0255 100644 --- a/libs/astx/tests/datatypes/test_operators.py +++ b/libs/astx/tests/datatypes/test_operators.py @@ -1,4 +1,6 @@ -"""Module for testing operators.""" +""" +title: Module for testing operators. +""" import pytest @@ -39,18 +41,29 @@ ], ) def test_binary_op(explicit: BinaryOp, implicit: BinaryOp) -> None: - """Test binary operator.""" + """ + title: Test binary operator. + parameters: + explicit: + type: BinaryOp + implicit: + type: BinaryOp + """ assert implicit.get_struct() == explicit.get_struct() def test_unary_op() -> None: - """Test unary operator.""" + """ + title: Test unary operator. + """ lit_a = LiteralInt32(1) UnaryOp(op_code="+", operand=lit_a) def test_walrus_op_init() -> None: - """Test WalrusOp initialization and properties.""" + """ + title: Test WalrusOp initialization and properties. + """ lhs = Variable("x") rhs = lit_1 walrus = WalrusOp(lhs=lhs, rhs=rhs) @@ -61,7 +74,9 @@ def test_walrus_op_init() -> None: def test_walrus_op_get_struct() -> None: - """Test WalrusOp get_struct method.""" + """ + title: Test WalrusOp get_struct method. + """ lhs = Variable("x") rhs = lit_1 walrus = WalrusOp(lhs=lhs, rhs=rhs) @@ -70,7 +85,9 @@ def test_walrus_op_get_struct() -> None: def test_compare_op_init() -> None: - """Test CompareOp initialization with single operator.""" + """ + title: Test CompareOp initialization with single operator. + """ compare = CompareOp(left=lit_1, ops=["=="], comparators=[lit_2]) assert compare.kind == ASTKind.CompareOpKind assert compare.ops == ["=="] @@ -80,7 +97,9 @@ def test_compare_op_init() -> None: def test_compare_op_get_struct() -> None: - """Test CompareOp get_struct returns correct structure.""" + """ + title: Test CompareOp get_struct returns correct structure. + """ compare = CompareOp(left=lit_1, ops=["=="], comparators=[lit_2]) struct = compare.get_struct(simplified=False) @@ -98,7 +117,9 @@ def test_compare_op_get_struct() -> None: def test_compare_op_with_variables() -> None: - """Test CompareOp with variables.""" + """ + title: Test CompareOp with variables. + """ var = Variable("x") compare = CompareOp(left=var, ops=[">"], comparators=[lit_1]) assert str(compare) == "Compare[>]" @@ -107,7 +128,9 @@ def test_compare_op_with_variables() -> None: def test_chained_compare_op() -> None: - """Test CompareOp with multiple chained comparisons.""" + """ + title: Test CompareOp with multiple chained comparisons. + """ var_a = Variable("a") var_b = Variable("b") var_c = Variable("c") diff --git a/libs/astx/tests/datatypes/test_ttypes.py b/libs/astx/tests/datatypes/test_ttypes.py index 6d56ee4f..3c42efef 100644 --- a/libs/astx/tests/datatypes/test_ttypes.py +++ b/libs/astx/tests/datatypes/test_ttypes.py @@ -1,4 +1,6 @@ -"""Test type objects.""" +""" +title: Test type objects. +""" import pytest @@ -75,5 +77,10 @@ @pytest.mark.parametrize("ttype", ttypes) def test_ttypes(ttype: DataType) -> None: - """Test ttypes.""" + """ + title: Test ttypes. + parameters: + ttype: + type: DataType + """ Variable("a", type_=ttype) diff --git a/libs/astx/tests/datatypes/test_types.py b/libs/astx/tests/datatypes/test_types.py index 5ee2797c..db8251cb 100644 --- a/libs/astx/tests/datatypes/test_types.py +++ b/libs/astx/tests/datatypes/test_types.py @@ -1,4 +1,6 @@ -"""Tests for classes in types.py.""" +""" +title: Tests for classes in types.py. +""" from __future__ import annotations @@ -9,7 +11,9 @@ def test_typecastexpr() -> None: - """Test TypeCastExpr.""" + """ + title: Test TypeCastExpr. + """ # Expression to cast expr = Variable(name="x") diff --git a/libs/astx/tests/examples/__init__.py b/libs/astx/tests/examples/__init__.py index ac5ce0fd..808d130f 100644 --- a/libs/astx/tests/examples/__init__.py +++ b/libs/astx/tests/examples/__init__.py @@ -1 +1,3 @@ -"""Test with real examples.""" +""" +title: Test with real examples. +""" diff --git a/libs/astx/tests/examples/test_fibonacci.py b/libs/astx/tests/examples/test_fibonacci.py index 478edd93..33b38f7f 100644 --- a/libs/astx/tests/examples/test_fibonacci.py +++ b/libs/astx/tests/examples/test_fibonacci.py @@ -1,4 +1,6 @@ -"""Test fibonnaci with astx.""" +""" +title: Test fibonnaci with astx. +""" from __future__ import annotations @@ -6,7 +8,9 @@ def test_function_call_fibonacci() -> None: - """Test the FunctionCall class with fibonacci.""" + """ + title: Test the FunctionCall class with fibonacci. + """ # Initialize the ASTx module module = astx.Module() diff --git a/libs/astx/tests/test_base.py b/libs/astx/tests/test_base.py index 302ba4b0..92f6d7da 100644 --- a/libs/astx/tests/test_base.py +++ b/libs/astx/tests/test_base.py @@ -1,4 +1,6 @@ -"""Test classes from the base module.""" +""" +title: Test classes from the base module. +""" from __future__ import annotations @@ -8,12 +10,16 @@ def test_is_using_jupyter_notebook() -> None: - """Test is_using_jupyter_notebook function.""" + """ + title: Test is_using_jupyter_notebook function. + """ assert not is_using_jupyter_notebook() def test_source_location() -> None: - """Test SourceLocation.""" + """ + title: Test SourceLocation. + """ line = 1 col = 2 @@ -23,14 +29,18 @@ def test_source_location() -> None: def test_ast_parent() -> None: - """Test AST parent usage.""" + """ + title: Test AST parent usage. + """ block = astx.Block() decl_a = astx.VariableDeclaration("a", type_=astx.Int32(), parent=block) assert block.nodes[0] == decl_a def test_ast_to_json() -> None: - """Test AST object to json.""" + """ + title: Test AST object to json. + """ block = astx.Block() astx.VariableDeclaration("a", type_=astx.Int32(), parent=block) assert block.to_json(simplified=True) != "" @@ -38,7 +48,9 @@ def test_ast_to_json() -> None: def test_ast_to_yaml() -> None: - """Test AST object to yaml.""" + """ + title: Test AST object to yaml. + """ block = astx.Block() astx.VariableDeclaration("a", type_=astx.Int32(), parent=block) assert block.to_yaml(simplified=True) != "" @@ -46,7 +58,9 @@ def test_ast_to_yaml() -> None: def test_ast_nodes() -> None: - """Test ASTNodes class.""" + """ + title: Test ASTNodes class. + """ block = astx.Block() astx.VariableDeclaration("a", type_=astx.Int32(), parent=block) @@ -63,7 +77,9 @@ def test_ast_nodes() -> None: def test_data_type() -> None: - """Test DataType class.""" + """ + title: Test DataType class. + """ dt = astx.DataType() assert str(dt) != "" assert repr(dt) != "" @@ -75,13 +91,17 @@ def test_data_type() -> None: def test_identifier_creation() -> None: - """Test basic identifier creation.""" + """ + title: Test basic identifier creation. + """ ident = astx.Identifier("test_var") assert ident.name == "test_var" def test_identifier_with_location() -> None: - """Test identifier with location.""" + """ + title: Test identifier with location. + """ loc = astx.SourceLocation(1, COLUMN_NUMBER) ident_with_loc = astx.Identifier("var2", loc=loc) assert ident_with_loc.name == "var2" @@ -90,21 +110,27 @@ def test_identifier_with_location() -> None: def test_identifier_as_part_of_block() -> None: - """Test identifier as part of a block.""" + """ + title: Test identifier as part of a block. + """ block = astx.Block() ident_with_parent = astx.Identifier("var3", parent=block) assert block.nodes[0] == ident_with_parent def test_struct_representation() -> None: - """Test struct representation.""" + """ + title: Test struct representation. + """ ident = astx.Identifier("test_var") struct = ident.get_struct(simplified=True) assert struct == {"IDENTIFIER[test_var]": "test_var"} def test_parenthesized_expr_1() -> None: - """Test ParenthesizedExpr 1.""" + """ + title: Test ParenthesizedExpr 1. + """ node = astx.ParenthesizedExpr( astx.AndOp(astx.LiteralBoolean(True), astx.LiteralBoolean(False)) ) @@ -113,7 +139,9 @@ def test_parenthesized_expr_1() -> None: def test_parenthesized_expr_2() -> None: - """Test ParenthesizedExpr 2.""" + """ + title: Test ParenthesizedExpr 2. + """ node_1 = astx.ParenthesizedExpr( astx.AndOp( astx.LiteralBoolean(True), diff --git a/libs/astx/tests/test_blocks.py b/libs/astx/tests/test_blocks.py index 3ce8eb8c..99df9aa9 100644 --- a/libs/astx/tests/test_blocks.py +++ b/libs/astx/tests/test_blocks.py @@ -1,4 +1,6 @@ -"""Module for testing different kind of ASTx blocks.""" +""" +title: Module for testing different kind of ASTx blocks. +""" from astx.blocks import Block from astx.data import Variable, VariableDeclaration @@ -8,7 +10,9 @@ def test_block() -> None: - """Test ASTx block.""" + """ + title: Test ASTx block. + """ block = Block() decl_a = VariableDeclaration("a", type_=Int32(), value=LiteralInt32(1)) diff --git a/libs/astx/tests/test_callables.py b/libs/astx/tests/test_callables.py index 722caa84..22469f83 100644 --- a/libs/astx/tests/test_callables.py +++ b/libs/astx/tests/test_callables.py @@ -1,4 +1,6 @@ -"""Test callable ASTx objects.""" +""" +title: Test callable ASTx objects. +""" import pytest @@ -27,7 +29,9 @@ def test_functiondef_creation_with_no_modifiers() -> None: - """Test function creation with no modifiers.""" + """ + title: Test function creation with no modifiers. + """ var_a = Argument("a", type_=Int32(), default=LiteralInt32(1)) var_b = Argument("b", type_=Int32(), default=LiteralInt32(1)) @@ -51,7 +55,9 @@ def test_functiondef_creation_with_no_modifiers() -> None: def test_functiondef_creation_with_modifiers() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ var_a = Argument("a", type_=Int32(), default=LiteralInt32(1)) var_b = Argument("b", type_=Int32(), default=LiteralInt32(1)) proto = FunctionPrototype( @@ -72,7 +78,9 @@ def test_functiondef_creation_with_modifiers() -> None: def test_function_call() -> None: - """Test the FunctionCall class.""" + """ + title: Test the FunctionCall class. + """ var_a = Argument("a", type_=Int32(), default=LiteralInt32(1)) var_b = Argument("b", type_=Int32(), default=LiteralInt32(1)) proto = FunctionPrototype( @@ -95,7 +103,9 @@ def test_function_call() -> None: def test_function_return() -> None: - """Test the FunctionReturn class.""" + """ + title: Test the FunctionReturn class. + """ fn_return = FunctionReturn(LiteralInt32(0)) assert str(fn_return) @@ -104,7 +114,9 @@ def test_function_return() -> None: def test_lambdaexpr() -> None: - """Test the LambdaExpr class.""" + """ + title: 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) @@ -115,7 +127,9 @@ def test_lambdaexpr() -> None: def test_lambdaexpr_noparams() -> None: - """Test the LambdaExpr class without params.""" + """ + title: Test the LambdaExpr class without params. + """ body = LiteralInt32(1) lambda_expr = LambdaExpr(body=body) @@ -125,7 +139,9 @@ def test_lambdaexpr_noparams() -> None: def test_functionasync_creation_with_no_modifiers() -> None: - """Test async function creation with no modifiers.""" + """ + title: Test async function creation with no modifiers. + """ var_a = Argument("a", type_=Int32(), default=LiteralInt32(1)) var_b = Argument("b", type_=Int32(), default=LiteralInt32(1)) @@ -149,7 +165,9 @@ def test_functionasync_creation_with_no_modifiers() -> None: def test_await_expr() -> None: - """Test `AwaitExpr` class.""" + """ + title: Test `AwaitExpr` class. + """ await_expr = AwaitExpr(value=LiteralInt32(1)) assert str(await_expr) @@ -159,7 +177,9 @@ def test_await_expr() -> None: def test_yield_expr() -> None: - """Test `YieldExpr` class.""" + """ + title: Test `YieldExpr` class. + """ yield_expr = YieldExpr(value=LiteralInt32(1)) assert str(yield_expr) @@ -169,7 +189,9 @@ def test_yield_expr() -> None: def test_yieldfrom_expr() -> None: - """Test `YieldFromExpr` class.""" + """ + title: Test `YieldFromExpr` class. + """ yieldfrom_expr = YieldFromExpr(value=LiteralInt32(1)) assert str(yieldfrom_expr) @@ -179,7 +201,9 @@ def test_yieldfrom_expr() -> None: def test_yield_stmt_basic() -> None: - """Test basic YieldStmt without a value.""" + """ + title: Test basic YieldStmt without a value. + """ yield_stmt = YieldStmt() assert str(yield_stmt) == "YieldStmt" @@ -189,7 +213,9 @@ def test_yield_stmt_basic() -> None: def test_yield_stmt_with_value() -> None: - """Test YieldStmt with a literal value.""" + """ + title: Test YieldStmt with a literal value. + """ yield_stmt = YieldStmt(value=LiteralInt32(42)) assert str(yield_stmt) @@ -199,7 +225,9 @@ def test_yield_stmt_with_value() -> None: def test_yield_stmt_with_expression() -> None: - """Test YieldStmt with a complex expression.""" + """ + title: Test YieldStmt with a complex expression. + """ var_x = Variable("x") expr = BinaryOp(op_code="+", lhs=var_x, rhs=LiteralInt32(1)) yield_stmt = YieldStmt(value=expr) @@ -211,7 +239,9 @@ def test_yield_stmt_with_expression() -> None: def test_yield_stmt_in_generator_block() -> None: - """Test YieldStmt as part of a generator function block.""" + """ + title: Test YieldStmt as part of a generator function block. + """ EXPECTED_BLOCK_LENGTH = 2 gen_block = Block(name="generator_body") diff --git a/libs/astx/tests/test_classes.py b/libs/astx/tests/test_classes.py index fb2774b2..5bdb62dc 100644 --- a/libs/astx/tests/test_classes.py +++ b/libs/astx/tests/test_classes.py @@ -1,4 +1,6 @@ -"""Tests for classes statements.""" +""" +title: Tests for classes statements. +""" from astx.base import DataType from astx.blocks import Block @@ -17,7 +19,9 @@ def test_class_decl() -> None: - """Test `ClassDeclStmt` class.""" + """ + title: Test `ClassDeclStmt` class. + """ # Decorators decorator1 = Variable(name="decorator_one") @@ -35,7 +39,9 @@ def test_class_decl() -> None: def test_class_def() -> None: - """Test `ClassDefStmt` class.""" + """ + title: Test `ClassDefStmt` class. + """ # class attribute var_decl = VariableDeclaration( name="my_variable", @@ -69,7 +75,9 @@ def test_class_def() -> None: def test_enum_decl() -> None: - """Test `EnumDeclStmt` class.""" + """ + title: Test `EnumDeclStmt` class. + """ # Enum attributes var_r = VariableDeclaration( name="RED", @@ -102,7 +110,9 @@ def test_enum_decl() -> None: def test_struct_decl() -> None: - """Test `StructDeclStmt` class.""" + """ + title: Test `StructDeclStmt` class. + """ # Define struct attributes attr1 = VariableDeclaration(name="id", type_=DataType()) attr2 = VariableDeclaration(name="value", type_=DataType()) @@ -124,7 +134,9 @@ def test_struct_decl() -> None: def test_struct_def() -> None: - """Test `StructDefStmt` class.""" + """ + title: Test `StructDefStmt` class. + """ # Define struct fields attr1 = VariableDeclaration(name="id", type_=DataType()) diff --git a/libs/astx/tests/test_comprehensions.py b/libs/astx/tests/test_comprehensions.py index a34aa068..0c67a032 100644 --- a/libs/astx/tests/test_comprehensions.py +++ b/libs/astx/tests/test_comprehensions.py @@ -1,4 +1,6 @@ -"""Tests for control flow statements.""" +""" +title: Tests for control flow statements. +""" import astx @@ -7,7 +9,9 @@ def test_list_comprehension() -> None: - """Test ListComprehension.""" + """ + title: Test ListComprehension. + """ list_compre = astx.ListComprehension( element=astx.BinaryOp( op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("x") @@ -40,7 +44,9 @@ def test_list_comprehension() -> None: def test_generator_expr() -> None: - """Test `GeneratorExpr` class with conditions of Iterable type.""" + """ + title: Test `GeneratorExpr` class with conditions of Iterable type. + """ comp_1 = astx.ComprehensionClause( target=astx.Variable("x"), iterable=astx.Variable("my_list"), @@ -86,7 +92,9 @@ def test_generator_expr() -> None: def test_set_comprehension() -> None: - """Test SetComprehension.""" + """ + title: Test SetComprehension. + """ set_comp = astx.SetComprehension( element=astx.BinaryOp( op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("x") diff --git a/libs/astx/tests/test_context_manager.py b/libs/astx/tests/test_context_manager.py index 8f27f962..ed78edef 100644 --- a/libs/astx/tests/test_context_manager.py +++ b/libs/astx/tests/test_context_manager.py @@ -1,4 +1,6 @@ -"""Tests for context manager related AST nodes.""" +""" +title: Tests for context manager related AST nodes. +""" import pytest @@ -14,36 +16,64 @@ # Fixtures @pytest.fixture def context_expr() -> Expr: - """Fixture providing a basic Expr instance.""" + """ + title: Fixture providing a basic Expr instance. + returns: + type: Expr + """ return LiteralInt32(42) @pytest.fixture def var_name() -> Identifier: - """Fixture providing a basic Identifier instance.""" + """ + title: Fixture providing a basic Identifier instance. + returns: + type: Identifier + """ return Identifier("x") @pytest.fixture def empty_block() -> Block: - """Fixture providing an empty Block instance.""" + """ + title: Fixture providing an empty Block instance. + returns: + type: Block + """ return Block(name="empty_block") class TestWithItem: - """Test suite for WithItem class.""" + """ + title: Test suite for WithItem class. + """ def test_init_basic( self, context_expr: Expr, var_name: Identifier ) -> None: - """Test basic initialization of WithItem.""" + """ + title: Test basic initialization of WithItem. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + """ item = WithItem(context_expr, var_name) assert item.context_expr == context_expr assert item.instance_name is not None assert item.instance_name == var_name def test_str_basic(self, context_expr: Expr, var_name: Identifier) -> None: - """Test string representation.""" + """ + title: Test string representation. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + """ item = WithItem(context_expr, var_name) # Type assertion since we know var_name is not None in this test assert var_name is not None # This helps the type checker @@ -52,7 +82,14 @@ def test_str_basic(self, context_expr: Expr, var_name: Identifier) -> None: def test_get_struct_basic( self, context_expr: Expr, var_name: Identifier ) -> None: - """Test basic structure representation.""" + """ + title: Test basic structure representation. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + """ item = WithItem(context_expr, var_name) struct = item.get_struct() expected_key = f"CONTEXT[{context_expr}]" @@ -68,12 +105,23 @@ def test_get_struct_basic( class TestWithStmt: - """Test suite for WithStmt class.""" + """ + title: Test suite for WithStmt class. + """ def test_init_basic( self, context_expr: Expr, var_name: Identifier, empty_block: Block ) -> None: - """Test basic initialization of WithStmt.""" + """ + title: Test basic initialization of WithStmt. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + empty_block: + type: Block + """ item = WithItem(context_expr, var_name) stmt = WithStmt([item], empty_block) assert stmt.items == [item] @@ -83,7 +131,16 @@ def test_init_basic( def test_str_basic( self, context_expr: Expr, var_name: Identifier, empty_block: Block ) -> None: - """Test string representation.""" + """ + title: Test string representation. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + empty_block: + type: Block + """ item = WithItem(context_expr, var_name) stmt = WithStmt([item], empty_block) expected = f"WithStmt[{context_expr} as {var_name}]" @@ -92,7 +149,16 @@ def test_str_basic( def test_get_struct_basic( self, context_expr: Expr, var_name: Identifier, empty_block: Block ) -> None: - """Test basic structure representation.""" + """ + title: Test basic structure representation. + parameters: + context_expr: + type: Expr + var_name: + type: Identifier + empty_block: + type: Block + """ item = WithItem(context_expr, var_name) stmt = WithStmt([item], empty_block) struct = stmt.get_struct() diff --git a/libs/astx/tests/test_exceptions.py b/libs/astx/tests/test_exceptions.py index 5f789051..ef342ccc 100644 --- a/libs/astx/tests/test_exceptions.py +++ b/libs/astx/tests/test_exceptions.py @@ -1,4 +1,6 @@ -"""Tests for exceptions classes.""" +""" +title: Tests for exceptions classes. +""" from astx.blocks import Block from astx.callables import ( @@ -21,7 +23,9 @@ def test_throw_stmt() -> None: - """Test `ThrowStmt` class.""" + """ + title: Test `ThrowStmt` class. + """ # specify the exception to be thrown exc = Identifier("exception_message") @@ -37,7 +41,14 @@ def test_throw_stmt() -> None: def fn_print( arg: LiteralString, ) -> FunctionCall: - """Return a FunctionCall to print a string.""" + """ + title: Return a FunctionCall to print a string. + parameters: + arg: + type: LiteralString + returns: + type: FunctionCall + """ proto = FunctionPrototype( name="print", args=Arguments(Argument("_", type_=String())), @@ -51,7 +62,9 @@ def fn_print( def test_catchhandler_stmt_onetype() -> None: - """Test `CatchHandler` class with one type.""" + """ + title: Test `CatchHandler` class with one type. + """ # Create the "except" block exception_types = [Identifier("A")] except_body1 = Block() @@ -67,7 +80,9 @@ def test_catchhandler_stmt_onetype() -> None: def test_catchhandler_stmt_multipletypes() -> None: - """Test `CatchHandler` class with multiple types.""" + """ + title: Test `CatchHandler` class with multiple types. + """ # Create the "except" block exception_types = [Identifier("A"), Identifier("B")] except_body1 = Block() @@ -83,7 +98,9 @@ def test_catchhandler_stmt_multipletypes() -> None: def test_catchhandler_stmt_notypes() -> None: - """Test `CatchHandler` class without types.""" + """ + title: Test `CatchHandler` class without types. + """ # Create the "except" block except_body1 = Block() except_body1.append(fn_print(LiteralString(value="passed"))) @@ -96,7 +113,9 @@ def test_catchhandler_stmt_notypes() -> None: def test_catchhandler_stmt_notypes_noname() -> None: - """Test `CatchHandler` class without types or names.""" + """ + title: Test `CatchHandler` class without types or names. + """ # Create the "except" block except_body1 = Block() except_body1.append(fn_print(LiteralString(value="passed"))) @@ -109,7 +128,9 @@ def test_catchhandler_stmt_notypes_noname() -> None: def test_catchhandler_stmt_noname() -> None: - """Test `CatchHandler` class without name.""" + """ + title: Test `CatchHandler` class without name. + """ # Create the "except" block exception_types = [Identifier("A")] except_body1 = Block() @@ -123,7 +144,9 @@ def test_catchhandler_stmt_noname() -> None: def test_exceptionhandler_stmt() -> None: - """Test `ExceptionHandlerStmt` class with one handler.""" + """ + title: Test `ExceptionHandlerStmt` class with one handler. + """ exception_types = [Identifier("A")] # Create the "except" block @@ -146,7 +169,9 @@ def test_exceptionhandler_stmt() -> None: def test_exceptionhandler_stmt_multiplehandlers() -> None: - """Test `ExceptionHandlerStmt` class with multiple handlers.""" + """ + title: Test `ExceptionHandlerStmt` class with multiple handlers. + """ # Create the "except" block exception1_types = [Identifier("A")] except_body1 = Block() @@ -178,7 +203,9 @@ def test_exceptionhandler_stmt_multiplehandlers() -> None: def test_finallyhandler_stmt_() -> None: - """Test `FinallyHandlerStmt` class.""" + """ + title: Test `FinallyHandlerStmt` class. + """ # Create the "finally" block finally_body = Block() finally_body.append(fn_print(LiteralString(value="run complete"))) @@ -192,7 +219,10 @@ def test_finallyhandler_stmt_() -> None: def test_exceptionhandler_stmt_multiplehandlers_finally() -> None: - """Test `ExceptionHandlerStmt` class with multiple handlers and finally.""" + """ + title: >- + Test `ExceptionHandlerStmt` class with multiple handlers and finally. + """ # Create the "except" block exception1_types = [Identifier("A")] except_body1 = Block() diff --git a/libs/astx/tests/test_flows.py b/libs/astx/tests/test_flows.py index bd71d90e..96f4a72e 100644 --- a/libs/astx/tests/test_flows.py +++ b/libs/astx/tests/test_flows.py @@ -1,4 +1,6 @@ -"""Tests for control flow statements.""" +""" +title: Tests for control flow statements. +""" from typing import Any, cast @@ -34,7 +36,9 @@ def test_if_stmt() -> None: - """Test `if` statement.""" + """ + title: Test `if` statement. + """ op = BinaryOp(op_code=">", lhs=LiteralInt32(1), rhs=LiteralInt32(2)) then_block = Block() if_stmt = IfStmt(condition=op, then=then_block) @@ -46,7 +50,9 @@ def test_if_stmt() -> None: def test_if_else_stmt() -> None: - """Test `if`/`else` statement.""" + """ + title: Test `if`/`else` statement. + """ cond = BinaryOp(op_code=">", lhs=LiteralInt32(1), rhs=LiteralInt32(2)) then_block = Block() else_block = Block() @@ -59,7 +65,9 @@ def test_if_else_stmt() -> None: def test_if_expr() -> None: - """Test `if` expression.""" + """ + title: Test `if` expression. + """ op = BinaryOp(op_code=">", lhs=LiteralInt32(1), rhs=LiteralInt32(2)) then_block = Block() if_expr = IfExpr(condition=op, then=then_block) @@ -71,7 +79,9 @@ def test_if_expr() -> None: def test_if_else_expr() -> None: - """Test `if`/`else` expression.""" + """ + title: Test `if`/`else` expression. + """ cond = BinaryOp(op_code=">", lhs=LiteralInt32(1), rhs=LiteralInt32(2)) then_block = Block() else_block = Block() @@ -84,7 +94,9 @@ def test_if_else_expr() -> None: def test_for_range_loop_expr() -> None: - """Test `For Range Loop` expression`.""" + """ + title: Test `For Range Loop` expression`. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(-1) ) @@ -104,7 +116,9 @@ def test_for_range_loop_expr() -> None: def test_for_range_loop_stmt() -> None: - """Test `For Range Loop` statement.""" + """ + title: Test `For Range Loop` statement. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(-1) ) @@ -124,7 +138,9 @@ def test_for_range_loop_stmt() -> None: def test_for_count_loop_stmt() -> None: - """Test `For Count Loop` statement.""" + """ + title: Test `For Count Loop` statement. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(0) ) @@ -144,7 +160,9 @@ def test_for_count_loop_stmt() -> None: def test_for_count_loop_expr() -> None: - """Test `For Count Loop` expression.""" + """ + title: Test `For Count Loop` expression. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(0) ) @@ -164,7 +182,9 @@ def test_for_count_loop_expr() -> None: def test_break_stmt() -> None: - """Test BreakStmt class.""" + """ + title: Test BreakStmt class. + """ break_stmt = BreakStmt() assert str(break_stmt) == "BreakStmt" @@ -180,7 +200,9 @@ def test_break_stmt() -> None: def test_continue_stmt() -> None: - """Test ContinueStmt class.""" + """ + title: Test ContinueStmt class. + """ continue_stmt = ContinueStmt() assert str(continue_stmt) == "ContinueStmt" @@ -196,7 +218,9 @@ def test_continue_stmt() -> None: def test_async_for_range_loop_expr() -> None: - """Test `Async For Range Loop` expression`.""" + """ + title: Test `Async For Range Loop` expression`. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(-1) ) @@ -216,7 +240,9 @@ def test_async_for_range_loop_expr() -> None: def test_async_for_range_loop_stmt() -> None: - """Test `Async For Range Loop` statement.""" + """ + title: Test `Async For Range Loop` statement. + """ decl_a = InlineVariableDeclaration( "a", type_=Int32(), value=LiteralInt32(-1) ) @@ -236,7 +262,9 @@ def test_async_for_range_loop_stmt() -> None: def test_while_expr() -> None: - """Test `WhileExpr` class.""" + """ + title: Test `WhileExpr` class. + """ # Define a condition: x < 5 x_var = Variable(name="x") condition = BinaryOp( @@ -260,7 +288,9 @@ def test_while_expr() -> None: def test_while_stmt() -> None: - """Test `WhileStmt` class.""" + """ + title: Test `WhileStmt` class. + """ # Define a condition: x < 5 x_var = Variable(name="x") condition = BinaryOp( @@ -284,7 +314,9 @@ def test_while_stmt() -> None: def test_case_stmt() -> None: - """Test `CaseStmt` class.""" + """ + title: Test `CaseStmt` class. + """ condition1 = LiteralInt32(value=1) body1 = astx.Block() body1.append(LiteralString(value="one")) @@ -297,7 +329,9 @@ def test_case_stmt() -> None: def test_case_stmt_error1() -> None: - """Test `CaseStmt` class for default/condition inconsistency (1).""" + """ + title: Test `CaseStmt` class for default/condition inconsistency (1). + """ # should raise error - mustn't have condition since default=True with pytest.raises(ValueError): condition1 = LiteralInt32(value=1) @@ -311,7 +345,9 @@ def test_case_stmt_error1() -> None: def test_case_stmt_error2() -> None: - """Test `CaseStmt` class for default/condition inconsistency (2).""" + """ + title: Test `CaseStmt` class for default/condition inconsistency (2). + """ # should raise error - must have condition since deault=False with pytest.raises(ValueError): body1 = astx.Block() @@ -320,7 +356,9 @@ def test_case_stmt_error2() -> None: def test_switch_stmt() -> None: - """Test `SwitchStmt` class.""" + """ + title: Test `SwitchStmt` class. + """ # The expression to match value_expr = Variable(name="x") @@ -354,7 +392,9 @@ def test_switch_stmt() -> None: def test_goto_stmt() -> None: - """Test `GotoStmt` class.""" + """ + title: Test `GotoStmt` class. + """ goto_stmt = astx.GotoStmt(astx.Identifier("label1")) assert str(goto_stmt) @@ -364,7 +404,9 @@ def test_goto_stmt() -> None: def test_comprehension() -> None: - """Test generic comphrehension.""" + """ + title: Test generic comphrehension. + """ target = astx.LiteralString("x") iterable = astx.LiteralString("range(10)") condition = astx.LiteralString("x > 5") @@ -383,7 +425,9 @@ def test_comprehension() -> None: def test_do_while_expr() -> None: - """Test `DoWhileExpr` class.""" + """ + title: Test `DoWhileExpr` class. + """ # Define a condition: x < 5 x_var = Variable(name="x") condition = BinaryOp( @@ -404,7 +448,9 @@ def test_do_while_expr() -> None: def test_do_while_stmt() -> None: - """Test `DoWhileStmt` class.""" + """ + title: Test `DoWhileStmt` class. + """ # Define a condition: x < 5 x_var = Variable(name="x") condition = BinaryOp( diff --git a/libs/astx/tests/test_operators.py b/libs/astx/tests/test_operators.py index 5e464aab..51fd101b 100644 --- a/libs/astx/tests/test_operators.py +++ b/libs/astx/tests/test_operators.py @@ -1,4 +1,6 @@ -"""Tests for operators.""" +""" +title: Tests for operators. +""" import astx import pytest @@ -16,7 +18,9 @@ def test_assignment_expr() -> None: - """Test `AssignmentExpr` class.""" + """ + title: Test `AssignmentExpr` class. + """ var_a = Variable(name="a") var_b = Variable(name="b") @@ -29,7 +33,9 @@ def test_assignment_expr() -> None: def test_variable_assign() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ assign_a = VariableAssignment("a", value=LiteralInt32(1)) assert str(assign_a) @@ -40,7 +46,9 @@ def test_variable_assign() -> None: def test_and_op() -> None: - """Test AndOp.""" + """ + title: Test AndOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.AndOp(lhs=lhs, rhs=rhs) @@ -53,7 +61,9 @@ def test_and_op() -> None: def test_or_op() -> None: - """Test OrOp.""" + """ + title: Test OrOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.OrOp(lhs=lhs, rhs=rhs) @@ -66,7 +76,9 @@ def test_or_op() -> None: def test_xor_op() -> None: - """Test XorOp.""" + """ + title: Test XorOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.XorOp(lhs=lhs, rhs=rhs) @@ -79,7 +91,9 @@ def test_xor_op() -> None: def test_nand_op() -> None: - """Test NandOp.""" + """ + title: Test NandOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.NandOp(lhs=lhs, rhs=rhs) @@ -91,7 +105,9 @@ def test_nand_op() -> None: def test_nor_op() -> None: - """Test NorOp.""" + """ + title: Test NorOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.NorOp(lhs=lhs, rhs=rhs) @@ -103,7 +119,9 @@ def test_nor_op() -> None: def test_xnor_op() -> None: - """Test XnorOp.""" + """ + title: Test XnorOp. + """ lhs = astx.LiteralBoolean(True) rhs = astx.LiteralBoolean(False) op = astx.XnorOp(lhs=lhs, rhs=rhs) @@ -115,7 +133,9 @@ def test_xnor_op() -> None: def test_not_op() -> None: - """Test NotOp.""" + """ + title: Test NotOp. + """ operand = astx.LiteralBoolean(True) op = astx.NotOp(operand=operand) @@ -143,7 +163,14 @@ def test_not_op() -> None: ], ) def test_aug_assign_operations(operator: OpCodeAugAssign, value: int) -> None: - """Test all augmented assignment operators using parametrize.""" + """ + title: Test all augmented assignment operators using parametrize. + parameters: + operator: + type: OpCodeAugAssign + value: + type: int + """ var_x = astx.Identifier(name="x") literal_value = LiteralInt32(value) aug_assign = AugAssign(var_x, operator, literal_value) @@ -154,7 +181,9 @@ def test_aug_assign_operations(operator: OpCodeAugAssign, value: int) -> None: def test_starred_creation() -> None: - """Test creating a Starred operator.""" + """ + title: Test creating a Starred operator. + """ var = astx.Variable(name="args") starred = astx.Starred(value=var) assert starred.value == var @@ -169,7 +198,9 @@ def test_starred_creation() -> None: def test_starred_with_different_expressions() -> None: - """Test Starred with different types of expressions.""" + """ + title: Test Starred with different types of expressions. + """ # Test with Identifier ident = Identifier("a") starred_ident = astx.Starred(value=ident) diff --git a/libs/astx/tests/test_packages.py b/libs/astx/tests/test_packages.py index b685b934..eee1cb46 100644 --- a/libs/astx/tests/test_packages.py +++ b/libs/astx/tests/test_packages.py @@ -1,4 +1,6 @@ -"""Module for testing different kind of ASTx blocks.""" +""" +title: Module for testing different kind of ASTx blocks. +""" from astx.data import Variable, VariableDeclaration from astx.literals.numeric import LiteralInt32 @@ -19,7 +21,9 @@ def test_module() -> None: - """Test ASTx module.""" + """ + title: Test ASTx module. + """ module = Module() decl_a = VariableDeclaration("a", type_=Int32(), value=LiteralInt32(1)) @@ -40,7 +44,9 @@ def test_module() -> None: def test_target() -> None: - """Test ASTx module.""" + """ + title: Test ASTx module. + """ target = Target( datalayout="e-m:e-i64:64-f80:128-n8:16:32:64-S128", triple="x86_64-pc-linux-gnu", @@ -53,7 +59,9 @@ def test_target() -> None: def test_packages() -> None: - """Test ASTx package.""" + """ + title: Test ASTx package. + """ package_main = Package() package_child = Package() module_main = Module() @@ -70,7 +78,9 @@ def test_packages() -> None: def test_program() -> None: - """Test ASTx program.""" + """ + title: Test ASTx program. + """ target = Target( datalayout="e-m:e-i64:64-f80:128-n8:16:32:64-S128", triple="x86_64-pc-linux-gnu", @@ -97,7 +107,9 @@ def test_program() -> None: def test_multiple_imports_stmt() -> None: - """Test ImportStmt multiple imports.""" + """ + title: Test ImportStmt multiple imports. + """ alias1 = AliasExpr(name="math") alias2 = AliasExpr(name="matplotlib", asname="mtlb") @@ -109,7 +121,9 @@ def test_multiple_imports_stmt() -> None: def test_import_from_stmt() -> None: - """Test ImportFromStmt importing from module.""" + """ + title: Test ImportFromStmt importing from module. + """ alias = AliasExpr(name="pyplot", asname="plt") import_from_stmt = ImportFromStmt( @@ -121,7 +135,9 @@ def test_import_from_stmt() -> None: def test_wildcard_import_from_stmt() -> None: - """Test ImportFromStmt wildcard import from module.""" + """ + title: Test ImportFromStmt wildcard import from module. + """ alias = AliasExpr(name="*") import_from_stmt = ImportFromStmt(module="matplotlib", names=[alias]) @@ -131,7 +147,9 @@ def test_wildcard_import_from_stmt() -> None: def test_future_import_from_stmt() -> None: - """Test ImportFromStmt from future import.""" + """ + title: Test ImportFromStmt from future import. + """ alias = AliasExpr(name="division") import_from_stmt = ImportFromStmt(module="__future__", names=[alias]) @@ -140,7 +158,9 @@ def test_future_import_from_stmt() -> None: def test_multiple_imports_expr() -> None: - """Test ImportExpr multiple imports.""" + """ + title: Test ImportExpr multiple imports. + """ alias1 = AliasExpr(name="sqrt", asname="square_root") alias2 = AliasExpr(name="pi") @@ -151,7 +171,9 @@ def test_multiple_imports_expr() -> None: def test_import_from_expr() -> None: - """Test ImportFromExpr importing from module.""" + """ + title: Test ImportFromExpr importing from module. + """ alias1 = AliasExpr(name="sqrt", asname="square_root") import_from_expr = ImportFromExpr(module="math", names=[alias1]) @@ -161,7 +183,9 @@ def test_import_from_expr() -> None: def test_wildcard_import_from_expr() -> None: - """Test ImportFromExpr wildcard import from module.""" + """ + title: Test ImportFromExpr wildcard import from module. + """ alias1 = AliasExpr(name="*") import_from_expr = ImportFromExpr(module="math", names=[alias1]) @@ -171,7 +195,9 @@ def test_wildcard_import_from_expr() -> None: def test_future_import_from_expr() -> None: - """Test ImportFromExpr from future import.""" + """ + title: Test ImportFromExpr from future import. + """ alias1 = AliasExpr(name="division") import_from_expr = ImportFromExpr(module="__future__", names=[alias1]) @@ -181,7 +207,9 @@ def test_future_import_from_expr() -> None: def test_relative_import_from_expr() -> None: - """Test ImportFromExpr relative imports.""" + """ + title: Test ImportFromExpr relative imports. + """ alias1 = AliasExpr(name="division") alias2 = AliasExpr(name="matplotlib", asname="mtlb") diff --git a/libs/astx/tests/test_readme_usage.py b/libs/astx/tests/test_readme_usage.py index 33179dd5..f5efe3cb 100644 --- a/libs/astx/tests/test_readme_usage.py +++ b/libs/astx/tests/test_readme_usage.py @@ -1,46 +1,54 @@ -"""Test to see if the usage demo in README.md still works.""" - -import textwrap - - -def usage_demo() -> str: - """Execute an exact copy of the code shown in README.md.""" - import astx - - # Define a simple function `add(x, y): return x + y` - args = astx.Arguments( - astx.Argument(name="x", type_=astx.Int32()), - astx.Argument(name="y", type_=astx.Int32()), - ) - fn_body = astx.Block() - fn_body.append( - astx.FunctionReturn( - value=astx.BinaryOp( - op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("y") - ) - ) - ) - add_function = astx.FunctionDef( - prototype=astx.FunctionPrototype( - name="add", args=args, return_type=astx.Int32() - ), - body=fn_body, - ) - - from astx_transpilers.python_string import ASTxPythonTranspiler - - # Transpile the AST to Python - transpiler = ASTxPythonTranspiler() - python_code = transpiler.visit(add_function) - - return str(python_code) - - -def test_readme_usage() -> None: - """Test usage demo as shown in README.md.""" - expected = """\ - def add(x: int, y: int) -> int: - return (x + y) - """ - - assert usage_demo() == textwrap.dedent(expected).strip() +""" +title: Test to see if the usage demo in README.md still works. +""" + +import textwrap + + +def usage_demo() -> str: + """ + title: Execute an exact copy of the code shown in README.md. + returns: + type: str + """ + import astx + + # Define a simple function `add(x, y): return x + y` + args = astx.Arguments( + astx.Argument(name="x", type_=astx.Int32()), + astx.Argument(name="y", type_=astx.Int32()), + ) + fn_body = astx.Block() + fn_body.append( + astx.FunctionReturn( + value=astx.BinaryOp( + op_code="+", lhs=astx.Variable("x"), rhs=astx.Variable("y") + ) + ) + ) + add_function = astx.FunctionDef( + prototype=astx.FunctionPrototype( + name="add", args=args, return_type=astx.Int32() + ), + body=fn_body, + ) + + from astx_transpilers.python_string import ASTxPythonTranspiler + + # Transpile the AST to Python + transpiler = ASTxPythonTranspiler() + python_code = transpiler.visit(add_function) + + return str(python_code) + + +def test_readme_usage() -> None: + """ + title: Test usage demo as shown in README.md. + """ + expected = """\ + def add(x: int, y: int) -> int: + return (x + y) + """ + + assert usage_demo() == textwrap.dedent(expected).strip() diff --git a/libs/astx/tests/test_subscript.py b/libs/astx/tests/test_subscript.py index 4ead2c6f..39836cb9 100644 --- a/libs/astx/tests/test_subscript.py +++ b/libs/astx/tests/test_subscript.py @@ -1,4 +1,6 @@ -"""Tests for subscripts.""" +""" +title: Tests for subscripts. +""" from typing import cast @@ -10,7 +12,9 @@ def test_subscriptexpr_upper_lower() -> None: - """Test `SubscriptExpr` class - slice of an array.""" + """ + title: Test `SubscriptExpr` class - slice of an array. + """ # Variable a_var = Variable(name="a") @@ -29,7 +33,9 @@ def test_subscriptexpr_upper_lower() -> None: def test_subscriptexpr_index() -> None: - """Test `SubscriptExpr` class - index of an array.""" + """ + title: Test `SubscriptExpr` class - index of an array. + """ # Variable a_var = Variable(name="a") @@ -46,7 +52,9 @@ def test_subscriptexpr_index() -> None: def test_ellipsis_basic_properties() -> None: - """Test basic properties of the Ellipsis class.""" + """ + title: Test basic properties of the Ellipsis class. + """ ellip = Ellipsis() assert ellip.kind == ASTKind.EllipsisKind assert str(ellip) == "Ellipsis" @@ -56,7 +64,9 @@ def test_ellipsis_basic_properties() -> None: def test_ellipsis_in_various_slice_positions() -> None: - """Test Ellipsis used in different positions in subscript expressions.""" + """ + title: Test Ellipsis used in different positions in subscript expressions. + """ arr = Variable(name="array") # Case 1:upper bound slice_upper = SubscriptExpr( @@ -84,7 +94,9 @@ def test_ellipsis_in_various_slice_positions() -> None: def test_ellipsis_as_standalone_index() -> None: - """Test using Ellipsis as a standalone index - array[...].""" + """ + title: Test using Ellipsis as a standalone index - array[...]. + """ arr = Variable(name="data") subscr = SubscriptExpr( value=arr, @@ -102,7 +114,9 @@ def test_ellipsis_as_standalone_index() -> None: def test_ellipsis_nested_expressions() -> None: - """Test Ellipsis in more complex nested expressions.""" + """ + title: Test Ellipsis in more complex nested expressions. + """ inner_arr = Variable(name="vector") inner_subscr = SubscriptExpr( value=inner_arr, diff --git a/libs/astx/tests/test_symbol_table.py b/libs/astx/tests/test_symbol_table.py index 82ea1cd8..bd2f0b50 100644 --- a/libs/astx/tests/test_symbol_table.py +++ b/libs/astx/tests/test_symbol_table.py @@ -1,11 +1,15 @@ -"""Test classes and functions about Symbol Table.""" +""" +title: Test classes and functions about Symbol Table. +""" from astx import Variable from astx.symbol_table import SymbolTable def test_symbol_table() -> None: - """Test SymbolTable class.""" + """ + title: Test SymbolTable class. + """ symtable = SymbolTable() var_a = Variable("var_a") @@ -16,7 +20,9 @@ def test_symbol_table() -> None: def test_scope() -> None: - """Test Scope class.""" + """ + title: Test Scope class. + """ symtable = SymbolTable() var_a = Variable("var_a") diff --git a/libs/astx/tests/test_variables.py b/libs/astx/tests/test_variables.py index 40e58a88..88ecd4b3 100644 --- a/libs/astx/tests/test_variables.py +++ b/libs/astx/tests/test_variables.py @@ -1,4 +1,6 @@ -"""Test callable ASTx objects.""" +""" +title: Test callable ASTx objects. +""" import astx @@ -6,7 +8,9 @@ def test_variable() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ var_a = astx.Variable("a") assert str(var_a) @@ -17,7 +21,9 @@ def test_variable() -> None: def test_variable_decl() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ decl_a = astx.VariableDeclaration( "a", type_=astx.Int32(), value=astx.LiteralInt32(1) ) @@ -30,7 +36,9 @@ def test_variable_decl() -> None: def test_inline_variable_decl() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ decl_a = astx.InlineVariableDeclaration( "a", type_=astx.Int32(), value=astx.LiteralInt32(1) ) @@ -43,7 +51,9 @@ def test_inline_variable_decl() -> None: def test_argument() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ arg_a = astx.Argument( "a", type_=astx.Int32(), default=astx.LiteralInt32(1) ) @@ -56,7 +66,9 @@ def test_argument() -> None: def test_arguments() -> None: - """Test function creation with modifiers.""" + """ + title: Test function creation with modifiers. + """ arg_a = astx.Argument( "a", type_=astx.Int32(), default=astx.LiteralInt32(1) ) @@ -78,7 +90,9 @@ def test_arguments() -> None: def test_delete_stmt() -> None: - """Test DeleteStmt creation and properties.""" + """ + title: Test DeleteStmt creation and properties. + """ var1 = astx.Identifier(name="x") var2 = astx.Identifier(name="y") diff --git a/libs/astx/tests/test_viz.py b/libs/astx/tests/test_viz.py index 05391061..0b27b86c 100644 --- a/libs/astx/tests/test_viz.py +++ b/libs/astx/tests/test_viz.py @@ -1,4 +1,6 @@ -"""Tests visualization methods.""" +""" +title: Tests visualization methods. +""" from astx.blocks import Block from astx.data import Variable, VariableDeclaration @@ -9,7 +11,9 @@ def test_viz_image() -> None: - """Test image visualization method.""" + """ + title: Test image visualization method. + """ var_a = Variable("a") var_b = Variable("b") @@ -25,7 +29,9 @@ def test_viz_image() -> None: def test_viz_ascii() -> None: - """Test ascii representation.""" + """ + title: Test ascii representation. + """ block = Block() decl_a = VariableDeclaration("a", type_=Int32(), value=LiteralInt32(1)) decl_b = VariableDeclaration("b", type_=Int32(), value=LiteralInt32(2)) diff --git a/poetry.lock b/poetry.lock index aaaccf74..bff6d90c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -168,7 +168,7 @@ test = ["astroid (>=2,<5)", "pytest (<9.0)", "pytest-cov", "pytest-xdist"] [[package]] name = "astx" -version = "0.23.1" +version = "0.24.0" description = "ASTx is an agnostic expression structure for AST." optional = false python-versions = ">=3.10,<4" @@ -192,7 +192,7 @@ url = "libs/astx" [[package]] name = "astx-transpilers" -version = "0.23.1" +version = "0.24.0" description = "ASTx is an agnostic expression structure for AST." optional = false python-versions = ">=3.10,<4" @@ -201,7 +201,7 @@ files = [] develop = true [package.dependencies] -astx = "0.23.1" +astx = "0.24.0" atpublic = ">=4.0" plum-dispatch = ">=2" typeguard = ">=4" @@ -1007,14 +1007,14 @@ files = [ [[package]] name = "douki" -version = "0.11.0" +version = "0.12.0" description = "Documetatio from annotations" optional = false python-versions = "<4,>=3.10" groups = ["dev"] files = [ - {file = "douki-0.11.0-py3-none-any.whl", hash = "sha256:1d2ca4ea589b4d7b082f0b74a40c5b3df0c2eb3c862b09e228a2ae5fd75f0b9c"}, - {file = "douki-0.11.0.tar.gz", hash = "sha256:c91a1b92b6d4289f434a716ef639a9cd586523b865b6364895034df6b62a5769"}, + {file = "douki-0.12.0-py3-none-any.whl", hash = "sha256:e93fc7d14186c3c6f92add490f8287be4f95d201d8d24815dd1fe05b247dcaee"}, + {file = "douki-0.12.0.tar.gz", hash = "sha256:e2e15f4aa328295471c01dad02829fccd744d6b7c74dc3bef8d58e611dc45182"}, ] [package.dependencies] @@ -4652,4 +4652,4 @@ test = ["coverage (>=5.3.1)", "prompt-toolkit (>=3.0.29)", "pygments (>=2.2)", " [metadata] lock-version = "2.1" python-versions = ">=3.10,<4" -content-hash = "20c024b113e24dd716d8f52e4bf8a7ac9a789bf37f60b5a447cb098efb2df07c" +content-hash = "b30ce2dd9424d1ab27fe584f51efc85221386db30a5f88185bbf4b4493acdc7f" diff --git a/pyproject.toml b/pyproject.toml index 81cef746..c9698bb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,7 +46,7 @@ makim = "1.27.0" nbmake = ">=1.5.3" types-requests = ">=2.31.0.20240406" pytest-xdist = ">=3.8.0" -douki = ">=0.11.0" +douki = ">=0.12.0" [build-system] requires = ["poetry-core>=2"] @@ -77,6 +77,7 @@ sort_by_size = true verbose = false [tool.ruff] +target-version = "py310" line-length = 79 force-exclude = true src = ["./"] @@ -96,15 +97,21 @@ ignore = [ select = [ "E", # pycodestyle "F", # pyflakes - "D", # pydocstyle "YTT", # flake8-2020 "PL", # PL "RUF", # Ruff-specific rules "I001", # isort ] +extend-select = [ + "UP006", # Prefer builtin generics in annotations + "UP007", # Prefer | syntax for unions and optionals +] -[tool.ruff.lint.pydocstyle] -convention = "numpy" +[tool.ruff.lint.per-file-ignores] +"libs/astx/src/astx/base.py" = [ + "UP006", + "UP007", +] [tool.ruff.lint.isort] # Use a single line between direct and from import diff --git a/scripts/gen_ref_nav.py b/scripts/gen_ref_nav.py index 40eee35b..5918898c 100644 --- a/scripts/gen_ref_nav.py +++ b/scripts/gen_ref_nav.py @@ -1,10 +1,8 @@ """ +title: Generate the code reference pages and navigation. +summary: |- -Generate the code reference pages and navigation. - -REF: -https://github.com/mkdocstrings/mkdocstrings/blob/main/scripts/gen_ref_nav.py - + https://github.com/mkdocstrings/mkdocstrings/blob/main/scripts/gen_ref_nav.py """ from pathlib import Path