In the last part, I described what generators are and what they can be used for. In this post, I'll be explaining how I used them to build the GWT Exporter.
The first step is to decide what your generator is going to do. In my case, I want the generator to introspect one of my GWT classes, and generate an exported JS API with bridge methods.
What's a bridge method?
Imagine you have the following GWT Class:
And you want to allow JS users to call the doSomethingUseful() function?
Today, you would use JSNI to export 'bridge methods' like so:
$wnd stands for the top-level window object, and by assigning to its doSomethingUseful property, you ensure GWT won't obfuscate it. The JSNI call to Util.doSomethingUseful will be obfuscated however, thus the bridge method is neccessary to export the obfuscated symbol.
It gets more complicated if you want to bridge a non-static function, but here's an example:
Which you may use as
As you can see, manual bridging gets tedious!
Generators to the rescue!
The first step in implementing a generator is to decide on a type that will be used to trigger the generator. So let's introduce a new marker interface called 'Exportable'. We also want the generated class to implement the Exporter interface, primarily, the export() method.
Here they are:
Simple eh? Next we'll add the following line to our GwtExporter.gwt.xml module file:
What does this mean?
It means that when GWT.create() is invoked with a type that can be assigned to an Exportable, invoke the generator. That is, we want to write
and have it invoke the generator.
Specifying what gets exported
Next we have to decide on the rules for exporting. Which methods of an Exportable get exported? How do we control the generated JS namespace? etc. For now, let's settle on the following logic -- a method is exportable IF and ONLY IF:
- The class enclosing the method implements Exportable
- Metadata has determined it's ok to export (more on this later)
- a primitive type (int, float, etc)
- another Exportable
- an immutable JRE type (String, Integer, Double, etc)
GWT has its own form of annotations similar to JavaDoc/XDocLet tags. We will use this to control export policy. We will support two forms of export policy:
- White List
- By default, nothing exported.
- Each method to be exported must have a "@gwt.export" metadata annotation
- Black List
- Place "@gwt.export" on class itself (in JavaDoc for class)
- By default, all public methods exported
- Each method to be removed from export consideration tagged with "@gwt.noexport"
As an example:
and uses black-list policy to export getFirstName() but supress the export of getLastName(); Using white-list policy, you would write:
to achieve the same effect.
At this time, we are not considering function overloading.
This concludes the specification process, and part 2. Coming up: Part 3, the guts of the generator implementation.