summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpectedTypeUtils.java
blob: c14da9f55373595e0a7da81c6e458a0d51f0ca4f (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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
/*
 * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers
 *
 * 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 com.siyeh.ig.psiutils;

import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashSet;
import java.util.Set;

public class ExpectedTypeUtils {

  private ExpectedTypeUtils() {}

  @Nullable
  public static PsiType findExpectedType(@NotNull PsiExpression expression, boolean calculateTypeForComplexReferences) {
    return findExpectedType(expression, calculateTypeForComplexReferences, false);
  }

  public static PsiType findExpectedType(PsiExpression expression, boolean calculateTypeForComplexReferences, boolean reportCasts) {
    PsiElement context = expression.getParent();
    PsiExpression wrappedExpression = expression;
    while (context instanceof PsiParenthesizedExpression) {
      wrappedExpression = (PsiExpression)context;
      context = context.getParent();
    }
    if (context == null) {
      return null;
    }
    final ExpectedTypeVisitor visitor = new ExpectedTypeVisitor(wrappedExpression, calculateTypeForComplexReferences, reportCasts);
    context.accept(visitor);
    return visitor.getExpectedType();
  }

  private static class ExpectedTypeVisitor extends JavaElementVisitor {

    /**
     * @noinspection StaticCollection
     */
    private static final Set<IElementType> arithmeticOps = new HashSet<IElementType>(5);

    private static final Set<IElementType> booleanOps = new HashSet<IElementType>(5);

    private static final Set<IElementType> shiftOps = new HashSet<IElementType>(3);

    private static final Set<IElementType> operatorAssignmentOps = new HashSet<IElementType>(11);

    static {
      arithmeticOps.add(JavaTokenType.PLUS);
      arithmeticOps.add(JavaTokenType.MINUS);
      arithmeticOps.add(JavaTokenType.ASTERISK);
      arithmeticOps.add(JavaTokenType.DIV);
      arithmeticOps.add(JavaTokenType.PERC);

      booleanOps.add(JavaTokenType.ANDAND);
      booleanOps.add(JavaTokenType.AND);
      booleanOps.add(JavaTokenType.XOR);
      booleanOps.add(JavaTokenType.OROR);
      booleanOps.add(JavaTokenType.OR);

      shiftOps.add(JavaTokenType.LTLT);
      shiftOps.add(JavaTokenType.GTGT);
      shiftOps.add(JavaTokenType.GTGTGT);

      operatorAssignmentOps.add(JavaTokenType.PLUSEQ);
      operatorAssignmentOps.add(JavaTokenType.MINUSEQ);
      operatorAssignmentOps.add(JavaTokenType.ASTERISKEQ);
      operatorAssignmentOps.add(JavaTokenType.DIVEQ);
      operatorAssignmentOps.add(JavaTokenType.ANDEQ);
      operatorAssignmentOps.add(JavaTokenType.OREQ);
      operatorAssignmentOps.add(JavaTokenType.XOREQ);
      operatorAssignmentOps.add(JavaTokenType.PERCEQ);
      operatorAssignmentOps.add(JavaTokenType.LTLTEQ);
      operatorAssignmentOps.add(JavaTokenType.GTGTEQ);
      operatorAssignmentOps.add(JavaTokenType.GTGTGTEQ);
    }

    @NotNull private final PsiExpression wrappedExpression;
    private final boolean calculateTypeForComplexReferences;
    private final boolean reportCasts;
    private PsiType expectedType = null;

    ExpectedTypeVisitor(@NotNull PsiExpression wrappedExpression, boolean calculateTypeForComplexReferences, boolean reportCasts) {
      this.wrappedExpression = wrappedExpression;
      this.calculateTypeForComplexReferences = calculateTypeForComplexReferences;
      this.reportCasts = reportCasts;
    }

    public PsiType getExpectedType() {
      return expectedType;
    }

    @Override
    public void visitField(@NotNull PsiField field) {
      final PsiExpression initializer = field.getInitializer();
      if (wrappedExpression.equals(initializer)) {
        expectedType = field.getType();
      }
    }

    @Override
    public void visitVariable(@NotNull PsiVariable variable) {
      expectedType = variable.getType();
    }

    @Override
    public void visitAssertStatement(PsiAssertStatement statement) {
      final PsiExpression condition = statement.getAssertCondition();
      if (wrappedExpression == condition) {
        expectedType = PsiType.BOOLEAN;
      }
      else {
        expectedType = TypeUtils.getStringType(statement);
      }
    }

    @Override
    public void visitArrayInitializerExpression(PsiArrayInitializerExpression initializer) {
      final PsiType type = initializer.getType();
      if (!(type instanceof PsiArrayType)) {
        expectedType = null;
        return;
      }
      final PsiArrayType arrayType = (PsiArrayType)type;
      expectedType = arrayType.getComponentType();
    }

    @Override
    public void visitArrayAccessExpression(PsiArrayAccessExpression accessExpression) {
      final PsiExpression indexExpression = accessExpression.getIndexExpression();
      if (wrappedExpression.equals(indexExpression)) {
        expectedType = PsiType.INT;
      }
    }

    @Override
    public void visitBinaryExpression(@NotNull PsiBinaryExpression binaryExpression) {
      final PsiExpression rhs = binaryExpression.getROperand();
      if (rhs == null) {
        expectedType = null;
        return;
      }
      final PsiExpression lhs = binaryExpression.getLOperand();
      PsiType lhsType = lhs.getType();
      if (lhsType == null) {
        expectedType = null;
        return;
      }
      PsiType rhsType = rhs.getType();
      if (rhsType == null) {
        expectedType = null;
        return;
      }
      final IElementType tokenType = binaryExpression.getOperationTokenType();
      final PsiType type = binaryExpression.getType();
      if (TypeUtils.isJavaLangString(type) || isArithmeticOperation(tokenType) || isBooleanOperation(tokenType)) {
        expectedType = type;
      }
      else if (isShiftOperation(tokenType)) {
        if (lhs == wrappedExpression) {
          expectedType = unaryNumericPromotion(lhsType);
        }
        else {
          expectedType = unaryNumericPromotion(rhsType);
        }
      }
      else if (ComparisonUtils.isEqualityComparison(binaryExpression)) {
        // JLS 15.21.1 Numerical Equality Operators == and !=
        final PsiType wrappedExpressionType = wrappedExpression.getType();
        if (TypeConversionUtil.isPrimitiveAndNotNull(wrappedExpressionType)) {
          expectedType = wrappedExpressionType;
          return;
        }
        if (lhs == wrappedExpression) {
          if (TypeConversionUtil.isPrimitiveAndNotNull(rhsType)) {
            expectedType = PsiPrimitiveType.getUnboxedType(wrappedExpressionType);
            return;
          }
          expectedType = TypeUtils.getObjectType(wrappedExpression);
        }
        else {
         if (TypeConversionUtil.isPrimitiveAndNotNull(lhsType)) {
            expectedType = PsiPrimitiveType.getUnboxedType(wrappedExpressionType);
            return;
          }
          expectedType = TypeUtils.getObjectType(wrappedExpression);
        }
      }
      else if (ComparisonUtils.isComparisonOperation(tokenType)) {
        if (lhs == wrappedExpression && !TypeConversionUtil.isPrimitiveAndNotNull(lhsType)) {
          lhsType = PsiPrimitiveType.getUnboxedType(lhsType);
          if (lhsType == null) {
            expectedType = null;
            return;
          }
        }
        if (rhs == wrappedExpression && !TypeConversionUtil.isPrimitiveAndNotNull(rhsType)) {
          rhsType = PsiPrimitiveType.getUnboxedType(rhsType);
          if (rhsType == null) {
            expectedType = null;
            return;
          }
        }
        // JLS 5.6.2 Binary Numeric Promotion
        if (PsiType.DOUBLE.equals(lhsType) || PsiType.DOUBLE.equals(rhsType)) {
          expectedType = PsiType.DOUBLE;
        }
        else if (PsiType.FLOAT.equals(lhsType) || PsiType.FLOAT.equals(rhsType)) {
          expectedType = PsiType.FLOAT;
        }
        else if (PsiType.LONG.equals(lhsType) || PsiType.LONG.equals(rhsType)) {
          expectedType = PsiType.LONG;
        }
        else {
          expectedType = PsiType.INT;
        }
      }
      else {
        expectedType = null;
      }
    }

    /**
     * JLS 5.6.1 Unary Numeric Promotion
     */
    private static PsiType unaryNumericPromotion(PsiType type) {
      if (type == null) {
        return null;
      }
      if (type.equalsToText("java.lang.Byte") || type.equalsToText("java.lang.Short") ||
          type.equalsToText("java.lang.Character") || type.equalsToText("java.lang.Integer") ||
          type.equals(PsiType.BYTE) || type.equals(PsiType.SHORT) || type.equals(PsiType.CHAR)) {
        return PsiType.INT;
      }
      else if (type.equalsToText("java.lang.Long")) {
        return PsiType.LONG;
      }
      else if (type.equalsToText("java.lang.Float")) {
        return PsiType.FLOAT;
      }
      else if (type.equalsToText("java.lang.Double")) {
        return PsiType.DOUBLE;
      }
      return type;
    }

    @Override
    public void visitPrefixExpression(@NotNull PsiPrefixExpression expression) {
      final PsiType type = expression.getType();
      if (type instanceof PsiPrimitiveType) {
        expectedType = type;
      }
      else {
        expectedType = PsiPrimitiveType.getUnboxedType(type);
      }
    }

    @Override
    public void visitPostfixExpression(@NotNull PsiPostfixExpression expression) {
      final PsiType type = expression.getType();
      if (type instanceof PsiPrimitiveType) {
        expectedType = type;
      }
      else {
        expectedType = PsiPrimitiveType.getUnboxedType(type);
      }
    }

    @Override
    public void visitSwitchStatement(PsiSwitchStatement statement) {
      final PsiExpression expression = statement.getExpression();
      if (expression == null) {
        return;
      }
      final PsiType type = expression.getType();
      final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(type);
      if (unboxedType != null) {
        expectedType = unboxedType;
      }
      else {
        expectedType = type;
      }
    }

    @Override
    public void visitTypeCastExpression(PsiTypeCastExpression expression) {
      if (reportCasts) {
        expectedType = expression.getType();
      }
    }

    @Override
    public void visitWhileStatement(@NotNull PsiWhileStatement whileStatement) {
      expectedType = PsiType.BOOLEAN;
    }

    @Override
    public void visitForStatement(@NotNull PsiForStatement statement) {
      expectedType = PsiType.BOOLEAN;
    }

    @Override
    public void visitForeachStatement(PsiForeachStatement statement) {
      final PsiExpression iteratedValue = statement.getIteratedValue();
      if (iteratedValue == null) {
        expectedType = null;
        return;
      }
      final PsiType iteratedValueType = iteratedValue.getType();
      if (!(iteratedValueType instanceof PsiClassType)) {
        expectedType = null;
        return;
      }
      final PsiClassType classType = (PsiClassType)iteratedValueType;
      final PsiType[] parameters = classType.getParameters();
      final PsiClass iterableClass = ClassUtils.findClass(CommonClassNames.JAVA_LANG_ITERABLE, statement);
      if (iterableClass == null) {
        expectedType = null;
      }
      else {
        expectedType = JavaPsiFacade.getElementFactory(statement.getProject()).createType(iterableClass, parameters);
      }
    }

    @Override
    public void visitIfStatement(@NotNull PsiIfStatement statement) {
      expectedType = PsiType.BOOLEAN;
    }

    @Override
    public void visitDoWhileStatement(@NotNull PsiDoWhileStatement statement) {
      expectedType = PsiType.BOOLEAN;
    }

    @Override
    public void visitSynchronizedStatement(@NotNull PsiSynchronizedStatement statement) {
      expectedType = TypeUtils.getObjectType(statement);
    }

    @Override
    public void visitAssignmentExpression(@NotNull PsiAssignmentExpression assignment) {
      final PsiExpression rExpression = assignment.getRExpression();
      final IElementType tokenType = assignment.getOperationTokenType();
      final PsiExpression lExpression = assignment.getLExpression();
      final PsiType lType = lExpression.getType();
      if (rExpression != null && wrappedExpression.equals(rExpression)) {
        if (lType == null) {
          expectedType = null;
        }
        else if (TypeUtils.isJavaLangString(lType)) {
          if (JavaTokenType.PLUSEQ.equals(tokenType)) {
            // e.g. String += any type
            expectedType = rExpression.getType();
          }
          else {
            expectedType = lType;
          }
        }
        else if (isOperatorAssignmentOperation(tokenType)) {
          if (lType instanceof PsiPrimitiveType) {
            expectedType = lType;
          }
          else {
            expectedType = PsiPrimitiveType.getUnboxedType(lType);
          }
        }
        else {
          expectedType = lType;
        }
      }
      else {
        if (isOperatorAssignmentOperation(tokenType) && !(lType instanceof PsiPrimitiveType)) {
          expectedType = PsiPrimitiveType.getUnboxedType(lType);
        }
        else {
          expectedType = lType;
        }
      }
    }

    @Override
    public void visitConditionalExpression(PsiConditionalExpression conditional) {
      final PsiExpression condition = conditional.getCondition();
      if (condition.equals(wrappedExpression)) {
        expectedType = PsiType.BOOLEAN;
      }
      else {
        expectedType = conditional.getType();
      }
    }

    @Override
    public void visitReturnStatement(@NotNull PsiReturnStatement returnStatement) {
      final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class);
      if (method != null) {
        expectedType = method.getReturnType();
      }
    }

    @Override
    public void visitInstanceOfExpression(PsiInstanceOfExpression expression) {
      expectedType = TypeUtils.getObjectType(expression);
    }

    @Override
    public void visitDeclarationStatement(PsiDeclarationStatement declaration) {
      final PsiElement[] declaredElements = declaration.getDeclaredElements();
      for (PsiElement declaredElement : declaredElements) {
        if (declaredElement instanceof PsiVariable) {
          final PsiVariable variable = (PsiVariable)declaredElement;
          final PsiExpression initializer = variable.getInitializer();
          if (wrappedExpression.equals(initializer)) {
            expectedType = variable.getType();
            return;
          }
        }
      }
    }

    @Override
    public void visitExpressionList(PsiExpressionList expressionList) {
      final JavaResolveResult result = findCalledMethod(expressionList);
      final PsiMethod method = (PsiMethod)result.getElement();
      if (method == null) {
        expectedType = null;
      }
      else {
        final int parameterPosition = getParameterPosition(expressionList, wrappedExpression);
        expectedType = getTypeOfParameter(result, parameterPosition);
      }
    }

    @Override
    public void visitNewExpression(PsiNewExpression expression) {
      final PsiExpression[] arrayDimensions = expression.getArrayDimensions();
      for (PsiExpression arrayDimension : arrayDimensions) {
        if (wrappedExpression.equals(arrayDimension)) {
          expectedType = PsiType.INT;
        }
      }
    }

    @NotNull
    private static JavaResolveResult findCalledMethod(PsiExpressionList expressionList) {
      final PsiElement parent = expressionList.getParent();
      if (parent instanceof PsiCallExpression) {
        final PsiCallExpression call = (PsiCallExpression)parent;
        return call.resolveMethodGenerics();
      }
      else if (parent instanceof PsiAnonymousClass) {
        final PsiElement grandParent = parent.getParent();
        if (grandParent instanceof PsiCallExpression) {
          final PsiCallExpression callExpression = (PsiCallExpression)grandParent;
          return callExpression.resolveMethodGenerics();
        }
      }
      return JavaResolveResult.EMPTY;
    }

    @Override
    public void visitReferenceExpression(@NotNull PsiReferenceExpression referenceExpression) {
      if (calculateTypeForComplexReferences) {
        final Project project = referenceExpression.getProject();
        final JavaResolveResult resolveResult = referenceExpression.advancedResolve(false);
        final PsiElement element = resolveResult.getElement();
        PsiSubstitutor substitutor = resolveResult.getSubstitutor();
        final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
        if (element instanceof PsiField) {
          final PsiField field = (PsiField)element;
          if (!isAccessibleFrom(field, referenceExpression)) {
            return;
          }
          final PsiClass aClass = field.getContainingClass();
          if (aClass == null) {
            return;
          }
          final PsiElementFactory factory = psiFacade.getElementFactory();
          expectedType = factory.createType(aClass, substitutor);
        }
        else if (element instanceof PsiMethod) {
          final PsiElement parent = referenceExpression.getParent();
          final PsiType returnType;
          if (parent instanceof PsiMethodCallExpression) {
            final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)parent;
            final PsiType type = methodCallExpression.getType();
            if (!PsiType.VOID.equals(type)) {
              returnType = findExpectedType(methodCallExpression, true);
            }
            else {
              returnType = null;
            }
          }
          else {
            returnType = null;
          }
          final PsiMethod method = (PsiMethod)element;
          final PsiMethod superMethod = findDeepestVisibleSuperMethod(method, returnType, referenceExpression);
          final PsiClass aClass;
          if (superMethod != null) {
            aClass = superMethod.getContainingClass();
            if (aClass == null) {
              return;
            }
            substitutor = TypeConversionUtil.getSuperClassSubstitutor(aClass, method.getContainingClass(), substitutor);
          }
          else {
            aClass = method.getContainingClass();
            if (aClass == null) {
              return;
            }
          }
          final PsiElementFactory factory = psiFacade.getElementFactory();
          expectedType = factory.createType(aClass, substitutor);
        }
        else {
          expectedType = null;
        }
      }
    }

    @Nullable
    private static PsiMethod findDeepestVisibleSuperMethod(PsiMethod method, PsiType returnType, PsiElement element) {
      if (method.isConstructor()) {
        return null;
      }
      if (method.hasModifierProperty(PsiModifier.STATIC)) {
        return null;
      }
      if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
        return null;
      }
      final PsiClass aClass = method.getContainingClass();
      if (aClass == null) {
        return null;
      }
      final PsiMethod[] superMethods = aClass.findMethodsBySignature(method, true);
      PsiMethod topSuper = null;
      PsiClass topSuperContainingClass = null;
      for (PsiMethod superMethod : superMethods) {
        final PsiClass superClass = superMethod.getContainingClass();
        if (superClass == null) {
          continue;
        }
        if (aClass.equals(superClass)) {
          continue;
        }
        if (!isAccessibleFrom(superMethod, element)) {
          continue;
        }
        if (returnType != null) {
          final PsiType superReturnType = superMethod.getReturnType();
          if (superReturnType == null) {
            continue;
          }
          if (!returnType.isAssignableFrom(superReturnType)) {
            continue;
          }
        }
        if (topSuper != null && superClass.isInheritor(topSuperContainingClass, true)) {
          continue;
        }
        topSuper = superMethod;
        topSuperContainingClass = superClass;
      }
      return topSuper;
    }

    private static boolean isAccessibleFrom(PsiMember member, PsiElement referencingLocation) {
      if (member.hasModifierProperty(PsiModifier.PUBLIC)) {
        return true;
      }
      final PsiClass containingClass = member.getContainingClass();
      if (containingClass == null) {
        return false;
      }
      final PsiClass referencingClass = ClassUtils.getContainingClass(referencingLocation);
      if (referencingClass == null) {
        return false;
      }
      if (referencingClass.equals(containingClass)) {
        return true;
      }
      if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
        return false;
      }
      return ClassUtils.inSamePackage(containingClass, referencingLocation);
    }

    private static boolean isArithmeticOperation(@NotNull IElementType sign) {
      return arithmeticOps.contains(sign);
    }

    private static boolean isBooleanOperation(@NotNull IElementType sign) {
      return booleanOps.contains(sign);
    }

    private static boolean isShiftOperation(@NotNull IElementType sign) {
      return shiftOps.contains(sign);
    }

    private static boolean isOperatorAssignmentOperation(@NotNull IElementType sign) {
      return operatorAssignmentOps.contains(sign);
    }

    private static int getParameterPosition(@NotNull PsiExpressionList expressionList, PsiExpression expression) {
      final PsiExpression[] expressions = expressionList.getExpressions();
      for (int i = 0; i < expressions.length; i++) {
        if (expressions[i].equals(expression)) {
          return i;
        }
      }
      return -1;
    }

    @Nullable
    private static PsiType getTypeOfParameter(@NotNull JavaResolveResult result, int parameterPosition) {
      final PsiMethod method = (PsiMethod)result.getElement();
      if (method == null) {
        return null;
      }
      final PsiSubstitutor substitutor = result.getSubstitutor();
      final PsiParameterList parameterList = method.getParameterList();
      if (parameterPosition < 0) {
        return null;
      }
      final int parametersCount = parameterList.getParametersCount();
      final PsiParameter[] parameters;
      if (parameterPosition >= parametersCount) {
        final int lastParameterPosition = parametersCount - 1;
        if (lastParameterPosition < 0) {
          return null;
        }
        parameters = parameterList.getParameters();
        final PsiParameter lastParameter = parameters[lastParameterPosition];
        if (lastParameter.isVarArgs()) {
          final PsiArrayType arrayType = (PsiArrayType)lastParameter.getType();
          return substitutor.substitute(arrayType.getComponentType());
        }
        return null;
      }
      parameters = parameterList.getParameters();
      final PsiParameter parameter = parameters[parameterPosition];
      final PsiType parameterType = parameter.getType();
      if (parameter.isVarArgs()) {
        final PsiArrayType arrayType = (PsiArrayType)parameterType;
        return substitutor.substitute(arrayType.getComponentType());
      }
      final PsiType type = substitutor.substitute(parameterType);
      final TypeStringCreator typeStringCreator = new TypeStringCreator();
      type.accept(typeStringCreator);
      if (typeStringCreator.isModified()) {
        final PsiManager manager = method.getManager();
        final Project project = manager.getProject();
        final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        try {
          final String typeString = typeStringCreator.getTypeString();
          return factory.createTypeFromText(typeString, method);
        }
        catch (IncorrectOperationException e) {
          throw new AssertionError("incorrect type string generated from " + type + ": " + e.getMessage());
        }
      }
      return type;
    }

    /**
     * Creates a new type string without any wildcards with final
     * extends bounds from the visited type.
     */
    private static class TypeStringCreator extends PsiTypeVisitor<Object> {

      private final StringBuilder typeString = new StringBuilder();
      private boolean modified = false;

      @Override
      public Object visitType(PsiType type) {
        typeString.append(type.getCanonicalText());
        return super.visitType(type);
      }

      @Override
      public Object visitWildcardType(PsiWildcardType wildcardType) {
        if (wildcardType.isExtends()) {
          final PsiType extendsBound = wildcardType.getExtendsBound();
          if (extendsBound instanceof PsiClassType) {
            final PsiClassType classType = (PsiClassType)extendsBound;
            final PsiClass aClass = classType.resolve();
            if (aClass != null && aClass.hasModifierProperty(PsiModifier.FINAL)) {
              modified = true;
              return super.visitClassType(classType);
            }
          }
        }
        return super.visitWildcardType(wildcardType);
      }

      @Override
      public Object visitClassType(PsiClassType classType) {
        final PsiClassType rawType = classType.rawType();
        typeString.append(rawType.getCanonicalText());
        final PsiType[] parameterTypes = classType.getParameters();
        if (parameterTypes.length > 0) {
          typeString.append('<');
          final PsiType parameterType1 = parameterTypes[0];
          // IDEADEV-25549 says this can be null
          if (parameterType1 != null) {
            parameterType1.accept(this);
          }
          for (int i = 1; i < parameterTypes.length; i++) {
            typeString.append(',');
            final PsiType parameterType = parameterTypes[i];
            // IDEADEV-25549 again
            if (parameterType != null) {
              parameterType.accept(this);
            }
          }
          typeString.append('>');
        }
        return null;
      }

      public String getTypeString() {
        return typeString.toString();
      }

      public boolean isModified() {
        return modified;
      }
    }
  }
}