Java code generation with XPAND (nested packages)

601 views Asked by At

I'm working on generating code from an existing model with XPAND. This model contains nested packages as one knows them from Java for example.

As far as I understand there are no loops or anything, so that I could concatenate for example the package declaration string.

I would like to do something like this:

model:
package kitchen
--package electronics
--package food
----class tomatoe

wanted output:

package kitchen.food;
class tomatoe{}

I should add that it should have the possibility to ask the classes for their parent classes. How to generate the import string for nested packages?

1

There are 1 answers

1
jham On

I think the most simple way would be to define a biderectional reference between parent and child package. So in your metamodel it would be a biderectional reference of package class to itself like:

+---------+
|Package  |
|         |<>--+
`---------+    | 0..* containedPackages
        |      |
        +------+ 0..1 parentPackage

In Xpand you would do (untested, but should be enough to get the idea):

«DEFINE class FOR Class»
  import «EXPAND packagename FOR this.package»;
  class «this.name»{}
«ENDDEFINE»

«DEFINE packagename FOR Package»
  «FOREACH this.packageHierarchy() as p SEPARATOR '.' -»«p»«ENDFOREACH»
«ENDDEFINE»

Xtend - recursively find the parents, add them to the list and reverse the list order. Probably there's a more clean way which doesn't need the flatten() method:

List[Package] packageHierarchy(Package p):
    let list = {}:
    p.parentPackage == null ? list.add(p) : list.add(packageHierarchy(p.parentPackage)) ->
    list.flatten().reverse()
;  

I hope the code snippets are not too broken :)