223
|
1 package rep.optimizers;
|
|
2
|
|
3 import java.util.LinkedList;
|
|
4 import java.util.List;
|
|
5
|
|
6 import rep.REP;
|
|
7 import rep.REPCommand;
|
|
8
|
|
9 /**
|
|
10 *
|
348
|
11 * @author Tagano
|
223
|
12 *
|
|
13 */
|
331
|
14 public class DeleteInsertOptimizer implements REPCommandOptimizer {
|
223
|
15
|
331
|
16 public List<REPCommand> optimize(List<REPCommand> cmdlist){
|
|
17 List<REPCommand> output = new LinkedList<REPCommand>();
|
|
18 for (REPCommand cmd: cmdlist){
|
|
19 if (cmd.cmd==REP.REPCMD_NOP) continue;
|
|
20 output.add(0,new REPCommand(cmd));
|
|
21 }
|
223
|
22 for(int i = 0; i < output.size(); i++){
|
|
23 REPCommand r = output.get(i);
|
|
24 switch(r.cmd){
|
271
|
25 case REPCMD_INSERT:
|
223
|
26 break;
|
271
|
27 case REPCMD_DELETE:
|
223
|
28 optimizedAdd(output,r,i);
|
|
29 break;
|
348
|
30 case REPCMD_NOP:
|
|
31 output.remove(r);
|
|
32 i--;
|
|
33 break;
|
223
|
34 }
|
|
35 }
|
331
|
36 java.util.Collections.reverse(output);
|
|
37 return output;
|
223
|
38
|
|
39 }
|
331
|
40
|
223
|
41 private void optimizedAdd(List<REPCommand> output, REPCommand r, int ln) {
|
|
42 int lineno = r.lineno;
|
354
|
43 for(int i = ln+1; i < output.size(); i++){
|
223
|
44 REPCommand s = output.get(i);
|
|
45 if(s.cmd==REP.REPCMD_INSERT) {
|
368
|
46 if(s.lineno <= lineno){
|
223
|
47 lineno --;
|
|
48 }else if(s.lineno == lineno){
|
348
|
49
|
354
|
50 lineNumberCorrection(output,s.lineno,i,ln);
|
223
|
51 output.remove(r);
|
|
52 output.remove(s);
|
|
53 ln--;
|
|
54 break;
|
|
55 }
|
|
56 }else if(s.cmd==REP.REPCMD_DELETE){
|
354
|
57 if(s.lineno <= lineno){
|
223
|
58 lineno ++;
|
|
59 }
|
|
60 }else{
|
|
61 System.out.println("There are no such commands.");
|
|
62 }
|
|
63 }
|
|
64 }
|
|
65
|
|
66 private void lineNumberCorrection(List<REPCommand> opt, int ln, int count, int r){
|
354
|
67 for(int i = r+1; i < count; i++){
|
223
|
68 REPCommand o = opt.get(i);
|
348
|
69 if(o.lineno == 0){
|
368
|
70 }else if(ln <= o.lineno){
|
348
|
71 o.lineno -= 1;
|
|
72 }
|
223
|
73 }
|
|
74 }
|
|
75
|
|
76
|
|
77 }
|