private Optional<ConfigInfo> extractConfigInfo(PropertiesFile propertiesFile, CoffigResolver.Match match) { Optional<String> description = Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath())).map(IProperty::getValue); if (description.isPresent()) { // Base info ConfigInfo configInfo = new ConfigInfo(match.getFullPath(), description.get()); // Extended info Optional.ofNullable(propertiesFile.findPropertyByKey(match.getUnmatchedPath() + ".long")).map(IProperty::getValue).ifPresent(configInfo::setLongDescription); // Field info CoffigResolver.Match resolvedMatch = match.fullyResolve(); if (resolvedMatch.isFullyResolved()) { Optional<PsiField> psiField = resolvedMatch.resolveField(resolvedMatch.getUnmatchedPath()); psiField.map(PsiVariable::getType).map(PsiType::getPresentableText).ifPresent(configInfo::setType); } return Optional.of(configInfo); } return Optional.empty(); }
@Override public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) { if (params.length == 0) return null; final Project project = context.getProject(); Result result = params[0].calculateQuickResult(context); if (result instanceof PsiElementResult) { final PsiElement element = ((PsiElementResult)result).getElement(); if (element instanceof PsiVariable) { return new PsiTypeResult(((PsiVariable)element).getType(), project); } } else if (result instanceof TextResult) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument()); PsiElement place = file.findElementAt(context.getStartOffset()); final PsiVariable[] vars = MacroUtil.getVariablesVisibleAt(place, ""); final String name = result.toString(); for (final PsiVariable var : vars) { if (name.equals(var.getName())) return new PsiTypeResult(var.getType(), project); } } return null; }
public ContextRelevantStaticMethod(final PsiMethod psiMethod, @Nullable final TIntObjectHashMap<PsiVariable> parameters) { this.psiMethod = psiMethod; if (parameters == null) { this.parameters = null; } else { this.parameters = new TIntObjectHashMap<SubLookupElement>(parameters.size()); parameters.forEachEntry(new TIntObjectProcedure<PsiVariable>() { @SuppressWarnings("ConstantConditions") @Override public boolean execute(final int pos, final PsiVariable var) { ContextRelevantStaticMethod.this.parameters.put(pos, new VariableSubLookupElement(var)); return true; } }); } }
@Override protected void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiNameIdentifierOwner owner = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiVariable.class, PsiMethod.class); if (owner == null) { return; } final RefactoringActionHandler handler = JavaRefactoringActionHandlerFactory.getInstance().createInvertBooleanHandler(); final Runnable runnable = new Runnable() { @Override public void run() { handler.invoke(project, new PsiElement[]{owner}, null); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { runnable.run(); } else { ApplicationManager.getApplication().invokeLater(runnable, project.getDisposed()); } }
@Override public void visitVariable(@NotNull PsiVariable variable) { super.visitVariable(variable); final PsiType type = variable.getType(); final PsiType componentType = type.getDeepComponentType(); if (!(componentType instanceof PsiClassType)) { return; } final String className = ((PsiClassType)componentType).getClassName(); @NonNls final String javaLangReflect = "java.lang.reflect."; if (!className.startsWith(javaLangReflect)) { return; } final PsiTypeElement typeElement = variable.getTypeElement(); if (typeElement == null) { return; } registerError(typeElement); }
@Override public void visitVariable(PsiVariable variable) { super.visitVariable(variable); if (!PsiType.BOOLEAN.equals(variable.getType())) { return; } final String name = variable.getName(); final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(variable.getProject()); final String prefix = codeStyleManager.getPrefixByVariableKind(codeStyleManager.getVariableKind(variable)); for (final String negativeName : NEGATIVE_NAMES) { if (isNegativelyNamed(name, negativeName) || !prefix.isEmpty() && isNegativelyNamed(name, prefix + negativeName)) { registerVariableError(variable, variable); break; } } }
public static boolean isVariableDefinitelyInitializedCached(@NotNull PsiVariable var, @NotNull GroovyPsiElement context, @NotNull Instruction[] controlFlow) { Map<GroovyPsiElement, Boolean> map = KEY.getCachedValue(var); if (map == null) { map = ContainerUtil.newHashMap(); KEY.putCachedValue(var, map); } final Boolean cached = map.get(context); if (cached != null) return cached.booleanValue(); final boolean result = isVariableDefinitelyInitialized(var.getName(), controlFlow); map.put(context, result); return result; }
@Override @NotNull public PsiVariable getPsi(PsiManager manager, final String containingClassName) { if (myPsi != null) return myPsi; Boolean isStatic = isStatic(); String type = getType(); if (type == null || type.trim().isEmpty()) { type = CommonClassNames.JAVA_LANG_OBJECT; } myPsi = new GrDynamicImplicitProperty(manager, getName(), type, containingClassName); if (isStatic != null && isStatic.booleanValue()) { myPsi.getModifierList().addModifier(PsiModifier.STATIC); } return myPsi; }
public static Result searchForVarsToWrap(GroovyPsiElement root, Result analyzedVars, ExpressionContext context) { LocalVarAnalyzer visitor = new LocalVarAnalyzer(); root.accept(visitor); Map<PsiVariable, String> varToName = analyzedVars == null ? new HashMap<PsiVariable, String>() : analyzedVars.varToName; Set<PsiVariable> toWrap = analyzedVars == null ? new HashSet<PsiVariable>() : analyzedVars.toWrap; Set<PsiVariable> toMakeFinal = analyzedVars == null ? new HashSet<PsiVariable>() : analyzedVars.toMakeFinal; for (PsiVariable v : visitor.touched) { if (visitor.rewritten.contains(v)) { toWrap.add(v); if (v instanceof PsiParameter) { varToName.put(v, GenerationUtil.suggestVarName(v.getType(), root, context)); } else { varToName.put(v, v.getName()); } } else { toMakeFinal.add(v); varToName.put(v, v.getName()); } } return analyzedVars == null ? new Result(toMakeFinal, toWrap, varToName) : analyzedVars; }
public boolean satisfiedBy(PsiElement element) { if (!(element instanceof PsiVariable)) { return false; } if (ErrorUtil.containsError(element)) { return false; } final PsiVariable var = (PsiVariable)element; final PsiTypeElement typeElement = var.getTypeElement(); if (typeElement == null) { return false; // Could be true for enum constants. } final PsiType elementType = typeElement.getType(); final PsiType type = var.getType(); return elementType.getArrayDimensions() != type.getArrayDimensions(); }
@Nullable protected final ProblemDescriptor[] verifyAnnotationDeclaredCorrectly( @NotNull PsiVariable psiVariable, @NotNull PsiAnnotation structureAnnotation, @NotNull InspectionManager manager ) { StructureAnnotationDeclarationValidationResult annotationCheck = validateStructureAnnotationDeclaration( psiVariable ); switch( annotationCheck ) { case invalidInjectionType: String message = message( "injections.structure.annotation.declared.correctly.error.invalid.injection.type", psiVariable.getType().getCanonicalText() ); AbstractFix removeStructureAnnotationFix = createRemoveAnnotationFix( structureAnnotation ); ProblemDescriptor problemDescriptor = manager.createProblemDescriptor( structureAnnotation, message, removeStructureAnnotationFix, GENERIC_ERROR_OR_WARNING ); return new ProblemDescriptor[]{ problemDescriptor }; } return null; }
private PsiMethodCallExpression findMethodCall(PsiElement element) { // This covers the case if there is a method being used to initialize a variable.. // i.e int a = random(); if (element instanceof PsiDeclarationStatement) { PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement) element; for (PsiElement declarationElement : declarationStatement.getDeclaredElements()) { if (declarationElement instanceof PsiVariable) { PsiVariable variable = (PsiVariable) declarationElement; PsiExpression initializer = variable.getInitializer(); if (initializer instanceof PsiMethodCallExpression) { return (PsiMethodCallExpression) initializer; } } } } if (element instanceof PsiExpressionStatement) { PsiExpression expression = ((PsiExpressionStatement) element).getExpression(); if (expression instanceof PsiMethodCallExpression) { return (PsiMethodCallExpression) expression; } } return null; }
public ContextRelevantStaticMethod(final PsiMethod psiMethod, @Nullable final TIntObjectHashMap<PsiVariable> parameters) { this.psiMethod = psiMethod; if (parameters == null) { this.parameters = null; } else { this.parameters = new TIntObjectHashMap<SubLookupElement>(parameters.size()); parameters.forEachEntry(new TIntObjectProcedure<PsiVariable>() { @SuppressWarnings("ConstantConditions") @Override public boolean execute(final int pos, final PsiVariable var) { ContextRelevantStaticMethod.this.parameters.put(pos, new VariableSubLookupElement(var)); return false; } }); } }
ChainCompletionContext(final PsiMethod contextMethod, final String targetQName, final Set<String> containingClassQNames, final MultiMap<String, PsiVariable> contextVars, final MultiMap<String, PsiMethod> containingClassGetters, final MultiMap<String, ContextRelevantVariableGetter> contextVarsGetters, final Map<String, PsiVariable> stringVars, final Set<String> excludedQNames, final Project project, final GlobalSearchScope resolveScope) { myContextMethod = contextMethod; myTargetQName = targetQName; myContainingClassQNames = containingClassQNames; myContextVars = contextVars; myContainingClassGetters = containingClassGetters; myContextVarsGetters = contextVarsGetters; myStringVars = stringVars; myExcludedQNames = excludedQNames; myResolveScope = resolveScope; myProject = project; myStaticMethodSearcher = new CachedRelevantStaticMethodSearcher(project, resolveScope); }
@Override public void visitVariable(@NotNull PsiVariable var) { super.visitVariable(var); final PsiType declaredType = var.getType(); if (declaredType.getArrayDimensions() == 0) { return; } final PsiTypeElement typeElement = var.getTypeElement(); if (typeElement == null) { return; // Could be true for enum constants. } final PsiType elementType = typeElement.getType(); if (elementType.equals(declaredType)) { return; } registerVariableError(var); }
@NotNull public PsiVariable getPsi(PsiManager manager, final String containingClassName) { if (myPsi != null) return myPsi; Boolean isStatic = isStatic(); String type = getType(); if (type == null || type.trim().length() == 0) { type = CommonClassNames.JAVA_LANG_OBJECT; } myPsi = new GrDynamicImplicitProperty(manager, getName(), type, containingClassName); if (isStatic != null && isStatic.booleanValue()) { myPsi.getModifierList().addModifier(PsiModifier.STATIC); } return myPsi; }
@Override public void appendBuildPrepare(@NotNull StringBuilder buildMethodCode, @NotNull PsiVariable psiVariable, @NotNull String fieldName) { final PsiManager psiManager = psiVariable.getManager(); final PsiType psiFieldType = psiVariable.getType(); final PsiType rowKeyType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 0); final PsiType columnKeyType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 1); final PsiType valueType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager, COM_GOOGLE_COMMON_COLLECT_TABLE, 2); buildMethodCode.append(MessageFormat.format( "{4}<{1}, {2}, {3}> {0} = " + "this.{0} == null ? " + "{4}.<{1}, {2}, {3}>of() : " + "this.{0}.build();\n", fieldName, rowKeyType.getCanonicalText(false), columnKeyType.getCanonicalText(false), valueType.getCanonicalText(false), collectionQualifiedName)); }
private boolean validateSingular(@NotNull PsiClass psiClass, @NotNull ProblemBuilder problemBuilder) { boolean result = true; final AccessorsInfo accessorsInfo = AccessorsInfo.build(psiClass); final Collection<PsiField> builderFields = getBuilderFields(psiClass, Collections.<PsiField>emptySet(), accessorsInfo); for (PsiVariable builderVariable : builderFields) { final PsiAnnotation singularAnnotation = PsiAnnotationSearchUtil.findAnnotation(builderVariable, Singular.class); if (null != singularAnnotation) { final String qualifiedName = PsiTypeUtil.getQualifiedName(builderVariable.getType()); if (SingularHandlerFactory.isInvalidSingularType(qualifiedName)) { problemBuilder.addError("Lombok does not know how to create the singular-form builder methods for type '%s'; " + "they won't be generated.", qualifiedName != null ? qualifiedName : builderVariable.getType().getCanonicalText()); result = false; } final String variableName = builderVariable.getName(); if (!AbstractSingularHandler.validateSingularName(singularAnnotation, accessorsInfo.removePrefix(variableName))) { problemBuilder.addError("Can't singularize this name: \"%s\"; please specify the singular explicitly (i.e. @Singular(\"sheep\"))", variableName); result = false; } } } return result; }
private boolean validateObtainViaAnnotations(@NotNull Collection<? extends PsiVariable> psiVaraibles, @NotNull ProblemBuilder problemBuilder) { boolean result = true; for (PsiVariable psiVariable : psiVaraibles) { final PsiAnnotation obtainViaAnnotation = PsiAnnotationSearchUtil.findAnnotation(psiVariable, BUILDER_OBTAIN_VIA_ANNOTATION); if (null != obtainViaAnnotation) { final String viaFieldName = PsiAnnotationUtil.getStringAnnotationValue(obtainViaAnnotation, BUILDER_OBTAIN_VIA_FIELD); final String viaMethodName = PsiAnnotationUtil.getStringAnnotationValue(obtainViaAnnotation, BUILDER_OBTAIN_VIA_METHOD); final boolean viaStaticCall = PsiAnnotationUtil.getBooleanAnnotationValue(obtainViaAnnotation, BUILDER_OBTAIN_VIA_STATIC, false); if (StringUtils.isEmpty(viaFieldName) == StringUtils.isEmpty(viaMethodName)) { problemBuilder.addError("The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\")."); result = false; } if (StringUtils.isEmpty(viaMethodName) && viaStaticCall) { problemBuilder.addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set."); result = false; } } } return result; }
private PsiClass getTypeByBindingType(AnnotationSearchResult result, PsiClass templateClass) { final BindingType bindType = getBindingType(result); if (bindType == BindingType.UNKNOWN) { return null; } if (versionSpec == VersionSpec.V3_0 && bindType == BindingType.RAW_MODEL) { return Util.getTypeOfElement(result.getOwningElement()); } if (bindType == BindingType.DATA_BINDER) { return Util.getErasedTypeParam( templateClass.getProject(), ((PsiVariable) result.getOwningElement()).getType().getCanonicalText() ); } return null; }
@Override public void prepareRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames) { final XmlAttributeValue attributeValue = (XmlAttributeValue) element; final PsiFile templateFile = TemplateUtil.getFileFromElement(attributeValue); final Collection<TemplateMetaData> templateOwners = TemplateUtil.getTemplateOwners(templateFile); for (TemplateMetaData metaData : templateOwners) { final Map<String,ConsolidateDataFieldElementResult> consolidatedDataFields = metaData.getConsolidatedDataFields(); final ConsolidateDataFieldElementResult result = consolidatedDataFields.get(attributeValue.getValue()); if (result != null && result.isDataFieldInClass()) { PsiVariable variable = (PsiVariable) result.getElement(); allRenames.put(variable, newName); } } }
@Nullable private SourcePosition getSourcePositionForLocalVariable(String name, @NotNull Project project, @NotNull DebuggerContextImpl context, boolean nearest) { PsiElement place = PositionUtil.getContextElement(context); if(place == null) { return null; } PsiVariable psiVariable = JavaPsiFacade.getInstance(project).getResolveHelper().resolveReferencedVariable(name, place); if(psiVariable == null) { return null; } PsiFile containingFile = psiVariable.getContainingFile(); if(containingFile == null) { return null; } if(nearest) { return DebuggerContextUtil.findNearest(context, psiVariable, containingFile); } return SourcePosition.createFromElement(psiVariable); }
public void visitAnnotation(PsiAnnotation annotation){ super.visitAnnotation(annotation); if(!"com.google.inject.servlet.RequestParameters".equals(annotation.getQualifiedName())){ return; } final PsiVariable variable = PsiTreeUtil.getParentOfType(annotation, PsiVariable.class); if(variable == null){ return; } final PsiType type = variable.getType(); String typeText = type.getCanonicalText(); typeText = typeText.replaceAll(" ", ""); if(typeText.equals("java.util.Map<java.lang.String,java.lang.String[]>")){ return; } registerError(annotation); }
public void visitAnnotation(PsiAnnotation annotation){ super.visitAnnotation(annotation); if(!isBindingAnnotation(annotation)){ return; } final PsiVariable boundVariable = PsiTreeUtil.getParentOfType(annotation, PsiVariable.class); if(boundVariable == null){ return; } if(boundVariable instanceof PsiField){ if(!GoogleGuiceAnnotationUtil.isAnnotatedByInject(boundVariable, true)){ registerError(annotation); } } else if(boundVariable instanceof PsiParameter){ final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(boundVariable, PsiMethod.class); if(containingMethod == null){ return; } if(!GoogleGuiceAnnotationUtil.isAnnotatedByInject(containingMethod, true)){ registerError(annotation); } } }
@Nullable private PsiVariable checkCodeFragment(PsiElement refElement) { PsiElement codeFragment = ControlFlowUtil.findCodeFragment(refElement); if (refElement instanceof PsiParameter) { final PsiElement declarationScope = ((PsiParameter)refElement).getDeclarationScope(); if (declarationScope instanceof PsiMethod) { codeFragment = ((PsiMethod)declarationScope).getBody(); } else if (declarationScope instanceof PsiLambdaExpression) { codeFragment = ((PsiLambdaExpression)declarationScope).getBody(); } } if (codeFragment == null) return null; if (myCodeFragment.getContainingFile() == codeFragment.getContainingFile() && // in order for jsp includes to work !myCodeFragment.equals(codeFragment)) { return null; } return (PsiVariable)refElement; }
public static Object computeConstantExpression(PsiExpression expression, @Nullable Set<PsiVariable> visitedVars, boolean throwExceptionOnOverflow, final PsiConstantEvaluationHelper.AuxEvaluator auxEvaluator) { if (expression == null) return null; JavaConstantExpressionEvaluator evaluator = new JavaConstantExpressionEvaluator(visitedVars, throwExceptionOnOverflow, expression.getProject(), auxEvaluator); if (expression instanceof PsiCompiledElement) { // in case of compiled elements we are not allowed to use PSI walking // but really in Cls there are only so many cases to handle if (expression instanceof PsiPrefixExpression) { PsiElement operand = ((PsiPrefixExpression)expression).getOperand(); if (operand == null) return null; Object value = evaluator.myConstantExpressionVisitor.handle(operand); ConstantExpressionVisitor.store(operand, value); } return evaluator.myConstantExpressionVisitor.handle(expression); } expression.accept(evaluator); Object cached = evaluator.getCached(expression); return cached == NO_VALUE ? null : cached; }
private static boolean isUnusedInAnonymousClass(@NotNull PsiMethod method) { PsiClass containingClass = method.getContainingClass(); if(!(containingClass instanceof PsiAnonymousClass)) { return false; } if(containingClass.getParent() instanceof PsiNewExpression && containingClass.getParent().getParent() instanceof PsiVariable && !method.getHierarchicalMethodSignature().getSuperSignatures() .isEmpty()) { // references outside anonymous class can still resolve to this method, see com.intellij.psi.scope.util.PsiScopesUtil.setupAndRunProcessor() return false; } return MethodReferencesSearch.search(method, new LocalSearchScope(containingClass), false).findFirst() == null; }
@Override public boolean tryInlineCall(@NotNull CFGBuilder builder, @NotNull PsiMethodCallExpression call) { FactoryInfo factoryInfo = STATIC_FACTORIES.mapFirst(call); if(factoryInfo == null) { return false; } PsiExpression[] args = call.getArgumentList().getExpressions(); for(PsiExpression arg : args) { builder.pushExpression(arg).pop(); } PsiVariable variable = builder.createTempVariable(call.getType()); DfaValueFactory factory = builder.getFactory(); DfaVariableValue variableValue = factory.getVarFactory().createVariableValue(variable, false); builder.pushVariable(variable) // tmpVar = <Value of collection type> .push(factory.createTypeValue(call.getType(), Nullness.NOT_NULL)).assign() // leave tmpVar on stack: it's result of method call .push(factoryInfo.mySizeField.createValue(factory, variableValue)) // tmpVar.size = <size> .push(factory.getConstFactory().createFromValue(factoryInfo.mySize, PsiType.INT, null)).assign().pop(); return true; }
@Override public boolean isAvailableFor(@NotNull UsageView usageView) { UsageTarget[] targets = ((UsageViewImpl) usageView).getTargets(); if(targets.length == 0) { return false; } UsageTarget target = targets[0]; if(!(target instanceof PsiElementUsageTarget)) { return false; } PsiElement element = ((PsiElementUsageTarget) target).getElement(); if(element == null || !element.isValid()) { return false; } if(!(element instanceof PsiVariable)) { return false; } PsiFile file = element.getContainingFile(); return file instanceof PsiJavaFile; }
@Override public boolean isEnabledOnElements(@NotNull PsiElement[] elements) { if(elements.length > 1) { return false; } for(PsiElement element : elements) { if(!(element instanceof PsiMethod || element instanceof PsiVariable)) { return false; } } return true; }
@Override public void visitDeclarationStatement( @NotNull PsiDeclarationStatement statement) { if (assignedFrom) { return; } super.visitDeclarationStatement(statement); final PsiElement[] declaredElements = statement.getDeclaredElements(); for (PsiElement declaredElement : declaredElements) { if (declaredElement instanceof PsiVariable) { final PsiVariable declaredVariable = (PsiVariable)declaredElement; final PsiExpression initializer = declaredVariable.getInitializer(); if (initializer != null && VariableAccessUtils.mayEvaluateToVariable(initializer, variable)) { assignedFrom = true; return; } } } }
protected void doAction() { Map<PsiClass, String> parameterNames = new LinkedHashMap<PsiClass, String>(); for (final PsiClass aClass : myThisClassesMap.keySet()) { EditorTextField field = myOldClassParameterNameFields.get(aClass); if (field.isEnabled()) { String parameterName = field.getText().trim(); if (!PsiNameHelper.getInstance(myMethod.getProject()).isIdentifier(parameterName)) { Messages .showErrorDialog(getProject(), RefactoringBundle.message("move.method.enter.a.valid.name.for.parameter"), myRefactoringName); return; } parameterNames.put(aClass, parameterName); } } final PsiVariable targetVariable = (PsiVariable)myList.getSelectedValue(); if (targetVariable == null) return; final MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(myMethod.getProject(), myMethod, targetVariable, myVisibilityPanel.getVisibility(), parameterNames); if (!verifyTargetClass(processor.getTargetClass())) return; invokeRefactoring(processor); }