Linking visitMethod_declaration and visitIfStatement methods of Antlr4

18 views
Skip to first unread message

abhay dhar

unread,
May 5, 2024, 1:20:54 AMMay 5
to antlr-discussion

I am using ANTLR4 to read the C# files as I need to get all the conditional statements within the methods. For this purpose, I am overriding the visitIfStatement method, but the method does not have context of the current method. As I need to parse each method first and then go over its conditional statements sequentially. the below method gives me all the IF conditions of the input file. But I need the IF conditions method by method.

Question - Is there a way to set IfStatementContext within visitMethod_declaration so that I can get the conditions only within the methods. I need to do this because the object we are constructing has method body and then it has the if conditions within the methodBody.

I am trying to generate a custom class(py) object which would contain csharp method body and method's if/while/for conditions set on individual properties. With the below code , the IfStatementContext returns the complete class files conditions and there is no way to map the method context under which the if condition resides.

def visitIfStatement(self, ctx: CSharpParser.IfStatementContext): if_statement = self.getAllText(ctx.getPayload()) for i in range(ctx.start.line, ctx.stop.line): if i not in self.codeLineNumbers: self.codeLineNumbers.append(i) else: self.presentFlag = True if not self.presentFlag: print("Before adding to dict" + if_statement) result = dict(conditional_stmt=if_statement, start_line=ctx.start.line, end_line=ctx.stop.line, number_of_conditionals=self.ifcounter(if_statement) ) self.Program.DecisionNodeList.append(result) return self.visitChildren(ctx)



Also had created this SO question - https://stackoverflow.com/questions/78424669/linking-visitmember-access-and-visitifstatement-methods-of-antlr4/78428400#78428400

Reply all
Reply to author
Forward
0 new messages