summaryrefslogtreecommitdiff
path: root/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/main/rels/NestedMemberAccess.java
blob: 7e5eaa54326af644d565c0e5ded919054c6028c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.java.decompiler.main.rels;

import org.jetbrains.java.decompiler.code.CodeConstants;
import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode;
import org.jetbrains.java.decompiler.main.DecompilerContext;
import org.jetbrains.java.decompiler.main.collectors.CounterContainer;
import org.jetbrains.java.decompiler.main.collectors.VarNamesCollector;
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences;
import org.jetbrains.java.decompiler.modules.decompiler.exps.*;
import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph;
import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectNode;
import org.jetbrains.java.decompiler.modules.decompiler.vars.VarVersionPaar;
import org.jetbrains.java.decompiler.struct.StructMethod;
import org.jetbrains.java.decompiler.struct.gen.MethodDescriptor;
import org.jetbrains.java.decompiler.util.InterpreterUtil;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;

public class NestedMemberAccess {

  private static final int METHOD_ACCESS_NORMAL = 1;
  private static final int METHOD_ACCESS_FIELD_GET = 2;
  private static final int METHOD_ACCESS_FIELD_SET = 3;
  private static final int METHOD_ACCESS_METHOD = 4;

  private boolean noSynthFlag;
  private Map<MethodWrapper, Integer> mapMethodType = new HashMap<MethodWrapper, Integer>();


  public void propagateMemberAccess(ClassNode root) {
    if (root.nested.isEmpty()) {
      return;
    }

    noSynthFlag = DecompilerContext.getOption(IFernflowerPreferences.SYNTHETIC_NOT_SET);

    computeMethodTypes(root);

    eliminateStaticAccess(root);
  }


  private void computeMethodTypes(ClassNode node) {
    if (node.type == ClassNode.CLASS_LAMBDA) {
      return;
    }

    for (ClassNode nd : node.nested) {
      computeMethodTypes(nd);
    }

    for (MethodWrapper method : node.wrapper.getMethods()) {
      computeMethodType(node, method);
    }
  }

  private void computeMethodType(ClassNode node, MethodWrapper method) {
    int type = METHOD_ACCESS_NORMAL;

    if (method.root != null) {
      DirectGraph graph = method.getOrBuildGraph();

      StructMethod mt = method.methodStruct;
      if ((noSynthFlag || mt.isSynthetic()) && mt.hasModifier(CodeConstants.ACC_STATIC)) {
        if (graph.nodes.size() == 2) {  // incl. dummy exit node
          if (graph.first.exprents.size() == 1) {
            Exprent exprent = graph.first.exprents.get(0);

            MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor());
            int parcount = mtdesc.params.length;

            Exprent exprCore = exprent;

            if (exprent.type == Exprent.EXPRENT_EXIT) {
              ExitExprent exexpr = (ExitExprent)exprent;
              if (exexpr.getExittype() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) {
                exprCore = exexpr.getValue();
              }
            }

            switch (exprCore.type) {
              case Exprent.EXPRENT_FIELD:
                FieldExprent fexpr = (FieldExprent)exprCore;
                if ((parcount == 1 && !fexpr.isStatic()) ||
                    (parcount == 0 && fexpr.isStatic())) {
                  if (fexpr.getClassname().equals(node.classStruct.qualifiedName)) {  // FIXME: check for private flag of the field
                    if (fexpr.isStatic() ||
                        (fexpr.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpr.getInstance()).getIndex() == 0)) {
                      type = METHOD_ACCESS_FIELD_GET;
                    }
                  }
                }
                break;
              case Exprent.EXPRENT_VAR:  // qualified this
                if (parcount == 1) {
                  // this or final variable
                  if (((VarExprent)exprCore).getIndex() != 0) {
                    type = METHOD_ACCESS_FIELD_GET;
                  }
                }

                break;
              case Exprent.EXPRENT_INVOCATION:
                type = METHOD_ACCESS_METHOD;
                break;
              case Exprent.EXPRENT_ASSIGNMENT:
                AssignmentExprent asexpr = (AssignmentExprent)exprCore;
                if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) {
                  FieldExprent fexpras = (FieldExprent)asexpr.getLeft();
                  if ((parcount == 2 && !fexpras.isStatic()) ||
                      (parcount == 1 && fexpras.isStatic())) {
                    if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field
                      if (fexpras.isStatic() ||
                          (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) {
                        if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) {
                          type = METHOD_ACCESS_FIELD_SET;
                        }
                      }
                    }
                  }
                }
            }


            if (type == METHOD_ACCESS_METHOD) { // FIXME: check for private flag of the method

              type = METHOD_ACCESS_NORMAL;

              InvocationExprent invexpr = (InvocationExprent)exprCore;

              if ((invexpr.isStatic() && invexpr.getLstParameters().size() == parcount) ||
                  (!invexpr.isStatic() && invexpr.getInstance().type == Exprent.EXPRENT_VAR
                   && ((VarExprent)invexpr.getInstance()).getIndex() == 0 && invexpr.getLstParameters().size() == parcount - 1)) {

                boolean equalpars = true;

                for (int i = 0; i < invexpr.getLstParameters().size(); i++) {
                  Exprent parexpr = invexpr.getLstParameters().get(i);
                  if (parexpr.type != Exprent.EXPRENT_VAR ||
                      ((VarExprent)parexpr).getIndex() != i + (invexpr.isStatic() ? 0 : 1)) {
                    equalpars = false;
                    break;
                  }
                }

                if (equalpars) {
                  type = METHOD_ACCESS_METHOD;
                }
              }
            }
          }
          else if (graph.first.exprents.size() == 2) {
            Exprent exprentFirst = graph.first.exprents.get(0);
            Exprent exprentSecond = graph.first.exprents.get(1);

            if (exprentFirst.type == Exprent.EXPRENT_ASSIGNMENT &&
                exprentSecond.type == Exprent.EXPRENT_EXIT) {

              MethodDescriptor mtdesc = MethodDescriptor.parseDescriptor(mt.getDescriptor());
              int parcount = mtdesc.params.length;

              AssignmentExprent asexpr = (AssignmentExprent)exprentFirst;
              if (asexpr.getLeft().type == Exprent.EXPRENT_FIELD && asexpr.getRight().type == Exprent.EXPRENT_VAR) {
                FieldExprent fexpras = (FieldExprent)asexpr.getLeft();
                if ((parcount == 2 && !fexpras.isStatic()) ||
                    (parcount == 1 && fexpras.isStatic())) {
                  if (fexpras.getClassname().equals(node.classStruct.qualifiedName)) { // FIXME: check for private flag of the field
                    if (fexpras.isStatic() ||
                        (fexpras.getInstance().type == Exprent.EXPRENT_VAR && ((VarExprent)fexpras.getInstance()).getIndex() == 0)) {
                      if (((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) {

                        ExitExprent exexpr = (ExitExprent)exprentSecond;
                        if (exexpr.getExittype() == ExitExprent.EXIT_RETURN && exexpr.getValue() != null) {
                          if (exexpr.getValue().type == Exprent.EXPRENT_VAR &&
                              ((VarExprent)asexpr.getRight()).getIndex() == parcount - 1) {
                            type = METHOD_ACCESS_FIELD_SET;
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    if (type != METHOD_ACCESS_NORMAL) {
      mapMethodType.put(method, type);
    }
    else {
      mapMethodType.remove(method);
    }
  }


  private void eliminateStaticAccess(ClassNode node) {

    if (node.type == ClassNode.CLASS_LAMBDA) {
      return;
    }

    for (MethodWrapper meth : node.wrapper.getMethods()) {

      if (meth.root != null) {

        boolean replaced = false;

        DirectGraph graph = meth.getOrBuildGraph();

        HashSet<DirectNode> setVisited = new HashSet<DirectNode>();
        LinkedList<DirectNode> stack = new LinkedList<DirectNode>();
        stack.add(graph.first);

        while (!stack.isEmpty()) {  // TODO: replace with interface iterator?

          DirectNode nd = stack.removeFirst();

          if (setVisited.contains(nd)) {
            continue;
          }
          setVisited.add(nd);

          for (int i = 0; i < nd.exprents.size(); i++) {
            Exprent exprent = nd.exprents.get(i);

            replaced |= replaceInvocations(node, meth, exprent);

            if (exprent.type == Exprent.EXPRENT_INVOCATION) {
              Exprent ret = replaceAccessExprent(node, meth, (InvocationExprent)exprent);

              if (ret != null) {
                nd.exprents.set(i, ret);
                replaced = true;
              }
            }
          }

          for (DirectNode ndx : nd.succs) {
            stack.add(ndx);
          }
        }

        if (replaced) {
          computeMethodType(node, meth);
        }
      }
    }

    for (ClassNode child : node.nested) {
      eliminateStaticAccess(child);
    }
  }


  private boolean replaceInvocations(ClassNode caller, MethodWrapper meth, Exprent exprent) {

    boolean res = false;

    for (Exprent expr : exprent.getAllExprents()) {
      res |= replaceInvocations(caller, meth, expr);
    }

    while (true) {

      boolean found = false;

      for (Exprent expr : exprent.getAllExprents()) {
        if (expr.type == Exprent.EXPRENT_INVOCATION) {
          Exprent newexpr = replaceAccessExprent(caller, meth, (InvocationExprent)expr);
          if (newexpr != null) {
            exprent.replaceExprent(expr, newexpr);
            found = true;
            res = true;
            break;
          }
        }
      }

      if (!found) {
        break;
      }
    }

    return res;
  }

  private static boolean sameTree(ClassNode caller, ClassNode callee) {

    if (caller.classStruct.qualifiedName.equals(callee.classStruct.qualifiedName)) {
      return false;
    }

    while (caller.parent != null) {
      caller = caller.parent;
    }

    while (callee.parent != null) {
      callee = callee.parent;
    }

    return caller == callee;
  }

  private Exprent replaceAccessExprent(ClassNode caller, MethodWrapper methdest, InvocationExprent invexpr) {

    ClassNode node = DecompilerContext.getClassProcessor().getMapRootClasses().get(invexpr.getClassname());

    MethodWrapper methsource = null;
    if (node != null && node.wrapper != null) {
      methsource = node.wrapper.getMethodWrapper(invexpr.getName(), invexpr.getStringDescriptor());
    }

    if (methsource == null || !mapMethodType.containsKey(methsource)) {
      return null;
    }

    // if same method, return
    if (node.classStruct.qualifiedName.equals(caller.classStruct.qualifiedName) &&
        methsource.methodStruct.getName().equals(methdest.methodStruct.getName()) &&
        methsource.methodStruct.getDescriptor().equals(methdest.methodStruct.getDescriptor())) {
      // no recursive invocations permitted!
      return null;
    }

    int type = mapMethodType.get(methsource);

    //		// FIXME: impossible case. METHOD_ACCESS_NORMAL is not saved in the map
    //		if(type == METHOD_ACCESS_NORMAL) {
    //			return null;
    //		}

    if (!sameTree(caller, node)) {
      return null;
    }

    DirectGraph graph = methsource.getOrBuildGraph();
    Exprent source = graph.first.exprents.get(0);

    Exprent retexprent = null;

    switch (type) {
      case METHOD_ACCESS_FIELD_GET:
        ExitExprent exsource = (ExitExprent)source;
        if (exsource.getValue().type == Exprent.EXPRENT_VAR) { // qualified this
          VarExprent var = (VarExprent)exsource.getValue();
          String varname = methsource.varproc.getVarName(new VarVersionPaar(var));

          if (!methdest.setOuterVarNames.contains(varname)) {
            VarNamesCollector vnc = new VarNamesCollector();
            vnc.addName(varname);

            methdest.varproc.refreshVarNames(vnc);
            methdest.setOuterVarNames.add(varname);
          }

          int index = methdest.counter.getCounterAndIncrement(CounterContainer.VAR_COUNTER);
          VarExprent ret = new VarExprent(index, var.getVartype(), methdest.varproc);
          methdest.varproc.setVarName(new VarVersionPaar(index, 0), varname);

          retexprent = ret;
        }
        else { // field
          FieldExprent ret = (FieldExprent)exsource.getValue().copy();
          if (!ret.isStatic()) {
            ret.replaceExprent(ret.getInstance(), invexpr.getLstParameters().get(0));
          }
          retexprent = ret;
        }
        break;
      case METHOD_ACCESS_FIELD_SET:
        AssignmentExprent ret;
        if (source.type == Exprent.EXPRENT_EXIT) {
          ExitExprent extex = (ExitExprent)source;
          ret = (AssignmentExprent)extex.getValue().copy();
        }
        else {
          ret = (AssignmentExprent)source.copy();
        }
        FieldExprent fexpr = (FieldExprent)ret.getLeft();

        if (fexpr.isStatic()) {
          ret.replaceExprent(ret.getRight(), invexpr.getLstParameters().get(0));
        }
        else {
          ret.replaceExprent(ret.getRight(), invexpr.getLstParameters().get(1));
          fexpr.replaceExprent(fexpr.getInstance(), invexpr.getLstParameters().get(0));
        }
        retexprent = ret;
        break;
      case METHOD_ACCESS_METHOD:
        if (source.type == Exprent.EXPRENT_EXIT) {
          source = ((ExitExprent)source).getValue();
        }

        InvocationExprent invret = (InvocationExprent)source.copy();

        int index = 0;
        if (!invret.isStatic()) {
          invret.replaceExprent(invret.getInstance(), invexpr.getLstParameters().get(0));
          index = 1;
        }

        for (int i = 0; i < invret.getLstParameters().size(); i++) {
          invret.replaceExprent(invret.getLstParameters().get(i), invexpr.getLstParameters().get(i + index));
        }

        retexprent = invret;
    }


    if (retexprent != null) {
      // hide synthetic access method
      boolean hide = true;

      if (node.type == ClassNode.CLASS_ROOT || (node.access & CodeConstants.ACC_STATIC) != 0) {
        StructMethod mt = methsource.methodStruct;
        if (!mt.isSynthetic()) {
          hide = false;
        }
      }
      if (hide) {
        node.wrapper.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(invexpr.getName(), invexpr.getStringDescriptor()));
      }
    }

    return retexprent;
  }
}