Showing posts with label netbeans. Show all posts
Showing posts with label netbeans. Show all posts

Tuesday, December 4, 2007

Improving code using more Scala features

A couple of days ago Eric Willigers gave me some nice feedback on how to improve the code of the quick fix created for the previous post.

Before modifying the document we are required to lock it and then release it. I did it like this:


...
doc.atomicLock
doc.replace(ifRange.getStart,ifRange.getLength,resultingStatement,null)
doc.atomicUnlock
...


However this is not safe since the replace method could throw a BadLocationException. One of the things we could do is to add a try/catch/finally block. However Eric pointed me to a much nicer way to do , by using two techniques called:



The Loan pattern is a way to ensure resource disposal when the control leaves some scope. For this propose closures are used.

The Pimp my library pattern, based on a Martin Odersky’s article, provides a way to extend existing class libraries with new operations without recompiling. New operations are added by defining a wrapper for specific classes. In this case we need to apply the Loan pattern to the BaseDocument class


class RichDocument(doc : BaseDocument) {
def withLock[T](f : BaseDocument => T ) = {
try {
doc.atomicLock()

f(doc)

} catch {
case ble : BadLocationException =>
Exceptions.printStackTrace(ble)
} finally {
doc.atomicUnlock()
}
}
}


This class defines our wrapper, the f is an anonymous function with code that will modify the document. Now we can add this functionality to the BaseDocument class by using the following declaration:


object DocumentImplicits {
implicit def toRichDocument(doc : BaseDocument) = new RichDocument(doc)
}



Putting using these definitions in the fix code leaves the code like this:


...
doc.withLock(_.replace(ifRange.getStart,
ifRange.getLength,
resultingStatement,
null))
...


The "_.replace ..." syntax is interesting way of specifying an anonymous function with one argument. For more information on this see Placeholder Syntax for Anonymous Functions in section 6.23 of the Scala Language Specification.


Another thing that could be done using this pattern is to eliminate direct uses of the AstUtilities class. By doing this we can add the following definitions:


object AstNodeImplicits {
implicit def toRichAstNode(node : Node) = new RichAstNode(node)
}

class RichAstNode(node : Node) {
def getRange() = AstUtilities.getRange(node)
}


Before using this implicits we need to import them:


import org.langexplr.nbhints.utils.DocumentImplicits.toRichDocument
import org.langexplr.nbhints.utils.AstNodeImplicits.toRichAstNode


The final code for the fix method is the following:


def implement() = {
val doc = info.getDocument.asInstanceOf[BaseDocument]
val conditionRange = condition.getRange()
val conditionText = getConditionText(doc,conditionRange)
val statementRange = statement.getRange()
val statementText = doc.getText(statementRange.getStart,
statementRange.getLength)
val ifRange = ifNode.getRange()

val resultingStatement = statementText + getModifierText + conditionText

doc.withLock(_.replace(ifRange.getStart,
ifRange.getLength,
resultingStatement,
null))
}


Code for this example can be found here (Now updated to the released Netbeans 6.0 ) .

Saturday, November 24, 2007

Creating Netbeans Ruby Hints with Scala, Part 2

In this part I'm going to show a quick fix for the Netbeans Ruby hint presented in part 1.

The quick fix class

The definition of the quick fix for the hint presented in part 1 is the following:


class IfToStatementModifierFix(
info : CompilationInfo,
condition : Node,
statement : Node,
ifNode : Node,
kind : StatementModifierFix) extends Fix {

def isSafe = true
def isInteractive = false

...

}


As shown in this fragment the class that represents the fix requires a reference to each tree element involved in the problem. In this case the important parts are the complete if statement, the condition and the then statement.

Also a kind argument(specific for this quick fix) is used to determine if a if or a unless statement modifier needs to be created. The definition for StatementModifierFix, looks like this:

abstract class StatementModifierFix
case class IfStatementModifierFix extends StatementModifierFix
case class UnlessStatementModifierFix extends StatementModifierFix


The quick fix implementation

The IfToStatementModifierFix class needs to implement the implement method in order to do its work, here's the code:


def implement() = {
val doc = info.getDocument.asInstanceOf[BaseDocument]
val conditionRange = AstUtilities.getRange(condition)
val conditionText = getConditionText(doc,conditionRange)
val statementRange = AstUtilities.getRange(statement)
val statementText = doc.getText(statementRange.getStart,statementRange.getLength)
val ifRange = AstUtilities.getRange(ifNode)

val resultingStatement = statementText + getModifierText + conditionText
doc.atomicLock
doc.replace(ifRange.getStart,ifRange.getLength,resultingStatement,null)
doc.atomicUnlock
}


In order to generate the unless statement we need to change the operator from != to ==.
The getConditionText method does this job:


def getConditionText(doc : BaseDocument,range: OffsetRange) = {
val text = doc.getText(range.getStart,range.getLength)
kind match {
case IfStatementModifierFix() => text
case UnlessStatementModifierFix() => text.replace("!=","==")
}
}


The last thing we need to do is to connect the hint with this quick fix. In order to do this we need to modify the run method of the IfToStatementModifierHint class presented in part 1. We need to add a fix for each identified case.

The case when a method is used as a condition:


...
case ifStat@IfStatement(methodCall : CallNode,
NewlineNode(thenStat),
null) => {

val range = AstUtilities.getRange(node)

val fixes = new java.util.ArrayList
fixes.add(
new IfToStatementModifierFix(info,methodCall,thenStat,ifStat,IfStatementModifierFix))

val desc =
new Description(this,
recomendationText,
info.getFileObject,range,
fixes,
600)
result.add(desc)
}
...


The case when the condition is a not-equal comparison with nil:


case ifStat@IfStatement(condition@NotNode(eqExp@EqualComparison(x,_ : NilNode)),
NewlineNode(thenStat),
null) => {


val range = AstUtilities.getRange(node)

val fixes = new java.util.ArrayList
fixes.add(
new IfToStatementModifierFix(info,condition,thenStat,ifStat,IfStatementModifierFix))
fixes.add(
new IfToStatementModifierFix(info,eqExp,thenStat,ifStat,UnlessStatementModifierFix))

val desc =
new Description(this,
recomendationText,
info.getFileObject,range,
fixes,
600)
result.add(desc)
}


Note that for this case we also offer the quick fix for unless.

Example 1

Activating the hint on this code:



Now displays the following quick fix:



And changes the code as:



Example 2

Also for code like this:



The following options are presented:



By selecting option 2 the code is changed as:



Code for this experiment can be found here.

Monday, November 12, 2007

Creating Netbeans Ruby Hints with Scala, Part 1

In this post I'm going to show a little experiment of creating a Netbeans Ruby Hint using the Scala language. This is the first of a two-part series of posts on this topic.

Netbeans Ruby Hints and Quick Fixes is a very nice feature that will be part of Netbeans 6.0 Ruby integration. This feature can be used to identify potential problems or to promote best practices in Ruby programs. I first learned about it by reading Tor Norbye's blog.

I really like the idea of mixing languages to accomplish something. This is the main reason I chose Scala to do this experiment. Also I wanted to try to apply some ideas from previous posts. For a future experiment it will be very nice to write this code using JRuby.

For this post I'm using Netbeans 6.0 Beta 2. As described below the APIs for writing hints are still not officially public because they're still under development. Again, as with previous posts, this is only an experiment to see how different programming languages could be used solve special tasks.

Motivation

Several weeks ago I wrote a post on Ruby's yield statement, there I showed a function that calculates the Fibonacci sequence using a while statement in a pretty traditional way. Then someone posted a comment with a much compact version of it by using some nice Ruby features. That got me thinking how Netbeans Ruby Hints could also be used to help Ruby beginners(like me) to find out about alternative ways to do something.

The Hint

One of the things I like about Ruby is statement modifiers. That's one of the first things you notice while reading the Why's (Poignant) Guide to Ruby.

I think statement modifiers makes the code look nice if used carefully.

So the hint that will be implement it's going to identify opportunities to apply the if or unless statement modifiers. For example:


table = Hash.new
...
if table.empty? then
puts "No items"
end
...


Could also be written as:


table = Hash.new
...
puts "No items" if table.empty?
...


Creating the Netbeans module

The biggest challenge I had was to create a Netbeans module using only Scala. The main issue is not having all the nice GUI facilities available to create to module.

Luckily there's a series of articles in Geertjan's Weblog called NetBeans Modules for Dummies Part 1,2,3,4. These articles provided a lot of information on how to create an NBM file using Ant tasks .

I also had to create a some Netbeans modules using Java to dissect the resulting NBM file and to provide some of the missing arguments. The resulting Ant file is can be found here.

Another challenge that I had was that some of the classes that I needed to access were only available to friend packages, this mainly because I was trying to access APIs that are still changing. Luckly, Tor Norbye from the Netbeans Ruby development list, provided a solution for this issue which could be found here. Again this is a consequence of using API's that are still not public.

The last issue that I had was to add the Scala Runtime Jar file as part of the package. The How do module dependencies/classloading work? Netbeans Faq entry was very helpful to solve this.

The code

By reading the code of existing hints, I learned that, the way to define hints (which is still under development) is very nice and very simple. Also there's useful documentation in the Writing New Ruby Hints entry from the Netbeans wiki.

Here's the code:

class IfToStatementModifierHint extends AstRule {

def appliesTo(info : CompilationInfo) = true

def getKinds() : Set = {
val nodeKinds = new HashSet()
nodeKinds.add(NodeTypes.IFNODE)
nodeKinds
}

def run(info :CompilationInfo,
node : Node,
path : AstPath ,
caretOffset : int,
result : java.util.List) : unit = {

node match {
case IfStatement(callNode : CallNode,
NewlineNode(thenStat),
null) => {

val range = AstUtilities.getRange(node)

val desc =
new Description(this,
recomendationText,
info.getFileObject,range,
Collections.emptyList,
600)
result.add(desc)
}
case IfStatement(NotNode(EqualComparison(x,_ : NilNode)),
NewlineNode(thenStat),
null) => {


val range = AstUtilities.getRange(node)

val desc =
new Description(this,
recomendationText,
info.getFileObject,range,
Collections.emptyList,
600)
result.add(desc)
}
case _ =>
{
}
}
}

def getId() = "TestHint1"

def getDisplayName() = "If statement as statement modifier"

def getDescription() = "Identifies certain ..."

def getDefaultEnabled() = true

def getDefaultSeverity() = HintSeverity.WARNING

def getCustomizer(node: Preferences) : JComponent = null

def showInTasklist() = true

def recomendationText = "Consider changing..."

}


The most interesting methods of this class are getHints and run.

The getHints method defines the kinds of AST nodes this method applies to. The run method identifies which kinds of if statement apply to this hint. To do this a couple of extractor objects defined in previous posts are used. Two special cases are identified:

  • One if statement with a method call as condition, one statement in the then section and no statements in the else section.

  • One if statement with an equal comparison to nil as condition, one statement in the then section and no statements in the else section.


This Hint is shown as a WARNING because it's the how severity that seems to apply. Although it will be very nice to have a RECOMMENDATION severity which seems to be more appropriate for this hint.

I really like this way of defining hints because you have to write exactly the code related to your problem.

Here's and example in action:




Code for this experiment can be found here.

For the next post I'll try to implement a quick fix for this hint.

Thursday, August 16, 2007

Enjoying Netbeans Ruby integration

While listening to the Java Posse I noticed the work that Sun is doing with the Netbeans Ruby integration

This integration can be found in NetBeans IDE 6.0 Milestone 10 (M10). However, by reading Tor Norbye's blog I learned about nice features that are only available with the daily builds. So I decided to download a recent build and give it a try.

Here's some things that I found interesting and useful:

Debugger

Nice debugger integration with the IDE.



Highlight block open/close element

This is a very useful feature to find out if nested blocks are closed.



Code navigator

To quickly program elements inside a file.



Hints

Display hints to improve the code or fix a bug. For example while editing a program from a previous post it showed me this:




Also it suggest a fix for that issue:




Very nice!