From fc370d5f3dabe99ea23ed6c1bdf97c98e6c9f39c Mon Sep 17 00:00:00 2001 From: Phodal Huang Date: Wed, 13 Nov 2024 22:07:03 +0800 Subject: [PATCH] refactor(ast): improve null safety and readability of PythonAst listeners - Modify `PythonAstBaseListener.kt` to use safe call operator for default parameter value assignment. - Change `buildAnnotation` function in `PythonAstBaseListener.kt` to private. - Simplify import usage name assignment in `PythonFullIdentListener.kt`. - Enhance null safety for alias name in import statement within `PythonFullIdentListener.kt`. --- .../kotlin/chapi/ast/pythonast/PythonAstBaseListener.kt | 4 ++-- .../chapi/ast/pythonast/PythonFullIdentListener.kt | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonAstBaseListener.kt b/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonAstBaseListener.kt index 7b171370..e0097aa0 100644 --- a/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonAstBaseListener.kt +++ b/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonAstBaseListener.kt @@ -21,7 +21,7 @@ open class PythonAstBaseListener : PythonParserBaseListener() { ) if (defParaCtx.ASSIGN() != null) { - parameter.DefaultValue = defParaCtx.test().text + parameter.DefaultValue = defParaCtx?.test()?.text ?: "" } parameter @@ -56,7 +56,7 @@ open class PythonAstBaseListener : PythonParserBaseListener() { return annotations } - fun buildAnnotation(node: PythonParser.DecoratorContext): CodeAnnotation { + private fun buildAnnotation(node: PythonParser.DecoratorContext): CodeAnnotation { val codeAnnotation = CodeAnnotation( Name = node.dotted_name().text ) diff --git a/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonFullIdentListener.kt b/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonFullIdentListener.kt index 6d885b63..28457097 100644 --- a/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonFullIdentListener.kt +++ b/chapi-ast-python/src/main/kotlin/chapi/ast/pythonast/PythonFullIdentListener.kt @@ -39,12 +39,12 @@ class PythonFullIdentListener(var fileName: String) : PythonAstBaseListener() { val codeImport = CodeImport(Source = sourceName) - ctx?.import_as_names()?.import_as_name()?.forEach { importAsNamecontext -> - val usageName = importAsNamecontext.name()[0].text + ctx?.import_as_names()?.import_as_name()?.forEach { nameContext -> + val usageName = nameContext.name()[0].text codeImport.UsageName += usageName - importAsNamecontext.AS()?.let { - codeImport.AsName = importAsNamecontext.name()[1].text + nameContext.AS()?.let { + codeImport.AsName = nameContext.name().getOrNull(1)?.text ?: "" } } @@ -126,6 +126,7 @@ class PythonFullIdentListener(var fileName: String) : PythonAstBaseListener() { if (defaultNode.Functions.isNotEmpty()) { this.codeContainer.DataStructures += defaultNode } + return this.codeContainer } }