Java 类com.intellij.psi.PsiLocalVariable 实例源码

项目:manifold-ij    文件:VarHandler.java   
@Nullable
public PsiType inferType( PsiTypeElement typeElement )
{
  PsiType psiType = null;

  final PsiElement parent = typeElement.getParent();
  if( (parent instanceof PsiLocalVariable && isVar( (PsiLocalVariable)parent )) ||
      (parent instanceof PsiParameter && isVarForEach( (PsiParameter)parent )) )
  {

    if( parent instanceof PsiLocalVariable )
    {
      psiType = processLocalVariableInitializer( ((PsiLocalVariable)parent).getInitializer() );
    }
    else
    {
      psiType = processForeach( ((PsiParameter)parent).getDeclarationScope() );
    }

    if( null == psiType )
    {
      psiType = PsiType.getJavaLangObject( typeElement.getManager(), GlobalSearchScope.allScope( typeElement.getProject() ) );
    }
  }
  return psiType;
}
项目:Android_Lint_SRP_Practice_Example    文件:ElementUtil.java   
private static void seekChildren(PsiElement element, PsiIdentifier target, Find find) {
    for (PsiElement child : element.getChildren()) {
        if (child instanceof PsiLocalVariable) {
            PsiLocalVariable localVariable = (PsiLocalVariable) child;
            if (isSameName(target, localVariable.getNameIdentifier())) {
                find.findLocalVariable = localVariable;
                return;
            }
        }
        if (child instanceof PsiParameter) {
            PsiParameter parameter = (PsiParameter) child;
            if (isSameName(target, parameter.getNameIdentifier())) {
                find.findParameter = parameter;
                return;
            }
        }
        seekChildren(child, target, find);
        if (!find.isEmpty()) return;
    }
}
项目:appetizer-intellij    文件:ReplaceInspection.java   
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) {
  return new JavaElementVisitor() {
    @Override
    public void visitReferenceExpression(PsiReferenceExpression psiReferenceExpression) {
    }

    @Override
    public void visitLocalVariable(PsiLocalVariable variable) {
      super.visitLocalVariable(variable);
      if (VariantPool.isJump()) {
        if (isFindYYY(variable.toString())) {
          holder.registerProblem(variable, DESCRIPTION_TEMPLATE, myQuickFix);
          log.info("isFindYYY" + variable );
        }
      }
    }
  };
}
项目:intellij-ce-playground    文件:IntroduceParameterSettingsUI.java   
public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable,
                                    PsiExpression onExpression,
                                    PsiMethod methodToReplaceIn,
                                    TIntArrayList parametersToRemove) {
  myHasInitializer = onLocalVariable != null && onLocalVariable.getInitializer() != null;
  myIsInvokedOnDeclaration = onExpression == null;
  final PsiParameter[] parameters = methodToReplaceIn.getParameterList().getParameters();
  myParametersToRemove = new PsiParameter[parameters.length];
  myParametersToRemoveChecked = new boolean[parameters.length];
  parametersToRemove.forEach(new TIntProcedure() {
    public boolean execute(final int paramNum) {
      myParametersToRemove[paramNum] = parameters[paramNum];
      return true;
    }
  });
  myIsLocalVariable = onLocalVariable != null;
}
项目:idea-android-studio-plugin    文件:AbstractInflateViewAction.java   
@Override
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if(file == null) {
        return;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return;
    }

    PsiLocalVariable psiLocalVariable = PsiTreeUtil.getParentOfType(psiElement, PsiLocalVariable.class);
    InflateViewAnnotator.InflateContainer inflateContainer = InflateViewAnnotator.matchInflate(psiLocalVariable);
    if(inflateContainer == null) {
        return;
    }

    generate(inflateContainer, editor, file);
}
项目:tools-idea    文件:CodeFragmentFactoryContextWrapper.java   
private PsiElement wrapContext(Project project, final PsiElement originalContext) {
  if (project.isDefault()) return originalContext;
  PsiElement context = originalContext;
  final DebugProcessImpl process = DebuggerManagerEx.getInstanceEx(project).getContext().getDebugProcess();
  if (process != null) {
    final Map<ObjectReference, ValueMarkup> markupMap = ValueDescriptorImpl.getMarkupMap(process);
    if (markupMap != null && markupMap.size() > 0) {
      final Pair<String, Map<String, ObjectReference>> markupVariables = createMarkupVariablesText(markupMap);
      int offset = markupVariables.getFirst().length() - 1;
      final TextWithImportsImpl textWithImports = new TextWithImportsImpl(CodeFragmentKind.CODE_BLOCK, markupVariables.getFirst(), "", myDelegate.getFileType());
      final JavaCodeFragment codeFragment = myDelegate.createCodeFragment(textWithImports, context, project);
      codeFragment.accept(new JavaRecursiveElementVisitor() {
        public void visitLocalVariable(PsiLocalVariable variable) {
          final String name = variable.getName();
          variable.putUserData(LABEL_VARIABLE_VALUE_KEY, markupVariables.getSecond().get(name));
        }
      });
      final PsiElement newContext = codeFragment.findElementAt(offset);
      if (newContext != null) {
        context = newContext;
      }
    }
  }
  return context;
}
项目:tools-idea    文件:IntroduceParameterSettingsUI.java   
public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable,
                                    PsiExpression onExpression,
                                    PsiMethod methodToReplaceIn,
                                    TIntArrayList parametersToRemove) {
  myHasInitializer = onLocalVariable != null && onLocalVariable.getInitializer() != null;
  myIsInvokedOnDeclaration = onExpression == null;
  final PsiParameter[] parameters = methodToReplaceIn.getParameterList().getParameters();
  myParametersToRemove = new PsiParameter[parameters.length];
  myParametersToRemoveChecked = new boolean[parameters.length];
  parametersToRemove.forEach(new TIntProcedure() {
    public boolean execute(final int paramNum) {
      myParametersToRemove[paramNum] = parameters[paramNum];
      return true;
    }
  });
  myIsLocalVariable = onLocalVariable != null;
}
项目:lombok-intellij-plugin    文件:ValProcessor.java   
public void verifyVariable(@NotNull final PsiLocalVariable psiLocalVariable, @NotNull final ProblemsHolder holder) {
  boolean isVal = isSameName(psiLocalVariable.getTypeElement().getText());
  boolean isVar = isVar(psiLocalVariable.getTypeElement().getText());
  final String ann = isVal ? "val" : "var";
  if (isVal || isVar) {
    final PsiExpression initializer = psiLocalVariable.getInitializer();
    if (initializer == null) {
      holder.registerProblem(psiLocalVariable, "'" + ann + "' on a local variable requires an initializer expression", ProblemHighlightType.ERROR);
    } else if (initializer instanceof PsiArrayInitializerExpression) {
      holder.registerProblem(psiLocalVariable, "'" + ann + "' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... })", ProblemHighlightType.ERROR);
    } else if (initializer instanceof PsiLambdaExpression) {
      holder.registerProblem(psiLocalVariable, "'" + ann + "' is not allowed with lambda expressions.", ProblemHighlightType.ERROR);
    } else if (isVal) {
      final PsiElement typeParentParent = psiLocalVariable.getParent();
      if (typeParentParent instanceof PsiDeclarationStatement && typeParentParent.getParent() instanceof PsiForStatement) {
        holder.registerProblem(psiLocalVariable, "'" + ann + "' is not allowed in old-style for loops", ProblemHighlightType.ERROR);
      }
    }
  }
}
项目:lombok-intellij-plugin    文件:ValProcessor.java   
@Nullable
public PsiType inferType(PsiTypeElement typeElement) {
  PsiType psiType = null;

  final PsiElement parent = typeElement.getParent();
  if ((parent instanceof PsiLocalVariable && isValOrVar((PsiLocalVariable) parent)) ||
    (parent instanceof PsiParameter && isValOrVarForEach((PsiParameter) parent))) {

    if (parent instanceof PsiLocalVariable) {
      psiType = processLocalVariableInitializer(((PsiLocalVariable) parent).getInitializer());
    } else {
      psiType = processParameterDeclaration(((PsiParameter) parent).getDeclarationScope());
    }

    if (null == psiType) {
      psiType = PsiType.getJavaLangObject(typeElement.getManager(), GlobalSearchScope.allScope(typeElement.getProject()));
    }
  }
  return psiType;
}
项目:lombok-intellij-plugin    文件:CleanupProcessor.java   
@NotNull
@Override
public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) {
  // TODO warning: "You're assigning an auto-cleanup variable to something else. This is a bad idea."
  final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(2);

  PsiLocalVariable psiVariable = PsiTreeUtil.getParentOfType(psiAnnotation, PsiLocalVariable.class);
  if (null != psiVariable) {
    final String cleanupName = PsiAnnotationUtil.getStringAnnotationValue(psiAnnotation, "value");

    if (StringUtil.isEmptyOrSpaces(cleanupName)) {
      problemNewBuilder.addError("'@Cleanup': value cannot be the empty string");
    } else {
      validateCleanUpMethodExists(psiVariable, cleanupName, problemNewBuilder);
    }

    validateInitializerExist(problemNewBuilder, psiVariable);

  } else {
    problemNewBuilder.addError("'@Cleanup' is legal only on local variable declarations");
  }

  return problemNewBuilder.getProblems();
}
项目:lombok-intellij-plugin    文件:CleanupProcessor.java   
private void validateCleanUpMethodExists(@NotNull PsiLocalVariable psiVariable, @NotNull String cleanupName, @NotNull ProblemNewBuilder problemNewBuilder) {
  final PsiType psiType = psiVariable.getType();
  if (psiType instanceof PsiClassType) {
    final PsiClassType psiClassType = (PsiClassType) psiType;
    final PsiClass psiClassOfField = psiClassType.resolve();
    final PsiMethod[] methods;

    if (psiClassOfField != null) {
      methods = psiClassOfField.findMethodsByName(cleanupName, true);
      boolean hasCleanupMethod = false;
      for (PsiMethod method : methods) {
        if (0 == method.getParameterList().getParametersCount()) {
          hasCleanupMethod = true;
        }
      }

      if (!hasCleanupMethod) {
        problemNewBuilder.addError("'@Cleanup': method '%s()' not found on target class", cleanupName);
      }
    }
  } else {
    problemNewBuilder.addError("'@Cleanup': is legal only on a local variable declaration inside a block");
  }
}
项目:lombok-intellij-plugin    文件:ValModifierTest.java   
public void testValModifiersEditing() {
  PsiFile file = myFixture.configureByText("a.java", "import lombok.val;\nclass Foo { {val o = <caret>;} }");
  PsiLocalVariable var = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), PsiLocalVariable.class);
  assertNotNull(var);

  PsiType type1 = var.getType();
  assertNotNull(type1);
  assertEquals("lombok.val", type1.getCanonicalText(false));

  myFixture.type('1');
  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  assertTrue(var.isValid());

  assertNotNull(var.getModifierList());
  assertTrue("val should make variable final", var.getModifierList().hasModifierProperty(PsiModifier.FINAL));
}
项目:consulo-java    文件:ExternalAnnotationsLineMarkerProvider.java   
@Nullable
static PsiModifierListOwner getAnnotationOwner(@Nullable PsiElement element)
{
    if(element == null)
    {
        return null;
    }

    PsiElement owner = element.getParent();
    if(!(owner instanceof PsiModifierListOwner) || !(owner instanceof PsiNameIdentifierOwner))
    {
        return null;
    }
    if(owner instanceof PsiParameter || owner instanceof PsiLocalVariable)
    {
        return null;
    }

    // support non-Java languages where getNameIdentifier may return non-physical psi with the same range
    PsiElement nameIdentifier = ((PsiNameIdentifierOwner) owner).getNameIdentifier();
    if(nameIdentifier == null || !nameIdentifier.getTextRange().equals(element.getTextRange()))
    {
        return null;
    }
    return (PsiModifierListOwner) owner;
}
项目:consulo-java    文件:IntroduceParameterSettingsUI.java   
public IntroduceParameterSettingsUI(PsiLocalVariable onLocalVariable,
                                    PsiExpression onExpression,
                                    PsiMethod methodToReplaceIn,
                                    TIntArrayList parametersToRemove) {
  myHasInitializer = onLocalVariable != null && onLocalVariable.getInitializer() != null;
  myIsInvokedOnDeclaration = onExpression == null;
  final PsiParameter[] parameters = methodToReplaceIn.getParameterList().getParameters();
  myParametersToRemove = new PsiParameter[parameters.length];
  myParametersToRemoveChecked = new boolean[parameters.length];
  parametersToRemove.forEach(new TIntProcedure() {
    public boolean execute(final int paramNum) {
      myParametersToRemove[paramNum] = parameters[paramNum];
      return true;
    }
  });
  myIsLocalVariable = onLocalVariable != null;
}
项目:consulo-java    文件:IntroduceParameterTest.java   
private static void performForLocal(boolean searchForSuper, boolean removeLocalVariable, boolean replaceAllOccurrences, boolean declareFinal, final boolean removeUnusedParameters)
{
    final int offset = myEditor.getCaretModel().getOffset();
    final PsiElement element = myFile.findElementAt(offset).getParent();
    assertTrue(element instanceof PsiLocalVariable);
    PsiMethod method = Util.getContainingMethod(element);
    final PsiMethod methodToSearchFor;
    if(searchForSuper)
    {
        final PsiMethod deepestSuperMethod = method.findDeepestSuperMethod();
        methodToSearchFor = deepestSuperMethod != null ? deepestSuperMethod : method;
    }
    else
    {
        methodToSearchFor = method;
    }
    assertNotNull(method);
    assertNotNull(methodToSearchFor);
    final PsiLocalVariable localVariable = (PsiLocalVariable) element;
    final PsiExpression parameterInitializer = localVariable.getInitializer();
    TIntArrayList parametersToRemove = removeUnusedParameters ? Util.findParametersToRemove(method, parameterInitializer, null) : new TIntArrayList();

    new IntroduceParameterProcessor(getProject(), method, methodToSearchFor, parameterInitializer, null, localVariable, removeLocalVariable, localVariable.getName(), replaceAllOccurrences,
            IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE, declareFinal, false, null, parametersToRemove).run();
}
项目:CustomLintRules    文件:DynamicNewViewDetector.java   
@Override
public void visitNewExpression(PsiNewExpression expression) {
    super.visitNewExpression(expression);

    PsiMethod constructor = expression.resolveConstructor();
    if (constructor == null) return;

    JavaEvaluator evaluator = mContext.getEvaluator();
    PsiClass cls = constructor.getContainingClass();
    boolean isView = evaluator.extendsClass(cls, CLASS_VIEW, true);
    if (!isView) return;

    Location location = this.mContext.getLocation(expression);

    PsiElement psiElement = expression.getParent();

    //创建的变量没有赋值给本地变量,无法指定注解
    if (!(psiElement instanceof PsiLocalVariable)) {
        this.mContext.report(DynamicNewViewDetector.ISSUE, expression, location, "检测到动态创建view操作,new 操作的结果需要赋值给本地变量");
        return;
    }

    PsiLocalVariable localVariable = (PsiLocalVariable) psiElement;
    PsiModifierList modifierList = localVariable.getModifierList();
    if (modifierList == null) {
        this.mContext.report(DynamicNewViewDetector.ISSUE, expression, location, "检测到动态创建view操作,确认是否为view指定了唯一标识");
        return;
    }

    PsiAnnotation[] annotations = modifierList.getAnnotations();
    for (PsiAnnotation annotation : annotations) {
        String fullName = annotation.getQualifiedName();
        if (IDENTIFIER_ANNOTATION.equals(fullName)) {
            return;
        }
    }

    this.mContext.report(DynamicNewViewDetector.ISSUE, expression, location, "检测到动态创建view操作,确认是否为view指定了唯一标识");
}
项目:Android_Lint_SRP_Practice_Example    文件:ElementUtil.java   
/**
 * ローカル変数取得 (宣言文で定義された変数)
 * @param declaration ルートノード
 * @return ローカル変数 (空要素の場合もあります)
 */
public static @Nullable PsiLocalVariable getVariable(PsiDeclarationStatement declaration) {
    PsiElement[] elements = declaration.getDeclaredElements();
    for (PsiElement element : elements) {
        if (element instanceof PsiLocalVariable) {
            PsiLocalVariable valiable = (PsiLocalVariable) element;
            return valiable;
        }
    }
    return null;
}
项目:Android_Lint_SRP_Practice_Example    文件:ElementUtil.java   
private static void extractLocalVariable(@NonNull PsiElement element, List<PsiLocalVariable> variables) {
    for (PsiElement child : element.getChildren()) {
        if (child instanceof PsiLocalVariable) {
            variables.add((PsiLocalVariable) child);
            continue;
        }
        extractLocalVariable(child, variables);
    }
}
项目:Android_Lint_SRP_Practice_Example    文件:ElementUtil.java   
private static void seekElderBrother(PsiElement element, PsiIdentifier target, Find find){
    PsiElement parent = LintUtils.skipParentheses(element.getParent());
    if (parent == null) return;

    int myIndex = getMyBrotherIndex(element);
    PsiElement[] brothers = parent.getChildren();
    for (int index = myIndex -1; index >= 0; index--) {
        PsiElement brother = brothers[index];
        // 兄弟のブロック内のノードは、アクセス不能なので除外
        if (brother instanceof PsiBlockStatement) continue;
        if (brother instanceof PsiLocalVariable) {
            PsiLocalVariable localVariable = (PsiLocalVariable) brother;
            if (isSameName(target, localVariable.getNameIdentifier())) {
                find.findLocalVariable = localVariable;
                return;
            }
        }
        if (brother instanceof PsiParameter) {
            PsiParameter parameter = (PsiParameter) brother;
            if (isSameName(target, parameter.getNameIdentifier())) {
                find.findParameter = parameter;
                return;
            }
        }
        seekChildren(brother, target, find);
        if (!find.isEmpty()) return;
    }
}
项目:Android_Lint_SRP_Practice_Example    文件:ElementUtil.java   
public static void debugVariable(PsiLocalVariable variable) {
    if (variable != null) {
        PsiIdentifier id = variable.getNameIdentifier();
        PsiTypeElement type = variable.getTypeElement();
        PsiExpression init = variable.getInitializer();
        System.out.println("variable -> " + variable.getText()
                + ", id=" + (id != null ? id.getText() : "null")
                + ", type=" + (type != null ? type.getText() : "null")
                + ", init=" + (init != null ? init.getText() : "null"));
    }
}
项目:intellij-mockito-postfix-plugin    文件:MockTemplate.java   
@Nullable
@Override
public String getTemplateString(PsiElement psiElement) {
    String clazz;
    if (psiElement instanceof PsiReference) {
        // foo.mock
        PsiReference psiReference = (PsiReference) psiElement;
        PsiLocalVariable psiLocalVariable = (PsiLocalVariable) psiReference.resolve();
        if (psiLocalVariable == null) {
            return psiElement.getText();
        }
        PsiType psiType = psiLocalVariable.getType();
        clazz = psiType.getPresentableText() + ".class";
    } else if (psiElement instanceof PsiClassObjectAccessExpression) {
        // String.class.mock
        PsiClassObjectAccessExpression psiClassObjectAccessExpression = (PsiClassObjectAccessExpression) psiElement;
        String classText = psiClassObjectAccessExpression.getText();
        if (classText == null) {
            return psiElement.getText();
        }
        clazz = classText;
    } else {
        return psiElement.getText();
    }

    return "org.mockito.Mockito.mock(" + clazz + ")$END$";
}
项目:thinr    文件:ThinrDetector.java   
private void markLeakSuspects(PsiElement element, PsiElement lambdaBody, @NonNull final JavaContext context) {
    if (element instanceof PsiReferenceExpression) {
        PsiReferenceExpression ref = (PsiReferenceExpression) element;

        if (ref.getQualifierExpression() == null) {

            PsiElement res = ref.resolve();
            if (!(res instanceof PsiParameter)) {
                if (!(res instanceof PsiClass)) {

                    boolean error = false;
                    if (res instanceof PsiLocalVariable) {
                        PsiLocalVariable lVar = (PsiLocalVariable) res;
                        if (!isParent(lambdaBody, lVar.getParent())) {
                            error = true;
                        }
                    }

                    if (res instanceof PsiField) {
                        PsiField field = (PsiField) res;
                        final PsiModifierList modifierList = field.getModifierList();
                        if (modifierList == null) {
                            error = true;
                        } else if (!modifierList.hasExplicitModifier(PsiModifier.STATIC)) {
                            error = true;
                        }
                    }

                    if (error) {
                        context.report(ISSUE, element, context.getNameLocation(element), "Possible leak");
                    }
                }
            }
        }
    }

    for (PsiElement psiElement : element.getChildren()) {
        markLeakSuspects(psiElement, lambdaBody, context);
    }
}
项目:intellij-ce-playground    文件:CodeFragmentFactoryContextWrapper.java   
private PsiElement wrapContext(Project project, final PsiElement originalContext) {
  if (project.isDefault()) return originalContext;
  //TODO [egor] : does not work for anything other than java anyway, see IDEA-132677
  if (!(myDelegate instanceof DefaultCodeFragmentFactory)) {
    return originalContext;
  }
  PsiElement context = originalContext;
  XDebugSession session = XDebuggerManager.getInstance(project).getCurrentSession();
  if (session != null) {
    XValueMarkers<?, ?> markers = ((XDebugSessionImpl)session).getValueMarkers();
    Map<?, ValueMarkup> markupMap = markers != null ? markers.getAllMarkers() : null;
    //final Map<ObjectReference, ValueMarkup> markupMap = ValueDescriptorImpl.getMarkupMap(process);
    if (markupMap != null && markupMap.size() > 0) {
      final Pair<String, Map<String, ObjectReference>> markupVariables = createMarkupVariablesText(markupMap);
      int offset = markupVariables.getFirst().length() - 1;
      final TextWithImportsImpl textWithImports = new TextWithImportsImpl(CodeFragmentKind.CODE_BLOCK, markupVariables.getFirst(), "", myDelegate.getFileType());
      final JavaCodeFragment codeFragment = myDelegate.createCodeFragment(textWithImports, context, project);
      codeFragment.accept(new JavaRecursiveElementVisitor() {
        public void visitLocalVariable(PsiLocalVariable variable) {
          final String name = variable.getName();
          variable.putUserData(LABEL_VARIABLE_VALUE_KEY, markupVariables.getSecond().get(name));
        }
      });
      final PsiElement newContext = codeFragment.findElementAt(offset);
      if (newContext != null) {
        context = newContext;
      }
    }
  }
  return context;
}
项目:intellij-ce-playground    文件:AbstractJavaInplaceIntroduceTest.java   
protected AbstractInplaceIntroducer invokeRefactoring(MyIntroduceHandler introduceHandler) {
  final PsiExpression expression = getExpressionFromEditor();
  if (expression != null) {
    introduceHandler.invokeImpl(LightPlatformTestCase.getProject(), expression, getEditor());
  } else {
    final PsiLocalVariable localVariable = getLocalVariableFromEditor();
    introduceHandler.invokeImpl(LightPlatformTestCase.getProject(), localVariable, getEditor());
  }
  return introduceHandler.getInplaceIntroducer();
}
项目:intellij-ce-playground    文件:InlineLocalTest.java   
public static void performInline(Project project, Editor editor) {
  PsiElement element = TargetElementUtil
    .findTargetElement(editor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED);
  assertTrue(element instanceof PsiLocalVariable);

  InlineLocalHandler.invoke(project, editor, (PsiLocalVariable)element, null);
}
项目:intellij-ce-playground    文件:InlineLocalTest.java   
public static void performDefInline(Project project, Editor editor) {
  PsiReference reference = TargetElementUtil.findReference(editor);
  assertTrue(reference instanceof PsiReferenceExpression);
  final PsiElement local = reference.resolve();
  assertTrue(local instanceof PsiLocalVariable);

  InlineLocalHandler.invoke(project, editor, (PsiLocalVariable)local, (PsiReferenceExpression)reference);
}
项目:intellij-ce-playground    文件:LocalVariableOfConcreteClassInspection.java   
@Override
public void visitLocalVariable(
  @NotNull PsiLocalVariable variable) {
  super.visitLocalVariable(variable);
  final PsiTypeElement typeElement = variable.getTypeElement();
  if (!ConcreteClassUtil.typeIsConcreteClass(typeElement,
                                             ignoreAbstractClasses)) {
    return;
  }
  registerError(typeElement, variable);
}
项目:idea-android-studio-plugin    文件:AbstractInflateViewAction.java   
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);

    if(!PlatformPatterns.psiElement().inside(PsiLocalVariable.class).accepts(psiElement)) {
        return false;
    }

    PsiLocalVariable psiLocalVariable = PsiTreeUtil.getParentOfType(psiElement, PsiLocalVariable.class);
    return InflateViewAnnotator.matchInflate(psiLocalVariable) != null;
}
项目:tools-idea    文件:AbstractJavaInplaceIntroduceTest.java   
@Override
protected AbstractInplaceIntroducer invokeRefactoring() {
  final MyIntroduceHandler introduceHandler = createIntroduceHandler();
  final PsiExpression expression = getExpressionFromEditor();
  if (expression != null) {
    introduceHandler.invokeImpl(LightPlatformTestCase.getProject(), expression, getEditor());
  } else {
    final PsiLocalVariable localVariable = getLocalVariableFromEditor();
    introduceHandler.invokeImpl(LightPlatformTestCase.getProject(), localVariable, getEditor());
  }
  return introduceHandler.getInplaceIntroducer();
}
项目:tools-idea    文件:InlineLocalTest.java   
public static void performInline(Project project, Editor editor) {
  PsiElement element = TargetElementUtilBase
    .findTargetElement(editor, TargetElementUtilBase.ELEMENT_NAME_ACCEPTED | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED);
  assertTrue(element instanceof PsiLocalVariable);

  InlineLocalHandler.invoke(project, editor, (PsiLocalVariable)element, null);
}
项目:tools-idea    文件:InlineLocalTest.java   
public static void performDefInline(Project project, Editor editor) {
  PsiReference reference = TargetElementUtilBase.findReference(editor);
  assertTrue(reference instanceof PsiReferenceExpression);
  final PsiElement local = reference.resolve();
  assertTrue(local instanceof PsiLocalVariable);

  InlineLocalHandler.invoke(project, editor, (PsiLocalVariable)local, (PsiReferenceExpression)reference);
}
项目:tools-idea    文件:IntroduceParameterTest.java   
private static void performForLocal(boolean searchForSuper, boolean removeLocalVariable, boolean replaceAllOccurrences, boolean declareFinal,
                                    final boolean removeUnusedParameters) {
  final int offset = myEditor.getCaretModel().getOffset();
  final PsiElement element = myFile.findElementAt(offset).getParent();
  assertTrue(element instanceof PsiLocalVariable);
  PsiMethod method = Util.getContainingMethod(element);
  final PsiMethod methodToSearchFor;
  if (searchForSuper) {
    final PsiMethod deepestSuperMethod = method.findDeepestSuperMethod();
    methodToSearchFor = deepestSuperMethod != null ? deepestSuperMethod : method;
  }
  else {
    methodToSearchFor = method;
  }
  assertNotNull(method);
  assertNotNull(methodToSearchFor);
  final PsiLocalVariable localVariable = (PsiLocalVariable)element;
  final PsiExpression parameterInitializer = localVariable.getInitializer();
  TIntArrayList parametersToRemove = removeUnusedParameters ? Util.findParametersToRemove(method, parameterInitializer, null) : new TIntArrayList();

  new IntroduceParameterProcessor(
    getProject(), method, methodToSearchFor,
    parameterInitializer, null, localVariable, removeLocalVariable,
    localVariable.getName(), replaceAllOccurrences,
    IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE,
    declareFinal, false, null, parametersToRemove).run();
}
项目:tools-idea    文件:LocalVariableOfConcreteClassInspection.java   
@Override
public void visitLocalVariable(
  @NotNull PsiLocalVariable variable) {
  super.visitLocalVariable(variable);
  final PsiTypeElement typeElement = variable.getTypeElement();
  if (!ConcreteClassUtil.typeIsConcreteClass(typeElement,
                                             ignoreAbstractClasses)) {
    return;
  }
  registerError(typeElement, variable);
}
项目:lombok-intellij-plugin    文件:ValModifierTest.java   
public void testValModifiers() {
  PsiFile file = myFixture.configureByFile(getTestName(false) + ".java");
  PsiLocalVariable var = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), PsiLocalVariable.class);

  assertNotNull(var);
  assertNotNull(var.getModifierList());
  assertTrue("val should make variable final", var.getModifierList().hasModifierProperty(PsiModifier.FINAL));
}
项目:lombok-intellij-plugin    文件:ValTest.java   
private void verifyLocalVariableType(final String expectedType) {
  final PsiElement elementAtCaret = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
  assertTrue(elementAtCaret instanceof PsiIdentifier);
  final PsiElement localVariable = elementAtCaret.getParent();
  assertTrue(localVariable.toString(), localVariable instanceof PsiLocalVariable);
  final PsiType type = ((PsiLocalVariable) localVariable).getType();
  assertNotNull(localVariable.toString(), type);
  assertTrue(type.getCanonicalText(), type.equalsToText(expectedType));
}
项目:consulo-java    文件:LocalsControlFlowPolicy.java   
@Override
public PsiVariable getUsedVariable(PsiReferenceExpression refExpr) {
  if (refExpr.isQualified()) return null;

  PsiElement refElement = refExpr.resolve();
  return refElement instanceof PsiLocalVariable || refElement instanceof PsiParameter ? checkCodeFragment(refElement) : null;
}
项目:consulo-java    文件:CountingLoop.java   
private CountingLoop(@NotNull PsiLoopStatement loop, @NotNull PsiLocalVariable counter, @NotNull PsiExpression initializer, @NotNull PsiExpression bound, boolean including)
{
    myInitializer = initializer;
    myCounter = counter;
    myLoop = loop;
    myBound = bound;
    myIncluding = including;
}
项目:consulo-java    文件:IntroduceHandlerBase.java   
public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
  LOG.assertTrue(elements.length >= 1 && elements[0] instanceof PsiExpression, "incorrect invoke() parameters");
  final PsiElement tempExpr = elements[0];
  final Editor editor;
  if (dataContext != null) {
    final Editor editorFromDC = dataContext.getData(PlatformDataKeys.EDITOR);
    final PsiFile cachedPsiFile = editorFromDC != null ? PsiDocumentManager.getInstance(project).getCachedPsiFile(editorFromDC.getDocument()) : null;
    if (cachedPsiFile != null && PsiTreeUtil.isAncestor(cachedPsiFile, tempExpr, false)) {
      editor = editorFromDC;
    }
    else {
      editor = null;
    }
  }
  else {
    editor = null;
  }
  if (tempExpr instanceof PsiExpression) {
    invokeImpl(project, (PsiExpression)tempExpr, editor);
  }
  else if(tempExpr instanceof PsiLocalVariable) {
    invokeImpl(project, (PsiLocalVariable)tempExpr, editor);
  }
  else {
    LOG.error("elements[0] should be PsiExpression or PsiLocalVariable");
  }
}
项目:consulo-java    文件:IntroduceParameterDialog.java   
IntroduceParameterDialog(@NotNull Project project,
                         @NotNull List<UsageInfo> classMembersList,
                         PsiExpression[] occurences,
                         PsiLocalVariable onLocalVariable,
                         PsiExpression onExpression,
                         @NotNull NameSuggestionsGenerator generator,
                         @NotNull TypeSelectorManager typeSelectorManager,
                         @NotNull PsiMethod methodToSearchFor,
                         @NotNull PsiMethod methodToReplaceIn,
                         @NotNull TIntArrayList parametersToRemove,
                         final boolean mustBeFinal) {
  super(project, true);
  myPanel = new IntroduceParameterSettingsPanel(onLocalVariable, onExpression, methodToReplaceIn, parametersToRemove);
  myProject = project;
  myClassMembersList = classMembersList;
  myOccurenceNumber = occurences.length;
  for (PsiExpression occurence : occurences) {
    if (PsiUtil.isAccessedForWriting(occurence)) {
      myHasWriteAccess = true;
      break;
    }
  }
  myExpression = onExpression;
  myLocalVar = onLocalVariable;
  myMethodToReplaceIn = methodToReplaceIn;
  myMustBeFinal = mustBeFinal;
  myMethodToSearchFor = methodToSearchFor;
  myNameSuggestionsGenerator = generator;
  myTypeSelectorManager = typeSelectorManager;
  setTitle(REFACTORING_NAME);
  init();
}
项目:consulo-java    文件:IntroduceFieldDialog.java   
public IntroduceFieldDialog(Project project,
                            PsiClass parentClass,
                            PsiExpression initializerExpression,
                            PsiLocalVariable localVariable,
                            boolean isCurrentMethodConstructor, boolean isInvokedOnDeclaration, boolean willBeDeclaredStatic,
                            PsiExpression[] occurrences, boolean allowInitInMethod, boolean allowInitInMethodIfAll,
                            TypeSelectorManager typeSelectorManager, String enteredName) {
  super(project, true);
  myProject = project;
  myParentClass = parentClass;
  myInitializerExpression = initializerExpression;
  myEnteredName = enteredName;
  myCentralPanel =
    new IntroduceFieldDialogPanel(parentClass, initializerExpression, localVariable, isCurrentMethodConstructor, isInvokedOnDeclaration,
                                   willBeDeclaredStatic, occurrences, allowInitInMethod, allowInitInMethodIfAll,
                                   typeSelectorManager);
  myLocalVariable = localVariable;
  myIsInvokedOnDeclaration = isInvokedOnDeclaration;
  myWillBeDeclaredStatic = willBeDeclaredStatic;

  myTypeSelectorManager = typeSelectorManager;

  setTitle(REFACTORING_NAME);
  init();

  myCentralPanel.initializeControls(initializerExpression, ourLastInitializerPlace);
  updateButtons();
}