Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ilya.Kazakevich
2014-03-11 18:50:50 +04:00
44 changed files with 609 additions and 703 deletions
+2 -2
View File
@@ -1,11 +1,11 @@
<component name="libraryTable">
<library name="Eclipse">
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/ecj-4.2.1.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/ecj-4.3.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/lib/src/ecjsrc-4.2.1.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/src/ecjsrc-4.3.2.jar!/" />
</SOURCES>
</library>
</component>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* 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.
@@ -45,6 +45,8 @@ import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider {
/**
@@ -82,7 +84,6 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
protected boolean myUseChildAttributes = false;
@NotNull protected final AlignmentStrategy myAlignmentStrategy;
private boolean myIsAfterClassKeyword = false;
private Wrap myAnnotationWrap = null;
protected Alignment myReservedAlignment;
protected Alignment myReservedAlignment2;
@@ -137,15 +138,14 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
}
return strategy.getAlignment(node.getElementType());
}
@NotNull
public static Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
Alignment alignment)
{
Alignment alignment) {
return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment));
}
@@ -166,8 +166,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
@Nullable Indent indent,
Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy,
int startOffset)
{
int startOffset) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent;
final IElementType elementType = child.getElementType();
Alignment alignment = alignmentStrategy.getAlignment(elementType);
@@ -189,8 +188,9 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings);
}
if (child instanceof PsiComment && child instanceof PsiLanguageInjectionHost && InjectedLanguageUtil
.hasInjections((PsiLanguageInjectionHost)child)) {
if (child instanceof PsiComment &&
child instanceof PsiLanguageInjectionHost &&
InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) {
return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings);
}
if (child instanceof LeafElement) {
@@ -500,36 +500,26 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
if (mySettings.PREFER_PARAMETERS_WRAP) {
wrap.ignoreParentWraps();
}
child = processParenthesisBlock(result,
child,
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
final Wrap wrap;
Wrap reservedWrap = getReservedWrap(JavaElementType.MODIFIER_LIST);
// There is a possible case that particular annotated method definition is too long. We may wrap either after annotation
// or after opening lbrace then. Our strategy is to wrap after annotation whenever possible.
if (reservedWrap == null) {
wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
}
else {
wrap = Wrap.createChildWrap(reservedWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
}
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) {
final Wrap reservedWrap = getReservedWrap(JavaElementType.MODIFIER_LIST);
final Wrap wrap = reservedWrap != null
? Wrap.createChildWrap(reservedWrap, getWrapType(mySettings.RESOURCE_LIST_WRAP), false)
: Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false);
child = processParenthesisBlock(result, child, WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_RESOURCES);
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_RESOURCES);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
@@ -548,63 +538,37 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, alignmentStrategy, defaultWrap, childIndent);
}
else if (childType == JavaElementType.LOCAL_VARIABLE
|| childType == JavaElementType.DECLARATION_STATEMENT && myNode.getElementType() == JavaElementType.METHOD)
{
else if (childType == JavaElementType.LOCAL_VARIABLE ||
childType == JavaElementType.DECLARATION_STATEMENT && myNode.getElementType() == JavaElementType.METHOD) {
result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings));
}
else {
AlignmentStrategy alignmentStrategyToUse = AlignmentStrategy.wrap(arrangeChildAlignment(child, alignmentStrategy));
if (myAlignmentStrategy.getAlignment(nodeType, childType) != null
&& (nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS))
{
if (myAlignmentStrategy.getAlignment(nodeType, childType) != null &&
(nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) {
alignmentStrategyToUse = myAlignmentStrategy;
}
final Block block = createJavaBlock(
child, mySettings, myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategyToUse, childOffset
);
if (childType == JavaElementType.MODIFIER_LIST && containsAnnotations(child)) {
myAnnotationWrap = Wrap.createWrap(getWrapType(getAnnotationWrapType(child)), true);
}
Wrap wrap = arrangeChildWrap(child, defaultWrap);
Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset);
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION
|| nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION)
{
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION ||
nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType);
javaBlock.setReservedWrap(getReservedWrap(childType), childType);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap, nodeType);
}
else if (childType == JavaElementType.MODIFIER_LIST) {
javaBlock.setReservedWrap(myAnnotationWrap, JavaElementType.MODIFIER_LIST);
if (!lastChildIsAnnotation(child)) {
myAnnotationWrap = null;
}
}
else if (childType == JavaElementType.PARAMETER_LIST && nodeType == JavaElementType.METHOD) {
// We prefer wrapping after method annotation to wrapping method parameter list, hence, deliver target wrap object
// to child block if necessary.
if (!result.isEmpty()) {
Block firstChildBlock = result.get(0);
if (firstChildBlock instanceof AbstractJavaBlock) {
AbstractJavaBlock childJavaBlock = (AbstractJavaBlock)firstChildBlock;
if (firstChildIsAnnotation(childJavaBlock.getNode())) {
javaBlock.setReservedWrap(childJavaBlock.getReservedWrap(JavaElementType.MODIFIER_LIST), JavaElementType.MODIFIER_LIST);
}
}
}
}
}
result.add(block);
}
}
return child;
}
@@ -647,7 +611,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
* <code>'Composite field definition'</code> looks like {@code 'int i1, i2 = 2'}. It produces two nodes of type
* {@link JavaElementType#FIELD} - {@code 'int i1'} and {@code 'i2 = 2'}. This method returns the second node if the first one
* is given (the given node is returned for <code>'single'</code> fields).
*
*
* @param child child field node to check
* @return last child field node at the field group identified by the given node if any; given child otherwise
*/
@@ -777,62 +741,6 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
}
}
private static boolean firstChildIsAnnotation(@NotNull final ASTNode child) {
ASTNode current = child.getFirstChildNode();
while (current != null && current.getElementType() == TokenType.WHITE_SPACE) {
current = current.getTreeNext();
}
return current != null && current.getElementType() == JavaElementType.ANNOTATION;
}
private static boolean lastChildIsAnnotation(@NotNull final ASTNode child) {
ASTNode current = child.getLastChildNode();
while (current != null && current.getElementType() == TokenType.WHITE_SPACE) {
current = current.getTreePrev();
}
return current != null && current.getElementType() == JavaElementType.ANNOTATION;
}
private static boolean containsAnnotations(@NotNull final ASTNode child) {
PsiElement psi = child.getPsi();
return psi instanceof PsiModifierList && ((PsiModifierList)psi).getAnnotations().length > 0;
}
private int getAnnotationWrapType(@NotNull ASTNode child) {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.METHOD) {
return mySettings.METHOD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.CLASS) {
// There is a possible case that current document state is invalid from language syntax point of view, e.g. the user starts
// typing field definition and re-formatting is triggered by 'auto insert javadoc' processing. Example:
// class Test {
// @NotNull Object
// }
// Here '@NotNull' has a 'class' node as a parent but we want to use field annotation setting value. Hence, we check if subsequent
// parsed info is valid.
for (ASTNode node = child.getTreeNext(); node != null; node = node.getTreeNext()) {
if (TokenType.WHITE_SPACE == node.getElementType() || node instanceof PsiTypeElement) {
continue;
}
if (node instanceof PsiErrorElement) {
return mySettings.FIELD_ANNOTATION_WRAP;
}
}
return mySettings.CLASS_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.FIELD) {
return mySettings.FIELD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.PARAMETER) {
return mySettings.PARAMETER_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.LOCAL_VARIABLE) {
return mySettings.VARIABLE_ANNOTATION_WRAP;
}
return CommonCodeStyleSettings.DO_NOT_WRAP;
}
@Nullable
private Alignment arrangeChildAlignment(@NotNull final ASTNode child, @NotNull final AlignmentStrategy alignmentStrategy) {
int role = getChildRole(child);
@@ -905,7 +813,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
}
return null;
}
else {
return defaultAlignment;
}
@@ -944,21 +852,6 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
return myAlignmentStrategy.getAlignment(childType);
}
/*
private boolean isAfterClassKeyword(final ASTNode child) {
ASTNode treePrev = child.getTreePrev();
while (treePrev != null) {
if (treePrev.getElementType() == ElementType.CLASS_KEYWORD ||
treePrev.getElementType() == ElementType.INTERFACE_KEYWORD) {
return true;
}
treePrev = treePrev.getTreePrev();
}
return false;
}
*/
@Nullable
private static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment;
@@ -971,37 +864,14 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
if (myAnnotationWrap != null) {
try {
return myAnnotationWrap;
}
finally {
myAnnotationWrap = null;
}
}
return myWrapManager.arrangeChildWrap(child, myNode, getSettings(), defaultWrap, this);
}
@NotNull
private static WrapType getWrapType(final int wrap) {
switch (wrap) {
case CommonCodeStyleSettings.WRAP_ALWAYS:
return WrapType.ALWAYS;
case CommonCodeStyleSettings.WRAP_AS_NEEDED:
return WrapType.NORMAL;
case CommonCodeStyleSettings.DO_NOT_WRAP:
return WrapType.NONE;
default:
return WrapType.CHOP_DOWN_IF_LONG;
}
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull List<Block> result,
@NotNull ASTNode child,
@NotNull WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
@@ -1010,7 +880,6 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull IElementType from,
@Nullable final IElementType to,
@@ -1084,22 +953,22 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) {
// The general idea is to handle situations like below:
// test(new Runnable() {
// test(new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// }
// );
// I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument
// I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument
// at the same line, e.g.:
// test("this is a long argument", new Runnable() {
// test("this is a long argument", new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// }
// );
if (!isAnonymousClass(child)) {
@@ -1122,7 +991,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
}
return true;
}
private boolean shouldEnforceIndentToChildren() {
if (myNode.getElementType() != JavaElementType.EXPRESSION_LIST) {
return false;
@@ -1144,7 +1013,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
ASTNode lastChild = node.getLastChildNode();
return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS;
}
@Nullable
private ASTNode processEnumBlock(@NotNull List<Block> result,
@Nullable ASTNode child,
@@ -1194,7 +1063,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
return getCodeBlockInternalIndent(baseChildrenIndent, false);
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent, boolean enforceParentIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
@@ -1209,7 +1078,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
protected static Indent createNormalIndent(final int baseChildrenIndent) {
return createNormalIndent(baseChildrenIndent, false);
}
protected static Indent createNormalIndent(final int baseChildrenIndent, boolean enforceIndentToChildren) {
if (baseChildrenIndent == 1) {
return Indent.getIndent(Indent.Type.NORMAL, false, enforceIndentToChildren);
@@ -1370,9 +1239,9 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
}
final boolean rBrace = isRBrace(child);
Indent childIndent = rBrace ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent, false);
if (!rBrace && child.getElementType() == JavaElementType.CODE_BLOCK
&& (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED
|| getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2))
if (!rBrace && child.getElementType() == JavaElementType.CODE_BLOCK
&& (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED
|| getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2))
{
childIndent = Indent.getNormalIndent();
}
@@ -1384,7 +1253,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
return child;
}
}
if (child != null) {
child = child.getTreeNext();
}
@@ -1418,11 +1287,11 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
* <p/>
* <pre>
* int i1, i2 = 2;
* </pre>
* </pre>
* <p/>
* Parsing such a code produces two fields - {@code 'int i1'} and {@code 'i2 = 2'}. This method returns <code>true</code>
* for the second one.
*
*
* @param node node to check
* @return <code>true</code> if given node is a non-first part of composite field definition; <code>false</code> otherwise
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* 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.
@@ -15,6 +15,7 @@
*/
package com.intellij.psi.formatter.java;
import com.intellij.formatting.WrapType;
import com.intellij.lang.ASTNode;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
@@ -39,8 +40,7 @@ public class JavaFormatterUtil {
JavaElementType.ASSIGNMENT_EXPRESSION, JavaElementType.LOCAL_VARIABLE, JavaElementType.FIELD
));
private JavaFormatterUtil() {
}
private JavaFormatterUtil() { }
/**
* Allows to answer if given node wraps assignment operation.
@@ -119,4 +119,17 @@ public class JavaFormatterUtil {
&& node.textContains('\n');
}
@NotNull
public static WrapType getWrapType(int wrap) {
switch (wrap) {
case CommonCodeStyleSettings.WRAP_ALWAYS:
return WrapType.ALWAYS;
case CommonCodeStyleSettings.WRAP_AS_NEEDED:
return WrapType.NORMAL;
case CommonCodeStyleSettings.DO_NOT_WRAP:
return WrapType.NONE;
default:
return WrapType.CHOP_DOWN_IF_LONG;
}
}
}
@@ -18,9 +18,7 @@ package com.intellij.psi.formatter.java.wrap.impl;
import com.intellij.formatting.Wrap;
import com.intellij.formatting.WrapType;
import com.intellij.lang.ASTNode;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiPolyadicExpression;
import com.intellij.psi.PsiStatement;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.java.JavaFormatterUtil;
@@ -33,6 +31,9 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.Nullable;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
import static com.intellij.psi.impl.PsiImplUtil.isTypeAnnotation;
/**
* Encapsulates the implementation of
* {@link JavaWrapManager#arrangeChildWrap(ASTNode, ASTNode, CommonCodeStyleSettings, Wrap, ReservedWrapsProvider)}.
@@ -43,7 +44,6 @@ import org.jetbrains.annotations.Nullable;
* @since Apr 21, 2010
*/
public class JavaChildWrapArranger {
/**
* Provides implementation of {@link JavaWrapManager#arrangeChildWrap} method.
*
@@ -116,7 +116,7 @@ public class JavaChildWrapArranger {
return suggestedWrap;
}
else if (JavaFormatterUtil.isAssignment(parent)) {
else if (JavaFormatterUtil.isAssignment(parent) && role != ChildRole.TYPE) {
if (role == ChildRole.INITIALIZER_EQ) return settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE ? suggestedWrap : null;
if (role == ChildRole.OPERATION_SIGN) return settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE ? suggestedWrap : null;
if (role == ChildRole.INITIALIZER) return settings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE ? null : suggestedWrap;
@@ -148,29 +148,44 @@ public class JavaChildWrapArranger {
}
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.THROWS_LIST) {
return suggestedWrap;
}
else {
return null;
else if (parent.getPsi() instanceof PsiModifierListOwner) {
ASTNode prev = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prev != null && prev.getElementType() == JavaElementType.MODIFIER_LIST) {
ASTNode last = prev.getLastChildNode();
if (last != null && last.getElementType() == JavaElementType.ANNOTATION) {
if (isTypeAnnotation(last.getPsi())) {
return Wrap.createWrap(WrapType.NONE, false);
}
else {
return Wrap.createWrap(getWrapType(getAnnotationWrapType(parent, child, settings)), true);
}
}
}
return null;
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
if (childType == JavaElementType.ANNOTATION) {
return reservedWrapsProvider.getReservedWrap(JavaElementType.MODIFIER_LIST);
if (isTypeAnnotation(child.getPsi())) {
ASTNode prev = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prev == null || prev.getElementType() != JavaElementType.ANNOTATION || isTypeAnnotation(prev.getPsi())) {
return Wrap.createWrap(WrapType.NONE, false);
}
}
return Wrap.createWrap(getWrapType(getAnnotationWrapType(parent.getTreeParent(), child, settings)), true);
}
else if (childType == JavaTokenType.END_OF_LINE_COMMENT) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.ANNOTATION) {
return reservedWrapsProvider.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
else {
return null;
ASTNode prev = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prev != null && prev.getElementType() == JavaElementType.ANNOTATION) {
return Wrap.createWrap(getWrapType(getAnnotationWrapType(parent.getTreeParent(), child, settings)), true);
}
return null;
}
else if (nodeType == JavaElementType.ASSERT_STATEMENT) {
@@ -240,4 +255,47 @@ public class JavaChildWrapArranger {
return suggestedWrap;
}
private static int getAnnotationWrapType(ASTNode parent, ASTNode child, CommonCodeStyleSettings settings) {
IElementType nodeType = parent.getElementType();
if (nodeType == JavaElementType.METHOD) {
return settings.METHOD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.CLASS) {
// There is a possible case that current document state is invalid from language syntax point of view, e.g. the user starts
// typing field definition and re-formatting is triggered by 'auto insert javadoc' processing. Example:
// class Test {
// @NotNull Object
// }
// Here '@NotNull' has a 'class' node as a parent but we want to use field annotation setting value.
// Hence we check if subsequent parsed info is valid.
for (ASTNode node = child.getTreeNext(); node != null; node = node.getTreeNext()) {
if (node.getElementType() == TokenType.WHITE_SPACE || node instanceof PsiTypeElement) {
continue;
}
if (node instanceof PsiErrorElement) {
return settings.FIELD_ANNOTATION_WRAP;
}
}
return settings.CLASS_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.FIELD) {
return settings.FIELD_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.PARAMETER ||
nodeType == JavaElementType.RECEIVER_PARAMETER ||
nodeType == JavaElementType.RESOURCE_VARIABLE) {
return settings.PARAMETER_ANNOTATION_WRAP;
}
if (nodeType == JavaElementType.LOCAL_VARIABLE) {
return settings.VARIABLE_ANNOTATION_WRAP;
}
return CommonCodeStyleSettings.DO_NOT_WRAP;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -21,96 +21,66 @@ import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
public class MutationUtils {
private MutationUtils() {
super();
private MutationUtils() { }
public static void replaceType(@NotNull String newTypeText, @NotNull PsiTypeElement typeElement) throws IncorrectOperationException {
final Project project = typeElement.getProject();
final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiType newType = factory.createTypeFromText(newTypeText, null);
final PsiTypeElement newTypeElement = factory.createTypeElement(newType);
final PsiElement insertedElement = typeElement.replace(newTypeElement);
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement);
CodeStyleManager.getInstance(project).reformat(shortenedElement);
}
public static void replaceExpression(@NotNull String newExpression, @NotNull PsiExpression exp) throws IncorrectOperationException {
final Project project = exp.getProject();
final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiExpression newCall = factory.createExpressionFromText(newExpression, null);
final PsiElement insertedElement = exp.replace(newCall);
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement);
CodeStyleManager.getInstance(project).reformat(shortenedElement);
}
public static void replaceExpressionIfValid(@NotNull String newExpression, @NotNull PsiExpression exp) throws IncorrectOperationException {
try {
replaceExpression(newExpression, exp);
}
catch (IncorrectOperationException ignored) { }
}
public static void replaceType(String newExpression,
PsiTypeElement typeElement)
throws IncorrectOperationException {
final PsiManager mgr = typeElement.getManager();
final PsiElementFactory factory = JavaPsiFacade.getInstance(mgr.getProject()).getElementFactory();
final PsiType newType =
factory.createTypeFromText(newExpression, null);
final PsiTypeElement newTypeElement = factory.createTypeElement(newType);
final PsiElement insertedElement = typeElement.replace(newTypeElement);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(mgr.getProject());
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(mgr.getProject()).shortenClassReferences(insertedElement);
codeStyleManager.reformat(shortenedElement);
}
public static void replaceExpression(String newExpression,
PsiExpression exp)
throws IncorrectOperationException {
final PsiManager mgr = exp.getManager();
final PsiElementFactory factory = JavaPsiFacade.getInstance(mgr.getProject()).getElementFactory();
final PsiExpression newCall =
factory.createExpressionFromText(newExpression, null);
final PsiElement insertedElement = exp.replace(newCall);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(mgr.getProject());
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(mgr.getProject()).shortenClassReferences(insertedElement);
codeStyleManager.reformat(shortenedElement);
}
public static void replaceExpressionIfValid(String newExpression,
PsiExpression exp) throws IncorrectOperationException{
final PsiManager mgr = exp.getManager();
final PsiElementFactory factory = JavaPsiFacade.getInstance(mgr.getProject()).getElementFactory();
final PsiExpression newCall;
try{
newCall = factory.createExpressionFromText(newExpression, null);
} catch(IncorrectOperationException e){
return;
}
final PsiElement insertedElement = exp.replace(newCall);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(mgr.getProject());
final PsiElement shortenedElement =JavaCodeStyleManager.getInstance(mgr.getProject()).shortenClassReferences(insertedElement);
codeStyleManager.reformat(shortenedElement);
}
public static void replaceReference(String className,
PsiJavaCodeReferenceElement reference)
throws IncorrectOperationException {
final PsiManager mgr = reference.getManager();
final Project project = mgr.getProject();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(mgr.getProject());
public static void replaceReference(@NotNull String className, @NotNull PsiJavaCodeReferenceElement ref) throws IncorrectOperationException {
final Project project = ref.getProject();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
final PsiElementFactory factory = facade.getElementFactory();
final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
final PsiElement insertedElement;
final PsiElement parent = reference.getParent();
final PsiElement parent = ref.getParent();
if (parent instanceof PsiReferenceExpression) {
final PsiClass aClass = facade.findClass(className, scope);
if (aClass == null) return;
((PsiReferenceExpression)parent).setQualifierExpression(factory.createReferenceExpression(aClass));
insertedElement = ((PsiReferenceExpression)parent).getQualifierExpression();
assert insertedElement != null : parent;
}
else {
final PsiJavaCodeReferenceElement newReference =
factory.createReferenceElementByFQClassName(className, scope);
insertedElement = reference.replace(newReference);
final PsiJavaCodeReferenceElement newReference = factory.createReferenceElementByFQClassName(className, scope);
insertedElement = ref.replace(newReference);
}
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(mgr.getProject());
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(mgr.getProject()).shortenClassReferences(insertedElement);
codeStyleManager.reformat(shortenedElement);
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement);
CodeStyleManager.getInstance(project).reformat(shortenedElement);
}
public static void replaceStatement(String newStatement,
PsiStatement statement)
throws IncorrectOperationException {
final Project project = statement.getProject();
final PsiManager mgr = PsiManager.getInstance(project);
final PsiElementFactory factory = JavaPsiFacade.getInstance(mgr.getProject()).getElementFactory();
final PsiStatement newCall =
factory.createStatementFromText(newStatement, null);
final PsiElement insertedElement = statement.replace(newCall);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(mgr.getProject());
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(mgr.getProject()).shortenClassReferences(insertedElement);
codeStyleManager.reformat(shortenedElement);
}
public static void replaceStatement(@NotNull String newStatement, @NotNull PsiStatement statement) throws IncorrectOperationException {
final Project project = statement.getProject();
final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiStatement newCall = factory.createStatementFromText(newStatement, null);
final PsiElement insertedElement = statement.replace(newCall);
final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement);
CodeStyleManager.getInstance(project).reformat(shortenedElement);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -20,12 +20,11 @@ import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
@SuppressWarnings({"AbstractClassExtendsConcreteClass"})
public abstract class FixableUsageInfo extends UsageInfo {
public FixableUsageInfo(PsiElement element) {
super(element);
}
public FixableUsageInfo(PsiElement element) {
super(element);
}
public abstract void fixUsage() throws IncorrectOperationException;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -22,117 +22,113 @@ import com.intellij.psi.PsiTypeParameter;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import org.jetbrains.annotations.NonNls;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class ReturnValueBeanBuilder {
private String className = null;
private String packageName = null;
private final List<PsiTypeParameter> typeParams = new ArrayList<PsiTypeParameter>();
private Project myProject = null;
private PsiType valueType = null;
private final List<PsiTypeParameter> myTypeParams = new ArrayList<PsiTypeParameter>();
private String myClassName = null;
private String myPackageName = null;
private Project myProject = null;
private PsiType myValueType = null;
private boolean myStatic;
public void setClassName(String className) {
this.className = className;
myClassName = className;
}
public void setPackageName(String packageName) {
myPackageName = packageName;
}
public void setTypeArguments(List<PsiTypeParameter> typeParams) {
myTypeParams.clear();
myTypeParams.addAll(typeParams);
}
public void setProject(Project project) {
myProject = project;
}
public void setValueType(PsiType valueType) {
myValueType = valueType;
}
public void setStatic(boolean isStatic) {
myStatic = isStatic;
}
public String buildBeanClass() throws IOException {
final StringBuilder out = new StringBuilder(1024);
if (myPackageName.length() > 0) {
out.append("package ").append(myPackageName).append(";\n\n");
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setTypeArguments(List<PsiTypeParameter> typeParams) {
this.typeParams.clear();
this.typeParams.addAll(typeParams);
}
public void setCodeStyleSettings(Project settings) {
this.myProject = settings;
}
public String buildBeanClass() throws IOException {
@NonNls final StringBuffer out = new StringBuffer(1024);
if (packageName.length() > 0) out.append("package " + packageName + ';');
out.append('\n');
out.append("public ");
if (myStatic) out.append("static ");
out.append("class ").append(className);
if (!typeParams.isEmpty()) {
out.append('<');
boolean first = true;
for (PsiTypeParameter typeParam : typeParams) {
if (!first) {
out.append(',');
}
final String parameterText = typeParam.getText();
out.append(parameterText);
first = false;
}
out.append('>');
out.append("public ");
if (myStatic) out.append("static ");
out.append("class ").append(myClassName);
if (!myTypeParams.isEmpty()) {
out.append('<');
boolean first = true;
for (PsiTypeParameter typeParam : myTypeParams) {
if (!first) {
out.append(',');
}
out.append('\n');
out.append('{');
outputField(out);
out.append('\n');
outputConstructor(out);
out.append('\n');
outputGetter(out);
out.append("}\n");
return out.toString();
final String parameterText = typeParam.getText();
out.append(parameterText);
first = false;
}
out.append('>');
}
private void outputGetter(@NonNls StringBuffer out) {
final String typeText = valueType.getCanonicalText();
@NonNls final String name = "value";
final String capitalizedName = StringUtil.capitalize(name);
out.append("\tpublic " + typeText + " get" + capitalizedName + "()\n");
out.append("\t{\n");
final String fieldName = getFieldName(name);
out.append("\t\treturn " + fieldName + ";\n");
out.append("\t}\n");
out.append('\n');
}
out.append(" {\n");
outputField(out);
out.append("\n\n");
outputConstructor(out);
out.append("\n\n");
outputGetter(out);
out.append("\n}\n");
private void outputField(@NonNls StringBuffer out) {
final String typeText = valueType.getCanonicalText();
out.append('\t' + "private final " + typeText + ' ' + getFieldName("value") + ";\n");
}
return out.toString();
}
private void outputConstructor(@NonNls StringBuffer out) {
out.append("\tpublic " + className + '(');
final String typeText = valueType.getCanonicalText();
@NonNls final String name = "value";
final String parameterName =
JavaCodeStyleManager.getInstance(myProject).propertyNameToVariableName(name, VariableKind.PARAMETER);
out.append(CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS ? "final " : "");
out.append(typeText + ' ' + parameterName);
out.append(")\n");
out.append("\t{\n");
final String fieldName = getFieldName(name);
if (fieldName.equals(parameterName)) {
out.append("\t\tthis." + fieldName + " = " + parameterName + ";\n");
} else {
out.append("\t\t" + fieldName + " = " + parameterName + ";\n");
}
out.append("\t}\n");
out.append('\n');
private void outputField(StringBuilder out) {
final String typeText = myValueType.getCanonicalText(false);
out.append('\t' + "private final ").append(typeText).append(' ').append(getFieldName("value")).append(";");
}
private void outputConstructor(StringBuilder out) {
final String typeText = myValueType.getCanonicalText(true);
final String name = "value";
final String parameterName = JavaCodeStyleManager.getInstance(myProject).propertyNameToVariableName(name, VariableKind.PARAMETER);
final String fieldName = getFieldName(name);
out.append("\tpublic ").append(myClassName).append('(');
out.append(CodeStyleSettingsManager.getSettings(myProject).GENERATE_FINAL_PARAMETERS ? "final " : "");
out.append(typeText).append(' ').append(parameterName);
out.append(") {\n");
if (fieldName.equals(parameterName)) {
out.append("\t\tthis.").append(fieldName).append(" = ").append(parameterName).append(";\n");
}
else {
out.append("\t\t").append(fieldName).append(" = ").append(parameterName).append(";\n");
}
out.append("\t}");
}
private void outputGetter(StringBuilder out) {
final String typeText = myValueType.getCanonicalText(true);
final String name = "value";
final String capitalizedName = StringUtil.capitalize(name);
final String fieldName = getFieldName(name);
out.append("\tpublic ").append(typeText).append(" get").append(capitalizedName).append("() {\n");
out.append("\t\treturn ").append(fieldName).append(";\n");
out.append("\t}");
}
private String getFieldName(final String name) {
return JavaCodeStyleManager.getInstance(myProject).propertyNameToVariableName(name, VariableKind.FIELD);
}
public void setValueType(PsiType valueType) {
this.valueType = valueType;
}
public void setStatic(final boolean isStatic) {
myStatic = isStatic;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* 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.
@@ -19,7 +19,7 @@ import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.ide.util.PackageUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
@@ -47,7 +47,6 @@ import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
@@ -57,47 +56,47 @@ import java.util.List;
import java.util.Set;
public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("com.siyeh.rpp.wrapreturnvalue.WrapReturnValueProcessor");
private MoveDestination myMoveDestination;
private final PsiMethod method;
private final String className;
private final String packageName;
private final PsiMethod myMethod;
private final String myClassName;
private final String myPackageName;
private final boolean myCreateInnerClass;
private final PsiField myDelegateField;
private final String myQualifiedName;
private final boolean myUseExistingClass;
private final List<PsiTypeParameter> typeParams;
@NonNls
private final String unwrapMethodName;
private final List<PsiTypeParameter> myTypeParameters;
private final String myUnwrapMethodName;
public WrapReturnValueProcessor(String className,
String packageName,
MoveDestination moveDestination, PsiMethod method,
MoveDestination moveDestination,
PsiMethod method,
boolean useExistingClass,
final boolean createInnerClass, PsiField delegateField) {
final boolean createInnerClass,
PsiField delegateField) {
super(method.getProject());
myMoveDestination = moveDestination;
this.method = method;
this.className = className;
this.packageName = packageName;
myMethod = method;
myClassName = className;
myPackageName = packageName;
myCreateInnerClass = createInnerClass;
myDelegateField = delegateField;
myQualifiedName = StringUtil.getQualifiedName(packageName, className);
this.myUseExistingClass = useExistingClass;
myUseExistingClass = useExistingClass;
final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>();
final TypeParametersVisitor visitor = new TypeParametersVisitor(typeParamSet);
final PsiTypeElement returnTypeElement = method.getReturnTypeElement();
assert returnTypeElement != null;
returnTypeElement.accept(visitor);
typeParams = new ArrayList<PsiTypeParameter>(typeParamSet);
myTypeParameters = new ArrayList<PsiTypeParameter>(typeParamSet);
if (useExistingClass) {
unwrapMethodName = calculateUnwrapMethodName();
myUnwrapMethodName = calculateUnwrapMethodName();
}
else {
unwrapMethodName = "getValue";
myUnwrapMethodName = "getValue";
}
}
@@ -118,13 +117,15 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
}
@NotNull
@Override
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usageInfos) {
return new WrapReturnValueUsageViewDescriptor(method, usageInfos);
return new WrapReturnValueUsageViewDescriptor(myMethod, usageInfos);
}
@Override
public void findUsages(@NotNull List<FixableUsageInfo> usages) {
findUsagesForMethod(method, usages);
for (PsiMethod overridingMethod : OverridingMethodsSearch.search(method)) {
findUsagesForMethod(myMethod, usages);
for (PsiMethod overridingMethod : OverridingMethodsSearch.search(myMethod)) {
findUsagesForMethod(overridingMethod, usages);
}
}
@@ -134,7 +135,7 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
final PsiElement referenceElement = reference.getElement();
final PsiElement parent = referenceElement.getParent();
if (parent instanceof PsiCallExpression) {
usages.add(new UnwrapCall((PsiCallExpression)parent, unwrapMethodName));
usages.add(new UnwrapCall((PsiCallExpression)parent, myUnwrapMethodName));
}
}
final String returnType = calculateReturnTypeString();
@@ -143,11 +144,12 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
}
private String calculateReturnTypeString() {
final String qualifiedName = StringUtil.getQualifiedName(packageName, className);
final String qualifiedName = StringUtil.getQualifiedName(myPackageName, myClassName);
final StringBuilder returnTypeBuffer = new StringBuilder(qualifiedName);
if (!typeParams.isEmpty()) {
if (!myTypeParameters.isEmpty()) {
returnTypeBuffer.append('<');
returnTypeBuffer.append(StringUtil.join(typeParams, new Function<PsiTypeParameter, String>() {
returnTypeBuffer.append(StringUtil.join(myTypeParameters, new Function<PsiTypeParameter, String>() {
@Override
public String fun(final PsiTypeParameter typeParameter) {
final String paramName = typeParameter.getName();
LOG.assertTrue(paramName != null);
@@ -165,19 +167,19 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
final PsiClass existingClass = JavaPsiFacade.getInstance(myProject).findClass(myQualifiedName, GlobalSearchScope.allScope(myProject));
if (myUseExistingClass) {
if (existingClass == null) {
conflicts.putValue(existingClass, RefactorJBundle.message("could.not.find.selected.wrapping.class"));
conflicts.putValue(null, RefactorJBundle.message("could.not.find.selected.wrapping.class"));
}
else {
boolean foundConstructor = false;
final Set<PsiType> returnTypes = new HashSet<PsiType>();
returnTypes.add(method.getReturnType());
final PsiCodeBlock methodBody = method.getBody();
returnTypes.add(myMethod.getReturnType());
final PsiCodeBlock methodBody = myMethod.getBody();
if (methodBody != null) {
methodBody.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitReturnStatement(final PsiReturnStatement statement) {
super.visitReturnStatement(statement);
if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != method) return;
if (PsiTreeUtil.getParentOfType(statement, PsiMethod.class) != myMethod) return;
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null) {
returnTypes.add(returnValue.getType());
@@ -223,7 +225,7 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
conflicts.putValue(existingClass, "Existing class does not have appropriate constructor");
}
}
if (unwrapMethodName.length() == 0) {
if (myUnwrapMethodName.length() == 0) {
conflicts.putValue(existingClass,
"Existing class does not have getter for selected field");
}
@@ -232,28 +234,29 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
if (existingClass != null) {
conflicts.putValue(existingClass, RefactorJBundle.message("there.already.exists.a.class.with.the.selected.name"));
}
if (myMoveDestination != null && !myMoveDestination.isTargetAccessible(myProject, method.getContainingFile().getVirtualFile())) {
conflicts.putValue(method, "Created class won't be accessible in the call place");
if (myMoveDestination != null && !myMoveDestination.isTargetAccessible(myProject, myMethod.getContainingFile().getVirtualFile())) {
conflicts.putValue(myMethod, "Created class won't be accessible in the call place");
}
}
return showConflicts(conflicts, refUsages.get());
}
@Override
protected void performRefactoring(UsageInfo[] usageInfos) {
if (!myUseExistingClass && !buildClass()) return;
super.performRefactoring(usageInfos);
}
private boolean buildClass() {
final PsiManager manager = method.getManager();
final Project project = method.getProject();
final PsiManager manager = myMethod.getManager();
final Project project = myMethod.getProject();
final ReturnValueBeanBuilder beanClassBuilder = new ReturnValueBeanBuilder();
beanClassBuilder.setCodeStyleSettings(project);
beanClassBuilder.setTypeArguments(typeParams);
beanClassBuilder.setClassName(className);
beanClassBuilder.setPackageName(packageName);
beanClassBuilder.setStatic(myCreateInnerClass && method.hasModifierProperty(PsiModifier.STATIC));
final PsiType returnType = method.getReturnType();
beanClassBuilder.setProject(project);
beanClassBuilder.setTypeArguments(myTypeParameters);
beanClassBuilder.setClassName(myClassName);
beanClassBuilder.setPackageName(myPackageName);
beanClassBuilder.setStatic(myCreateInnerClass && myMethod.hasModifierProperty(PsiModifier.STATIC));
final PsiType returnType = myMethod.getReturnType();
beanClassBuilder.setValueType(returnType);
final String classString;
@@ -267,29 +270,32 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
try {
final PsiFileFactory factory = PsiFileFactory.getInstance(project);
final PsiJavaFile psiFile = (PsiJavaFile)factory.createFileFromText(className + ".java", JavaFileType.INSTANCE, classString);
final PsiJavaFile psiFile = (PsiJavaFile)factory.createFileFromText(myClassName + ".java", JavaFileType.INSTANCE, classString);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
if (myCreateInnerClass) {
final PsiClass containingClass = method.getContainingClass();
final PsiClass containingClass = myMethod.getContainingClass();
final PsiElement innerClass = containingClass.add(psiFile.getClasses()[0]);
JavaCodeStyleManager.getInstance(project).shortenClassReferences(innerClass);
} else {
final PsiFile containingFile = method.getContainingFile();
}
else {
final PsiFile containingFile = myMethod.getContainingFile();
final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
final PsiDirectory directory;
if (myMoveDestination != null) {
directory = myMoveDestination.getTargetDirectory(containingDirectory);
} else {
final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
directory = PackageUtil.findOrCreateDirectoryForPackage(module, packageName, containingDirectory, true, true);
}
else {
final Module module = ModuleUtilCore.findModuleForPsiElement(containingFile);
directory = PackageUtil.findOrCreateDirectoryForPackage(module, myPackageName, containingDirectory, true, true);
}
if (directory != null) {
final PsiElement shortenedFile = JavaCodeStyleManager.getInstance(project).shortenClassReferences(psiFile);
final PsiElement reformattedFile = codeStyleManager.reformat(shortenedFile);
directory.add(reformattedFile);
} else {
}
else {
return false;
}
}
@@ -302,8 +308,8 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
}
protected String getCommandName() {
final PsiClass containingClass = method.getContainingClass();
return RefactorJBundle.message("wrapped.return.command.name", className, containingClass.getName(), '.', method.getName());
final PsiClass containingClass = myMethod.getContainingClass();
return RefactorJBundle.message("wrapped.return.command.name", myClassName, containingClass.getName(), '.', myMethod.getName());
}
@@ -334,7 +340,7 @@ public class WrapReturnValueProcessor extends FixableUsagesRefactoringProcessor
if (callExpression.getArgumentList().getExpressions().length == 0) {
final PsiReferenceExpression callMethodExpression = callExpression.getMethodExpression();
final String methodName = callMethodExpression.getReferenceName();
if (Comparing.strEqual(unwrapMethodName, methodName)) {
if (Comparing.strEqual(myUnwrapMethodName, methodName)) {
final PsiExpression qualifier = callMethodExpression.getQualifierExpression();
if (qualifier != null) {
final PsiType qualifierType = qualifier.getType();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -23,19 +23,19 @@ import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
public class ChangeReturnType extends FixableUsageInfo {
@NotNull
private final PsiMethod method;
@NotNull
private final String type;
private final PsiMethod myMethod;
private final String myType;
public ChangeReturnType(@NotNull PsiMethod method, @NotNull String type) {
super(method);
this.type = type;
this.method = method;
}
public ChangeReturnType(@NotNull PsiMethod method, @NotNull String type) {
super(method);
myMethod = method;
myType = type;
}
public void fixUsage() throws IncorrectOperationException {
final PsiTypeElement returnType = method.getReturnTypeElement();
MutationUtils.replaceType(type, returnType);
}
@Override
public void fixUsage() throws IncorrectOperationException {
PsiTypeElement returnType = myMethod.getReturnTypeElement();
assert returnType != null : myMethod;
MutationUtils.replaceType(myType, returnType);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -21,24 +21,21 @@ import com.intellij.psi.PsiReturnStatement;
import com.intellij.refactoring.psi.MutationUtils;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
public class ReturnWrappedValue extends FixableUsageInfo {
private final PsiReturnStatement statement;
private final PsiReturnStatement myStatement;
public ReturnWrappedValue(PsiReturnStatement statement) {
super(statement);
this.statement = statement;
}
public ReturnWrappedValue(PsiReturnStatement statement) {
super(statement);
myStatement = statement;
}
public void fixUsage() throws IncorrectOperationException{
final PsiMethodCallExpression returnValue =
(PsiMethodCallExpression) statement.getReturnValue();
assert returnValue != null;
final PsiExpression qualifier =
returnValue.getMethodExpression().getQualifierExpression();
assert qualifier != null;
@NonNls final String newExpression = qualifier.getText();
MutationUtils.replaceExpression(newExpression, returnValue);
}
@Override
public void fixUsage() throws IncorrectOperationException {
PsiMethodCallExpression returnValue = (PsiMethodCallExpression)myStatement.getReturnValue();
assert returnValue != null;
PsiExpression qualifier = returnValue.getMethodExpression().getQualifierExpression();
assert qualifier != null;
MutationUtils.replaceExpression(qualifier.getText(), returnValue);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -19,23 +19,21 @@ import com.intellij.psi.PsiCallExpression;
import com.intellij.refactoring.psi.MutationUtils;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class UnwrapCall extends FixableUsageInfo {
@NotNull
private final PsiCallExpression call;
@NotNull
private final String unwrapMethod;
private final PsiCallExpression myCall;
private final String myUnwrapMethod;
public UnwrapCall(@NotNull PsiCallExpression call, @NotNull String unwrapMethod) {
super(call);
this.call =call;
this.unwrapMethod = unwrapMethod;
}
public UnwrapCall(@NotNull PsiCallExpression call, @NotNull String unwrapMethod) {
super(call);
myCall = call;
myUnwrapMethod = unwrapMethod;
}
public void fixUsage() throws IncorrectOperationException {
@NonNls final String newExpression = call.getText() + '.' + unwrapMethod +"()";
MutationUtils.replaceExpression(newExpression, call);
}
@Override
public void fixUsage() throws IncorrectOperationException {
String newExpression = myCall.getText() + '.' + myUnwrapMethod + "()";
MutationUtils.replaceExpression(newExpression, myCall);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -20,23 +20,23 @@ import com.intellij.psi.PsiReturnStatement;
import com.intellij.refactoring.psi.MutationUtils;
import com.intellij.refactoring.util.FixableUsageInfo;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class WrapReturnValue extends FixableUsageInfo {
private final PsiReturnStatement statement;
private final String type;
private final PsiReturnStatement myStatement;
private final String myType;
public WrapReturnValue(PsiReturnStatement statement, String type) {
super(statement);
this.type = type;
this.statement = statement;
}
public WrapReturnValue(@NotNull PsiReturnStatement statement, @NotNull String type) {
super(statement);
myStatement = statement;
myType = type;
}
public void fixUsage() throws IncorrectOperationException {
final PsiExpression returnValue = statement.getReturnValue();
assert returnValue != null;
@NonNls final String newExpression =
"new " + type + '(' + returnValue.getText() + ')';
MutationUtils.replaceExpression(newExpression, returnValue);
}
@Override
public void fixUsage() throws IncorrectOperationException {
PsiExpression returnValue = myStatement.getReturnValue();
assert returnValue != null;
String newExpression = "new " + myType + '(' + returnValue.getText() + ')';
MutationUtils.replaceExpression(newExpression, returnValue);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* 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.
@@ -487,15 +487,17 @@ public class ExceptionUtil {
}
@NotNull
public static List<PsiClassType> getCloserExceptions(@NotNull final PsiResourceVariable resource) {
final PsiMethod method = PsiUtil.getResourceCloserMethod(resource);
return method != null ? getExceptionsByMethod(method, PsiSubstitutor.EMPTY) : Collections.<PsiClassType>emptyList();
public static List<PsiClassType> getCloserExceptions(@NotNull PsiResourceVariable resource) {
PsiMethod method = PsiUtil.getResourceCloserMethod(resource);
PsiSubstitutor substitutor = PsiUtil.resolveGenericsClassInType(resource.getType()).getSubstitutor();
return method != null ? getExceptionsByMethod(method, substitutor) : Collections.<PsiClassType>emptyList();
}
@NotNull
public static List<PsiClassType> getUnhandledCloserExceptions(@NotNull final PsiResourceVariable resource, @Nullable final PsiElement topElement) {
final PsiMethod method = PsiUtil.getResourceCloserMethod(resource);
return method != null ? getUnhandledExceptions(method, resource, topElement, PsiSubstitutor.EMPTY) : Collections.<PsiClassType>emptyList();
public static List<PsiClassType> getUnhandledCloserExceptions(@NotNull PsiResourceVariable resource, @Nullable PsiElement topElement) {
PsiMethod method = PsiUtil.getResourceCloserMethod(resource);
PsiSubstitutor substitutor = PsiUtil.resolveGenericsClassInType(resource.getType()).getSubstitutor();
return method != null ? getUnhandledExceptions(method, resource, topElement, substitutor) : Collections.<PsiClassType>emptyList();
}
@NotNull
@@ -294,7 +294,7 @@ public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements Ps
@Override
public PsiParameter createParameter(@NotNull @NonNls String name, PsiType type, PsiElement context) throws IncorrectOperationException {
final PsiMethod psiMethod = createMethodFromText("void f(" + type.getCanonicalText() + " " + name + ") {}", context);
final PsiMethod psiMethod = createMethodFromText("void f(" + type.getCanonicalText(true) + " " + name + ") {}", context);
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
return parameters[0];
}
@@ -762,7 +762,7 @@ public class PsiImplUtil {
private static final Key<Boolean> TYPE_ANNO_MARK = Key.create("type.annotation.mark");
public static void markTypeAnnotations(@NotNull PsiTypeElement typeElement) {
PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class);
PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class);
if (left instanceof PsiModifierList) {
for (PsiAnnotation annotation : ((PsiModifierList)left).getAnnotations()) {
if (isTypeAnnotation(annotation)) {
@@ -773,7 +773,7 @@ public class PsiImplUtil {
}
public static void deleteTypeAnnotations(@NotNull PsiTypeElement typeElement) {
PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiAnnotation.class);
PsiElement left = PsiTreeUtil.skipSiblingsBackward(typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class);
if (left instanceof PsiModifierList) {
for (PsiAnnotation annotation : ((PsiModifierList)left).getAnnotations()) {
if (TYPE_ANNO_MARK.get(annotation) == Boolean.TRUE) {
@@ -1,18 +1,3 @@
/*
* Copyright 2000-2012 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.
*/
class C {
static class E extends Exception { }
static class E1 extends E { }
@@ -25,7 +10,15 @@ class C {
@Override public void close() throws E3 { }
}
static interface I extends AutoCloseable { }
interface I extends AutoCloseable { }
interface Gen<E extends Exception> extends AutoCloseable {
@Override void close() throws E;
class Impl implements Gen<E2> {
@Override public void close() throws E2 { }
}
}
void m1() {
try (MyResource r = new MyResource()) { r.doSomething(); }
@@ -90,4 +83,8 @@ class C {
MyResource r;
try (MyResource r1 = <error descr="Variable 'r' might not have been initialized">r</error>) { }
}
void m5() {
try (<error descr="Unhandled exception from auto-closeable resource: C.E2">Gen<E2> gen = new Gen.Impl()</error>) { }
}
}
@@ -0,0 +1,17 @@
// "Implement Methods" "true"
import java.lang.annotation.*;
import java.util.*;
@Target(ElementType.TYPE_USE)
@interface TA { int value() default 0; }
interface I {
@TA List<@TA String> i(@TA int p1, @TA(1) int @TA(2) [] p2 @TA(3) []) throws @TA IllegalArgumentException;
}
class C implements I {
@Override
public @TA List<@TA String> i(@TA int p1, @TA(1) int @TA(2) [] @TA(3) [] p2) throws @TA IllegalArgumentException {
return null;
}
}
@@ -0,0 +1,13 @@
// "Implement Methods" "true"
import java.lang.annotation.*;
import java.util.*;
@Target(ElementType.TYPE_USE)
@interface TA { int value() default 0; }
interface I {
@TA List<@TA String> i(@TA int p1, @TA(1) int @TA(2) [] p2 @TA(3) []) throws @TA IllegalArgumentException;
}
<caret>class C implements I {
}
@@ -5,9 +5,7 @@ public class Wrapper<T> {
this.value = value;
}
public T getValue() {
return value;
}
}
@@ -1,5 +1,5 @@
abstract class Test {
abstract Wrapper foo();
abstract Wrapper foo();
public class Wrapper {
private final String value;
@@ -8,10 +8,8 @@ abstract class Test {
this.value = value;
}
public String getValue() {
return value;
}
}
}
@@ -1,3 +1,3 @@
abstract class Test {
abstract String foo();
abstract String foo();
}
@@ -1,11 +1,11 @@
class Test {
Wrapper foo() {
return new Wrapper("");
}
return new Wrapper("");
}
void bar() {
String s = foo().getValue();
}
void bar() {
String s = foo().getValue();
}
public class Wrapper {
private final String value;
@@ -14,10 +14,8 @@ class Test {
this.value = value;
}
public String getValue() {
return value;
}
}
}
@@ -1,9 +1,9 @@
class Test {
String foo() {
return "";
}
String foo() {
return "";
}
void bar() {
String s = foo();
}
void bar() {
String s = foo();
}
}
@@ -1,9 +1,9 @@
class Test {
Wrapper foo() {
return new Wrapper((o) -> {
return 0;
});
}
return new Wrapper((o) -> {
return 0;
});
}
public class Wrapper {
private final Comparable<String> value;
@@ -12,10 +12,8 @@ class Test {
this.value = value;
}
public Comparable<String> getValue() {
return value;
}
}
}
@@ -1,7 +1,7 @@
class Test {
Comparable<String> foo() {
return (o) -> {
return 0;
};
}
Comparable<String> foo() {
return (o) -> {
return 0;
};
}
}
@@ -5,9 +5,7 @@ public class Wrapper {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -1,11 +1,11 @@
class Test {
static Wrapper foo() {
return new Wrapper("");
}
static Wrapper foo() {
return new Wrapper("");
}
void bar() {
String s = foo().getValue();
}
void bar() {
String s = foo().getValue();
}
public static class Wrapper {
private final String value;
@@ -14,10 +14,8 @@ class Test {
this.value = value;
}
public String getValue() {
return value;
}
}
}
@@ -1,9 +1,9 @@
class Test {
static String foo() {
return "";
}
static String foo() {
return "";
}
void bar() {
String s = foo();
}
void bar() {
String s = foo();
}
}
@@ -0,0 +1,10 @@
import java.lang.annotation.*;
@Target({ElementType.TYPE_USE})
@interface TA { }
class Test {
Wrapper foo() {
return new Wrapper(null);
}
}
@@ -0,0 +1,13 @@
import java.util.List;
public class Wrapper {
private final List<String> value;
public Wrapper(@TA List<@TA String> value) {
this.value = value;
}
public @TA List<@TA String> getValue() {
return value;
}
}
@@ -0,0 +1,11 @@
import java.lang.annotation.*;
import java.util.*;
@Target({ElementType.TYPE_USE})
@interface TA { }
class Test {
@TA List<@TA String> foo() {
return null;
}
}
@@ -133,8 +133,7 @@ import java.util.Collection;
@Target(ElementType.TYPE_USE) @interface TA { }
class Test {
@TA
Collection<caret> c;
@TA Collection<caret> c;
}
'''
}
@@ -157,8 +156,7 @@ import java.util.Collection;
@Target(ElementType.TYPE_USE) @interface TA { }
class Test {
@TA
Collection<caret> c;
@TA Collection<caret> c;
}
'''
}
@@ -15,11 +15,14 @@
*/
package com.intellij.psi.formatter.java;
import com.intellij.idea.Bombed;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import java.util.Calendar;
/**
* Is intended to hold specific java formatting tests for 'wrapping' settings.
*
@@ -242,6 +245,7 @@ public class JavaFormatterWrapTest extends AbstractJavaFormatterTest {
);
}
@Bombed(user = "Roman Shevchenko", year = 2014, month = Calendar.MARCH, day = 14)
public void testWrapMethodAnnotationBeforeParams() {
// Inspired by IDEA-59536
getSettings().getRootSettings().RIGHT_MARGIN = 90;
@@ -251,8 +255,7 @@ public class JavaFormatterWrapTest extends AbstractJavaFormatterTest {
doClassTest(
"@SuppressWarnings({\"SomeInspectionIWantToIgnore\"}) public void doSomething(int x, int y) {}",
"@SuppressWarnings({\"SomeInspectionIWantToIgnore\"})\n" +
"public void doSomething(int x, int y) {" +
"\n}"
"public void doSomething(int x, int y) {\n}"
);
}
@@ -399,4 +402,34 @@ public class JavaFormatterWrapTest extends AbstractJavaFormatterTest {
doMethodTest(before, after);
}
public void testFieldAnnotationWithoutModifier() {
doClassTest("@NotNull String myFoo = null;", "@NotNull\nString myFoo = null;");
}
public void testTypeAnnotationsInModifierList() {
getSettings().getRootSettings().FORMATTER_TAGS_ENABLED = true;
String prefix =
"import java.lang.annotation.*;\n\n" +
"//@formatter:off\n" +
"@interface A { }\n" +
"@Target({ElementType.TYPE_USE}) @interface TA { int value() default 0; }\n" +
"//@formatter:on\n\n";
doTextTest(
prefix + "interface C {\n" +
" @TA(0)String m();\n" +
" @A @TA(1) @TA(2)String m();\n" +
" @A public @TA String m();\n" +
"}",
prefix + "interface C {\n" +
" @TA(0) String m();\n\n" +
" @A\n" +
" @TA(1) @TA(2) String m();\n\n" +
" @A\n" +
" public @TA String m();\n" +
"}");
}
}
@@ -13,11 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* User: anna
* Date: 20-Aug-2008
*/
package com.intellij.refactoring;
import com.intellij.openapi.vfs.VirtualFile;
@@ -30,7 +25,10 @@ import com.intellij.JavaTestUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class WrapReturnValueTest extends MultiFileTestCase{
/**
* @author anna
*/
public class WrapReturnValueTest extends MultiFileTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
@@ -42,39 +40,43 @@ public class WrapReturnValueTest extends MultiFileTestCase{
return "/refactoring/wrapReturnValue/";
}
private void doTest(final boolean existing) throws Exception {
public void testSimple() { doTest(false); }
public void testGenerics() { doTest(false); }
public void testInconsistentWrapper() { doTest(true, "Existing class does not have getter for selected field"); }
public void testWrapper() { doTest(true); }
public void testStrip() { doTest(true); }
public void testNoConstructor() { doTest(true, "Existing class does not have appropriate constructor"); }
public void testInnerClass() { doTest(false, null, true); }
public void testHierarchy() { doTest(false, null, true); }
public void testAnonymous() { doTest(true, null, false); }
public void testWrongFieldAssignment() { doTest(true, "Existing class does not have appropriate constructor", false); }
public void testWrongFieldType() { doTest(true, "Existing class does not have appropriate constructor", false); }
public void testStaticMethodInnerClass() { doTest(false, null, true); }
public void testRawReturnType() { doTest(true, "Existing class does not have appropriate constructor"); }
public void testReturnInsideLambda() { doTest(false, null, true); }
public void testTypeAnnotations() { doTest(false); }
private void doTest(final boolean existing) {
doTest(existing, null);
}
private void doTest(final boolean existing, @NonNls String exceptionMessage) throws Exception {
private void doTest(final boolean existing, @NonNls String exceptionMessage) {
doTest(existing, exceptionMessage, false);
}
private void doTest(final boolean existing, String exceptionMessage, final boolean createInnerClass) throws Exception {
private void doTest(final boolean existing, String exceptionMessage, final boolean createInnerClass) {
try {
doTest(new PerformAction() {
@Override
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) throws Exception {
public void performAction(final VirtualFile rootDir, final VirtualFile rootAfter) {
PsiClass aClass = myJavaFacade.findClass("Test", GlobalSearchScope.projectScope(getProject()));
assertNotNull("Class Test not found", aClass);
final PsiMethod method = aClass.findMethodsByName("foo", false)[0];
@NonNls final String wrapperClassName = "Wrapper";
final PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject()));
PsiMethod method = aClass.findMethodsByName("foo", false)[0];
String wrapperClassName = "Wrapper";
PsiClass wrapperClass = myJavaFacade.findClass(wrapperClassName, GlobalSearchScope.projectScope(getProject()));
assertTrue(!existing || wrapperClass != null);
final PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null;
WrapReturnValueProcessor processor = new WrapReturnValueProcessor(wrapperClassName, "",
null, method, existing, createInnerClass,
delegateField);
processor.run();
/*LocalFileSystem.getInstance().refresh(false);
FileDocumentManager.getInstance().saveAllDocuments();*/
PsiField delegateField = existing ? wrapperClass.findFieldByName("myField", false) : null;
new WrapReturnValueProcessor(wrapperClassName, "", null, method, existing, createInnerClass, delegateField).run();
}
});
}
@@ -89,61 +91,4 @@ public class WrapReturnValueTest extends MultiFileTestCase{
fail("Conflict was not found");
}
}
public void testSimple() throws Exception {
doTest(false);
}
public void testGenerics() throws Exception {
doTest(false);
}
public void testInconsistentWrapper() throws Exception {
doTest(true, "Existing class does not have getter for selected field");
}
public void testWrapper() throws Exception {
doTest(true);
}
public void testStrip() throws Exception {
doTest(true);
}
public void testNoConstructor() throws Exception {
doTest(true, "Existing class does not have appropriate constructor");
}
public void testInnerClass() throws Exception {
doTest(false, null, true);
}
public void testHierarchy() throws Exception {
doTest(false, null, true);
}
public void testAnonymous() throws Exception {
doTest(true, null, false);
}
public void testWrongFieldAssignment() throws Exception {
doTest(true, "Existing class does not have appropriate constructor", false);
}
public void testWrongFieldType() throws Exception {
doTest(true, "Existing class does not have appropriate constructor", false);
}
public void testStaticMethodInnerClass() throws Exception {
doTest(false, null, true);
}
public void testRawReturnType() throws Exception {
doTest(true, "Existing class does not have appropriate constructor");
}
public void testReturnInsideLambda() throws Exception {
doTest(false, null, true);
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -12,7 +12,7 @@ httpcore-4.3.1.jar
httpclient-4.3.2.jar
fluent-hc-4.3.2.jar
httpmime-4.3.2.jar
ecj-4.2.1.jar
ecj-4.3.2.jar
groovy-all-2.2.1.jar
gson-2.2.4.jar
guava-14.0.1.jar
Binary file not shown.
Binary file not shown.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* 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.
@@ -22,7 +22,6 @@ package com.intellij.formatting;
*
* @see com.intellij.formatting.Block#getWrap()
*/
public abstract class Wrap {
/**
* Converts a low-priority wrap setting to a regular wrap setting.
@@ -32,29 +31,20 @@ public abstract class Wrap {
private static WrapFactory myFactory;
/**
* @deprecated use {@link WrapType#ALWAYS} instead
*/
@Deprecated
/** @deprecated use {@link WrapType#ALWAYS} (to remove in IDEA 14) */
@SuppressWarnings({"UnusedDeclaration"})
public static WrapType ALWAYS = WrapType.ALWAYS;
/**
* @deprecated use {@link WrapType#NORMAL} instead
*/
@Deprecated
/** @deprecated use {@link WrapType#NORMAL} (to remove in IDEA 14) */
@SuppressWarnings({"UnusedDeclaration"})
public static WrapType NORMAL = WrapType.NORMAL;
/**
* @deprecated use {@link WrapType#NONE} instead
*/
@Deprecated
/** @deprecated use {@link WrapType#NONE} (to remove in IDEA 14) */
@SuppressWarnings({"UnusedDeclaration"})
public static WrapType NONE = WrapType.NONE;
/**
* @deprecated use {@link WrapType#CHOP_DOWN_IF_LONG} instead
*/
/** @deprecated use {@link WrapType#CHOP_DOWN_IF_LONG} (to remove in IDEA 14) */
@SuppressWarnings({"UnusedDeclaration"})
@Deprecated
public static WrapType CHOP_DOWN_IF_LONG = WrapType.CHOP_DOWN_IF_LONG;
static void setFactory(WrapFactory factory) {
@@ -82,7 +72,7 @@ public abstract class Wrap {
* <p/>
* Example:
* <pre>
* |
* |
* foo(123, 4|56
* |
* | &lt;- right margin
@@ -121,10 +111,9 @@ public abstract class Wrap {
* @param wrapFirstElement if true, the first element in a sequence of elements of the same type
* is also wrapped.
* @return the wrap setting instance.
* @see #ignoreParentWraps()
* @see #ignoreParentWraps()
*/
public static Wrap createChildWrap(final Wrap parentWrap, final WrapType wrapType, final boolean wrapFirstElement) {
return myFactory.createChildWrap(parentWrap, wrapType, wrapFirstElement);
return myFactory.createChildWrap(parentWrap, wrapType, wrapFirstElement);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* 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.
@@ -19,7 +19,7 @@ package com.intellij.formatting;
* Internal interface for creating wrap setting instances.
*/
interface WrapFactory {
public Wrap createWrap(WrapType type, boolean wrapFirstElement);
Wrap createWrap(WrapType type, boolean wrapFirstElement);
public Wrap createChildWrap(final Wrap parentWrap, final WrapType wrapType, final boolean wrapFirstElement);
Wrap createChildWrap(Wrap parentWrap, WrapType wrapType, boolean wrapFirstElement);
}
@@ -18,31 +18,15 @@ package com.intellij.openapi.keymap.impl;
public class ShortcutRestrictions {
public static final ShortcutRestrictions NO_RESTRICTIONS = new ShortcutRestrictions(true, true, true, true);
private final boolean myAllowMouseShortcut;
private final boolean myAllowMouseDoubleClick;
private final boolean myAllowKeyboardShortcut;
private final boolean myAllowAbbreviation;
public final boolean allowMouseShortcut;
public final boolean allowMouseDoubleClick;
public final boolean allowKeyboardShortcut;
public final boolean allowAbbreviation;
public ShortcutRestrictions(boolean allowMouseShortcut, boolean allowMouseDoubleClick, boolean allowKeyboardShortcut, boolean allowAbbreviation) {
myAllowMouseShortcut = allowMouseShortcut;
myAllowMouseDoubleClick = allowMouseDoubleClick;
myAllowKeyboardShortcut = allowKeyboardShortcut;
myAllowAbbreviation = allowAbbreviation;
}
public boolean allowMouseShortcut() {
return myAllowMouseShortcut;
}
public boolean allowMouseDoubleClick() {
return myAllowMouseDoubleClick;
}
public boolean allowKeyboardShortcut() {
return myAllowKeyboardShortcut;
}
public boolean allowAbbreviation() {
return myAllowAbbreviation;
this.allowMouseShortcut = allowMouseShortcut;
this.allowMouseDoubleClick = allowMouseDoubleClick;
this.allowKeyboardShortcut = allowKeyboardShortcut;
this.allowAbbreviation = allowAbbreviation;
}
}
@@ -961,7 +961,7 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
final ShortcutRestrictions restrictions = ActionShortcutRestrictions.getForActionId(actionId);
if (restrictions.allowKeyboardShortcut()) {
if (restrictions.allowKeyboardShortcut) {
group.add(new DumbAwareAction("Add Keyboard Shortcut") {
@Override
public void actionPerformed(AnActionEvent e) {
@@ -978,7 +978,7 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
});
}
if (restrictions.allowMouseShortcut()) {
if (restrictions.allowMouseShortcut) {
group.add(new DumbAwareAction("Add Mouse Shortcut") {
@Override
public void actionPerformed(AnActionEvent e) {
@@ -994,7 +994,7 @@ public class KeymapPanel extends JPanel implements SearchableConfigurable, Confi
});
}
if (Registry.is("actionSystem.enableAbbreviations") && restrictions.allowAbbreviation()) {
if (Registry.is("actionSystem.enableAbbreviations") && restrictions.allowAbbreviation) {
group.add(new DumbAwareAction("Add Abbreviation") {
@Override
public void actionPerformed(AnActionEvent e) {
@@ -101,7 +101,7 @@ class MouseShortcutDialog extends DialogWrapper{
myModifiers=-1;
}
myRbDoubleClick.setEnabled(restrictions.allowMouseDoubleClick());
myRbDoubleClick.setEnabled(restrictions.allowMouseDoubleClick);
updatePreviewAndConflicts();