Skip to content

Commit

Permalink
feat: <python> add func annotation support
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Feb 11, 2020
1 parent 937a950 commit 74b9394
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ open class PythonAstBaseListener : PythonParserBaseListener() {
return 0
}

fun buildAnnotationsByIndex(ctx: PythonParser.ClassdefContext, ctxIndex: Int): Array<CodeAnnotation> {
fun buildAnnotationsByIndex(ctx: ParseTree, ctxIndex: Int): Array<CodeAnnotation> {
var nodes: Array<PythonParser.DecoratorContext> = arrayOf()
for (i in 0 until ctxIndex) {
nodes += ctx.parent.getChild(i) as PythonParser.DecoratorContext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ class PythonFullIdentListener(var fileName: String) : PythonAstBaseListener() {
currentFunction.Modifiers += ctx.ASYNC().text
}

val ctxIndex = this.getNodeIndex(ctx)
if (ctxIndex > 0) {
currentFunction.Annotations = this.buildAnnotationsByIndex(ctx, ctxIndex)
}

if (ctx.typedargslist() != null) {
currentFunction.Parameters = this.buildParameters(ctx.typedargslist())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,26 @@ class multiple_annotation():
assertEquals(codeFile.DataStructures[0].Annotations[0].KeyValues[0].Key, "key")
assertEquals(codeFile.DataStructures[0].Annotations[0].KeyValues[0].Value, "\"value\"")
}

@Test
internal fun shouldIdentifyMultipleFunctionAnnotationKeyValue() {
val code = """
@accepts(int, int)
@returns(float)
def bar(low,high):
pass
"""

val codeFile = PythonAnalyser().analysis(code, "")
val firstFunc = codeFile.DataStructures[0].Functions[0]

assertEquals(firstFunc.Annotations[0].Name, "accepts")
assertEquals(firstFunc.Annotations[0].KeyValues.size, 2)
assertEquals(firstFunc.Annotations[0].KeyValues[0].Key, "int")
assertEquals(firstFunc.Annotations[0].KeyValues[1].Key, "int")

assertEquals(firstFunc.Annotations[1].Name, "returns")
assertEquals(firstFunc.Annotations[1].KeyValues[0].Key, "float")
}
}

0 comments on commit 74b9394

Please # to comment.