0

I'm trying to build an interface program in java to analyzing any java file and get the Halstead metrics result but i face a problem in parsing the input file, I read a lot about Antlr and JavaParsing projects but really can't understand how we can use it. My questions is:

1- is there any default command line in java compiler parsing any string and find any operand or operator in this input string line. 2 - if the answer is no can any one help in sending small example about using Javaparsing or Antlr libraries

Your usual support appreciated Best Regards

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
JavaTrainner
  • 37
  • 1
  • 5

1 Answers1

0

I'm not aware of any command line parser that does this.

ANTLR isn't simple but what you want to do is create a parser from a Java Grammar. This is how we generate our grammar (you can download the grammar here - https://github.com/antlr/grammars-v4/tree/master/java) :

public class GenerateVisitor {

  public static void main(String[] args) {
      String[] arg0 = { "-visitor", "D:/grammars/antlr/Java.g4", "-package", "com.virtualmachinery.jhawk.antlr" };
      org.antlr.v4.Tool.main(arg0);
  }  }

When you have done this you will find you have 6 generated classes and two files.

Obviously I can't teach you how to use ANTLR in 5 minutes but what you want to do is create a visitor that extends the JavaVisitor class that has been created. You can then override the methods that visit the methods and then analyse the context that is passed in. You can then separate out the tokens that are operators and the tokens that are operands using a switch statement.

In our code we do something like this:

public static void handleTokens(ParseTree ctx)
        List<Token> tokens = getTokens(ctx);
        int type;
        for (Token each: tokens) {
            type = getHalsteadType(type);
         }
}

The types are all defined as constants in the JavaParser class. There is some debate about which tokens can be ignored, which are operators and which are operators - you can find some information on how to make that decision here -

www.virtualmachinery.com/sidebar2.htm

Ken Hall
  • 209
  • 2
  • 5