Skip to content

Commit

Permalink
feat: <python> add annotation key value support
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Feb 11, 2020
1 parent 2a84471 commit 937a950
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package chapi.ast.pythonast

import chapi.ast.antlr.PythonParser
import chapi.ast.antlr.PythonParserBaseListener
import domain.core.AnnotationKeyValue
import domain.core.CodeAnnotation
import domain.core.CodeProperty
import org.antlr.v4.runtime.tree.ParseTree
Expand Down Expand Up @@ -43,12 +44,12 @@ open class PythonAstBaseListener : PythonParserBaseListener() {
}

fun buildAnnotationsByIndex(ctx: PythonParser.ClassdefContext, ctxIndex: Int): Array<CodeAnnotation> {
var nodes : Array<PythonParser.DecoratorContext> = arrayOf()
var nodes: Array<PythonParser.DecoratorContext> = arrayOf()
for (i in 0 until ctxIndex) {
nodes += ctx.parent.getChild(i) as PythonParser.DecoratorContext
}

var annotations : Array<CodeAnnotation> = arrayOf()
var annotations: Array<CodeAnnotation> = arrayOf()
for (node in nodes) {
annotations += this.buildAnnotation(node)
}
Expand All @@ -61,6 +62,29 @@ open class PythonAstBaseListener : PythonParserBaseListener() {
Name = node.dotted_name().text
)

if (node.arglist() != null) {
codeAnnotation.KeyValues = this.buildArgList(node.arglist())
}

return codeAnnotation
}

private fun buildArgList(arglistCtx: PythonParser.ArglistContext?): Array<AnnotationKeyValue> {
var arguments: Array<AnnotationKeyValue> = arrayOf()
for (argCtx in arglistCtx!!.argument()) {
val key = argCtx.test(0).text
var value = ""
if (argCtx.test().size > 1) {
value = argCtx.test(1).text
}

val annotation = AnnotationKeyValue(
Key = key,
Value = value
)
arguments += annotation
}

return arguments
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,19 @@ class foo:
assertEquals(codeFile.DataStructures[0].Annotations[0].Name, "cache")
assertEquals(codeFile.DataStructures[0].Annotations[1].Name, "decorator")
}

@Test
internal fun shouldIdentifyMultipleClassAnnotationKeyValue() {
val code = """
@cache(key="value")
class multiple_annotation():
pass
"""

val codeFile = PythonAnalyser().analysis(code, "")
assertEquals(codeFile.DataStructures[0].Annotations[0].Name, "cache")
assertEquals(codeFile.DataStructures[0].Annotations[0].KeyValues[0].Key, "key")
assertEquals(codeFile.DataStructures[0].Annotations[0].KeyValues[0].Value, "\"value\"")
}
}

0 comments on commit 937a950

Please # to comment.