Question

Does a modifier node in the Rascal m3 Java Abstract Syntax tree exists? I want to check if a certain method is public, private or protected.

In the description, an abstract data type is declared, but in any file i try to visit, there is no match found.

In the other ADT's there is also no link to the modifier. Below the code with which i try to find any modifier.

public void visitModifier(loc file){ Declaration decl = createAstFromFile(file, true); visit(decl){ case \private(): println("private"); case \public(): println("public"); case \protected(): println("protected"); } }

Was it helpful?

Solution

Excellent question. In the current version the modifiers are stored as annotations on the declarations. Annotations are not visited by default by the visit statement, so you have to project them out yourself:

void visitModifier(loc file){
  Declaration decl = createAstFromFile(file, true);
  visit (decl){
    case Declaration d: 
       switch (d@modifiers?[]) { // get out the modifiers or generate empty list 
          case [*_,\public(),*_]   : println("public");
          case [*_,\private(),*_]  : println("private");
          case [*_,\protected(),*_]: println("protected");
          default                  : println("friendly");
        }
  }
}

Note that d@modifiers produces a list of modifiers, so you could find \static() and \final() in there as well. Without list matching it can also be done of course:

void visitModifier2(loc file){
  Declaration decl = createAstFromFile(file, true);
  visit (decl){
    case Declaration d: {
       mods = d@modifiers?[];
       if (\public() <- mods) // or if (\public() in mods)
         println("public");
       else if (\private() <- mods)
         println("private");
       else if (\protected() <- mods)
         println("protected");
       else
         println("friendly");
    }
  }
}

or, you could just collect all modifiers in a list like so:

[ *(d@modifiers?[]) | /Declaration d := decl ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top