4

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
Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
  • Is using a text diff library an option for you? – terrorrussia-keeps-killing Dec 18 '20 at 11:57
  • @fluffy: I am not sure, I was hoping for JavaParser to have something like that built in. I have to admit that I did not yet explore other options such as text diff libraries, but that would most probably be the necessary step if such a task can not be achieved with JavaParser alone. – Markus Weninger Dec 18 '20 at 12:08

0 Answers0