Search code examples
rascal

Get modifiers from class


I'm trying to get all the modifiers from a class in Rascal.

m = createM3FromEclipseProject(projectLocation);
for(cl <- classes(m)){
    set[Modifier] modi = { f | f <- m@modifiers[cl], f.scheme == "java+class"};
    println(modi);
}

This gives me an empty set of modifiers for all classes, but if I check m@modifiers, it is not empty.

So m@modifiers[cl] won't give me the modifiers that belong to that the class with location cl. How do I get these modifiers?


Solution

  • Something's wrong with the code you presented. If you try to do it step by step on the REPL you will see why:

    For an example project with Fruit and such extracted into the M3 model m I have this:

    rascal>classes(m)
    set[loc]: {
      |java+class:///Fruit|,
      |java+class:///Apple|,
      |java+class:///HelloWorld|
    }
    
    rascal>m@modifiers
    rel[loc definition,Modifier modifier]: {
      <|java+interface:///IFruit|,public()>,
      <|java+method:///HelloWorld/main(java.lang.String%5B%5D)|,static()>,
      <|java+class:///Fruit|,abstract()>,
      <|java+method:///Apple/edible()|,public()>,
      <|java+method:///Fruit/edible()|,public()>,
      <|java+class:///Apple|,public()>,
      <|java+method:///HelloWorld/main(java.lang.String%5B%5D)|,public()>,
      <|java+class:///HelloWorld|,public()>,
      <|java+method:///Fruit/edible()|,abstract()>,
      <|java+class:///Fruit|,public()>
    }
    

    So m@modifiers[someClass] returns a set of modifiers:

    rascal>m@modifiers[|java+class:///Fruit|]
    set[Modifier]: {
      abstract(),
      public()
    }
    

    In your code f <- m@modifiers[cl] the f thus binds to a modifier and not to a source location. Somehow the code does not throw an exception but rather lets the condition fail for you? Because I get this result instead:

    rascal>{ f | cl <- classes(m), f <- m@modifiers[cl], f.scheme == "java+class"};
    |prompt:///|(46,1,<1,46>,<1,47>): Undeclared field: scheme for Modifier
    Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredField/UndeclaredField.html|
    

    If you want to print the modifiers for each class, then this code should do it:

    for (cl <- classes(m)) {
      println("modifiers for <cl> are <m@modifiers[cl]>");
    }