Track line number changes in JavaParser

89 Views Asked by At

I currently try to use JavaParser to slightly modify existing source code. I now would like to able to track line number changes introduced by theses modifications.

As an example, assume that we have a ModifierVisitor that adds one line to the body of every while loop (the code that is processed may contain multiple loops). Processing the following code

1 public class X {
2     public static void main(String[] args) {
3         int a = 1;
4         while(a < 100) {
5             a *= 2;
6         }
7     }
8 }

would transform it into

1 public class X {
2     public static void main(String[] args) {
3         int a = 1;
4         while(a < 100) {
5             a *= 2;
6             System.out.println("Hello, I am the new line");
7         }
8     }
9 }

Question: Is there an easy way / a built-in feature in JavaParser to create a line mapping between those two version?

I would like to have a mapping from the new line numbers to the old ones (or vice-versa). For the example above, the map should look something like:

New -> Old
  1 ->   1
  2 ->   2
  3 ->   3
  4 ->   4
  5 ->   5
  6 ->  -1 (did not exist in the old version)
  7 ->   6
  8 ->   7
  9 ->   8
0

There are 0 best solutions below