Wednesday, September 3, 2008

@SuppressWarnings completion

Why it was made
Although NetBeans is capable of suggesting and auto-inserting @SuppressWarnings, it doesn't actually provide code completion or documentation for these values. Indeed, as I've blogged about before, it is tricky to track down the exact enumeration and semantics of these magic values. This is due to the fact that they are entirely dependent on the compiler and IDE. This plugin adds support for the values currently supported by NetBeans 6.1, namely "cast", "deprecation", "divzero", "empty-statement", "empty", "fallthrough", "finally", "serial" and "unchecked". It also tries to explain how and when to use them.



How it was made
Creating plugins for NetBeans is relatively easy if you start by grabbing existing code and have invested in the RCP book. Especially blogs like Geertjan's and Sandip's are virtual goldmines. So for this one, I used the Geertjan's blog entry entitled Caret Aware Code Completion. I had some trouble hooking into the Java parser as the tutorial shows, whenever invoking completion, there would be a lag between obtaining the caret position and resolving the current element. I did not figure out why this is, other than for some reason, the mapping from caret position to the underlying AST went out of sync. So instead I ended up relying only on the build-in Java lexer, which did not exhibit the same lag. This means there were a little bit of manual parsing to do, to assert if indeed the context invites for @SuppressWarnings values. The following scenarios had to be accounted for:


@SuppressWarnings(STRING_LITERAL
@SuppressWarnings({STRING_LITERAL
@SuppressWarnings({STRING_LITERAL, STRING_LITERAL
@SuppressWarnings(value=STRING_LITERAL
@SuppressWarnings(value={STRING_LITERAL, STRING_LITERAL



In other words, we have to consume the Java token stream in reverse, from any open of closed STRING_LITERAL, and pass the following finite-state machine:



This is implemented by a simple recursive descent parser, which looks like this. Should you care to use it for your own parsing of a DSL inside Java String tokens, you can download the complete source code here.


Where to get it
There might still be some bugs and perhaps I a missing something, but if you want to give it a spin, you can download the plugin from NetBeans plugin central.

The hardest thing was to gather information regarding the valid values, since it differs from compiler to compiler and the various IDE's. If you do happen to find a bug or something incorrect, please let me know so I can correct it.

Post a Comment