IDEA-19061 Integrate the Rearranger-plugin into core-IDEA

*) 'groovy' dependency is added to the 'rearranger' module;
*) RearrangerTest is re-written to groovy;
*) refactorings;
This commit is contained in:
Denis.Zhdanov
2012-05-15 15:56:45 +04:00
parent e2917706cf
commit a10da2400a
43 changed files with 728 additions and 721 deletions
+1
View File
@@ -17,6 +17,7 @@
<orderEntry type="module" module-name="java-impl" scope="TEST" />
<orderEntry type="module" module-name="testFramework-java" scope="TEST" />
<orderEntry type="module" module-name="idea-ui" />
<orderEntry type="library" name="Groovy" level="project" />
</component>
</module>
@@ -152,7 +152,7 @@ public final class RearrangerActionHandler extends EditorActionHandler {
wb.whenTrue();
}
catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
e.printStackTrace();
}
LOG.debug("end execute");
}
@@ -186,7 +186,7 @@ public final class RearrangerActionHandler extends EditorActionHandler {
}
LOG.debug("respacing document");
PsiDocumentManager.getInstance(project).commitDocument(document);
Spacer spacer = new Spacer(project, psiFile, document, settings);
Spacer spacer = new Spacer(psiFile, document, settings);
if (spacer.respace()) {
PsiDocumentManager.getInstance(project).commitDocument(document);
}
@@ -26,6 +26,7 @@ import com.intellij.psi.PsiField;
import com.wrq.rearranger.popup.FilePopupEntry;
import com.wrq.rearranger.popup.RearrangerTreeNode;
import com.wrq.rearranger.settings.RearrangerSettings;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
@@ -37,18 +38,18 @@ public abstract class ClassContentsEntry
extends RangeEntry
implements FilePopupEntry
{
public ClassContentsEntry(final PsiElement start,
final PsiElement end,
public ClassContentsEntry(@Nullable final PsiElement start,
@Nullable final PsiElement end,
final int modifiers,
final String modifierString,
final String name,
final @Nullable String name,
final String type)
{
super(start, end, modifiers, modifierString, name, type);
}
public ClassContentsEntry(final PsiElement start,
final PsiElement end,
public ClassContentsEntry(@Nullable final PsiElement start,
@Nullable final PsiElement end,
final boolean fixedHeader,
final boolean fixedTrailer)
{
@@ -57,10 +58,10 @@ public abstract class ClassContentsEntry
public DefaultMutableTreeNode addToPopupTree(DefaultMutableTreeNode parent, RearrangerSettings settings) {
DefaultMutableTreeNode node = null;
if ((end instanceof PsiField && settings.isShowFields()) ||
if ((myEnd instanceof PsiField && settings.isShowFields()) ||
(this instanceof ClassEntry))
{
node = new RearrangerTreeNode(this, name);
node = new RearrangerTreeNode(this, myName);
parent.add(node);
}
return node;
@@ -35,6 +35,8 @@ import com.wrq.rearranger.rearrangement.GenericRearranger;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.util.ModifierUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
@@ -48,36 +50,33 @@ import java.util.List;
* Describes an entire class's range and type.
* This information is used when reordering outer classes.
*/
public class ClassEntry
extends ClassContentsEntry
implements FilePopupEntry
{
public class ClassEntry extends ClassContentsEntry implements FilePopupEntry {
private static final Logger LOG = Logger.getInstance("#" + ClassEntry.class.getName());
protected final List<ClassContentsEntry> contents;
private List<RuleInstance> myResultRuleInstances;
private final RearrangerSettings settings;
private final int nestingLevel;
protected final List<ClassContentsEntry> myContents;
private List<RuleInstance> myResultRuleInstances;
private final RearrangerSettings mySettings;
private final int myNestingLevel;
public ClassEntry(PsiElement start,
PsiElement end,
public ClassEntry(@Nullable PsiElement start,
@Nullable PsiElement end,
int modifiers,
String modifierString,
String name,
@Nullable String name,
int nestingLevel,
RearrangerSettings settings)
{
RearrangerSettings settings) {
super(start, end, modifiers, modifierString, name, "");
contents = new ArrayList<ClassContentsEntry>();
myContents = new ArrayList<ClassContentsEntry>();
myResultRuleInstances = null;
this.settings = settings;
this.nestingLevel = nestingLevel;
mySettings = settings;
myNestingLevel = nestingLevel;
}
public String getTypeIconName() {
String result = "nodes/class";
if (end.getParent() instanceof PsiClass) {
PsiClass psiClass = (PsiClass)end.getParent();
if (myEnd.getParent() instanceof PsiClass) {
PsiClass psiClass = (PsiClass)myEnd.getParent();
if (psiClass.isEnum()) {
result = "nodes/enum";
}
@@ -89,15 +88,20 @@ public class ClassEntry
}
public String[] getAdditionalIconNames() {
if (end instanceof PsiJavaToken && end.getText().equals("{")) {
PsiClass psiClass = (PsiClass)end.getParent();
if (psiClass.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
if (myEnd instanceof PsiJavaToken && myEnd.getText().equals("{")) {
PsiClass psiClass = (PsiClass)myEnd.getParent();
final PsiModifierList modifierList = psiClass.getModifierList();
if (modifierList == null) {
return null;
}
if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) {
return new String[]{"nodes/c_public"};
}
if (psiClass.getModifierList().hasModifierProperty(PsiModifier.PROTECTED)) {
if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) {
return new String[]{"nodes/c_protected"};
}
if (psiClass.getModifierList().hasModifierProperty(PsiModifier.PRIVATE)) {
if (modifierList.hasModifierProperty(PsiModifier.PRIVATE)) {
return new String[]{"nodes/c_private"};
}
return new String[]{"nodes/c_plocal"};
@@ -106,20 +110,19 @@ public class ClassEntry
}
public JLabel getPopupEntryText(RearrangerSettings settings) {
return new JLabel(name);
return new JLabel(myName);
}
protected void parseRemainingClassContents(final Project project,
int startingIndex,
final PsiElement psiClass
)
{
) {
final PsiSearchHelper psh = PsiSearchHelper.SERVICE.getInstance(project);
int lastIndex = startingIndex;
/**
* if option indicates, don't parse inner class contents; leave them unchanged.
*/
if (settings.isRearrangeInnerClasses() || nestingLevel <= 1) {
if (mySettings.isRearrangeInnerClasses() || myNestingLevel <= 1) {
for (int i = startingIndex; i < psiClass.getChildren().length; i++) {
PsiElement child = psiClass.getChildren()[i];
if (child instanceof PsiJavaToken && child.getText().equals("{")) {
@@ -163,7 +166,7 @@ public class ClassEntry
);
}
if (child instanceof PsiClass) {
parseClassAttributes(child, attributes);
parseClassAttributes((PsiClass)child, attributes);
//
// if child is an enum, set the last entry past the LBrace to the final enumeration or the
// semicolon thereafter, if any.
@@ -189,8 +192,8 @@ public class ClassEntry
attributes.modifiers,
attributes.modifierString,
attributes.name,
nestingLevel + 1,
settings
myNestingLevel + 1,
mySettings
);
classContentsEntry = entry;
entry.parseRemainingClassContents(
@@ -206,7 +209,7 @@ public class ClassEntry
attributes.modifierString,
attributes.name);
}
contents.add(classContentsEntry);
myContents.add(classContentsEntry);
classContentsEntry.checkForComment();
lastIndex = i + 1; // next class includes everything since the end of the prior class.
}
@@ -222,7 +225,7 @@ public class ClassEntry
psiClass.getChildren()[psiClass.getChildren().length - 1],
false, true
);
contents.add(miscellaneousTextEntry);
myContents.add(miscellaneousTextEntry);
miscellaneousTextEntry.checkForComment();
}
}
@@ -467,13 +470,16 @@ public class ClassEntry
}
}
private void parseClassAttributes(PsiElement child, MemberAttributes attributes) {
attributes.childClass = (PsiClass)child;
private static void parseClassAttributes(@NotNull PsiClass child, @NotNull MemberAttributes attributes) {
attributes.childClass = child;
attributes.name = attributes.childClass.getName();
if (attributes.name == null) {
attributes.name = "";
}
attributes.modifierString = attributes.childClass.getModifierList().getText();
final PsiModifierList modifierList = child.getModifierList();
if (modifierList != null) {
attributes.modifierString = modifierList.getText();
}
attributes.modifiers = ModifierUtils.getModifierMask(attributes.modifierString);
attributes.type = attributes.childClass.isEnum() ? "enum" : "class";
if (attributes.childClass.isEnum()) {
@@ -514,14 +520,14 @@ public class ClassEntry
LOG.debug("identifying setters and extracted (related) methods");
for (ClassContentsEntry contentsEntry : getContents()) {
if (contentsEntry instanceof IRelatableEntry) {
((IRelatableEntry)contentsEntry).determineSettersAndMethodCalls(settings, getContents());
if (contentsEntry instanceof RelatableEntry) {
((RelatableEntry)contentsEntry).determineSettersAndMethodCalls(mySettings, getContents());
}
}
LOG.debug("relating extracted methods");
for (ClassContentsEntry contentsEntry : getContents()) {
if (contentsEntry instanceof IRelatableEntry) {
((IRelatableEntry)contentsEntry).determineExtractedMethod(settings.getExtractedMethodsSettings());
if (contentsEntry instanceof RelatableEntry) {
((RelatableEntry)contentsEntry).determineExtractedMethod(mySettings.getExtractedMethodsSettings());
}
}
/**
@@ -532,18 +538,18 @@ public class ClassEntry
* check for overloaded extracted methods; if configured to be kept together, attach subsequent
* methods to the first and remove them from consideration for other alignment.
*/
MethodEntry.handleOverloadedMethods(getContents(), settings);
MethodEntry.handleOverloadedMethods(getContents(), mySettings);
final GenericRearranger classContentsRearranger =
new GenericRearranger(settings.getItemOrderAttributeList(),
contents,
nestingLevel,
settings)
new GenericRearranger(mySettings.getItemOrderAttributeList(),
myContents,
myNestingLevel,
mySettings)
{
public void rearrangeRelatedItems(List<ClassContentsEntry> entries,
List<RuleInstance> ruleInstanceList)
{
for (RuleInstance ruleInstance : ruleInstanceList) {
ruleInstance.rearrangeRuleItems(entries, settings);
ruleInstance.rearrangeRuleItems(entries, mySettings);
}
}
};
@@ -551,13 +557,13 @@ public class ClassEntry
}
private void buildMethodCallGraph() {
if (settings.getExtractedMethodsSettings().isMoveExtractedMethods() ||
settings.isKeepGettersSettersTogether())
if (mySettings.getExtractedMethodsSettings().isMoveExtractedMethods() ||
mySettings.isKeepGettersSettersTogether())
{
LOG.debug("building method call & getter-setter graph");
for (ClassContentsEntry contentsEntry : getContents()) {
if (contentsEntry instanceof IRelatableEntry) {
((IRelatableEntry)contentsEntry).determineGetterSetterAndExtractedMethodStatus(settings);
if (contentsEntry instanceof RelatableEntry) {
((RelatableEntry)contentsEntry).determineGetterSetterAndExtractedMethodStatus(mySettings);
}
}
}
@@ -566,7 +572,7 @@ public class ClassEntry
// End Methods of Interface IFilePopupEntry
public final List<ClassContentsEntry> getContents() {
return contents;
return myContents;
}
public List<RuleInstance> getResultRuleInstances() {
@@ -61,7 +61,7 @@ public class ClassInitializerEntry
public DefaultMutableTreeNode addToPopupTree(DefaultMutableTreeNode parent, RearrangerSettings settings) {
LOG.debug("add class initializer to popup tree");
DefaultMutableTreeNode node = new RearrangerTreeNode(this, name);
DefaultMutableTreeNode node = new RearrangerTreeNode(this, myName);
parent.add(node);
return node;
}
@@ -54,16 +54,16 @@ public class FieldEntry
}
public String getTypeIconName() {
if (end instanceof PsiField) {
PsiField f = (PsiField)end;
if (myEnd instanceof PsiField) {
PsiField f = (PsiField)myEnd;
return ((PsiModifierList)f.getModifierList()).hasModifierProperty(PsiModifier.STATIC) ? "nodes/staticField" : "nodes/field";
}
return null;
}
public String[] getAdditionalIconNames() {
if (end instanceof PsiField) {
PsiField f = (PsiField)end;
if (myEnd instanceof PsiField) {
PsiField f = (PsiField)myEnd;
if (f.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) return new String[]{"nodes/c_public"};
if (f.getModifierList().hasModifierProperty(PsiModifier.PROTECTED)) return new String[]{"nodes/c_protected"};
if (f.getModifierList().hasModifierProperty(PsiModifier.PRIVATE)) return new String[]{"nodes/c_private"};
@@ -74,7 +74,7 @@ public class FieldEntry
public JLabel getPopupEntryText(RearrangerSettings settings) {
StringBuffer name = new StringBuffer(80);
PsiField f = (PsiField)end;
PsiField f = (PsiField)myEnd;
name.append(f.getName());
name.append(": ");
name.append(f.getTypeElement().getText());
@@ -89,7 +89,7 @@ public class FieldEntry
DefaultMutableTreeNode node = super.addToPopupTree(parent, settings);
if (node != null && getterMethod != null) {
getterMethod.addToPopupTree(node, settings);
for (MethodEntry me : getterMethod.correspondingGetterSetters) {
for (MethodEntry me : getterMethod.myCorrespondingGetterSetters) {
me.addToPopupTree(node, settings);
}
}
@@ -47,7 +47,7 @@ import java.util.*;
*/
public class MethodEntry
extends ClassContentsEntry
implements IRelatableEntry
implements RelatableEntry
{
// ------------------------------ FIELDS ------------------------------
@@ -58,22 +58,23 @@ public class MethodEntry
* the corresponding setter will be placed in calledMethods. This allows the same code to rearrange both
* types of related methods.
*/
List<MethodEntry> calledMethods = new ArrayList<MethodEntry>();
List<MethodEntry> calledByMethods = new ArrayList<MethodEntry>();
List<MethodEntry> overloadedMethods = new ArrayList<MethodEntry>();
private final List<MethodEntry> myCalledMethods = new ArrayList<MethodEntry>();
private final List<MethodEntry> myCalledByMethods = new ArrayList<MethodEntry>();
private final List<MethodEntry> myOverloadedMethods = new ArrayList<MethodEntry>();
// MethodEntry correspondingSetter = null; // TODO - avoid wrong level for setters
List<MethodEntry> correspondingGetterSetters = new ArrayList<MethodEntry>();
private boolean keptWithProperty;
private boolean relatedMethod;
final List<MethodEntry> myCorrespondingGetterSetters = new ArrayList<MethodEntry>();
private boolean myKeptWithProperty;
private boolean myRelatedMethod;
/** @return true if the method is related to another. In this case, the method is exempt from rule matching. */
public boolean isRelatedMethod() {
return relatedMethod;
return myRelatedMethod;
}
/** @return true if the method is a setter and will be emitted below a corresponding getter. */
public boolean isEmittableSetter() {
return setter && correspondingGetterSetters.size() > 0;
return setter && myCorrespondingGetterSetters.size() > 0;
}
private boolean isOverloadedMethod;
@@ -151,16 +152,16 @@ public class MethodEntry
{
List<RangeEntry> parentEntries = new ArrayList<RangeEntry>(ruleInstance.getMatches());
for (RangeEntry o : parentEntries) {
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
if (me.isGetter()) {
if (me.keptWithProperty) {
if (me.myKeptWithProperty) {
if (me.getMatchedRule() != null && me.getMatchedRule().getMatches() != null) {
// prevent the getter from appearing under a rule it matches; it will be placed under the property
me.getMatchedRule().getMatches().remove(me);
}
}
for (MethodEntry theSetter : me.correspondingGetterSetters) {
for (MethodEntry theSetter : me.myCorrespondingGetterSetters) {
final RuleInstance theRule = theSetter.getMatchedRule();
LOG.debug(
"rearrangeRelatedItems: for getter method " +
@@ -173,7 +174,7 @@ public class MethodEntry
{
LOG.debug(
"remove entry " +
theSetter.end +
theSetter.myEnd +
" from matched rule" +
theRule +
"; matches = " +
@@ -183,15 +184,15 @@ public class MethodEntry
}
}
}
if (me.calledMethods.size() > 0) {
if (me.myCalledMethods.size() > 0) {
List<MethodEntry> parents = new LinkedList<MethodEntry>();
parents.add(me);
moveRelatedItems(
entries,
parents,
rms,
((PsiMethod)me.end).getName(),
((PsiMethod)me.end).getName() + "()",
((PsiMethod)me.myEnd).getName(),
((PsiMethod)me.myEnd).getName() + "()",
1
);
if (LOG.isDebugEnabled()) {
@@ -234,10 +235,10 @@ public class MethodEntry
ListIterator li = entries.listIterator();
while (li.hasNext()) {
Object o = li.next();
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
for (MethodEntry entry : parents) {
if (me.calledByMethods.contains(entry)) {
if (me.myCalledByMethods.contains(entry)) {
children.add(me);
li.remove();
break;
@@ -255,10 +256,10 @@ public class MethodEntry
ListIterator li = entries.listIterator();
while (li.hasNext()) {
Object o = li.next();
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
for (MethodEntry entry : parents) {
if (me.calledByMethods.contains(entry)) {
if (me.myCalledByMethods.contains(entry)) {
me.insertAlphabetically(children);
li.remove();
break;
@@ -274,7 +275,7 @@ public class MethodEntry
* Add these to the list of children in order of invocation.
*/
for (MethodEntry me : parents) {
for (MethodEntry child : me.calledMethods) {
for (MethodEntry child : me.myCalledMethods) {
if (entries.contains(child)) {
children.add(child);
entries.remove(child);
@@ -292,7 +293,7 @@ public class MethodEntry
if (children.size() > 0) {
if (rms.isDepthFirstOrdering()) {
for (MethodEntry entry : children) {
if (entry.calledMethods.size() == 0) {
if (entry.myCalledMethods.size() == 0) {
continue;
}
List<MethodEntry> parent = new LinkedList<MethodEntry>();
@@ -302,7 +303,7 @@ public class MethodEntry
parent,
rms,
topLevelMethodName,
allMethodNames + "." + ((PsiMethod)entry.end).getName() + "()",
allMethodNames + "." + ((PsiMethod)entry.myEnd).getName() + "()",
level + 1
);
}
@@ -336,7 +337,7 @@ public class MethodEntry
allMN.append(",");
}
first = false;
allMN.append(((PsiMethod)entry.end).getName());
allMN.append(((PsiMethod)entry.myEnd).getName());
}
}
if (parents.size() > 1) {
@@ -348,11 +349,11 @@ public class MethodEntry
public void insertAlphabetically(final List<MethodEntry> list) {
Comparator<MethodEntry> comparator = new Comparator<MethodEntry>() {
public int compare(MethodEntry me, MethodEntry me2) {
String s = ((PsiMethod)me.end).getName();
String s = ((PsiMethod)me.myEnd).getName();
if (me.isGetter()) {
s = MethodUtil.getPropertyName((PsiMethod)me.end);
s = MethodUtil.getPropertyName((PsiMethod)me.myEnd);
}
return s.compareTo(((PsiMethod)me2.end).getName());
return s.compareTo(((PsiMethod)me2.myEnd).getName());
}
};
insertInList(list, comparator);
@@ -365,7 +366,7 @@ public class MethodEntry
MethodEntry entry = ((MethodEntry)li.next());
if (comparator.compare(this, entry) < 0) {
LOG.debug(
"insertInList dependent method: add " + end.toString() + " at index " + (li.nextIndex() - 1)
"insertInList dependent method: add " + myEnd.toString() + " at index " + (li.nextIndex() - 1)
);
list.add(li.nextIndex() - 1, this);
inserted = true;
@@ -377,7 +378,7 @@ public class MethodEntry
}
void dumpChild(int level) {
LOG.debug(level + ": " + ((PsiMethod)end).getName());
LOG.debug(level + ": " + ((PsiMethod)myEnd).getName());
for (MethodEntry methodEntry : sortedMethods) {
methodEntry.dumpChild(level + 1);
}
@@ -397,7 +398,7 @@ public class MethodEntry
*/
public static void eliminateCycles(List<ClassContentsEntry> contents) {
for (ClassContentsEntry entry : contents) {
if (entry instanceof IRelatableEntry) {
if (entry instanceof RelatableEntry) {
MethodEntry current = (MethodEntry)entry;
List<MethodEntry> set = new LinkedList<MethodEntry>();
set.add(current);
@@ -407,13 +408,13 @@ public class MethodEntry
}
private static void test(MethodEntry current, List<MethodEntry> set) {
Iterator<MethodEntry> it = current.calledMethods.iterator();
Iterator<MethodEntry> it = current.myCalledMethods.iterator();
while (it.hasNext()) {
MethodEntry callee = it.next();
if (set.contains(callee)) {
callee.calledByMethods.remove(current);
if (callee.calledByMethods.size() == 0) {
callee.relatedMethod = false;
callee.myCalledByMethods.remove(current);
if (callee.myCalledByMethods.size() == 0) {
callee.myRelatedMethod = false;
}
it.remove();
}
@@ -443,10 +444,10 @@ public class MethodEntry
cullOverloadedMethods(contents, false);
List<ClassContentsEntry> copy = new ArrayList<ClassContentsEntry>(contents);
for (ClassContentsEntry rangeEntry : copy) {
if (rangeEntry instanceof IRelatableEntry) {
if (rangeEntry instanceof RelatableEntry) {
MethodEntry current = (MethodEntry)rangeEntry;
if (current.overloadedMethods.size() > 0) {
List<MethodEntry> newList = new ArrayList<MethodEntry>(current.overloadedMethods.size() + 1);
if (current.myOverloadedMethods.size() > 0) {
List<MethodEntry> newList = new ArrayList<MethodEntry>(current.myOverloadedMethods.size() + 1);
newList.add(current);
/**
* we are looking at the head of a list of overloaded methods. We need to sort the list
@@ -456,11 +457,11 @@ public class MethodEntry
case RearrangerSettings.OVERLOADED_ORDER_RETAIN_ORIGINAL:
// list is already in original order, except perhaps that the top-most extracted method
// comes first (if there is one).
newList.addAll(current.overloadedMethods);
newList.addAll(current.myOverloadedMethods);
break;
case RearrangerSettings.OVERLOADED_ORDER_ASCENDING_PARAMETERS:
case RearrangerSettings.OVERLOADED_ORDER_DESCENDING_PARAMETERS:
for (MethodEntry entry : current.overloadedMethods) {
for (MethodEntry entry : current.myOverloadedMethods) {
boolean inserted = false;
for (int index = 0; index < newList.size(); index++) {
MethodEntry me = newList.get(index);
@@ -479,7 +480,7 @@ public class MethodEntry
}
break;
}
current.overloadedMethods.clear();
current.myOverloadedMethods.clear();
/**
* if the head of the arraylist is not the same as "current", then the sort operation moved
* another method to the head of the list. Replace that in the contents array. Then assign
@@ -513,23 +514,23 @@ public class MethodEntry
{
List<ClassContentsEntry> copy = new ArrayList<ClassContentsEntry>(contents);
for (ClassContentsEntry o : copy) {
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
if ((me.isRelatedMethod() == doExtractedMethods) && !me.isOverloadedMethod) {
String meName = me.end.toString();
String meName = me.myEnd.toString();
// search contents list for methods with identical name, and attach them as overloaded methods.
ListIterator<ClassContentsEntry> contentIterator = contents.listIterator();
while (contentIterator.hasNext()) {
Object o1 = contentIterator.next();
if (o1 instanceof IRelatableEntry) {
if (o1 instanceof RelatableEntry) {
MethodEntry me2 = (MethodEntry)o1;
if (me2 == me) {
continue;
}
String me2Name = me2.end.toString();
String me2Name = me2.myEnd.toString();
if (meName.equals(me2Name)) {
contentIterator.remove();
me.overloadedMethods.add(me2);
me.myOverloadedMethods.add(me2);
me2.isOverloadedMethod = true; // set flag so array copy will skip this entry.
}
}
@@ -564,8 +565,8 @@ public class MethodEntry
public String[] getAdditionalIconNames() {
ArrayList<String> result = new ArrayList<String>();
String[] sa = new String[0];
if (end instanceof PsiMethod) {
PsiMethod m = (PsiMethod)end;
if (myEnd instanceof PsiMethod) {
PsiMethod m = (PsiMethod)myEnd;
if (m.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
result.add("nodes/c_public");
}
@@ -595,8 +596,8 @@ public class MethodEntry
}
public String getTypeIconName() {
if (end instanceof PsiMethod) {
PsiMethod m = (PsiMethod)end;
if (myEnd instanceof PsiMethod) {
PsiMethod m = (PsiMethod)myEnd;
return (((PsiModifierList)m.getModifierList()).hasModifierProperty(PsiModifier.STATIC)) ? "nodes/staticMethod" : "nodes/method";
}
return null;
@@ -610,7 +611,7 @@ public class MethodEntry
public JLabel getPopupEntryText(RearrangerSettings settings) {
StringBuffer name = new StringBuffer(80);
PsiMethod m = (PsiMethod)end;
PsiMethod m = (PsiMethod)myEnd;
if (m.getReturnTypeElement() != null && !settings.isShowTypeAfterMethod()) {
name.append(m.getReturnTypeElement().getText());
name.append(' ');
@@ -670,13 +671,13 @@ public class MethodEntry
*/
setGetter(
MethodUtil.isGetter(
(PsiMethod)end,
(PsiMethod)myEnd,
settings.getDefaultGSDefinition()
)
);
setSetter(
MethodUtil.isSetter(
(PsiMethod)end,
(PsiMethod)myEnd,
settings.getDefaultGSDefinition()
)
);
@@ -686,7 +687,7 @@ public class MethodEntry
if (((IRestrictMethodExtraction)rule).isNoExtractedMethods()) {
LOG.debug(
"excluding " +
end.toString() +
myEnd.toString() +
" from extracted method consideration"
);
setNoExtractedMethods(true);
@@ -739,47 +740,47 @@ public class MethodEntry
* option to keep getters and setters together is set. This is a special case.)
*/
public void determineExtractedMethod(RelatedMethodsSettings settings) {
relatedMethod = false;
myRelatedMethod = false;
if (!isGetter() && !isSetter()) {
if (calledByMethods.size() > 0) {
PsiMethod m = (PsiMethod)end;
if (myCalledByMethods.size() > 0) {
PsiMethod m = (PsiMethod)myEnd;
if (!m.getModifierList().hasModifierProperty(PsiModifier.PRIVATE)) {
switch (settings.getNonPrivateTreatment()) {
case RelatedMethodsSettings.NON_PRIVATE_EXTRACTED_NEVER:
break;
case RelatedMethodsSettings.NON_PRIVATE_EXTRACTED_ONE_CALLER:
if (calledByMethods.size() == 1) {
relatedMethod = true;
if (myCalledByMethods.size() == 1) {
myRelatedMethod = true;
}
break;
case RelatedMethodsSettings.NON_PRIVATE_EXTRACTED_ANY_CALLERS:
relatedMethod = true;
myRelatedMethod = true;
break;
}
}
else {
relatedMethod = true;
myRelatedMethod = true;
}
}
}
else {
if (isSetter() && calledByMethods.size() > 0 && correspondingGetterSetters.size() == 0) {
relatedMethod = true;
LOG.debug(end.toString() + " is setter but has no getter, treated as extracted method");
if (isSetter() && myCalledByMethods.size() > 0 && myCorrespondingGetterSetters.size() == 0) {
myRelatedMethod = true;
LOG.debug(myEnd.toString() + " is setter but has no getter, treated as extracted method");
}
else {
LOG.debug(end.toString() + " is getter/setter, not treated as extracted method");
LOG.debug(myEnd.toString() + " is getter/setter, not treated as extracted method");
}
}
LOG.debug("determined " + end.toString() + " is extracted method? " + relatedMethod);
LOG.debug("determined " + myEnd.toString() + " is extracted method? " + myRelatedMethod);
/**
* If this is not an extracted method, remove it from any callers so that it won't be moved.
*/
if (!relatedMethod) {
ListIterator<MethodEntry> li = calledByMethods.listIterator();
if (!myRelatedMethod) {
ListIterator<MethodEntry> li = myCalledByMethods.listIterator();
while (li.hasNext()) {
MethodEntry entry = (li.next());
entry.calledMethods.remove(this);
entry.myCalledMethods.remove(this);
li.remove();
}
}
@@ -787,31 +788,31 @@ public class MethodEntry
* Remaining entries are only extracted methods at this point. Using first/last rule, keep only the call by
* the calling method that this child method will be grouped with, and discard the rest.
*/
if (calledByMethods.size() > 1) {
if (myCalledByMethods.size() > 1) {
ListIterator<MethodEntry> li;
if (settings.isBelowFirstCaller()) {
li = calledByMethods.listIterator(1);
li = myCalledByMethods.listIterator(1);
while (li.hasNext()) {
MethodEntry entry = (li.next());
entry.calledMethods.remove(this);
entry.myCalledMethods.remove(this);
li.remove();
}
}
else {
li = calledByMethods.listIterator(calledByMethods.size() - 1);
li = myCalledByMethods.listIterator(myCalledByMethods.size() - 1);
while (li.hasPrevious()) {
MethodEntry entry = (li.previous());
entry.calledMethods.remove(this);
entry.myCalledMethods.remove(this);
li.remove();
}
}
}
if (relatedMethod) {
if (myRelatedMethod) {
LOG.debug(
"extracted method " +
toString() +
" will be arranged under " +
calledByMethods.get(0).toString()
myCalledByMethods.get(0).toString()
);
}
}
@@ -819,11 +820,11 @@ public class MethodEntry
// -------------------------- OTHER METHODS --------------------------
public DefaultMutableTreeNode addToPopupTree(DefaultMutableTreeNode parent, RearrangerSettings settings) {
DefaultMutableTreeNode node = new RearrangerTreeNode(this, name);
DefaultMutableTreeNode node = new RearrangerTreeNode(this, myName);
parent.add(node);
ListIterator li;
for (MethodEntry methodEntry : sortedMethods) {
if (methodEntry.isSetter() && methodEntry.calledByMethods.size() > 0) {
if (methodEntry.isSetter() && methodEntry.myCalledByMethods.size() > 0) {
// setters are arranged with getters when "keep getters/setters together" option is checked.
// but setters are not really called by getters. So attach them to the upper level.
methodEntry.addToPopupTree(parent, settings);
@@ -832,7 +833,7 @@ public class MethodEntry
methodEntry.addToPopupTree(node, settings);
}
}
for (MethodEntry methodEntry : overloadedMethods) {
for (MethodEntry methodEntry : myOverloadedMethods) {
methodEntry.addToPopupTree(node, settings);
}
return node;
@@ -850,15 +851,15 @@ public class MethodEntry
String allMethodNames,
int level)
{
final String currentMethodName = ((PsiMethod)end).getName();
final String currentMethodName = ((PsiMethod)myEnd).getName();
String[] callingNames = new String[allCallingMethods.size()];
for (int i = 0; i < allCallingMethods.size(); i++) {
MethodEntry me = allCallingMethods.get(i);
callingNames[i] = ((PsiMethod)me.end).getName();
callingNames[i] = ((PsiMethod)me.myEnd).getName();
}
MethodEntry topLevel = this;
while (topLevel.calledByMethods.size() > 0) {
topLevel = (topLevel.calledByMethods.get(0));
while (topLevel.myCalledByMethods.size() > 0) {
topLevel = (topLevel.myCalledByMethods.get(0));
}
switch (rms.getCommentType()) {
case RelatedMethodsSettings.COMMENT_TYPE_TOP_LEVEL:
@@ -886,14 +887,14 @@ public class MethodEntry
rms.getPrecedingComment(),
currentMethodName,
allMethodNames,
((PsiMethod)topLevel.end).getName(),
((PsiMethod)topLevel.myEnd).getName(),
level
);
customizedTrailingComment = expandComment(
rms.getTrailingComment(),
currentMethodName,
allMethodNames,
((PsiMethod)topLevel.end).getName(),
((PsiMethod)topLevel.myEnd).getName(),
level
);
// recursively assign comments.
@@ -929,7 +930,7 @@ public class MethodEntry
rms.getPrecedingComment(),
currentMethodName,
allMethodNames,
((PsiMethod)topLevel.end).getName(),
((PsiMethod)topLevel.myEnd).getName(),
level
);
}
@@ -954,7 +955,7 @@ public class MethodEntry
rms.getPrecedingComment(),
currentMethodName,
allMethodNames,
((PsiMethod)topLevel.end).getName(),
((PsiMethod)topLevel.myEnd).getName(),
level
);
// recursively assign comments for each level.
@@ -980,7 +981,7 @@ public class MethodEntry
rms.getTrailingComment(),
currentMethodName,
allMethodNames,
((PsiMethod)topLevel.end).getName(),
((PsiMethod)topLevel.myEnd).getName(),
level
);
}
@@ -1059,15 +1060,15 @@ public class MethodEntry
* to only that text up to and including the open brace. Temporarily remove the rest of the text; append
* it again after checking for comments.
*/
int brace = alternateValue.indexOf('{');
int brace = myAlternateValue.indexOf('{');
String temp = "";
if (brace >= 0) {
// every method should have an open brace -- unless it is abstract.
temp = alternateValue.substring(brace + 1, alternateValue.length());
alternateValue = alternateValue.substring(0, brace + 1);
temp = myAlternateValue.substring(brace + 1, myAlternateValue.length());
myAlternateValue = myAlternateValue.substring(0, brace + 1);
}
super.checkForComment();
alternateValue += temp;
myAlternateValue += temp;
}
/**
@@ -1085,7 +1086,7 @@ public class MethodEntry
/**
* recursively walk the method's code block looking for method calls.
*/
final PsiMethod thisMethod = (PsiMethod)end;
final PsiMethod thisMethod = (PsiMethod)myEnd;
final MethodEntry thisMethodEntry = this;
JavaRecursiveElementVisitor rev = new JavaRecursiveElementVisitor() {
@@ -1095,11 +1096,11 @@ public class MethodEntry
/**
* if the called method is already in our list, don't add it again.
*/
if (c != null && !calledMethods.contains(c)) {
if (c != null && !myCalledMethods.contains(c)) {
for (ClassContentsEntry o : possibleMethods) {
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
PsiMethod m = (PsiMethod)me.end;
PsiMethod m = (PsiMethod)me.myEnd;
if (c == m) {
if (settings.isKeepOverloadedMethodsTogether() &&
m.getName().equals(thisMethod.getName()))
@@ -1108,8 +1109,8 @@ public class MethodEntry
}
else {
LOG.debug("method " + thisMethod.toString() + " calls " + m.toString());
calledMethods.add(me);
me.calledByMethods.add(thisMethodEntry);
myCalledMethods.add(me);
me.myCalledByMethods.add(thisMethodEntry);
}
break;
}
@@ -1138,40 +1139,40 @@ public class MethodEntry
{
return;
}
final PsiMethod thisMethod = (PsiMethod)end;
final PsiMethod thisMethod = (PsiMethod)myEnd;
String thisProperty = MethodUtil.getPropertyName(thisMethod);
if (isGetter() && !keptWithProperty) {
if (isGetter() && !myKeptWithProperty) {
if (settings.isKeepGettersSettersWithProperty()) {
hookGetterToProperty(possibleMethods);
}
}
for (ClassContentsEntry o : possibleMethods) {
if (o instanceof IRelatableEntry) {
if (o instanceof RelatableEntry) {
MethodEntry me = (MethodEntry)o;
// don't use a setter twice (could be two methods which both look like getters; assign the setter
// to only one of them.) Also, associate all getter/setter methods for the same property with the
// first one encountered.
if ((me.isSetter() ||
me.isGetter()) &&
me.correspondingGetterSetters.size() == 0 &&
me.myCorrespondingGetterSetters.size() == 0 &&
me != this)
{
PsiMethod m = (PsiMethod)me.end;
PsiMethod m = (PsiMethod)me.myEnd;
String otherProperty = MethodUtil.getPropertyName(m);
if (thisProperty.equals(otherProperty)) {
LOG.debug("method " + thisMethod.toString() + " is getter; its setter is " + m.toString());
// place getters ahead of setters
if (me.isGetter()) {
correspondingGetterSetters.add(0, me);
myCorrespondingGetterSetters.add(0, me);
// clear the getter flag and set the setter flag; this causes the method to be emitted
// under the first getter encountered.
me.setGetter(false);
me.setSetter(true);
}
else {
correspondingGetterSetters.add(me);
myCorrespondingGetterSetters.add(me);
}
me.correspondingGetterSetters.add(this);
me.myCorrespondingGetterSetters.add(this);
}
}
}
@@ -1186,7 +1187,7 @@ public class MethodEntry
*/
private void hookGetterToProperty(List<ClassContentsEntry> entries) {
ListIterator<ClassContentsEntry> li = entries.listIterator();
String property = MethodUtil.getPropertyName((PsiMethod)end);
String property = MethodUtil.getPropertyName((PsiMethod)myEnd);
while (li.hasNext()) {
Object o = li.next();
if (o instanceof FieldEntry) {
@@ -1195,7 +1196,7 @@ public class MethodEntry
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
if (fe.getGetterMethod() == null && property.equals(sb.toString())) {
fe.setGetterMethod(this);
keptWithProperty = true;
myKeptWithProperty = true;
break;
}
}
@@ -1203,7 +1204,7 @@ public class MethodEntry
}
public void emit(Emitter emitter) {
StringBuffer sb = emitter.getStringBuffer();
StringBuilder sb = emitter.getTextBuffer();
if (getCustomizedPrecedingComment().length() > 0) {
sb.append("\n");
sb.append(getCustomizedPrecedingComment());
@@ -1218,11 +1219,11 @@ public class MethodEntry
*/
ListIterator li;
if (isGetter()) {
for (MethodEntry entry : correspondingGetterSetters) {
for (MethodEntry entry : myCorrespondingGetterSetters) {
entry.emit(emitter);
}
}
for (MethodEntry me : overloadedMethods) {
for (MethodEntry me : myOverloadedMethods) {
me.emit(emitter);
}
for (MethodEntry me : sortedMethods) {
@@ -1230,17 +1231,17 @@ public class MethodEntry
}
}
protected void emitAllElements(StringBuffer sb, Document document) {
if (alternateValue != null) {
protected void emitAllElements(StringBuilder sb, Document document) {
if (myAlternateValue != null) {
/**
* protect body of method from removing newlines.
*/
int brace = alternateValue.indexOf('{');
int brace = myAlternateValue.indexOf('{');
String temp = "";
if (brace >= 0) {
// every method should have an open brace -- unless it is abstract.
temp = alternateValue.substring(brace + 1, alternateValue.length());
alternateValue = alternateValue.substring(0, brace + 1);
temp = myAlternateValue.substring(brace + 1, myAlternateValue.length());
myAlternateValue = myAlternateValue.substring(0, brace + 1);
}
super.emitAllElements(sb, document);
sb.append(temp);
@@ -1253,8 +1254,8 @@ public class MethodEntry
public void insertInterfaceOrder(List<MethodEntry> list) {
Comparator<MethodEntry> comparator = new Comparator<MethodEntry>() {
public int compare(MethodEntry o1, MethodEntry o2) {
final int offset1 = getMethodOffsetInInterface((PsiMethod)o1.end);
final int offset2 = getMethodOffsetInInterface((PsiMethod)o2.end);
final int offset1 = getMethodOffsetInInterface((PsiMethod)o1.myEnd);
final int offset2 = getMethodOffsetInInterface((PsiMethod)o2.myEnd);
if (offset1 < offset2) return -1;
if (offset1 == offset2) return 0;
return 1;
@@ -1263,7 +1264,7 @@ public class MethodEntry
insertInList(list, comparator);
}
private int getMethodOffsetInInterface(PsiMethod method) {
private static int getMethodOffsetInInterface(PsiMethod method) {
final PsiMethod[] superMethods = method.findSuperMethods();
// final PsiMethod[] superMethods = PsiSuperMethodUtil.findSuperMethods(method); // todo - for IDEA 5.0
if (superMethods.length == 0) return 0;
@@ -1277,11 +1278,11 @@ public class MethodEntry
public String toString() {
return "MethodEntry " +
end.toString() +
myEnd.toString() +
"; calls " +
calledMethods.size() +
myCalledMethods.size() +
", called by " +
calledByMethods.size() +
myCalledByMethods.size() +
", nParameters=" + nParameters;
}
}
@@ -23,13 +23,13 @@ package com.wrq.rearranger.entry;
import com.intellij.psi.PsiElement;
import com.wrq.rearranger.settings.RearrangerSettings;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/** Corresponds to comments and whitespace that surround Java syntactic items like classes and methods. */
public class MiscellaneousTextEntry
extends ClassContentsEntry
{
public class MiscellaneousTextEntry extends ClassContentsEntry {
public MiscellaneousTextEntry(final PsiElement start,
final PsiElement end,
final boolean fixedHeader,
@@ -38,6 +38,7 @@ public class MiscellaneousTextEntry
super(start, end, fixedHeader, fixedTrailer);
}
@Nullable
public String getTypeIconName() {
// do not show headers and trailers in the file structure popup.
return null;
@@ -47,6 +48,7 @@ public class MiscellaneousTextEntry
return null;
}
@Nullable
public JLabel getPopupEntryText(RearrangerSettings settings) {
return null;
}
@@ -59,7 +61,7 @@ public class MiscellaneousTextEntry
else {
result = "Trailer";
}
if (alternateValue != null) {
if (myAlternateValue != null) {
result += "; comments removed";
}
return result;
@@ -26,13 +26,11 @@ import com.wrq.rearranger.settings.RearrangerSettings;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Created by IntelliJ IDEA.
* User: davek
* Date: Feb 18, 2004
* Time: 9:17:56 AM
* To change this template use File | Settings | File Templates.
*/
public interface IPopupTreeRangeEntry {
public interface PopupTreeRangeEntry {
/**
* Gives individual entries control over their appearance, depending on settings.
@@ -27,6 +27,7 @@ import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiWhiteSpace;
import com.wrq.rearranger.settings.RearrangerSettings;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -36,27 +37,24 @@ import java.util.List;
* members, and trailing text, we can create a dummy "class" which will parse the file. Header text
* will include the package and import statements, and outer classes will be its members.
*/
public class PsiFileEntry
extends ClassEntry
{
public PsiFileEntry(RearrangerSettings settings) {
public class PsiFileEntry extends ClassEntry {
public PsiFileEntry(@NotNull RearrangerSettings settings) {
super(null, null, 0, "", null, 0, settings);
}
/**
* Strip off leading elements which do not belong to the first class, and place them in
* Strips off leading elements which do not belong to the first class, and place them in
* a MiscellaneousText entry.
*
*
* @param project
* @param psiFile
* @param commentList
* @return
*/
public List<ClassContentsEntry> parseFile(Project project,
PsiElement psiFile,
List commentList)
{
public List<ClassContentsEntry> parseFile(Project project, PsiElement psiFile) {
int startingIndex = 0;
// TODO den re-write to the 'firstChild & nextSibling'
for (int i = 0; i < psiFile.getChildren().length; i++) {
PsiElement child = psiFile.getChildren()[i];
if (child instanceof PsiClass) {
@@ -86,8 +84,8 @@ public class PsiFileEntry
}
parseRemainingClassContents(project, startingIndex, psiFile);
if (miscellaneousTextEntry != null) {
contents.add(0, miscellaneousTextEntry);
myContents.add(0, miscellaneousTextEntry);
}
return contents;
return myContents;
}
}
@@ -23,12 +23,15 @@ package com.wrq.rearranger.entry;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.wrq.rearranger.popup.RearrangerTreeNode;
import com.wrq.rearranger.rearrangement.Emitter;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.util.CommentUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.regex.Matcher;
@@ -38,66 +41,67 @@ import java.util.regex.Matcher;
* contains start and end Psi elements for each item (which could be identical), as well as modifier
* flags and special flags to mark any miscellaneous text or comments that precede or follow the item.
*/
abstract public class RangeEntry implements IPopupTreeRangeEntry {
abstract public class RangeEntry implements PopupTreeRangeEntry {
// ------------------------------ FIELDS ------------------------------
private static final Logger LOG = Logger.getInstance("#" + RangeEntry.class.getName());
String alternateValue;
final String name;
protected final PsiElement start;
protected final PsiElement end;
private final int modifiers;
private final String modifierString;
private final boolean fixedHeader;
private final boolean fixedTrailer;
private final String type;
private RuleInstance myMatchedRule;
private boolean separatorCommentPrecedes;
String myAlternateValue;
final String myName;
protected final PsiElement myStart;
protected final PsiElement myEnd;
private final int myModifiers;
private final String myModifierString;
private final boolean myFixedHeader;
private final boolean myFixedTrailer;
private final String myType;
private RuleInstance myMatchedRule;
private boolean mySeparatorCommentPrecedes;
// --------------------------- CONSTRUCTORS ---------------------------
public RangeEntry(final PsiElement start,
final PsiElement end,
public RangeEntry(@Nullable final PsiElement start,
@Nullable final PsiElement end,
final boolean fixedHeader,
final boolean fixedTrailer)
{
this(start, end, 0, "", "", "", fixedHeader, fixedTrailer);
}
RangeEntry(final PsiElement start,
final PsiElement end,
RangeEntry(@Nullable final PsiElement start,
@Nullable final PsiElement end,
final int modifiers,
final String modifierString,
final String name,
@Nullable final String name,
final String type)
{
this(start, end, modifiers, modifierString, name, type, false, false);
}
private RangeEntry(final PsiElement start,
final PsiElement end,
private RangeEntry(@Nullable final PsiElement start,
@Nullable final PsiElement end,
final int modifiers,
final String modifierString,
final String name,
@Nullable final String name,
final String type,
final boolean fixedHeader,
final boolean fixedTrailer)
{
this.start = start;
this.end = end;
this.modifiers = modifiers;
this.modifierString = modifierString;
this.fixedHeader = fixedHeader;
this.fixedTrailer = fixedTrailer;
this.name = name;
this.type = type;
alternateValue = null;
myStart = start;
myEnd = end;
myModifiers = modifiers;
myModifierString = modifierString;
myFixedHeader = fixedHeader;
myFixedTrailer = fixedTrailer;
myName = name;
myType = type;
myAlternateValue = null;
}
// --------------------- GETTER / SETTER METHODS ---------------------
public PsiElement getEnd() {
return end;
return myEnd;
}
public RuleInstance getMatchedRule() {
@@ -109,59 +113,59 @@ abstract public class RangeEntry implements IPopupTreeRangeEntry {
}
public int getModifiers() {
return modifiers;
return myModifiers;
}
public String getModifierString() {
return modifierString;
return myModifierString;
}
public String getName() {
return name;
return myName;
}
public String getType() {
return type;
return myType;
}
public PsiElement getStart() {
return start;
return myStart;
}
public boolean isFixedHeader() {
return fixedHeader;
return myFixedHeader;
}
public boolean isFixedTrailer() {
return fixedTrailer;
return myFixedTrailer;
}
// ------------------------ CANONICAL METHODS ------------------------
public String toString() {
String result = (name == null ? "<unnamed>" : name);
if (start != null && end != null) {
String result = (myName == null ? "<unnamed>" : myName);
if (myStart != null && myEnd != null) {
result += "; range from " +
start.toString() +
myStart.toString() +
" [" +
start.getTextRange().getStartOffset() +
myStart.getTextRange().getStartOffset() +
"] to " +
end.toString() +
myEnd.toString() +
" [" +
end.getTextRange().getEndOffset() +
myEnd.getTextRange().getEndOffset() +
"]; modifiers=0x" +
Integer.toHexString(modifiers);
Integer.toHexString(myModifiers);
}
else {
result += "; no start/end specified";
}
if (fixedHeader) {
if (myFixedHeader) {
result = "Header: " + result;
}
if (fixedTrailer) {
if (myFixedTrailer) {
result = "Trailer: " + result;
}
if (alternateValue != null) {
if (myAlternateValue != null) {
result += "; comments removed";
}
return result;
@@ -173,7 +177,7 @@ abstract public class RangeEntry implements IPopupTreeRangeEntry {
// --------------------- Interface IPopupTreeRangeEntry ---------------------
public DefaultMutableTreeNode addToPopupTree(DefaultMutableTreeNode parent, RearrangerSettings settings) {
DefaultMutableTreeNode myNode = new RearrangerTreeNode(this, name);
DefaultMutableTreeNode myNode = new RearrangerTreeNode(this, myName);
parent.add(myNode);
return myNode;
}
@@ -189,40 +193,37 @@ abstract public class RangeEntry implements IPopupTreeRangeEntry {
* for each separator comment specified by the user, check to see if this comment matches.
*/
for (Matcher matcher : CommentUtil.getCommentMatchers()) {
matcher.reset(alternateValue);
matcher.reset(myAlternateValue);
boolean foundMatch = matcher.find();
if (foundMatch) {
LOG.debug("found comment pattern '" +
matcher.pattern().pattern().replaceAll("\n", "#") +
"' in '" +
alternateValue.replaceAll("\n", "#") +
myAlternateValue.replaceAll("\n", "#") +
"'");
StringBuffer sb = new StringBuffer(alternateValue.length());
StringBuffer sb = new StringBuffer(myAlternateValue.length());
do {
boolean leadingNewlines = start.getTextRange().getStartOffset() > 0;
boolean leadingNewlines = myStart.getTextRange().getStartOffset() > 0;
matcher.appendReplacement(sb,
leadingNewlines ? "\n" : "");
foundMatch = matcher.find();
}
while (foundMatch);
matcher.appendTail(sb);
alternateValue = sb.toString();
LOG.debug("RangeEntry alternateValue=" + alternateValue.replaceAll("\n", "#"));
myAlternateValue = sb.toString();
LOG.debug("RangeEntry alternateValue=" + myAlternateValue.replaceAll("\n", "#"));
}
}
}
protected void createAlternateValueString() {
if (alternateValue != null) {
if (myAlternateValue != null) {
return;
}
final StringBuffer sb = new StringBuffer(
end.getTextRange().getEndOffset() -
start.getTextRange().getStartOffset()
);
PsiElement e = start;
while (e != null && e != end) {
if (e == end.getParent()) {
final StringBuilder sb = new StringBuilder(myEnd.getTextRange().getEndOffset() - myStart.getTextRange().getStartOffset());
PsiElement e = myStart;
while (e != null && e != myEnd) {
if (e == myEnd.getParent()) {
e = e.getFirstChild();
}
else {
@@ -230,58 +231,52 @@ abstract public class RangeEntry implements IPopupTreeRangeEntry {
e = e.getNextSibling();
}
}
if (e == end) {
sb.append(end.getText());
if (e == myEnd) {
sb.append(myEnd.getText());
}
alternateValue = sb.toString();
myAlternateValue = sb.toString();
}
public void emit(Emitter emitter) {
emitAllElements(emitter.getStringBuffer(), emitter.getDocument());
emitAllElements(emitter.getTextBuffer(), emitter.getDocument());
}
protected void emitAllElements(StringBuffer sb, Document document) {
if (alternateValue != null) {
String result = alternateValue;
if (separatorCommentPrecedes) {
protected void emitAllElements(StringBuilder buffer, Document document) {
if (myAlternateValue != null) {
String result = myAlternateValue;
if (mySeparatorCommentPrecedes) {
// remove all leading blank lines. The only blank lines we want are the ones explicitly appended
// to the preceding separator comment.
LOG.debug("emitAllElements: separator comment precedes " +
name + "; original value=" +
alternateValue.replaceAll("\n", "#"));
result = alternateValue.replaceFirst("\n[ \t\n]*\n", "\n");
myName + "; original value=" +
myAlternateValue.replaceAll("\n", "#"));
result = myAlternateValue.replaceFirst("\n[ \t\n]*\n", "\n");
LOG.debug("emitAllElements: resulting value=" +
alternateValue.replaceAll("\n", "#"));
myAlternateValue.replaceAll("\n", "#"));
}
sb.append(result);
buffer.append(result);
}
else {
PsiElement curr = start;
while (curr != null && curr != end) {
if (curr == end.getParent()) {
PsiElement curr = myStart;
while (curr != null && curr != myEnd) {
if (curr == myEnd.getParent()) {
curr = curr.getFirstChild();
}
else {
emitElement(curr, sb, document);
emitElement(curr, buffer, document);
curr = curr.getNextSibling();
}
}
if (curr == end) {
emitElement(end, sb, document);
if (curr == myEnd) {
emitElement(myEnd, buffer, document);
}
}
}
private void emitElement(final PsiElement curr,
final StringBuffer sb,
final Document document)
{
private static void emitElement(@NotNull final PsiElement curr, @NotNull final StringBuilder sb, @NotNull final Document document) {
final TextRange range = curr.getTextRange();
try {
sb.append(
document.getCharsSequence().toString().toCharArray(), // for Irida (builds 3185 etc).
curr.getTextRange().getStartOffset(),
curr.getTextRange().getEndOffset() - curr.getTextRange().getStartOffset()
);
sb.append(document.getCharsSequence(), range.getStartOffset(), range.getEndOffset());
}
catch (ArrayIndexOutOfBoundsException oob) {
LOG.error("internal error attempting to append text to document");
@@ -290,17 +285,17 @@ abstract public class RangeEntry implements IPopupTreeRangeEntry {
LOG.error("document...toCharArray.length=" + document.getCharsSequence().toString().toCharArray().length);
LOG.error("current PSI element=" + curr.toString());
LOG.error("current PSI element text=" + curr.getText());
LOG.error("current PSI element text range, start offset=" + curr.getTextRange().getStartOffset());
LOG.error("current PSI element text range, end offset=" + curr.getTextRange().getEndOffset());
LOG.error("current PSI element text range, length=" + curr.getTextRange().getLength());
LOG.error("current PSI element text range, start offset=" + range.getStartOffset());
LOG.error("current PSI element text range, end offset=" + range.getEndOffset());
LOG.error("current PSI element text range, length=" + range.getLength());
LOG.error(oob);
throw oob;
}
}
public void setSeparatorCommentPrecedes(boolean precedes) {
this.separatorCommentPrecedes = precedes;
LOG.debug("emitAllElements: set separator comment precedes " + name);
this.mySeparatorCommentPrecedes = precedes;
LOG.debug("emitAllElements: set separator comment precedes " + myName);
}
}
@@ -30,7 +30,7 @@ import java.util.List;
* Defines methods implemented by entries which may be related to others, i.e. getters and setters,
* method entries which call other methods, and overloaded method entries.
*/
public interface IRelatableEntry {
public interface RelatableEntry {
/**
* Determine if the entry is a getter/setter or is excluded from extracted method consideration by an
* overriding rule.
@@ -29,6 +29,7 @@ import javax.swing.*;
/** Interface implemented by objects which can appear as entries in the file structure popup. */
public interface FilePopupEntry {
/** @return the name of the icon representing the popup entry's type of Java object (method, class, etc.) */
@Nullable
String getTypeIconName();
/**
@@ -39,5 +40,6 @@ public interface FilePopupEntry {
String[] getAdditionalIconNames();
/** @return a JLabel containing the text of the popup tree entry. */
@Nullable
JLabel getPopupEntryText(RearrangerSettings settings);
}
@@ -24,41 +24,48 @@ package com.wrq.rearranger.rearrangement;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.PsiFile;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/** Emits a new document from the rearranged entries. */
public final class Emitter {
private final PsiFile psiFile;
private final List<RuleInstance> myResultRuleInstances;
private final Document document;
private StringBuffer stringBuffer;
public Emitter(final PsiFile psiFile, final List<RuleInstance> resultRuleInstances, final Document document) {
this.psiFile = psiFile;
this.myResultRuleInstances = resultRuleInstances;
this.document = document;
stringBuffer = new StringBuffer(psiFile.getText().length() + 100); // room for inserted blank lines
@NotNull private final StringBuilder myStringBuffer = new StringBuilder();
@NotNull private final List<RuleInstance> myResultRuleInstances = new ArrayList<RuleInstance>();
@NotNull private final PsiFile myFile;
@NotNull private final Document myDocument;
public Emitter(@NotNull final PsiFile file, @NotNull final List<RuleInstance> resultRuleInstances, @NotNull final Document document) {
myFile = file;
myResultRuleInstances.addAll(resultRuleInstances);
myDocument = document;
myStringBuffer.ensureCapacity(myFile.getText().length() + 100 /* room for inserted blank lines */);
}
@NotNull
public Document getDocument() {
return document;
return myDocument;
}
public StringBuffer getStringBuffer() {
return stringBuffer;
@NotNull
public StringBuilder getTextBuffer() {
return myStringBuffer;
}
public void emitRearrangedDocument() {
emitRuleInstances(myResultRuleInstances);
document.replaceString(
psiFile.getTextRange().getStartOffset(),
psiFile.getTextRange().getEndOffset(),
stringBuffer.toString()
myDocument.replaceString(
myFile.getTextRange().getStartOffset(),
myFile.getTextRange().getEndOffset(),
myStringBuffer.toString()
);
}
public void emitRuleInstances(List<RuleInstance> resultRuleInstances) {
public void emitRuleInstances(@Nullable List<RuleInstance> resultRuleInstances) {
if (resultRuleInstances == null) {
return;
}
@@ -24,7 +24,7 @@ package com.wrq.rearranger.rearrangement;
import com.intellij.openapi.diagnostic.Logger;
import com.wrq.rearranger.entry.ClassContentsEntry;
import com.wrq.rearranger.entry.ClassEntry;
import com.wrq.rearranger.entry.IRelatableEntry;
import com.wrq.rearranger.entry.RelatableEntry;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.ruleinstance.CommentRuleInstance;
import com.wrq.rearranger.ruleinstance.RuleInstance;
@@ -37,23 +37,24 @@ import java.util.ListIterator;
/** Template for generic rearrangement of items in a class or in a Java file. */
public abstract class GenericRearranger {
private static final Logger LOG = Logger.getInstance("#" + GenericRearranger.class.getName());
private final List<AttributeGroup> rules;
private final List<ClassContentsEntry> entries;
private final List<RuleInstance> myResultRuleInstances;
private final int nestingLevel;
private final RearrangerSettings settings;
private final List<AttributeGroup> myRules;
private final List<ClassContentsEntry> myEntries;
private final List<RuleInstance> myResultRuleInstances;
private final int myNestingLevel;
private final RearrangerSettings mySettings;
@SuppressWarnings({"AssignmentToCollectionOrArrayFieldFromParameter"})
protected GenericRearranger(final List<AttributeGroup> rules,
final List<ClassContentsEntry> outerClasses,
final int nestingLevel,
final RearrangerSettings settings)
{
this.rules = rules;
entries = outerClasses;
this.nestingLevel = nestingLevel;
this.settings = settings;
final RearrangerSettings settings) {
this.myRules = rules;
myEntries = outerClasses;
this.myNestingLevel = nestingLevel;
this.mySettings = settings;
myResultRuleInstances = new ArrayList<RuleInstance>(rules.size() + 4);
}
@@ -66,27 +67,23 @@ public abstract class GenericRearranger {
public final List<RuleInstance> rearrangeEntries() {
final List<RuleInstance> prioritizedRuleInstances = new ArrayList<RuleInstance>();
buildRuleInstanceLists(prioritizedRuleInstances);
/**
* recursively reorder contents of every nested ClassEntry.
*/
for (ClassContentsEntry entry : entries) {
// Recursively reorder contents of every nested ClassEntry
for (ClassContentsEntry entry : myEntries) {
if (entry instanceof ClassEntry) {
((ClassEntry)entry).rearrangeContents();
}
}
matchPrioritizedRules(prioritizedRuleInstances);
/**
* Move related methods together. Extracted methods and setters (emitted with getters)
* were not moved by the rearrangement code ("MatchPrioritizedRules()") just above.
*/
rearrangeRelatedItems(entries, myResultRuleInstances);
/**
* Now go back and determine which comments are going to be emitted, based on their criteria and the
* state of the immediately surrounding rules. Ignore inner classes if no rearrangement of inner
* classes is taking place.
*/
if (nestingLevel <= 1 || settings.isRearrangeInnerClasses()) {
// Move related methods together. Extracted methods and setters (emitted with getters)
// were not moved by the rearrangement code ("MatchPrioritizedRules()") just above.
rearrangeRelatedItems(myEntries, myResultRuleInstances);
// Now go back and determine which comments are going to be emitted, based on their criteria and the
// state of the immediately surrounding rules. Ignore inner classes if no rearrangement of inner
// classes is taking place.
if (myNestingLevel <= 1 || mySettings.isRearrangeInnerClasses()) {
determineEmittedComments();
}
return myResultRuleInstances;
@@ -103,7 +100,9 @@ public abstract class GenericRearranger {
for (int j = i + 1; j < myResultRuleInstances.size(); j++) {
RuleInstance instance = myResultRuleInstances.get(j);
if (instance.hasMatches()) {
RangeEntry entry = (instance.getMatches().get(0));
final List<RangeEntry> matches = instance.getMatches();
assert matches != null;
RangeEntry entry = (matches.get(0));
entry.setSeparatorCommentPrecedes(true);
break;
}
@@ -125,14 +124,14 @@ public abstract class GenericRearranger {
private void matchPrioritizedRules(List<RuleInstance> prioritizedRules) {
for (RuleInstance ruleInstance : prioritizedRules) {
final Rule rule = ruleInstance.getRule();
final ListIterator entryIterator = entries.listIterator();
final ListIterator entryIterator = myEntries.listIterator();
while (entryIterator.hasNext()) {
final RangeEntry entry = (RangeEntry)entryIterator.next();
if (entry instanceof IRelatableEntry) {
if (entry instanceof RelatableEntry) {
// if this is an extracted (i.e. related) method, or
// if this is a setter that will be emitted under the corresponding getter,
// don't test it for match against the rule.
final IRelatableEntry relatableEntry = ((IRelatableEntry)entry);
final RelatableEntry relatableEntry = ((RelatableEntry)entry);
if (relatableEntry.isRelatedMethod() || relatableEntry.isEmittableSetter()) {
continue;
}
@@ -154,18 +153,14 @@ public abstract class GenericRearranger {
* @param prioritizedRuleInstances
*/
private void buildRuleInstanceLists(final List<RuleInstance> prioritizedRuleInstances) {
/**
* add a HeaderTrailerRuleInstance to pick up any headers that might exist.
*/
// Add a HeaderTrailerRuleInstance to pick up any headers that might exist.
RuleInstance hri = new HeaderRule().createRuleInstance();
myResultRuleInstances.add(hri);
prioritizedRuleInstances.add(hri);
for (Rule rule : rules) {
for (Rule rule : myRules) {
RuleInstance instance = rule.createRuleInstance();
myResultRuleInstances.add(instance);
/**
* now insert the rule instance into the prioritized list; highest priority first; stable insertion.
*/
// Now insert the rule instance into the prioritized list; highest priority first; stable insertion.
boolean inserted = false;
for (int i = prioritizedRuleInstances.size() - 1; i >= 0; i--) {
RuleInstance entry = (prioritizedRuleInstances.get(i));
@@ -196,7 +191,6 @@ public abstract class GenericRearranger {
* @param entries
* @param rearrangedEntries
*/
public abstract void rearrangeRelatedItems(List<ClassContentsEntry> entries,
List<RuleInstance> rearrangedEntries);
public abstract void rearrangeRelatedItems(List<ClassContentsEntry> entries, List<RuleInstance> rearrangedEntries);
}
@@ -30,22 +30,21 @@ import java.util.List;
/** Moves (rearranges) classes and class members according to rules specified by the user. */
public final class Mover {
private final List<ClassContentsEntry> outerClasses;
private final RearrangerSettings settings;
public Mover(final List<ClassContentsEntry> outerClasses,
final RearrangerSettings settings)
{
this.outerClasses = new ArrayList<ClassContentsEntry>(outerClasses);
this.settings = settings;
private final List<ClassContentsEntry> myOuterClasses = new ArrayList<ClassContentsEntry>();
private final RearrangerSettings mySettings;
public Mover(final List<? extends ClassContentsEntry> outerClasses, final RearrangerSettings settings) {
myOuterClasses.addAll(outerClasses);
mySettings = settings;
}
public List<RuleInstance> rearrangeOuterClasses() {
final GenericRearranger outerClassRearranger = new GenericRearranger(
settings.getClassOrderAttributeList(),
outerClasses,
mySettings.getClassOrderAttributeList(),
myOuterClasses,
0,
settings)
mySettings)
{
/**
* There are no items related to outer classes -- outer classes are completely disjoint
@@ -55,9 +54,7 @@ public final class Mover {
@param rearrangedEntries
*/
public void rearrangeRelatedItems(List<ClassContentsEntry> entries,
List<RuleInstance> rearrangedEntries)
{
public void rearrangeRelatedItems(List<ClassContentsEntry> entries, List<RuleInstance> rearrangedEntries) {
}
};
@@ -29,34 +29,36 @@ import com.wrq.rearranger.entry.ClassEntry;
import com.wrq.rearranger.entry.PsiFileEntry;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.settings.RearrangerSettings;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/** Creates a list of entries for classes and class members by parsing the Java file. */
public final class Parser {
private static final Logger LOG = Logger.getInstance("#" + Parser.class.getName());
private final Project project;
private final RearrangerSettings settings;
private final PsiFile psiFile;
public Parser(final Project project,
final RearrangerSettings settings,
final PsiFile psiFile)
{
this.project = project;
this.settings = settings;
this.psiFile = psiFile;
private static final Logger LOG = Logger.getInstance("#" + Parser.class.getName());
private final Project myProject;
private final RearrangerSettings mySettings;
private final PsiFile myPsiFile;
public Parser(final @NotNull Project project, final @NotNull RearrangerSettings settings, final @NotNull PsiFile psiFile) {
myProject = project;
mySettings = settings;
myPsiFile = psiFile;
}
@NotNull
public List<ClassContentsEntry> parseOuterLevel() {
/**
* Parse the top level contents of the PsiFile here.
*/
PsiFileEntry fileEntry = new PsiFileEntry(settings);
return fileEntry.parseFile(project, psiFile, settings.getClassOrderAttributeList());
PsiFileEntry fileEntry = new PsiFileEntry(mySettings);
return fileEntry.parseFile(myProject, myPsiFile);
}
private void dumpOuterClasses(final List<? extends ClassEntry> outerClasses) {
@SuppressWarnings("UnusedDeclaration")
private static void dumpOuterClasses(final List<? extends ClassEntry> outerClasses) {
LOG.debug("Outer class entries:");
for (ClassEntry classEntry : outerClasses) {
LOG.debug(classEntry.toString());
@@ -23,7 +23,6 @@ package com.wrq.rearranger.rearrangement;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.wrq.rearranger.settings.ForceBlankLineSetting;
import com.wrq.rearranger.settings.RearrangerSettings;
@@ -34,24 +33,22 @@ import java.util.Map;
/** Responsible for adjusting the number of blank lines at strategic places in the source file. */
public class Spacer {
private static final Logger LOG = Logger.getInstance("#" + Spacer.class.getName());
private final Project project;
private final PsiFile psiFile;
private final Document document;
private final PsiElementFactory factory;
private final RearrangerSettings settings;
private final char[] newlineChars;
private boolean changesMade;
private StringBuffer sb;
private final PsiFile myFile;
private final Document myDocument;
private final RearrangerSettings mySettings;
private final char[] myNewlineChars;
private boolean myChangesMade;
private StringBuilder myBuffer;
private Map<PsiWhiteSpace, VirtualElement> virtualElements = new HashMap<PsiWhiteSpace, VirtualElement>();
public Spacer(Project project, PsiFile psiFile, Document document, RearrangerSettings settings) {
this.project = project;
this.psiFile = psiFile;
this.document = document;
this.settings = settings;
changesMade = false;
factory = JavaPsiFacade.getInstance(project).getElementFactory();
public Spacer(PsiFile psiFile, Document document, RearrangerSettings settings) {
myFile = psiFile;
myDocument = document;
mySettings = settings;
myChangesMade = false;
int size = 0;
size += settings.getAfterClassLBrace().getnBlankLines() + 1;
size += settings.getBeforeMethodLBrace().getnBlankLines() + 1;
@@ -61,9 +58,9 @@ public class Spacer {
size += settings.getBeforeClassRBrace().getnBlankLines() + 1;
size += settings.getAfterClassRBrace().getnBlankLines() + 1;
LOG.debug("constructor allocating " + size + " newline chars for max insertion");
newlineChars = new char[size];
myNewlineChars = new char[size];
while (size > 0) {
newlineChars[--size] = '\n';
myNewlineChars[--size] = '\n';
}
LOG.debug(settings.getAfterClassLBrace().toString());
LOG.debug(settings.getBeforeMethodLBrace().toString());
@@ -74,7 +71,7 @@ public class Spacer {
LOG.debug(settings.getAfterClassRBrace().toString());
final int ROOM_FOR_EXPANSION = 100;
int maxSize = document.getTextLength() + ROOM_FOR_EXPANSION;
sb = new StringBuffer(maxSize);
myBuffer = new StringBuilder(maxSize);
}
private class AbortRespacing extends RuntimeException {
@@ -86,7 +83,7 @@ public class Spacer {
}
}
private void handleBadPsiElementException(BadPsiElement bpe, String desc, PsiElement element)
private void handleBadPsiElementException(String desc, PsiElement element)
throws AbortRespacing
{
JOptionPane.showMessageDialog(null,
@@ -96,7 +93,7 @@ public class Spacer {
}
public boolean respace() {
sb.append(document.getText());
myBuffer.append(myDocument.getText());
JavaElementVisitor visitor = new JavaRecursiveElementVisitor() {
private int bias = 0;
@@ -106,13 +103,13 @@ public class Spacer {
public void visitFile(PsiFile psiFile) {
super.visitFile(psiFile);
if (settings.getNewLinesAtEOF().isForce()) {
if (mySettings.getNewLinesAtEOF().isForce()) {
// remove all newlines at end of file, then append as many as are declared in configuration.
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
while (myBuffer.length() > 0 && myBuffer.charAt(myBuffer.length() - 1) == '\n') {
myBuffer.setLength(myBuffer.length() - 1);
}
for (int count = 0; count < settings.getNewLinesAtEOF().getnBlankLines(); count++) {
sb.append('\n');
for (int count = 0; count < mySettings.getNewLinesAtEOF().getnBlankLines(); count++) {
myBuffer.append('\n');
}
}
}
@@ -131,32 +128,28 @@ public class Spacer {
bias += adjustSpacing(
psiClass.getLBrace(),
psiClass.getRBrace(),
settings.getAfterClassLBrace(),
mySettings.getAfterClassLBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"class " + psiClass.getName() + " missing left brace. Body follows:",
psiClass);
handleBadPsiElementException("class " + psiClass.getName() + " missing left brace. Body follows:", psiClass);
}
log(settings.getAfterClassLBrace(), psiClass.getName(), oldbias, bias);
log(mySettings.getAfterClassLBrace(), psiClass.getName(), oldbias, bias);
super.visitClass(psiClass);
oldbias = bias;
try {
bias += adjustSpacing(
psiClass.getRBrace(),
psiClass.getLBrace(),
settings.getBeforeClassRBrace(),
mySettings.getBeforeClassRBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"class " + psiClass.getName() + " missing right brace. Body follows:",
psiClass);
handleBadPsiElementException("class " + psiClass.getName() + " missing right brace. Body follows:", psiClass);
}
log(settings.getBeforeClassRBrace(), psiClass.getName(), oldbias, bias);
log(mySettings.getBeforeClassRBrace(), psiClass.getName(), oldbias, bias);
if (anonymous) {
return;
@@ -176,16 +169,14 @@ public class Spacer {
bias += adjustSpacing(
psiClass.getRBrace(),
psiClass.getLBrace(),
settings.getAfterClassRBrace(),
mySettings.getAfterClassRBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"class " + psiClass.getName() + " missing left brace. Body follows:",
psiClass);
handleBadPsiElementException("class " + psiClass.getName() + " missing left brace. Body follows:", psiClass);
}
log(settings.getAfterClassRBrace(), psiClass.getName(), oldbias, bias);
log(mySettings.getAfterClassRBrace(), psiClass.getName(), oldbias, bias);
}
else {
LOG.debug(
@@ -230,38 +221,34 @@ public class Spacer {
bias += adjustSpacing(
psiMethod.getBody().getLBrace(),
psiMethod.getBody().getRBrace(),
settings.getBeforeMethodLBrace(),
mySettings.getBeforeMethodLBrace(),
bias
);
bias += adjustSpacing(
psiMethod.getBody().getLBrace(),
psiMethod.getBody().getRBrace(),
settings.getAfterMethodLBrace(),
mySettings.getAfterMethodLBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"body of method " + psiMethod.getName() + " missing left brace. Body follows:",
psiMethod);
handleBadPsiElementException("body of method " + psiMethod.getName() + " missing left brace. Body follows:", psiMethod);
}
log(settings.getAfterMethodLBrace(), psiMethod.getName(), oldbias, bias);
log(mySettings.getAfterMethodLBrace(), psiMethod.getName(), oldbias, bias);
super.visitMethod(psiMethod);
oldbias = bias;
try {
bias += adjustSpacing(
psiMethod.getBody().getRBrace(),
psiMethod.getBody().getLBrace(),
settings.getBeforeMethodRBrace(),
mySettings.getBeforeMethodRBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"body of method " + psiMethod.getName() + " missing right brace. Body follows:",
psiMethod);
handleBadPsiElementException("body of method " + psiMethod.getName() + " missing right brace. Body follows:", psiMethod);
}
log(settings.getBeforeMethodRBrace(), psiMethod.getName(), oldbias, bias);
log(mySettings.getBeforeMethodRBrace(), psiMethod.getName(), oldbias, bias);
}
else {
LOG.debug("method " + psiMethod.getName() + " is empty, no internal spacing changes");
@@ -285,16 +272,14 @@ public class Spacer {
bias += adjustSpacing(
psiMethod.getBody().getRBrace(),
psiMethod.getBody().getLBrace(),
settings.getAfterMethodRBrace(),
mySettings.getAfterMethodRBrace(),
bias
);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"body of method " + psiMethod.getName() + " missing right brace. Body follows:",
psiMethod);
handleBadPsiElementException("body of method " + psiMethod.getName() + " missing right brace. Body follows:", psiMethod);
}
log(settings.getAfterMethodRBrace(), psiMethod.getName(), oldbias, bias);
log(mySettings.getAfterMethodRBrace(), psiMethod.getName(), oldbias, bias);
}
else {
LOG.debug(
@@ -308,7 +293,7 @@ public class Spacer {
public void visitCodeBlock(PsiCodeBlock psiCodeBlock) {
int oldbias;
if (!(psiCodeBlock.getParent() instanceof PsiMethod) &&
settings.isRemoveBlanksInsideCodeBlocks())
mySettings.isRemoveBlanksInsideCodeBlocks())
{
oldbias = bias;
try {
@@ -316,43 +301,41 @@ public class Spacer {
psiCodeBlock.getRBrace(), false, 0, bias);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"code block missing left brace. Content follows:\n", psiCodeBlock);
handleBadPsiElementException("code block missing left brace. Content follows:\n", psiCodeBlock);
}
log("code block left brace", oldbias, bias);
}
super.visitCodeBlock(psiCodeBlock);
if (!(psiCodeBlock.getParent() instanceof PsiMethod) &&
settings.isRemoveBlanksInsideCodeBlocks())
mySettings.isRemoveBlanksInsideCodeBlocks())
{
oldbias = bias;
try {
bias += adjustSpacing(psiCodeBlock.getRBrace(), psiCodeBlock.getLBrace(), true, 0, bias);
}
catch (BadPsiElement badPsiElement) {
handleBadPsiElementException(badPsiElement,
"code block missing right brace. Content follows:\n", psiCodeBlock);
handleBadPsiElementException("code block missing right brace. Content follows:\n", psiCodeBlock);
}
log("code block right brace", oldbias, bias);
}
}
};
try {
psiFile.accept(visitor);
myFile.accept(visitor);
}
catch (AbortRespacing ar) {
return false;
}
if (changesMade) {
if (myChangesMade) {
LOG.debug(
"changes made to document; old length=" +
document.getTextLength() + ", new=" + sb.length()
myDocument.getTextLength() + ", new=" + myBuffer.length()
);
LOG.debug("old document is:\n" + document.getText());
LOG.debug("new document is:\n" + sb.toString());
document.replaceString(0, document.getTextLength(), sb.toString());
LOG.debug("old document is:\n" + myDocument.getText());
LOG.debug("new document is:\n" + myBuffer.toString());
myDocument.replaceString(0, myDocument.getTextLength(), myBuffer.toString());
}
return changesMade;
return myChangesMade;
}
/**
@@ -478,17 +461,17 @@ public class Spacer {
int direction = before ? -1 : +1;
int count = 0;
{
char braceChar = sb.charAt(offset);
char braceChar = myBuffer.charAt(offset);
if (braceChar != '{' && braceChar != '}') {
int L = offset - 50;
int R = offset + 50;
if (L < 0) {
L = 0;
}
if (R > sb.length()) {
R = sb.length();
if (R > myBuffer.length()) {
R = myBuffer.length();
}
String context = sb.toString().substring(L, R);
String context = myBuffer.toString().substring(L, R);
throw new RuntimeException(
"adjustSpacing: char at offset " +
offset +
@@ -539,7 +522,7 @@ public class Spacer {
/**
* first count the number of existing blank lines.
*/
if (offset + direction >= sb.length()) {
if (offset + direction >= myBuffer.length()) {
LOG.debug("at EOF, don't append any extra blank lines");
// we're at end of file. Don't append any extra blank lines.
nBlankLines = 0;
@@ -607,31 +590,31 @@ public class Spacer {
endIndex += offset + 1;
}
else {
offset = endIndex = sb.length();
offset = endIndex = myBuffer.length();
}
try {
changesMade = true;
myChangesMade = true;
LOG.debug(
"sb.replace(" +
offset +
"," +
endIndex + ") with " + desiredNewlineChars + " newline characters"
);
sb.replace(offset, endIndex, new String(newlineChars, 0, desiredNewlineChars));
myBuffer.replace(offset, endIndex, new String(myNewlineChars, 0, desiredNewlineChars));
result = desiredNewlineChars - (endIndex - offset);
// now update virtualWhiteSpace accordingly.
if (virtualWhiteSpace != null) {
offset -= virtualWhiteSpace.getTextOffset();
endIndex -= virtualWhiteSpace.getTextOffset();
StringBuffer vsb = new StringBuffer(virtualWhiteSpace.getText());
vsb.replace(offset, endIndex, new String(newlineChars, 0, desiredNewlineChars));
vsb.replace(offset, endIndex, new String(myNewlineChars, 0, desiredNewlineChars));
virtualWhiteSpace.setTextValue(vsb.toString());
}
}
catch (StringIndexOutOfBoundsException si) {
throw new RuntimeException(
"sb.length()=" +
sb.length() +
myBuffer.length() +
", offset=" +
offset +
", before=" +
@@ -640,7 +623,7 @@ public class Spacer {
count +
", desiredNewlineChars=" +
desiredNewlineChars +
", charAt offset=" + (offset < sb.length() ? "" + sb.charAt(offset) : "OOB"), si
", charAt offset=" + (offset < myBuffer.length() ? "" + myBuffer.charAt(offset) : "OOB"), si
);
}
return result;
@@ -33,32 +33,30 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Used to store a generated comment, and to determine if it should be emitted. */
public abstract class CommentRuleInstance
implements RuleInstance,
FilePopupEntry
{
protected final CommentRule commentRule;
protected boolean emit;
public abstract class CommentRuleInstance implements RuleInstance, FilePopupEntry {
protected final CommentRule myCommentRule;
protected boolean myEmit;
public CommentRuleInstance(final CommentRule commentRule) {
this.commentRule = commentRule;
emit = false;
this.myCommentRule = commentRule;
myEmit = false;
}
public boolean isEmit() {
return emit;
return myEmit;
}
public void setEmit(final boolean emit) {
this.emit = emit;
this.myEmit = emit;
}
public Rule getRule() {
return commentRule;
return myCommentRule;
}
/** Determine if this comment, in this instance, should be emitted. */
@@ -69,15 +67,15 @@ public abstract class CommentRuleInstance
}
public void emit(Emitter emitter) {
StringBuffer sb = emitter.getStringBuffer();
if (emit) {
StringBuilder sb = emitter.getTextBuffer();
if (myEmit) {
// emit a comment. Precede with a newline unless this is the first line of the file.
if (sb.length() > 0) {
sb.append('\n');
sb.append(commentRule.getExpandedCommentText());
sb.append(myCommentRule.getExpandedCommentText());
}
else {
sb.append(commentRule.getExpandedCommentText());
sb.append(myCommentRule.getExpandedCommentText());
sb.append('\n');
}
}
@@ -91,12 +89,10 @@ public abstract class CommentRuleInstance
}
public List<RangeEntry> getMatches() {
return new ArrayList<RangeEntry>();
return Collections.emptyList();
}
public void rearrangeRuleItems(List<ClassContentsEntry> entries,
RearrangerSettings settings)
{
public void rearrangeRuleItems(List<ClassContentsEntry> entries, RearrangerSettings settings) {
}
public void addRuleInstanceToPopupTree(DefaultMutableTreeNode node, RearrangerSettings settings) {
@@ -117,7 +113,7 @@ public abstract class CommentRuleInstance
* append the comment if generated and if showComments is set.
*/
if (isEmit()) {
commentRule.addToPopupTree(top, settings);
myCommentRule.addToPopupTree(top, settings);
}
}
@@ -131,14 +127,14 @@ public abstract class CommentRuleInstance
}
public JLabel getPopupEntryText(RearrangerSettings settings) {
JLabel label = new JLabel(commentRule.toString());
JLabel label = new JLabel(myCommentRule.toString());
Font font = label.getFont().deriveFont(Font.ITALIC);
label.setFont(font);
return label;
}
public String toString() {
return "instance of:" + commentRule.toString();
return "instance of:" + myCommentRule.toString();
}
/**
@@ -23,7 +23,7 @@ package com.wrq.rearranger.ruleinstance;
import com.intellij.openapi.diagnostic.Logger;
import com.wrq.rearranger.entry.ClassContentsEntry;
import com.wrq.rearranger.entry.IPopupTreeRangeEntry;
import com.wrq.rearranger.entry.PopupTreeRangeEntry;
import com.wrq.rearranger.entry.MethodEntry;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.popup.FilePopupEntry;
@@ -65,7 +65,7 @@ public abstract class CommonRuleInstance
*/
public void addEntry(RangeEntry entry) {
if (myRule instanceof CommonAttributes) {
SortOptions sortOptions = ((CommonAttributes)myRule).getSortAttr();
SortOptions sortOptions = ((CommonAttributes)myRule).getSortOptions();
insertionSort(entry, sortOptions);
}
else {
@@ -135,7 +135,7 @@ public abstract class CommonRuleInstance
/**
* append each of the matches to the top level.
*/
for (IPopupTreeRangeEntry entry : getMatches()) {
for (PopupTreeRangeEntry entry : getMatches()) {
entry.addToPopupTree(top, settings);
}
}
@@ -26,19 +26,20 @@ import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.rearrangement.Emitter;
import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.settings.attributeGroups.Rule;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.ArrayList;
import java.util.List;
/** Instance to pick up header text. */
public class HeaderTrailerRuleInstance
implements RuleInstance
{
private final Rule myRule;
private RangeEntry myEntry;
public class HeaderTrailerRuleInstance implements RuleInstance {
public HeaderTrailerRuleInstance(Rule rule) {
@NotNull private final Rule myRule;
@Nullable private RangeEntry myEntry;
public HeaderTrailerRuleInstance(@NotNull Rule rule) {
myRule = rule;
}
@@ -55,12 +56,13 @@ public class HeaderTrailerRuleInstance
return list;
}
@NotNull
public Rule getRule() {
return myRule;
}
public void addEntry(RangeEntry entry) {
this.myEntry = entry; // a header only has one entry
public void addEntry(@Nullable RangeEntry entry) {
myEntry = entry; // a header only has one entry
}
public void emit(Emitter emitter) {
@@ -118,20 +118,21 @@ public class InterfaceInstance
}
}
@SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder")
void emit(Emitter emitter) {
StringBuffer sb = emitter.getStringBuffer();
StringBuilder buffer = emitter.getTextBuffer();
String commentString = expandComment(rule.getPrecedingComment());
if (commentString.length() > 0) {
sb.append("\n");
sb.append(commentString);
buffer.append("\n");
buffer.append(commentString);
}
for (MethodEntry rangeEntry : methods) {
rangeEntry.emit(emitter);
}
commentString = expandComment(rule.getTrailingComment());
if (commentString.length() > 0) {
sb.append("\n");
sb.append(commentString);
buffer.append("\n");
buffer.append(commentString);
}
}
@@ -38,10 +38,10 @@ public class PrecedingCommentRuleInstance
public void determineEmit(List<RuleInstance> resultRuleInstances, int startIndex) {
if (match(
resultRuleInstances,
commentRule.getnPrecedingRulesToMatch(),
myCommentRule.getnPrecedingRulesToMatch(),
-1,
startIndex,
commentRule.isAllPrecedingRules()))
myCommentRule.isAllPrecedingRules()))
{
setEmit(true);
}
@@ -32,10 +32,11 @@ import javax.swing.tree.DefaultMutableTreeNode;
import java.util.List;
/**
* One RuleInstance exists for every execution of every rule. An execution of a rule is the process by which
* One {@link RuleInstance} exists for every execution of every rule. An execution of a rule is the process by which
* items are matched to a rule.
*/
public interface RuleInstance {
/** @return true if one or more items matched the rule in this instance. */
boolean hasMatches();
@@ -38,10 +38,10 @@ public class SubsequentCommentRuleInstance
public void determineEmit(List<RuleInstance> resultRuleInstances, int startIndex) {
if (match(
resultRuleInstances,
commentRule.getnSubsequentRulesToMatch(),
myCommentRule.getnSubsequentRulesToMatch(),
+1,
startIndex,
commentRule.isAllSubsequentRules()
myCommentRule.isAllSubsequentRules()
))
{
setEmit(true);
@@ -38,17 +38,17 @@ public class SurroundingCommentRuleInstance
public void determineEmit(List<RuleInstance> resultRuleInstances, int startIndex) {
if (match(
resultRuleInstances,
commentRule.getnPrecedingRulesToMatch(),
myCommentRule.getnPrecedingRulesToMatch(),
-1,
startIndex,
commentRule.isAllPrecedingRules()
myCommentRule.isAllPrecedingRules()
) &&
match(
resultRuleInstances,
commentRule.getnSubsequentRulesToMatch(),
myCommentRule.getnSubsequentRulesToMatch(),
+1,
startIndex,
commentRule.isAllSubsequentRules()
myCommentRule.isAllSubsequentRules()
))
{
setEmit(true);
@@ -21,7 +21,7 @@
*/
package com.wrq.rearranger.settings;
import com.wrq.rearranger.entry.IPopupTreeRangeEntry;
import com.wrq.rearranger.entry.PopupTreeRangeEntry;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.popup.FilePopupEntry;
import com.wrq.rearranger.popup.RearrangerTreeNode;
@@ -32,6 +32,7 @@ import com.wrq.rearranger.settings.attributeGroups.RegexUtil;
import com.wrq.rearranger.util.Constraints;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -50,7 +51,7 @@ import java.util.List;
/** Handles insertion of comment separators between sections of the rearranged file. */
public final class CommentRule
implements AttributeGroup,
IPopupTreeRangeEntry,
PopupTreeRangeEntry,
FilePopupEntry
{
// ------------------------------------------------------- FIELDS ------------------------------------------------------
@@ -417,6 +418,7 @@ public final class CommentRule
// ---------------------------------------------- Interface AttributeGroup ---------------------------------------------
@NotNull
public final /*CommentRule*/AttributeGroup deepCopy() {
final CommentRule comment = new CommentRule();
comment.commentText = commentText;
@@ -429,7 +431,7 @@ public final class CommentRule
return comment;
}
public final void writeExternal(final Element parent) {
public final void writeExternal(@NotNull final Element parent) {
final Element me = new Element("Comment");
me.setText(escape(commentText));
me.setAttribute("condition", "" + emitCondition);
@@ -464,11 +466,12 @@ public final class CommentRule
// -------------------------------------------------- Interface IRule --------------------------------------------------
@NotNull
public RuleInstance createRuleInstance() {
return CommentRuleInstanceFactory.buildCommentRuleInstance(this);
}
public boolean isMatch(RangeEntry rangeEntry) {
public boolean isMatch(@NotNull RangeEntry rangeEntry) {
return false; // comment rules match no entries -- they're just placeholders to generate comments.
}
@@ -22,15 +22,15 @@
package com.wrq.rearranger.settings.attributeGroups;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
/** Methods implemented by rule objects, which are saved in configuration. */
public interface AttributeGroup
extends Rule
{
public interface AttributeGroup extends Rule {
// -------------------------- OTHER METHODS --------------------------
public AttributeGroup deepCopy();
@NotNull
AttributeGroup deepCopy();
public void writeExternal(final Element parent);
void writeExternal(final @NotNull Element parent);
}
@@ -29,6 +29,8 @@ import com.wrq.rearranger.settings.atomicAttributes.AbstractAttribute;
import com.wrq.rearranger.settings.atomicAttributes.EnumAttribute;
import com.wrq.rearranger.util.Constraints;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
@@ -47,6 +49,7 @@ public final class ClassAttributes
// -------------------------- STATIC METHODS --------------------------
@Nullable
public static AttributeGroup readExternal(final Element element) {
if (element.getName().equals("Class")) {
final ClassAttributes result = new ClassAttributes();
@@ -82,11 +85,11 @@ public final class ClassAttributes
// ------------------------ CANONICAL METHODS ------------------------
public final String toString() {
final StringBuffer sb = new StringBuffer(70);
final StringBuilder sb = new StringBuilder(70);
sb.append(abAttr.getDescriptiveString());
sb.append(plAttr.getProtectionLevelString());
sb.append(stAttr.getDescriptiveString());
sb.append(fAttr.getDescriptiveString());
sb.append(getProtectionLevelAttributes().getProtectionLevelString());
sb.append(getStaticAttribute().getDescriptiveString());
sb.append(getFinalAttribute().getDescriptiveString());
sb.append(enumAttr.getDescriptiveString());
if (sb.length() == 0) {
sb.append("all classes");
@@ -94,11 +97,11 @@ public final class ClassAttributes
else {
sb.append("classes");
}
if (nameAttr.isMatch()) {
if (getNameAttribute().isMatch()) {
sb.append(' ');
sb.append(nameAttr.getDescriptiveString());
sb.append(getNameAttribute().getDescriptiveString());
}
sb.append(sortAttr.getDescriptiveString());
sb.append(getSortOptions().getDescriptiveString());
return sb.toString();
}
@@ -107,6 +110,7 @@ public final class ClassAttributes
// --------------------- Interface AttributeGroup ---------------------
@NotNull
public final /*ClassAttributes*/AttributeGroup deepCopy() {
final ClassAttributes result = new ClassAttributes();
deepCopyCommonItems(result);
@@ -115,7 +119,8 @@ public final class ClassAttributes
return result;
}
public final void writeExternal(final Element parent) {
@SuppressWarnings("unchecked")
public final void writeExternal(@NotNull final Element parent) {
final Element me = new Element("Class");
writeExternalCommonAttributes(me);
abAttr.appendAttributes(me);
@@ -146,27 +151,27 @@ public final class ClassAttributes
constraints.weightx = 1.0d;
constraints.weighty = 0.0d;
constraints.insets = new Insets(0, 0, 10, 0);
caPanel.add(getPlAttr().getProtectionLevelPanel(), constraints);
caPanel.add(getProtectionLevelAttributes().getProtectionLevelPanel(), constraints);
constraints.gridy = 4;
constraints.gridheight = 1;
caPanel.add(getStAttr().getAndNotPanel(), constraints);
caPanel.add(getStaticAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getAbAttr().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getfAttr().getAndNotPanel(), constraints);
caPanel.add(getFinalAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getEnumAttr().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getNameAttr().getStringPanel(), constraints);
caPanel.add(getNameAttribute().getStringPanel(), constraints);
constraints.gridy++;
constraints.gridheight = GridBagConstraints.REMAINDER;
constraints.weighty = 1.0d;
constraints.insets = new Insets(0, 0, 0, 0);
caPanel.add(sortAttr.getSortOptionsPanel(), constraints);
caPanel.add(getSortOptions().getSortOptionsPanel(), constraints);
return caPanel;
}
public final boolean isMatch(RangeEntry entry)
public final boolean isMatch(@NotNull RangeEntry entry)
// final int modifiers, final String name, final String returnType)
{
return entry.getEnd().getParent() instanceof PsiClass &&
@@ -27,6 +27,7 @@ import com.wrq.rearranger.ruleinstance.RuleInstance;
import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.settings.atomicAttributes.*;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -36,64 +37,63 @@ import java.util.List;
* protected, package), final modifier, and static modifier. Ability to match the name to a regular
* expression is also supported.
*/
public abstract class CommonAttributes
implements AttributeGroup, PrioritizedRule
{
public abstract class CommonAttributes implements AttributeGroup, PrioritizedRule {
// ------------------------------ FIELDS ------------------------------
ProtectionLevelAttributes plAttr;
FinalAttribute fAttr;
StaticAttribute stAttr;
NameAttribute nameAttr;
SortOptions sortAttr;
int priority; // 1 = low priority, > 1 is higher priority
private ProtectionLevelAttributes myProtectionLevelAttributes;
private FinalAttribute myFinalAttribute;
private StaticAttribute myStaticAttribute;
private NameAttribute myNameAttribute;
private SortOptions mySortOptions;
private int myPriority; // 1 = low priority, > 1 is higher priority
// -------------------------- STATIC METHODS --------------------------
static void readExternal(final CommonAttributes result, final Element item) {
result.plAttr = ProtectionLevelAttributes.readExternal(item);
result.stAttr = StaticAttribute.readExternal(item);
result.fAttr = FinalAttribute.readExternal(item);
result.nameAttr = NameAttribute.readExternal(item);
result.sortAttr = SortOptions.readExternal(item);
result.priority = RearrangerSettings.getIntAttribute(item, "priority", 1);
result.myProtectionLevelAttributes = ProtectionLevelAttributes.readExternal(item);
result.myStaticAttribute = StaticAttribute.readExternal(item);
result.myFinalAttribute = FinalAttribute.readExternal(item);
result.myNameAttribute = NameAttribute.readExternal(item);
result.mySortOptions = SortOptions.readExternal(item);
result.myPriority = RearrangerSettings.getIntAttribute(item, "priority", 1);
}
// --------------------------- CONSTRUCTORS ---------------------------
public CommonAttributes() {
plAttr = new ProtectionLevelAttributes();
fAttr = new FinalAttribute();
stAttr = new StaticAttribute();
nameAttr = new NameAttribute();
sortAttr = new SortOptions();
priority = 1;
myProtectionLevelAttributes = new ProtectionLevelAttributes();
myFinalAttribute = new FinalAttribute();
myStaticAttribute = new StaticAttribute();
myNameAttribute = new NameAttribute();
mySortOptions = new SortOptions();
myPriority = 1;
}
// --------------------- GETTER / SETTER METHODS ---------------------
public final NameAttribute getNameAttr() {
return nameAttr;
public final NameAttribute getNameAttribute() {
return myNameAttribute;
}
final public ProtectionLevelAttributes getPlAttr() {
return plAttr;
final public ProtectionLevelAttributes getProtectionLevelAttributes() {
return myProtectionLevelAttributes;
}
public int getPriority() {
return priority;
return myPriority;
}
public void setPriority(int priority) {
this.priority = priority;
this.myPriority = priority;
}
final public StaticAttribute getStAttr() {
return stAttr;
final public StaticAttribute getStaticAttribute() {
return myStaticAttribute;
}
public SortOptions getSortAttr() {
return sortAttr;
public SortOptions getSortOptions() {
return mySortOptions;
}
// ------------------------ CANONICAL METHODS ------------------------
@@ -103,12 +103,12 @@ public abstract class CommonAttributes
return false;
}
final CommonAttributes ca = (CommonAttributes)obj;
return plAttr.equals(ca.plAttr) &&
stAttr.equals(ca.stAttr) &&
fAttr.equals(ca.fAttr) &&
nameAttr.equals(ca.nameAttr) &&
sortAttr.equals(ca.sortAttr) &&
priority == ca.priority;
return myProtectionLevelAttributes.equals(ca.myProtectionLevelAttributes) &&
myStaticAttribute.equals(ca.myStaticAttribute) &&
myFinalAttribute.equals(ca.myFinalAttribute) &&
myNameAttribute.equals(ca.myNameAttribute) &&
mySortOptions.equals(ca.mySortOptions) &&
myPriority == ca.myPriority;
}
// ------------------------ INTERFACE METHODS ------------------------
@@ -116,16 +116,14 @@ public abstract class CommonAttributes
// --------------------- Interface IRule ---------------------
@NotNull
public RuleInstance createRuleInstance() {
return new DefaultRuleInstance(this);
}
public boolean isMatch(RangeEntry rangeEntry) {
final boolean result = plAttr.isMatch(rangeEntry.getModifiers()) &&
stAttr.isMatch(rangeEntry.getModifiers()) &&
fAttr.isMatch(rangeEntry.getModifiers()) &&
nameAttr.isMatch(rangeEntry.getName());
return result;
public boolean isMatch(@NotNull RangeEntry rangeEntry) {
return myProtectionLevelAttributes.isMatch(rangeEntry.getModifiers()) && myStaticAttribute.isMatch(rangeEntry.getModifiers())
&& myFinalAttribute.isMatch(rangeEntry.getModifiers()) && myNameAttribute.isMatch(rangeEntry.getName());
}
/**
@@ -147,38 +145,31 @@ public abstract class CommonAttributes
return 0;
}
/**
* Calculates a list of regular expression patterns, one for each comment that the rule might create, which will
* match any comment that the rule might generate. These can be combined to form a global comment pattern which
* will match all possible generated comments from all rules. These patterns will be appended to the supplied
* list.
*/
public void addCommentPatternsToList(List<String> list) {
return;
}
// -------------------------- OTHER METHODS --------------------------
final void deepCopyCommonItems(final CommonAttributes result) {
result.plAttr = (ProtectionLevelAttributes)plAttr.deepCopy();
result.fAttr = (FinalAttribute)fAttr.deepCopy();
result.stAttr = (StaticAttribute)stAttr.deepCopy();
result.nameAttr = (NameAttribute)nameAttr.deepCopy();
result.sortAttr = (SortOptions)sortAttr.deepCopy();
result.priority = priority;
result.myProtectionLevelAttributes = (ProtectionLevelAttributes)myProtectionLevelAttributes.deepCopy();
result.myFinalAttribute = (FinalAttribute)myFinalAttribute.deepCopy();
result.myStaticAttribute = (StaticAttribute)myStaticAttribute.deepCopy();
result.myNameAttribute = (NameAttribute)myNameAttribute.deepCopy();
result.mySortOptions = (SortOptions)mySortOptions.deepCopy();
result.myPriority = myPriority;
}
final public FinalAttribute getfAttr() {
return fAttr;
final public FinalAttribute getFinalAttribute() {
return myFinalAttribute;
}
final void writeExternalCommonAttributes(final Element child) {
plAttr.appendAttributes(child);
stAttr.appendAttributes(child);
fAttr.appendAttributes(child);
nameAttr.appendAttributes(child);
sortAttr.appendAttributes(child);
child.setAttribute("priority", "" + priority);
myProtectionLevelAttributes.appendAttributes(child);
myStaticAttribute.appendAttributes(child);
myFinalAttribute.appendAttributes(child);
myNameAttribute.appendAttributes(child);
mySortOptions.appendAttributes(child);
child.setAttribute("priority", String.valueOf(myPriority));
}
}
@@ -24,6 +24,7 @@ package com.wrq.rearranger.settings.attributeGroups;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.ruleinstance.DefaultRuleInstance;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -35,6 +36,7 @@ import java.util.List;
public class DefaultRule
implements Rule
{
@NotNull
public RuleInstance createRuleInstance() {
return new DefaultRuleInstance(this);
}
@@ -47,7 +49,7 @@ public class DefaultRule
// does nothing
}
public boolean isMatch(RangeEntry entry) {
public boolean isMatch(@NotNull RangeEntry entry) {
return !(entry.isFixedHeader() || entry.isFixedTrailer());
}
@@ -29,6 +29,7 @@ import com.wrq.rearranger.settings.atomicAttributes.TypeAttribute;
import com.wrq.rearranger.settings.atomicAttributes.VolatileAttribute;
import com.wrq.rearranger.util.Constraints;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -88,10 +89,10 @@ public final class FieldAttributes
// ------------------------ CANONICAL METHODS ------------------------
public final String toString() {
final StringBuffer sb = new StringBuffer(70);
sb.append(plAttr.getProtectionLevelString());
sb.append(stAttr.getDescriptiveString());
sb.append(fAttr.getDescriptiveString());
final StringBuilder sb = new StringBuilder(70);
sb.append(getProtectionLevelAttributes().getProtectionLevelString());
sb.append(getStaticAttribute().getDescriptiveString());
sb.append(getFinalAttribute().getDescriptiveString());
sb.append(transientAttr.getDescriptiveString());
sb.append(volatileAttr.getDescriptiveString());
@@ -109,21 +110,21 @@ public final class FieldAttributes
sb.append(" which are not initialized to an anonymous class");
}
}
if (nameAttr.isMatch()) {
if (getNameAttribute().isMatch()) {
if (initToAnonClassAttr.isValue()) {
sb.append(" and");
}
sb.append(' ');
sb.append(nameAttr.getDescriptiveString());
sb.append(getNameAttribute().getDescriptiveString());
}
if (typeAttr.isMatch()) {
if (nameAttr.isMatch() || initToAnonClassAttr.isValue()) {
if (getNameAttribute().isMatch() || initToAnonClassAttr.isValue()) {
sb.append(" and");
}
sb.append(' ');
sb.append(typeAttr.getDescriptiveString());
}
sb.append(sortAttr.getDescriptiveString());
sb.append(getSortOptions().getDescriptiveString());
return sb.toString();
}
@@ -132,6 +133,7 @@ public final class FieldAttributes
// --------------------- Interface AttributeGroup ---------------------
@NotNull
public final /*FieldAttributes*/AttributeGroup deepCopy() {
final FieldAttributes result = new FieldAttributes();
deepCopyCommonItems(result);
@@ -142,7 +144,8 @@ public final class FieldAttributes
return result;
}
public final void writeExternal(final Element parent) {
@SuppressWarnings("unchecked")
public final void writeExternal(@NotNull final Element parent) {
final Element child = new Element("Field");
writeExternalCommonAttributes(child);
initToAnonClassAttr.appendAttributes(child);
@@ -173,16 +176,16 @@ public final class FieldAttributes
constraints.gridwidth = 1;
constraints.gridheight = 4;
constraints.weightx = 1.0d;
plPanel.add(getPlAttr().getProtectionLevelPanel(), constraints);
plPanel.add(getProtectionLevelAttributes().getProtectionLevelPanel(), constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.gridy = 0;
constraints.gridx = 1;
constraints.gridheight = 1;
constraints.weighty = 0;
plPanel.add(getStAttr().getAndNotPanel(), constraints);
plPanel.add(getStaticAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
plPanel.add(getfAttr().getAndNotPanel(), constraints);
plPanel.add(getFinalAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
plPanel.add(getTransientAttr().getAndNotPanel(), constraints);
constraints.gridy++;
@@ -192,18 +195,18 @@ public final class FieldAttributes
constraints.gridy++;
plPanel.add(getInitToAnonClassAttr().getAndNotPanel(), constraints);
constraints.gridy++;
plPanel.add(getNameAttr().getStringPanel(), constraints);
plPanel.add(getNameAttribute().getStringPanel(), constraints);
constraints.gridy++;
plPanel.add(getTypeAttr().getStringPanel(), constraints);
constraints.gridy++;
constraints.gridheight = GridBagConstraints.REMAINDER;
constraints.weighty = 1.0d;
constraints.insets = new Insets(0, 0, 0, 0);
plPanel.add(sortAttr.getSortOptionsPanel(), constraints);
plPanel.add(getSortOptions().getSortOptionsPanel(), constraints);
return plPanel;
}
public boolean isMatch(RangeEntry rangeEntry) {
public boolean isMatch(@NotNull RangeEntry rangeEntry) {
return rangeEntry.getEnd() instanceof PsiField &&
initToAnonClassAttr.isMatch(rangeEntry.getModifiers()) &&
transientAttr.isMatch(rangeEntry.getModifiers()) &&
@@ -24,14 +24,16 @@ package com.wrq.rearranger.settings.attributeGroups;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.ruleinstance.HeaderTrailerRuleInstance;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/** A rule to match header text (text which does not constitute a matchable item such as a field or method.) */
public class HeaderRule
implements Rule
{
public class HeaderRule implements Rule {
@NotNull
public RuleInstance createRuleInstance() {
return new HeaderTrailerRuleInstance(this);
}
@@ -45,15 +47,15 @@ public class HeaderRule
// does nothing
}
public boolean isMatch(RangeEntry rangeEntry) {
public boolean isMatch(@NotNull RangeEntry rangeEntry) {
return rangeEntry.isFixedHeader();
}
public boolean commentsMatchGlobalPattern(String pattern) {
public boolean commentsMatchGlobalPattern(@Nullable String pattern) {
return true;
}
public List<String> getOffendingPatterns(String pattern) {
public List<String> getOffendingPatterns(@Nullable String pattern) {
return new ArrayList<String>(1);
}
@@ -61,6 +63,6 @@ public class HeaderRule
return 0;
}
public void addCommentPatternsToList(List<String> list) {
public void addCommentPatternsToList(@Nullable List<String> list) {
}
}
@@ -28,6 +28,7 @@ import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.settings.atomicAttributes.AbstractAttribute;
import com.wrq.rearranger.settings.atomicAttributes.EnumAttribute;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -72,11 +73,11 @@ public final class InnerClassAttributes
// ------------------------ CANONICAL METHODS ------------------------
public final String toString() {
final StringBuffer sb = new StringBuffer(70);
final StringBuilder sb = new StringBuilder(70);
sb.append(abAttr.getDescriptiveString());
sb.append(plAttr.getProtectionLevelString());
sb.append(stAttr.getDescriptiveString());
sb.append(fAttr.getDescriptiveString());
sb.append(getProtectionLevelAttributes().getProtectionLevelString());
sb.append(getStaticAttribute().getDescriptiveString());
sb.append(getFinalAttribute().getDescriptiveString());
sb.append(enumAttr.getDescriptiveString());
if (sb.length() == 0) {
sb.append("all inner classes");
@@ -84,11 +85,11 @@ public final class InnerClassAttributes
else {
sb.append("inner classes");
}
if (nameAttr.isMatch()) {
if (getNameAttribute().isMatch()) {
sb.append(' ');
sb.append(nameAttr.getDescriptiveString());
sb.append(getNameAttribute().getDescriptiveString());
}
sb.append(sortAttr.getDescriptiveString());
sb.append(getSortOptions().getDescriptiveString());
return sb.toString();
}
@@ -97,6 +98,7 @@ public final class InnerClassAttributes
// --------------------- Interface AttributeGroup ---------------------
@NotNull
public final /*InnerClassAttributes*/AttributeGroup deepCopy() {
final InnerClassAttributes result = new InnerClassAttributes();
deepCopyCommonItems(result);
@@ -105,7 +107,8 @@ public final class InnerClassAttributes
return result;
}
public final void writeExternal(final Element parent) {
@SuppressWarnings("unchecked")
public final void writeExternal(@NotNull final Element parent) {
final Element me = new Element("InnerClass");
writeExternalCommonAttributes(me);
abAttr.appendAttributes(me);
@@ -138,27 +141,27 @@ public final class InnerClassAttributes
constraints.weighty = 0.0d;
constraints.gridx = constraints.gridy = 0;
constraints.insets = new Insets(0, 0, 5, 0);
caPanel.add(getPlAttr().getProtectionLevelPanel(), constraints);
caPanel.add(getProtectionLevelAttributes().getProtectionLevelPanel(), constraints);
constraints.gridy = 1;
constraints.gridheight = 1;
caPanel.add(getStAttr().getAndNotPanel(), constraints);
caPanel.add(getStaticAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getAbAttr().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getfAttr().getAndNotPanel(), constraints);
caPanel.add(getFinalAttribute().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getEnumAttr().getAndNotPanel(), constraints);
constraints.gridy++;
caPanel.add(getNameAttr().getStringPanel(), constraints);
caPanel.add(getNameAttribute().getStringPanel(), constraints);
constraints.gridy++;
constraints.gridheight = GridBagConstraints.REMAINDER;
constraints.weighty = 1.0d;
constraints.insets = new Insets(0, 0, 0, 0);
caPanel.add(sortAttr.getSortOptionsPanel(), constraints);
caPanel.add(getSortOptions().getSortOptionsPanel(), constraints);
return caPanel;
}
public final boolean isMatch(RangeEntry entry) {
public final boolean isMatch(@NotNull RangeEntry entry) {
// return entry.getEnd() instanceof PsiClass &&
// entry.getEnd() should be the LBrace of a class.
return entry.getEnd().getParent() instanceof PsiClass &&
@@ -31,6 +31,7 @@ import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.settings.atomicAttributes.NameAttribute;
import com.wrq.rearranger.util.Constraints;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -136,11 +137,12 @@ public class InterfaceAttributes
return priority;
}
@NotNull
public RuleInstance createRuleInstance() {
return new InterfaceRuleInstance(this);
}
public final boolean isMatch(RangeEntry rangeEntry) {
public final boolean isMatch(@NotNull RangeEntry rangeEntry) {
if (rangeEntry instanceof MethodEntry) {
MethodEntry me = (MethodEntry)rangeEntry;
if (me.getInterfaceName() != null) {
@@ -191,6 +193,7 @@ public class InterfaceAttributes
return sb.toString();
}
@NotNull
public final /*InterfaceAttributes*/AttributeGroup deepCopy() {
final InterfaceAttributes result = new InterfaceAttributes();
result.nameAttr = (NameAttribute)nameAttr.deepCopy();
@@ -225,7 +228,7 @@ public class InterfaceAttributes
priority = RearrangerSettings.getIntAttribute(item, "priority", 1);
}
public final void writeExternal(final Element parent) {
public final void writeExternal(@NotNull final Element parent) {
final Element me = new Element("Interface");
parent.getChildren().add(me);
nameAttr.appendAttributes(me);
@@ -23,14 +23,15 @@ package com.wrq.rearranger.settings.attributeGroups;
import com.wrq.rearranger.settings.CommentRule;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/** Routines to handle attributes common to class members (fields, methods, and inner classes.) */
abstract public class ItemAttributes
extends CommonAttributes
{
abstract public class ItemAttributes extends CommonAttributes {
// -------------------------- STATIC METHODS --------------------------
@Nullable
public static AttributeGroup readExternal(final Element element) {
if (element.getName().equals("Field")) {
return FieldAttributes.readExternal(element);
@@ -57,6 +58,7 @@ abstract public class ItemAttributes
// --------------------- Interface AttributeGroup ---------------------
@NotNull
abstract public /*ItemAttributes*/AttributeGroup deepCopy();
}
@@ -29,6 +29,7 @@ import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.settings.atomicAttributes.*;
import com.wrq.rearranger.util.MethodUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -252,11 +253,11 @@ public final class MethodAttributes
public final String toString() {
// convert settings to readable English description of the method.
//
final StringBuffer sb = new StringBuffer(80);
final StringBuilder sb = new StringBuilder(80);
sb.append(plAttr.getProtectionLevelString());
sb.append(stAttr.getDescriptiveString());
sb.append(fAttr.getDescriptiveString());
sb.append(getProtectionLevelAttributes().getProtectionLevelString());
sb.append(getStaticAttribute().getDescriptiveString());
sb.append(getFinalAttribute().getDescriptiveString());
sb.append(staticInitAttr.getDescriptiveString());
sb.append(nativeAttr.getDescriptiveString());
sb.append(syncAttr.getDescriptiveString());
@@ -332,32 +333,32 @@ public final class MethodAttributes
}
}
}
if (nameAttr.isMatch()) {
if (getNameAttribute().isMatch()) {
checkPredicate(sb, false);
nextPredicate = nameAttr.getDescriptiveString();
nextPredicate = getNameAttribute().getDescriptiveString();
}
if (returnTypeAttr.isMatch()) {
checkPredicate(sb, false);
nextPredicate = returnTypeAttr.getDescriptiveString();
}
checkPredicate(sb, true);
sb.append(sortAttr.getDescriptiveString());
sb.append(getSortOptions().getDescriptiveString());
if (noExtractedMethods) {
sb.append(" (no extracted methods)");
}
return sb.toString();
}
private void checkPredicate(StringBuffer sb, boolean finalPredicate) {
private void checkPredicate(@NotNull StringBuilder buffer, boolean finalPredicate) {
if (predicateAdded && nextPredicate != null) {
sb.append(',');
buffer.append(',');
if (finalPredicate) {
sb.append(" and");
buffer.append(" and");
}
}
if (nextPredicate != null) {
sb.append(' ');
sb.append(nextPredicate);
buffer.append(' ');
buffer.append(nextPredicate);
predicateAdded = true;
nextPredicate = null;
}
@@ -369,6 +370,7 @@ public final class MethodAttributes
// --------------------- Interface AttributeGroup ---------------------
// Start Methods of Interface AttributeGroup
@NotNull
public final /*ItemAttributes*/AttributeGroup deepCopy() {
final MethodAttributes result = new MethodAttributes();
deepCopyCommonItems(result);
@@ -393,7 +395,8 @@ public final class MethodAttributes
return result;
}
public final void writeExternal(final Element parent) {
@SuppressWarnings("unchecked")
public final void writeExternal(@NotNull final Element parent) {
final Element me = new Element("Method");
writeExternalCommonAttributes(me);
abstractAttr.appendAttributes(me);
@@ -459,7 +462,7 @@ public final class MethodAttributes
constraints.weightx = 0.0d;
constraints.weighty = 0.0d;
constraints.gridx = constraints.gridy = 0;
methodPanel.add(getPlAttr().getProtectionLevelPanel(), constraints);
methodPanel.add(getProtectionLevelAttributes().getProtectionLevelPanel(), constraints);
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.gridheight = 1;
constraints.gridx = 1;
@@ -470,12 +473,12 @@ public final class MethodAttributes
constraints.gridx = 0;
constraints.gridheight = 1;
constraints.gridwidth = 1;
methodPanel.add(getStAttr().getAndNotPanel(), constraints);
methodPanel.add(getStaticAttribute().getAndNotPanel(), constraints);
constraints.gridx++;
methodPanel.add(getAbstractAttr().getAndNotPanel(), constraints);
constraints.gridx = 0;
constraints.gridy++;
methodPanel.add(getfAttr().getAndNotPanel(), constraints);
methodPanel.add(getFinalAttribute().getAndNotPanel(), constraints);
constraints.gridx++;
methodPanel.add(getSyncAttr().getAndNotPanel(), constraints);
constraints.gridx = 0;
@@ -500,7 +503,7 @@ public final class MethodAttributes
constraints.gridy++;
methodPanel.add(getMaxParamsAttr().getIntegerPanel(), constraints);
constraints.gridy++;
methodPanel.add(getNameAttr().getStringPanel(), constraints);
methodPanel.add(getNameAttribute().getStringPanel(), constraints);
constraints.gridy++;
methodPanel.add(getReturnTypeAttr().getStringPanel(), constraints);
constraints.gridy++;
@@ -509,7 +512,7 @@ public final class MethodAttributes
constraints.gridy++;
constraints.gridheight = GridBagConstraints.REMAINDER;
constraints.weighty = 1.0d;
methodPanel.add(sortAttr.getSortOptionsPanel(), constraints);
methodPanel.add(getSortOptions().getSortOptionsPanel(), constraints);
return methodPanel;
}
@@ -601,8 +604,8 @@ public final class MethodAttributes
});
gsDefButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
GetterSetterDefinition tempgsd = getterSetterDefinition.deepCopy();
final JPanel gsDefPanel = tempgsd.getGSDefinitionPanel();
GetterSetterDefinition tmpDefinition = getterSetterDefinition.deepCopy();
final JPanel gsDefPanel = tmpDefinition.getGSDefinitionPanel();
final JOptionPane op = new JOptionPane(
gsDefPanel,
JOptionPane.PLAIN_MESSAGE,
@@ -614,7 +617,7 @@ public final class MethodAttributes
if (result != null &&
((Integer)result) == JOptionPane.OK_OPTION)
{
getterSetterDefinition = tempgsd;
getterSetterDefinition = tmpDefinition;
}
}
});
@@ -625,7 +628,7 @@ public final class MethodAttributes
// End Methods of Interface AttributeGroup
// Start Methods of Interface IRule
public final boolean isMatch(RangeEntry entry) {
public final boolean isMatch(@NotNull RangeEntry entry) {
final boolean result = (entry.getEnd() instanceof PsiMethod ||
entry.getEnd() instanceof PsiClassInitializer) &&
super.isMatch(entry) &&
@@ -640,12 +643,12 @@ public final class MethodAttributes
returnTypeAttr.isMatch(entry.getType()) &&
minParamsAttr.isMatch(entry.getEnd()) &&
maxParamsAttr.isMatch(entry.getEnd());
if (result == false) {
if (!result) {
return false;
}
boolean typeResult = false;
if (isConstructorMethodType()) {
typeResult |= (entry.getModifiers() & ModifierConstants.CONSTRUCTOR) == ModifierConstants.CONSTRUCTOR;
typeResult = (entry.getModifiers() & ModifierConstants.CONSTRUCTOR) == ModifierConstants.CONSTRUCTOR;
}
if (isGetterSetterMethodType() &&
entry.getEnd() instanceof PsiMethod)
@@ -674,7 +677,7 @@ public final class MethodAttributes
{
typeResult = true; // true if no method type options are selected.
}
return result && typeResult;
return typeResult;
}
}
@@ -23,20 +23,23 @@ package com.wrq.rearranger.settings.attributeGroups;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/** Interface which all rules implement. */
public interface Rule {
@NotNull
RuleInstance createRuleInstance();
// all rules have a priority; but some are not settable by the user. Those that are user settable implement
// the marker interface IPrioritizableRule.
// the marker interface PrioritizedRule.
int getPriority();
void setPriority(int priority);
boolean isMatch(RangeEntry rangeEntry);
boolean isMatch(@NotNull RangeEntry rangeEntry);
/**
* @param pattern global pattern to which all comments should conform.
@@ -24,6 +24,7 @@ package com.wrq.rearranger.settings.attributeGroups;
import com.wrq.rearranger.entry.RangeEntry;
import com.wrq.rearranger.ruleinstance.HeaderTrailerRuleInstance;
import com.wrq.rearranger.ruleinstance.RuleInstance;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -32,6 +33,7 @@ import java.util.List;
public class TrailerRule
implements Rule
{
@NotNull
public RuleInstance createRuleInstance() {
return new HeaderTrailerRuleInstance(this);
}
@@ -45,7 +47,7 @@ public class TrailerRule
// does nothing
}
public boolean isMatch(RangeEntry rangeEntry) {
public boolean isMatch(@NotNull RangeEntry rangeEntry) {
return rangeEntry.isFixedTrailer();
}
@@ -21,8 +21,10 @@
*/
package com.wrq.rearranger.util;
import com.intellij.openapi.util.text.StringUtil;
import com.wrq.rearranger.settings.RearrangerSettings;
import com.wrq.rearranger.settings.attributeGroups.Rule;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -30,40 +32,38 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommentUtil {
final RearrangerSettings settings;
static CommentUtil singleton;
List<String> commentStrings;
List<Matcher> commentMatchers;
private final RearrangerSettings mySettings;
static CommentUtil singleton;
private final List<String> myCommentStrings = new ArrayList<String>();
private final List<Matcher> myCommentMatchers = new ArrayList<Matcher>();
public CommentUtil(RearrangerSettings settings) {
this.settings = settings;
public CommentUtil(@NotNull RearrangerSettings settings) {
mySettings = settings;
createCommentPatternList();
createCommentMatcherList();
singleton = this;
}
public static List<String> getCommentStrings() {
return singleton.commentStrings;
return singleton.myCommentStrings;
}
public static List<Matcher> getCommentMatchers() {
return singleton.commentMatchers;
return singleton.myCommentMatchers;
}
private void createCommentMatcherList() {
if (settings.getGlobalCommentPattern() != null &&
settings.getGlobalCommentPattern().length() > 0)
{
// create only one Matcher for the global comment pattern.
commentMatchers = new ArrayList<Matcher>(1);
commentMatchers.add((getMatcher(settings.getGlobalCommentPattern())));
if (StringUtil.isEmpty(mySettings.getGlobalCommentPattern())) {
myCommentMatchers.clear();
for (String comment : myCommentStrings) {
Matcher matcher = getMatcher(comment);
myCommentMatchers.add(matcher);
}
}
else {
commentMatchers = new ArrayList<Matcher>(commentStrings.size());
for (String comment : commentStrings) {
Matcher matcher = getMatcher(comment);
commentMatchers.add(matcher);
}
// create only one Matcher for the global comment pattern.
myCommentMatchers.clear();
myCommentMatchers.add((getMatcher(mySettings.getGlobalCommentPattern())));
}
}
@@ -78,7 +78,7 @@ public class CommentUtil {
* any leading space.
*/
private Matcher getMatcher(String comment) {
StringBuffer sb = new StringBuffer(comment);
StringBuilder sb = new StringBuilder(comment);
/**
* remove any literal newline characters or escaped equivalent ('\n') at beginning of comment.
*/
@@ -122,20 +122,19 @@ public class CommentUtil {
}
private void createCommentPatternList() {
commentStrings = new ArrayList<String>();
for (Rule rule : settings.getClassOrderAttributeList()) {
rule.addCommentPatternsToList(commentStrings);
for (Rule rule : mySettings.getClassOrderAttributeList()) {
rule.addCommentPatternsToList(myCommentStrings);
}
for (Rule rule : settings.getItemOrderAttributeList()) {
rule.addCommentPatternsToList(commentStrings);
for (Rule rule : mySettings.getItemOrderAttributeList()) {
rule.addCommentPatternsToList(myCommentStrings);
}
settings.getExtractedMethodsSettings().addCommentPatternsToList(commentStrings);
mySettings.getExtractedMethodsSettings().addCommentPatternsToList(myCommentStrings);
}
/**
* Calculate the apparent length of a string if tabs are expanded.
* Leading tabs are no problem; embedded tabs would be, if the %FS% fill string expansions are not multiples of
* "%FS%".length() == 4, because after expansion the embedded tabs would misalign. However, I'm not going to
* "%FS%".length() == 4, because after expansion the embedded tabs would mis-align. However, I'm not going to
* address that yet. (This is just to fix Thomas Singer's bug with leading tab.)
*
* @param s
@@ -171,9 +170,9 @@ public class CommentUtil {
int tabSize,
String fillString)
{
StringBuffer result = new StringBuffer(comment.length() * 2);
StringBuilder result = new StringBuilder(comment.length() * 2);
int EOLindex = 0;
StringBuffer fillChars = new StringBuffer();
StringBuilder fillChars = new StringBuilder();
if (fillString.length() == 0) {
fillString = " "; // fill with spaces if no pattern supplied
}
@@ -27,6 +27,7 @@ import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.wrq.rearranger.settings.RearrangerSettings
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
import com.wrq.rearranger.settings.attributeGroups.FieldAttributes
/** JUnit tests for the rearranger plugin. */
class RearrangerTest extends LightCodeInsightFixtureTestCase {
@@ -46,26 +47,21 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase {
mySettings.showParameterNames = true
mySettings.showParameterTypes = true
mySettings.showRules = true
mySettings.rearrangeInnerClasses =true
mySettings.rearrangeInnerClasses = true
}
public final void testNoRearrangement() throws Exception {
doTest('RearrangementTest', 'NoRearrangementResult1')
}
// public final void testPublicFieldRearrangement() throws Exception {
// configureByFile("/com/wrq/rearranger/RearrangementTest.java");
// final PsiFile file = getFile();
// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file);
// final FieldAttributes fa;
// fa = new FieldAttributes();
// fa.getPlAttr().setPlPublic(true);
// rs.addItem(fa, 0);
// final RearrangerActionHandler rah = new RearrangerActionHandler();
// rah.rearrangeDocument(getProject(), file, rs, doc);
// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult2.java");
// }
//
public final void testPublicFieldRearrangement() throws Exception {
doTest('RearrangementTest', 'RearrangementResult2') {
def attributes = new FieldAttributes()
attributes.protectionLevelAttributes.plPublic = true
mySettings.addItem(attributes, 0)
}
}
// public final void testNotPublicFieldRearrangement() throws Exception {
// configureByFile("/com/wrq/rearranger/RearrangementTest.java");
// final PsiFile file = getFile();
@@ -2178,8 +2174,11 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase {
// super.checkResultByFile("/com/wrq/rearranger/BitFieldResult.java");
// }
private void doTest(@NotNull String srcFileName, @Nullable String expectedResultFileName) {
private void doTest(@NotNull String srcFileName, @Nullable String expectedResultFileName, @Nullable Closure adjustment = null) {
myFixture.configureByFile("${srcFileName}.java")
if (adjustment) {
adjustment.call()
}
ApplicationManager.application.runWriteAction {
new RearrangerActionHandler().rearrangeDocument(myFixture.project, myFixture.file, mySettings, myFixture.editor.document);
}
@@ -14,7 +14,7 @@ public class MethodAttributesTest
public void testToString() throws Exception {
ma = new MethodAttributes();
// test various combinations of min/max parameters, name, and return type.
ma.getPlAttr().setPlPublic(true);
ma.getProtectionLevelAttributes().setPlPublic(true);
// min = ? max = ? name = ? return = ?
setma(false, 0, false, 0, null, null, "public methods");
// min = 1 max = ? name = ? return = ?
@@ -57,8 +57,8 @@ public class MethodAttributesTest
ma.getMinParamsAttr().setValue(min);
ma.getMaxParamsAttr().setMatch(maxMatch);
ma.getMaxParamsAttr().setValue(max);
ma.getNameAttr().setMatch(name != null);
ma.getNameAttr().setExpression(name);
ma.getNameAttribute().setMatch(name != null);
ma.getNameAttribute().setExpression(name);
ma.getReturnTypeAttr().setMatch(returnValue != null);
ma.getReturnTypeAttr().setExpression(returnValue);
assertEquals("wrong description", description, ma.toString());
@@ -10,8 +10,8 @@ public class RearrangementTest {
/** field 1. */
private int field1;
private int field2;
final int field5 = 5;
protected int field6 = 6;
final int field5 = 5;
protected int field6 = 6;
/** method 1 comment. */
void method1() {