1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-04-29 19:45:01 +02:00

Cosmetics.

This commit is contained in:
sprigogin 2011-07-13 22:18:06 -04:00
parent 78f658d473
commit 89e15ab2d8
8 changed files with 346 additions and 433 deletions

View file

@ -18,23 +18,18 @@ import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.ASTCommenter;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/** /**
* * ASTWriter main class. Generates source code from <code>IASTNode</code>.
* ASTWriter main class. Generates source code from <code>IASTNode</code>. Uses a * Uses a <code>hangeGeneratorWriterVisitor</code> to generate the code for the given nodes.
* <codeC>hangeGeneratorWriterVisitor</code> to generate the code for the given
* nodes.
* *
* @see ChangeGeneratorWriterVisitor * @see ChangeGeneratorWriterVisitor
* *
* @author Emanuel Graf * @author Emanuel Graf
*
*/ */
public class ASTWriter { public class ASTWriter {
private ChangeGeneratorWriterVisitor transformationVisitor; private ChangeGeneratorWriterVisitor transformationVisitor;
private ASTModificationStore modificationStore = new ASTModificationStore(); private ASTModificationStore modificationStore = new ASTModificationStore();
private String givenIndentation = ""; //$NON-NLS-1$ private String givenIndentation = ""; //$NON-NLS-1$
/** /**
* Creates a <code>ASTWriter</code>. * Creates a <code>ASTWriter</code>.
*/ */
@ -53,8 +48,7 @@ public class ASTWriter {
} }
/** /**
* * Generates the source code representing this node.
* Genereates the source code representing this node.
* *
* @param rootNode Node to write. * @param rootNode Node to write.
* @return A <code>String</code> representing the source code for the node. * @return A <code>String</code> representing the source code for the node.
@ -69,20 +63,22 @@ public class ASTWriter {
} }
/** /**
*
* Generates the source code representing this node including comments. * Generates the source code representing this node including comments.
* *
* @param rootNode Node to write. * @param rootNode Node to write.
* @param fileScope * @param fileScope
* @param commentMap Node Comment Map <code>ASTCommenter</code> * @param commentMap Node Comment Map <code>ASTCommenter</code>
* @return A <code>String</code> representing the source code for the node. * @return A <code>String</code> representing the source code for the node.
* @throws ProblemRuntimeException if the node or one of it's children is a <code>IASTProblemNode</code>. * @throws ProblemRuntimeException if the node or one of it's children is
* an <code>IASTProblemNode</code>.
* *
* @see ASTCommenter#getCommentedNodeMap(org.eclipse.cdt.core.dom.ast.IASTTranslationUnit) * @see ASTCommenter#getCommentedNodeMap(org.eclipse.cdt.core.dom.ast.IASTTranslationUnit)
*/ */
public String write(IASTNode rootNode, String fileScope, NodeCommentMap commentMap) throws ProblemRuntimeException { public String write(IASTNode rootNode, String fileScope, NodeCommentMap commentMap)
transformationVisitor = new ChangeGeneratorWriterVisitor(modificationStore, givenIndentation, fileScope, commentMap); throws ProblemRuntimeException {
if(rootNode != null){ transformationVisitor = new ChangeGeneratorWriterVisitor(modificationStore, givenIndentation,
fileScope, commentMap);
if (rootNode != null) {
rootNode.accept(transformationVisitor); rootNode.accept(transformationVisitor);
} }
String str = transformationVisitor.toString(); String str = transformationVisitor.toString();
@ -90,9 +86,7 @@ public class ASTWriter {
return str; return str;
} }
public void setModificationStore(ASTModificationStore modificationStore) { public void setModificationStore(ASTModificationStore modificationStore) {
this.modificationStore = modificationStore; this.modificationStore = modificationStore;
} }
} }

View file

@ -83,7 +83,6 @@ public class ASTWriterVisitor extends ASTVisitor {
scribe.setGivenIndentation(givenIndentation); scribe.setGivenIndentation(givenIndentation);
init(commentMap); init(commentMap);
this.commentMap = commentMap; this.commentMap = commentMap;
} }
private void init(NodeCommentMap commentMap) { private void init(NodeCommentMap commentMap) {
@ -100,13 +99,13 @@ public class ASTWriterVisitor extends ASTVisitor {
} }
@Override @Override
public String toString(){ public String toString() {
return scribe.toString(); return scribe.toString();
} }
@Override @Override
public int leave(IASTTranslationUnit tu) { public int leave(IASTTranslationUnit tu) {
for(IASTComment comment : commentMap.getFreestandingCommentsForNode(tu)) { for (IASTComment comment : commentMap.getFreestandingCommentsForNode(tu)) {
scribe.print(comment.getComment()); scribe.print(comment.getComment());
scribe.newLine(); scribe.newLine();
} }
@ -114,14 +113,12 @@ public class ASTWriterVisitor extends ASTVisitor {
} }
private void writeLeadingComments(IASTNode node) { private void writeLeadingComments(IASTNode node) {
for(IASTComment comment : getLeadingComments(node)) { for (IASTComment comment : getLeadingComments(node)) {
scribe.print(comment.getComment()); scribe.print(comment.getComment());
scribe.newLine(); scribe.newLine();
} }
} }
private ArrayList<IASTComment> getLeadingComments(IASTNode node) { private ArrayList<IASTComment> getLeadingComments(IASTNode node) {
ArrayList<IASTComment> leadingComments = commentMap.getLeadingCommentsForNode(node); ArrayList<IASTComment> leadingComments = commentMap.getLeadingCommentsForNode(node);
IASTNodeLocation[] locs = node.getNodeLocations(); IASTNodeLocation[] locs = node.getNodeLocations();
@ -139,7 +136,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTName name) { public int visit(IASTName name) {
writeLeadingComments(name); writeLeadingComments(name);
if(!macroHandler.checkisMacroExpansionNode(name)) { if (!macroHandler.checkisMacroExpansionNode(name)) {
nameWriter.writeName(name); nameWriter.writeName(name);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -155,11 +152,12 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTExpression expression) { public int visit(IASTExpression expression) {
writeLeadingComments(expression); writeLeadingComments(expression);
if(!macroHandler.checkisMacroExpansionNode(expression)) { if (!macroHandler.checkisMacroExpansionNode(expression)) {
if (expression instanceof IGNUASTCompoundStatementExpression) { if (expression instanceof IGNUASTCompoundStatementExpression) {
IGNUASTCompoundStatementExpression gnuCompStmtExp = (IGNUASTCompoundStatementExpression) expression; IGNUASTCompoundStatementExpression gnuCompStmtExp =
(IGNUASTCompoundStatementExpression) expression;
gnuCompStmtExp.getCompoundStatement().accept(this); gnuCompStmtExp.getCompoundStatement().accept(this);
}else { } else {
expWriter.writeExpression(expression); expWriter.writeExpression(expression);
} }
} }
@ -169,10 +167,11 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTStatement statement) { public int visit(IASTStatement statement) {
writeLeadingComments(statement); writeLeadingComments(statement);
if(macroHandler.isStatementWithMixedLocation(statement) && !(statement instanceof IASTCompoundStatement)){ if (macroHandler.isStatementWithMixedLocation(statement) &&
!(statement instanceof IASTCompoundStatement)) {
return statementWriter.writeMixedStatement(statement); return statementWriter.writeMixedStatement(statement);
} }
if(macroHandler.checkisMacroExpansionNode(statement)) { if (macroHandler.checkisMacroExpansionNode(statement)) {
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
} }
return statementWriter.writeStatement(statement, true); return statementWriter.writeStatement(statement, true);
@ -181,7 +180,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTDeclaration declaration) { public int visit(IASTDeclaration declaration) {
writeLeadingComments(declaration); writeLeadingComments(declaration);
if(!macroHandler.checkisMacroExpansionNode(declaration)) { if (!macroHandler.checkisMacroExpansionNode(declaration)) {
declarationWriter.writeDeclaration(declaration); declarationWriter.writeDeclaration(declaration);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -190,7 +189,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTDeclarator declarator) { public int visit(IASTDeclarator declarator) {
writeLeadingComments(declarator); writeLeadingComments(declarator);
if(!macroHandler.checkisMacroExpansionNode(declarator)) { if (!macroHandler.checkisMacroExpansionNode(declarator)) {
declaratorWriter.writeDeclarator(declarator); declaratorWriter.writeDeclarator(declarator);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -198,7 +197,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTArrayModifier amod) { public int visit(IASTArrayModifier amod) {
if(!macroHandler.checkisMacroExpansionNode(amod)) { if (!macroHandler.checkisMacroExpansionNode(amod)) {
declaratorWriter.writeArrayModifier(amod); declaratorWriter.writeArrayModifier(amod);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -207,7 +206,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTInitializer initializer) { public int visit(IASTInitializer initializer) {
writeLeadingComments(initializer); writeLeadingComments(initializer);
if(!macroHandler.checkisMacroExpansionNode(initializer)) { if (!macroHandler.checkisMacroExpansionNode(initializer)) {
initializerWriter.writeInitializer(initializer); initializerWriter.writeInitializer(initializer);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -216,11 +215,11 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(IASTParameterDeclaration parameterDeclaration) { public int visit(IASTParameterDeclaration parameterDeclaration) {
writeLeadingComments(parameterDeclaration); writeLeadingComments(parameterDeclaration);
if(!macroHandler.checkisMacroExpansionNode(parameterDeclaration)) { if (!macroHandler.checkisMacroExpansionNode(parameterDeclaration)) {
parameterDeclaration.getDeclSpecifier().accept(this); parameterDeclaration.getDeclSpecifier().accept(this);
IASTDeclarator declarator = getParameterDeclarator(parameterDeclaration); IASTDeclarator declarator = getParameterDeclarator(parameterDeclaration);
if(getParameterName(declarator).toString().length() != 0){ if (getParameterName(declarator).toString().length() != 0) {
scribe.printSpaces(1); scribe.printSpaces(1);
} }
declarator.accept(this); declarator.accept(this);
@ -232,15 +231,14 @@ public class ASTWriterVisitor extends ASTVisitor {
return declarator.getName(); return declarator.getName();
} }
protected IASTDeclarator getParameterDeclarator( protected IASTDeclarator getParameterDeclarator(IASTParameterDeclaration parameterDeclaration) {
IASTParameterDeclaration parameterDeclaration) {
return parameterDeclaration.getDeclarator(); return parameterDeclaration.getDeclarator();
} }
@Override @Override
public int visit(ICPPASTNamespaceDefinition namespace) { public int visit(ICPPASTNamespaceDefinition namespace) {
writeLeadingComments(namespace); writeLeadingComments(namespace);
if(!macroHandler.checkisMacroExpansionNode(namespace)) { if (!macroHandler.checkisMacroExpansionNode(namespace)) {
declarationWriter.writeDeclaration(namespace); declarationWriter.writeDeclaration(namespace);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
@ -249,7 +247,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override @Override
public int visit(ICPPASTTemplateParameter parameter) { public int visit(ICPPASTTemplateParameter parameter) {
writeLeadingComments(parameter); writeLeadingComments(parameter);
if(!macroHandler.checkisMacroExpansionNode(parameter)) { if (!macroHandler.checkisMacroExpansionNode(parameter)) {
tempParameterWriter.writeTemplateParameter(parameter); tempParameterWriter.writeTemplateParameter(parameter);
} }
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;

View file

@ -39,19 +39,15 @@ import org.eclipse.cdt.core.parser.Keywords;
import org.eclipse.cdt.internal.core.dom.parser.ASTQueries; import org.eclipse.cdt.internal.core.dom.parser.ASTQueries;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/** /**
*
* Generates source code of declaration nodes. The actual string operations are delegated * Generates source code of declaration nodes. The actual string operations are delegated
* to the <code>Scribe</code> class. * to the <code>Scribe</code> class.
* *
* @see Scribe * @see Scribe
* @see IASTDeclaration * @see IASTDeclaration
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*
*/ */
public class DeclarationWriter extends NodeWriter{ public class DeclarationWriter extends NodeWriter{
private static final String ASM_END = ")"; //$NON-NLS-1$ private static final String ASM_END = ")"; //$NON-NLS-1$
private static final String ASM_START = "asm("; //$NON-NLS-1$ private static final String ASM_START = "asm("; //$NON-NLS-1$
private static final String TEMPLATE_DECLARATION = "template<"; //$NON-NLS-1$ private static final String TEMPLATE_DECLARATION = "template<"; //$NON-NLS-1$
@ -101,12 +97,12 @@ public class DeclarationWriter extends NodeWriter{
writeVisibilityLabel((ICPPASTVisibilityLabel) declaration); writeVisibilityLabel((ICPPASTVisibilityLabel) declaration);
} }
if(hasTrailingComments(declaration)) { if (hasTrailingComments(declaration)) {
writeTrailingComments(declaration, addNewLine); writeTrailingComments(declaration, addNewLine);
}else if(addNewLine){ } else if (addNewLine) {
scribe.newLine(); scribe.newLine();
} }
if(hasFreestandingComments(declaration)){ if (hasFreestandingComments(declaration)) {
writeFreeStandingComments(declaration); writeFreeStandingComments(declaration);
} }
@ -144,7 +140,7 @@ public class DeclarationWriter extends NodeWriter{
private void writeUsingDeclaration(ICPPASTUsingDeclaration usingDeclaration) { private void writeUsingDeclaration(ICPPASTUsingDeclaration usingDeclaration) {
scribe.print(USING); scribe.print(USING);
if(usingDeclaration.isTypename()){ if (usingDeclaration.isTypename()) {
scribe.print(TYPENAME); scribe.print(TYPENAME);
} }
usingDeclaration.getName().accept(visitor); usingDeclaration.getName().accept(visitor);
@ -157,14 +153,14 @@ public class DeclarationWriter extends NodeWriter{
} }
protected void writeTemplateDeclaration(ICPPASTTemplateDeclaration templateDeclaration) { protected void writeTemplateDeclaration(ICPPASTTemplateDeclaration templateDeclaration) {
if(templateDeclaration.isExported()){ if (templateDeclaration.isExported()) {
scribe.print(EXPORT); scribe.print(EXPORT);
} }
scribe.print(TEMPLATE_DECLARATION); scribe.print(TEMPLATE_DECLARATION);
ICPPASTTemplateParameter[] paraDecls = templateDeclaration.getTemplateParameters(); ICPPASTTemplateParameter[] paraDecls = templateDeclaration.getTemplateParameters();
for(int i = 0; i < paraDecls.length; ++i) { for (int i = 0; i < paraDecls.length; ++i) {
paraDecls[i].accept(visitor); paraDecls[i].accept(visitor);
if(i + 1 < paraDecls.length) { if (i + 1 < paraDecls.length) {
scribe.print(','); scribe.print(',');
scribe.printSpaces(1); scribe.printSpaces(1);
} }
@ -174,7 +170,7 @@ public class DeclarationWriter extends NodeWriter{
templateDeclaration.getDeclaration().accept(visitor); templateDeclaration.getDeclaration().accept(visitor);
} }
protected void writeDeclaration(ICPPASTNamespaceDefinition declaration){ protected void writeDeclaration(ICPPASTNamespaceDefinition declaration) {
printSemicolon = true; printSemicolon = true;
writeNamespaceDefinition(declaration); writeNamespaceDefinition(declaration);
} }
@ -182,18 +178,18 @@ public class DeclarationWriter extends NodeWriter{
private void writeNamespaceDefinition(ICPPASTNamespaceDefinition namespaceDefinition) { private void writeNamespaceDefinition(ICPPASTNamespaceDefinition namespaceDefinition) {
scribe.print(NAMESPACE); scribe.print(NAMESPACE);
namespaceDefinition.getName().accept(visitor); namespaceDefinition.getName().accept(visitor);
if(!hasTrailingComments(namespaceDefinition.getName())) { if (!hasTrailingComments(namespaceDefinition.getName())) {
scribe.newLine(); scribe.newLine();
} }
scribe.printLBrace(); scribe.printLBrace();
scribe.newLine(); scribe.newLine();
writeDeclarationsInNamespace(namespaceDefinition, namespaceDefinition.getDeclarations()); writeDeclarationsInNamespace(namespaceDefinition, namespaceDefinition.getDeclarations());
if(hasFreestandingComments(namespaceDefinition)) { if (hasFreestandingComments(namespaceDefinition)) {
writeFreeStandingComments(namespaceDefinition); writeFreeStandingComments(namespaceDefinition);
} }
scribe.printRBrace(); scribe.printRBrace();
if(hasTrailingComments(namespaceDefinition)) { if (hasTrailingComments(namespaceDefinition)) {
writeTrailingComments(namespaceDefinition); writeTrailingComments(namespaceDefinition);
}else{ }else{
scribe.newLine(); scribe.newLine();
@ -220,7 +216,7 @@ public class DeclarationWriter extends NodeWriter{
scribe.printSpaces(1); scribe.printSpaces(1);
IASTDeclaration[] declarations = linkageSpecification.getDeclarations(); IASTDeclaration[] declarations = linkageSpecification.getDeclarations();
if(declarations.length > 1){ if (declarations.length > 1) {
scribe.printLBrace(); scribe.printLBrace();
scribe.decrementIndentationLevel(); scribe.decrementIndentationLevel();
scribe.newLine(); scribe.newLine();
@ -229,13 +225,13 @@ public class DeclarationWriter extends NodeWriter{
} }
scribe.printRBrace(); scribe.printRBrace();
scribe.incrementIndentationLevel(); scribe.incrementIndentationLevel();
} else if(declarations.length > 0) { } else if (declarations.length > 0) {
visitNodeIfNotNull(declarations[0]); visitNodeIfNotNull(declarations[0]);
} }
} }
private void writeExplicitTemplateInstantiation(ICPPASTExplicitTemplateInstantiation explicitTemplateInstantiation) { private void writeExplicitTemplateInstantiation(ICPPASTExplicitTemplateInstantiation explicitTemplateInstantiation) {
switch(explicitTemplateInstantiation.getModifier()){ switch(explicitTemplateInstantiation.getModifier()) {
case ICPPASTExplicitTemplateInstantiation.EXTERN: case ICPPASTExplicitTemplateInstantiation.EXTERN:
scribe.print(EXTERN); scribe.print(EXTERN);
break; break;
@ -259,7 +255,7 @@ public class DeclarationWriter extends NodeWriter{
} }
private void printSemicolon() { private void printSemicolon() {
if(printSemicolon) { if (printSemicolon) {
scribe.printSemicolon(); scribe.printSemicolon();
} }
} }
@ -269,7 +265,7 @@ public class DeclarationWriter extends NodeWriter{
declSpecifier.accept(visitor); declSpecifier.accept(visitor);
if (declSpecifier instanceof IASTSimpleDeclSpecifier) { if (declSpecifier instanceof IASTSimpleDeclSpecifier) {
IASTSimpleDeclSpecifier simDeclSpec = (IASTSimpleDeclSpecifier) declSpecifier; IASTSimpleDeclSpecifier simDeclSpec = (IASTSimpleDeclSpecifier) declSpecifier;
if(simDeclSpec.getType() != IASTSimpleDeclSpecifier.t_unspecified) { if (simDeclSpec.getType() != IASTSimpleDeclSpecifier.t_unspecified) {
scribe.printSpace(); scribe.printSpace();
} }
}else { }else {
@ -300,16 +296,16 @@ public class DeclarationWriter extends NodeWriter{
} }
} }
protected void writeCtorChainInitializer( protected void writeCtorChainInitializer(ICPPASTFunctionDefinition funcDec,
ICPPASTFunctionDefinition funcDec, ICPPASTConstructorChainInitializer[] ctorInitChain) { ICPPASTConstructorChainInitializer[] ctorInitChain) {
if(ctorInitChain.length != 0) { if (ctorInitChain.length != 0) {
scribe.newLine(); scribe.newLine();
scribe.print(':'); scribe.print(':');
} }
for(int i = 0; i < ctorInitChain.length; ++i) { for (int i = 0; i < ctorInitChain.length; ++i) {
ICPPASTConstructorChainInitializer initializer = ctorInitChain[i]; ICPPASTConstructorChainInitializer initializer = ctorInitChain[i];
initializer.accept(visitor); initializer.accept(visitor);
if(i+1 < ctorInitChain.length) { if (i + 1 < ctorInitChain.length) {
scribe.print(COMMA_SPACE); scribe.print(COMMA_SPACE);
} }
} }
@ -323,13 +319,13 @@ public class DeclarationWriter extends NodeWriter{
boolean noSpace = false; boolean noSpace = false;
if (declSpecifier instanceof IASTSimpleDeclSpecifier) { if (declSpecifier instanceof IASTSimpleDeclSpecifier) {
IASTSimpleDeclSpecifier simpleDeclSpecifier = (IASTSimpleDeclSpecifier) declSpecifier; IASTSimpleDeclSpecifier simpleDeclSpecifier = (IASTSimpleDeclSpecifier) declSpecifier;
if(simpleDeclSpecifier.getType() == IASTSimpleDeclSpecifier.t_unspecified) { if (simpleDeclSpecifier.getType() == IASTSimpleDeclSpecifier.t_unspecified) {
noSpace = true; noSpace = true;
} }
} }
if(decls.length > 0) { if (decls.length > 0) {
if(!noSpace) { if (!noSpace) {
scribe.printSpace(); scribe.printSpace();
} }
writeNodeList(decls); writeNodeList(decls);
@ -337,5 +333,4 @@ public class DeclarationWriter extends NodeWriter{
printSemicolon(); printSemicolon();
} }
} }

View file

@ -35,14 +35,12 @@ import org.eclipse.cdt.internal.core.pdom.dom.PDOMMacroReferenceName;
import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.CoreException;
/** /**
*
* Recognizes nodes that are the result of an macro expansion and replaces them * Recognizes nodes that are the result of an macro expansion and replaces them
* with a suitable macro call. * with a suitable macro call.
* @author Emanuel Graf IFS
* *
* @author Emanuel Graf IFS
*/ */
public class MacroExpansionHandler { public class MacroExpansionHandler {
private int lastMacroExpOffset; private int lastMacroExpOffset;
private final Scribe scribe; private final Scribe scribe;
private IASTTranslationUnit tu; private IASTTranslationUnit tu;
@ -58,7 +56,7 @@ public class MacroExpansionHandler {
protected boolean isStatementWithMixedLocation(IASTStatement node) { protected boolean isStatementWithMixedLocation(IASTStatement node) {
IASTNodeLocation[] nodeLocations = getNodeLocations(node); IASTNodeLocation[] nodeLocations = getNodeLocations(node);
if(nodeLocations != null && nodeLocations.length > 1) { if (nodeLocations != null && nodeLocations.length > 1) {
for (IASTNodeLocation loc : nodeLocations) { for (IASTNodeLocation loc : nodeLocations) {
if (loc instanceof IASTMacroExpansionLocation) { if (loc instanceof IASTMacroExpansionLocation) {
return true; return true;
@ -70,7 +68,7 @@ public class MacroExpansionHandler {
protected boolean macroExpansionAlreadyPrinted(IASTNode node) { protected boolean macroExpansionAlreadyPrinted(IASTNode node) {
IASTNodeLocation[] locs = node.getNodeLocations(); IASTNodeLocation[] locs = node.getNodeLocations();
if(locs.length ==1) { if (locs.length ==1) {
if (locs[0] instanceof IASTMacroExpansionLocation) { if (locs[0] instanceof IASTMacroExpansionLocation) {
IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0]; IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0];
if (macroNode.asFileLocation().getNodeOffset() == lastMacroExpOffset) { if (macroNode.asFileLocation().getNodeOffset() == lastMacroExpOffset) {
@ -83,7 +81,7 @@ public class MacroExpansionHandler {
protected boolean checkisMacroExpansionNode(IASTNode node, boolean write) { protected boolean checkisMacroExpansionNode(IASTNode node, boolean write) {
IASTTranslationUnit unit = node.getTranslationUnit(); IASTTranslationUnit unit = node.getTranslationUnit();
if(tu == null || !tu.equals(unit)) { if (tu == null || !tu.equals(unit)) {
initEmptyMacros(unit); initEmptyMacros(unit);
} }
IASTNodeLocation[] locs = getNodeLocations(node); IASTNodeLocation[] locs = getNodeLocations(node);
@ -124,19 +122,19 @@ public class MacroExpansionHandler {
} }
private void handleEmptyMacroExpansion(IASTNode node) { private void handleEmptyMacroExpansion(IASTNode node) {
if(node.getTranslationUnit() == null)return; if (node.getTranslationUnit() == null)return;
String file = node.getContainingFilename(); String file = node.getContainingFilename();
List<IIndexName> exps = macroExpansion.get(file); List<IIndexName> exps = macroExpansion.get(file);
if(exps != null && !exps.isEmpty()) { if (exps != null && !exps.isEmpty()) {
IASTFileLocation fileLocation = getFileLocation(node); IASTFileLocation fileLocation = getFileLocation(node);
if(fileLocation != null) { if (fileLocation != null) {
int nOff = fileLocation.getNodeOffset(); int nOff = fileLocation.getNodeOffset();
for (IIndexName iIndexName : exps) { for (IIndexName iIndexName : exps) {
if (iIndexName instanceof PDOMMacroReferenceName) { if (iIndexName instanceof PDOMMacroReferenceName) {
PDOMMacroReferenceName mName = (PDOMMacroReferenceName) iIndexName; PDOMMacroReferenceName mName = (PDOMMacroReferenceName) iIndexName;
int eOff = mName.getFileLocation().getNodeOffset(); int eOff = mName.getFileLocation().getNodeOffset();
int eLength = mName.getFileLocation().getNodeLength(); int eLength = mName.getFileLocation().getNodeLength();
if(eOff < nOff && Math.abs((eOff+eLength-nOff)) < 3) { if (eOff < nOff && Math.abs((eOff+eLength-nOff)) < 3) {
scribe.print(mName.toString() + " "); //$NON-NLS-1$ scribe.print(mName.toString() + " "); //$NON-NLS-1$
} }
} }
@ -161,29 +159,30 @@ public class MacroExpansionHandler {
if (unit != null) { if (unit != null) {
tu = unit; tu = unit;
IIndex index = tu.getIndex(); IIndex index = tu.getIndex();
if(index != null) { if (index != null) {
macroExpansion = new TreeMap<String, List<IIndexName>>(); macroExpansion = new TreeMap<String, List<IIndexName>>();
IASTPreprocessorMacroDefinition[] md = tu.getMacroDefinitions(); IASTPreprocessorMacroDefinition[] md = tu.getMacroDefinitions();
TreeSet<String>paths = new TreeSet<String>(); TreeSet<String>paths = new TreeSet<String>();
for(IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) { for (IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) {
if(!is.isSystemInclude()) { if (!is.isSystemInclude()) {
paths.add(is.getContainingFilename()); paths.add(is.getContainingFilename());
} }
} }
paths.add(tu.getContainingFilename()); paths.add(tu.getContainingFilename());
for (IASTPreprocessorMacroDefinition iastPreprocessorMacroDefinition : md) { for (IASTPreprocessorMacroDefinition iastPreprocessorMacroDefinition : md) {
if(iastPreprocessorMacroDefinition.getExpansion().length() == 0) { if (iastPreprocessorMacroDefinition.getExpansion().length() == 0) {
try { try {
IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(), IndexFilter.ALL, null); IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(),
if(macroBinding.length > 0) { IndexFilter.ALL, null);
if (macroBinding.length > 0) {
IIndexName[] refs = index.findReferences(macroBinding[0]); IIndexName[] refs = index.findReferences(macroBinding[0]);
for (IIndexName iIndexName : refs) { for (IIndexName iIndexName : refs) {
String filename2 = iIndexName.getFileLocation().getFileName(); String filename2 = iIndexName.getFileLocation().getFileName();
List<IIndexName>fileList = macroExpansion.get(filename2); List<IIndexName>fileList = macroExpansion.get(filename2);
if (paths.contains(filename2)) { if (paths.contains(filename2)) {
if(fileList == null) { if (fileList == null) {
fileList = new ArrayList<IIndexName>(); fileList = new ArrayList<IIndexName>();
macroExpansion.put(filename2, fileList); macroExpansion.put(filename2, fileList);
} }
@ -196,14 +195,13 @@ public class MacroExpansionHandler {
} }
} }
} }
}else { } else {
macroExpansion = Collections.emptyMap(); macroExpansion = Collections.emptyMap();
} }
} }
} }
public void reset(){ public void reset() {
lastMacroExpOffset = -1; lastMacroExpOffset = -1;
} }
} }

View file

@ -55,8 +55,6 @@ import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEditGroup; import org.eclipse.text.edits.TextEditGroup;
public class ChangeGenerator extends ASTVisitor { public class ChangeGenerator extends ASTVisitor {
private final LinkedHashMap<String, Integer> sourceOffsets = new LinkedHashMap<String, Integer>(); private final LinkedHashMap<String, Integer> sourceOffsets = new LinkedHashMap<String, Integer>();
public LinkedHashMap<IASTNode, List<ASTModification>> modificationParent = new LinkedHashMap<IASTNode, List<ASTModification>>(); public LinkedHashMap<IASTNode, List<ASTModification>> modificationParent = new LinkedHashMap<IASTNode, List<ASTModification>>();
private final LinkedHashMap<IFile, MultiTextEdit> changes = new LinkedHashMap<IFile, MultiTextEdit>(); private final LinkedHashMap<IFile, MultiTextEdit> changes = new LinkedHashMap<IFile, MultiTextEdit>();
@ -67,37 +65,23 @@ public class ChangeGenerator extends ASTVisitor {
{ {
shouldVisitExpressions = true; shouldVisitExpressions = true;
shouldVisitStatements = true; shouldVisitStatements = true;
shouldVisitNames = true; shouldVisitNames = true;
shouldVisitDeclarations = true; shouldVisitDeclarations = true;
shouldVisitDeclSpecifiers = true; shouldVisitDeclSpecifiers = true;
shouldVisitDeclarators = true; shouldVisitDeclarators = true;
shouldVisitArrayModifiers= true; shouldVisitArrayModifiers= true;
shouldVisitInitializers = true; shouldVisitInitializers = true;
shouldVisitBaseSpecifiers = true; shouldVisitBaseSpecifiers = true;
shouldVisitNamespaces = true; shouldVisitNamespaces = true;
shouldVisitTemplateParameters = true; shouldVisitTemplateParameters = true;
shouldVisitParameterDeclarations = true; shouldVisitParameterDeclarations = true;
shouldVisitTranslationUnit = true; shouldVisitTranslationUnit = true;
} }
public ChangeGenerator(ASTModificationStore modificationStore, NodeCommentMap commentMap) { public ChangeGenerator(ASTModificationStore modificationStore, NodeCommentMap commentMap) {
this.modificationStore = modificationStore; this.modificationStore = modificationStore;
this.commentMap = commentMap; this.commentMap = commentMap;
} }
public void generateChange(IASTNode rootNode) throws ProblemRuntimeException { public void generateChange(IASTNode rootNode) throws ProblemRuntimeException {
@ -110,7 +94,6 @@ public class ChangeGenerator extends ASTVisitor {
initParentModList(); initParentModList();
rootNode.accept(pathProvider); rootNode.accept(pathProvider);
for (IFile currentFile : changes.keySet()) { for (IFile currentFile : changes.keySet()) {
TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile); TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile);
subchange.setEdit(changes.get(currentFile)); subchange.setEdit(changes.get(currentFile));
change.add(subchange); change.add(subchange);
@ -118,20 +101,19 @@ public class ChangeGenerator extends ASTVisitor {
} }
private void initParentModList() { private void initParentModList() {
ASTModificationMap rootModifications = modificationStore ASTModificationMap rootModifications = modificationStore.getRootModifications();
.getRootModifications();
if (rootModifications != null) { if (rootModifications != null) {
for (IASTNode modifiedNode : rootModifications.getModifiedNodes()) { for (IASTNode modifiedNode : rootModifications.getModifiedNodes()) {
List<ASTModification> modificationsForNode = rootModifications List<ASTModification> modificationsForNode = rootModifications.getModificationsForNode(modifiedNode);
.getModificationsForNode(modifiedNode);
IASTNode modifiedNodeParent = determineParentToBeRewritten(modifiedNode, modificationsForNode); IASTNode modifiedNodeParent = determineParentToBeRewritten(modifiedNode, modificationsForNode);
List<ASTModification> list = modificationParent.get(modifiedNodeParent != null ? modifiedNodeParent : modifiedNode); List<ASTModification> list = modificationParent.get(modifiedNodeParent != null ?
if(list != null){ modifiedNodeParent : modifiedNode);
if (list != null) {
list.addAll(modificationsForNode); list.addAll(modificationsForNode);
}else{ } else {
List<ASTModification> modifiableList = new ArrayList<ASTModification>(modificationsForNode); List<ASTModification> modifiableList = new ArrayList<ASTModification>(modificationsForNode);
modificationParent.put(modifiedNodeParent != null ? modifiedNodeParent : modifiedNode, modificationParent.put(modifiedNodeParent != null ?
modifiableList); modifiedNodeParent : modifiedNode, modifiableList);
} }
} }
} }
@ -139,8 +121,8 @@ public class ChangeGenerator extends ASTVisitor {
private IASTNode determineParentToBeRewritten(IASTNode modifiedNode, List<ASTModification> modificationsForNode) { private IASTNode determineParentToBeRewritten(IASTNode modifiedNode, List<ASTModification> modificationsForNode) {
IASTNode modifiedNodeParent = modifiedNode; IASTNode modifiedNodeParent = modifiedNode;
for(ASTModification currentModification : modificationsForNode){ for (ASTModification currentModification : modificationsForNode) {
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE){ if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE) {
modifiedNodeParent = modifiedNode.getParent(); modifiedNodeParent = modifiedNode.getParent();
break; break;
} }
@ -152,21 +134,20 @@ public class ChangeGenerator extends ASTVisitor {
@Override @Override
public int visit(IASTTranslationUnit translationUnit) { public int visit(IASTTranslationUnit translationUnit) {
if (hasChangedChild(translationUnit)) { if (hasChangedChild(translationUnit)) {
synthTreatment(translationUnit); synthTreatment(translationUnit);
} }
IASTFileLocation location = getFileLocationOfEmptyTranslationUnit(translationUnit); IASTFileLocation location = getFileLocationOfEmptyTranslationUnit(translationUnit);
sourceOffsets.put(location.getFileName(), sourceOffsets.put(location.getFileName(), Integer.valueOf(location.getNodeOffset()));
Integer.valueOf(location.getNodeOffset()));
return super.visit(translationUnit); return super.visit(translationUnit);
} }
/** /**
* This is a Workaround for a known but not jet solved Problem in IASTNode. If you get the FileFocation of a translationUnit * This is a workaround for a known but not jet solved problem in IASTNode. If you get
* that was built on an empty file you will get null because there it explicitly returns null if the index and length is 0. * the FileFocation of a translation unit that was built on an empty file you will get null
* To get to the Filename and other information, the location is never the less needed. * because there it explicitly returns null if the index and length is 0.
* To get to the filename and other information, the location is never the less needed.
* @param node * @param node
* @return a hopefully "unnull" FileLocation * @return a hopefully non-{@code null} FileLocation
*/ */
public IASTFileLocation getFileLocationOfEmptyTranslationUnit(IASTNode node) { public IASTFileLocation getFileLocationOfEmptyTranslationUnit(IASTNode node) {
IASTFileLocation fileLocation = node.getFileLocation(); IASTFileLocation fileLocation = node.getFileLocation();
@ -175,7 +156,7 @@ public class ChangeGenerator extends ASTVisitor {
if (lr != null) { if (lr != null) {
fileLocation = lr.getMappedFileLocation(0, 0); fileLocation = lr.getMappedFileLocation(0, 0);
} else { } else {
// support for old location map // Support for old location map
fileLocation = node.getTranslationUnit().flattenLocationsToFile(node.getNodeLocations()); fileLocation = node.getTranslationUnit().flattenLocationsToFile(node.getNodeLocations());
} }
} }
@ -184,14 +165,11 @@ public class ChangeGenerator extends ASTVisitor {
@Override @Override
public int leave(IASTTranslationUnit tu) { public int leave(IASTTranslationUnit tu) {
return super.leave(tu); return super.leave(tu);
} }
private int getOffsetForNodeFile(IASTNode rootNode) { private int getOffsetForNodeFile(IASTNode rootNode) {
Integer offset = sourceOffsets.get(rootNode.getFileLocation().getFileName());
Integer offset = sourceOffsets.get(rootNode.getFileLocation()
.getFileName());
return offset == null ? 0 : offset.intValue(); return offset == null ? 0 : offset.intValue();
} }
@ -217,10 +195,8 @@ public class ChangeGenerator extends ASTVisitor {
createChange(synthNode, synthSource); createChange(synthNode, synthSource);
int newOffset = synthNode.getFileLocation().getNodeOffset() int newOffset = synthNode.getFileLocation().getNodeOffset() + synthNode.getFileLocation().getNodeLength();
+ synthNode.getFileLocation().getNodeLength();
sourceOffsets.put(synthNode.getFileLocation().getFileName(), Integer.valueOf(newOffset)); sourceOffsets.put(synthNode.getFileLocation().getFileName(), Integer.valueOf(newOffset));
} }
private void synthTreatment(IASTTranslationUnit synthTU) { private void synthTreatment(IASTTranslationUnit synthTU) {
@ -228,9 +204,8 @@ public class ChangeGenerator extends ASTVisitor {
synthWriter.setModificationStore(modificationStore); synthWriter.setModificationStore(modificationStore);
for (ASTModification modification : modificationParent.get(synthTU)) { for (ASTModification modification : modificationParent.get(synthTU)) {
IASTFileLocation targetLocation; IASTFileLocation targetLocation =
getFileLocationOfEmptyTranslationUnit(modification.getTargetNode());
targetLocation = getFileLocationOfEmptyTranslationUnit(modification.getTargetNode());
String currentFile = targetLocation.getFileName(); String currentFile = targetLocation.getFileName();
IPath implPath = new Path(currentFile); IPath implPath = new Path(currentFile);
IFile relevantFile= ResourceLookup.selectFileForLocation(implPath, null); IFile relevantFile= ResourceLookup.selectFileForLocation(implPath, null);
@ -256,14 +231,16 @@ public class ChangeGenerator extends ASTVisitor {
newNodeCode)); newNodeCode));
break; break;
case APPEND_CHILD: case APPEND_CHILD:
if(modification.getTargetNode() instanceof IASTTranslationUnit && ((IASTTranslationUnit)modification.getTargetNode()).getDeclarations().length > 0) { if (modification.getTargetNode() instanceof IASTTranslationUnit &&
((IASTTranslationUnit)modification.getTargetNode()).getDeclarations().length > 0) {
IASTTranslationUnit tu = (IASTTranslationUnit)modification.getTargetNode(); IASTTranslationUnit tu = (IASTTranslationUnit)modification.getTargetNode();
IASTDeclaration lastDecl = tu.getDeclarations()[tu.getDeclarations().length -1]; IASTDeclaration lastDecl = tu.getDeclarations()[tu.getDeclarations().length -1];
targetLocation = lastDecl.getFileLocation(); targetLocation = lastDecl.getFileLocation();
} }
String lineDelimiter = FileHelper.determineLineDelimiter(FileHelper.getIFilefromIASTNode(modification.getTargetNode())); String lineDelimiter = FileHelper.determineLineDelimiter(
edit.addChild(new InsertEdit(targetLocation.getNodeOffset() FileHelper.getIFilefromIASTNode(modification.getTargetNode()));
+ targetLocation.getNodeLength(),lineDelimiter + lineDelimiter + newNodeCode)); edit.addChild(new InsertEdit(targetLocation.getNodeOffset() + targetLocation.getNodeLength(),
lineDelimiter + lineDelimiter + newNodeCode));
break; break;
} }
} }
@ -302,15 +279,15 @@ public class ChangeGenerator extends ASTVisitor {
int nodeLength = node.getFileLocation().getNodeLength(); int nodeLength = node.getFileLocation().getNodeLength();
ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node); ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node);
if(!comments.isEmpty()) { if (!comments.isEmpty()) {
int startOffset = nodeOffset; int startOffset = nodeOffset;
int endOffset = nodeOffset + nodeLength; int endOffset = nodeOffset + nodeLength;
for(IASTComment comment : comments) { for (IASTComment comment : comments) {
IASTFileLocation commentLocation = comment.getFileLocation(); IASTFileLocation commentLocation = comment.getFileLocation();
if(commentLocation.getNodeOffset() < startOffset) { if (commentLocation.getNodeOffset() < startOffset) {
startOffset = commentLocation.getNodeOffset(); startOffset = commentLocation.getNodeOffset();
} }
if(commentLocation.getNodeOffset() + commentLocation.getNodeLength() >= endOffset) { if (commentLocation.getNodeOffset() + commentLocation.getNodeLength() >= endOffset) {
endOffset = commentLocation.getNodeOffset() + commentLocation.getNodeLength(); endOffset = commentLocation.getNodeOffset() + commentLocation.getNodeLength();
} }
} }
@ -323,11 +300,11 @@ public class ChangeGenerator extends ASTVisitor {
int nodeOffset = node.getFileLocation().getNodeOffset(); int nodeOffset = node.getFileLocation().getNodeOffset();
ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node); ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node);
if(!comments.isEmpty()) { if (!comments.isEmpty()) {
int startOffset = nodeOffset; int startOffset = nodeOffset;
for(IASTComment comment : comments) { for (IASTComment comment : comments) {
IASTFileLocation commentLocation = comment.getFileLocation(); IASTFileLocation commentLocation = comment.getFileLocation();
if(commentLocation.getNodeOffset() < startOffset) { if (commentLocation.getNodeOffset() < startOffset) {
startOffset = commentLocation.getNodeOffset(); startOffset = commentLocation.getNodeOffset();
} }
} }
@ -338,16 +315,13 @@ public class ChangeGenerator extends ASTVisitor {
private String getIndent(IASTNode nextNode) { private String getIndent(IASTNode nextNode) {
IASTFileLocation fileLocation = nextNode.getFileLocation(); IASTFileLocation fileLocation = nextNode.getFileLocation();
int length = fileLocation.getNodeOffset() int length = fileLocation.getNodeOffset() - getOffsetForNodeFile(nextNode);
- getOffsetForNodeFile(nextNode);
String originalSource = FileContentHelper.getContent(FileHelper String originalSource = FileContentHelper.getContent(FileHelper.getIFilefromIASTNode(nextNode),
.getIFilefromIASTNode(nextNode),
getOffsetForNodeFile(nextNode), length); getOffsetForNodeFile(nextNode), length);
StringBuilder indent = new StringBuilder(originalSource); StringBuilder indent = new StringBuilder(originalSource);
indent.reverse(); indent.reverse();
String lastline = indent String lastline = indent.substring(0, Math.max(indent.indexOf("\n"), 0)); //$NON-NLS-1$
.substring(0, Math.max(indent.indexOf("\n"), 0)); //$NON-NLS-1$
if (lastline.trim().length() == 0) { if (lastline.trim().length() == 0) {
return lastline; return lastline;
} }
@ -355,11 +329,9 @@ public class ChangeGenerator extends ASTVisitor {
} }
private boolean hasChangedChild(IASTNode parent) { private boolean hasChangedChild(IASTNode parent) {
return modificationParent.containsKey(parent); return modificationParent.containsKey(parent);
} }
@Override @Override
public int visit(IASTDeclarator declarator) { public int visit(IASTDeclarator declarator) {
if (hasChangedChild(declarator)) { if (hasChangedChild(declarator)) {
@ -378,10 +350,9 @@ public class ChangeGenerator extends ASTVisitor {
return super.visit(mod); return super.visit(mod);
} }
@Override @Override
public int visit(ICPPASTNamespaceDefinition namespaceDefinition) { public int visit(ICPPASTNamespaceDefinition namespaceDefinition) {
if(hasChangedChild(namespaceDefinition)){ if (hasChangedChild(namespaceDefinition)) {
synthTreatment(namespaceDefinition); synthTreatment(namespaceDefinition);
return ASTVisitor.PROCESS_SKIP; return ASTVisitor.PROCESS_SKIP;
} }
@ -443,7 +414,6 @@ public class ChangeGenerator extends ASTVisitor {
} }
class CodeComparer { class CodeComparer {
private final StringBuilder originalCode; private final StringBuilder originalCode;
private final StringBuilder synthCode; private final StringBuilder synthCode;
private int lastCommonInSynthStart; private int lastCommonInSynthStart;
@ -457,37 +427,37 @@ public class ChangeGenerator extends ASTVisitor {
calculatePositions(); calculatePositions();
} }
private void calculatePositions(){ private void calculatePositions() {
lastCommonInSynthStart = calcLastCommonPositionInSynthCode(); lastCommonInSynthStart = calcLastCommonPositionInSynthCode();
lastCommonInOriginalStart = calcLastCommonPositionInOriginalCode(); lastCommonInOriginalStart = calcLastCommonPositionInOriginalCode();
firstCommonInSynthEnd = calcFirstPositionOfCommonEndInSynthCode(lastCommonInSynthStart, lastCommonInOriginalStart); firstCommonInSynthEnd =
firstCommonInOriginalEnd = calcFirstPositionOfCommonEndInOriginalCode(lastCommonInOriginalStart, lastCommonInSynthStart); calcFirstPositionOfCommonEndInSynthCode(lastCommonInSynthStart, lastCommonInOriginalStart);
firstCommonInOriginalEnd =
calcFirstPositionOfCommonEndInOriginalCode(lastCommonInOriginalStart, lastCommonInSynthStart);
trimTrailingNewlines(); trimTrailingNewlines();
} }
private void trimTrailingNewlines() { private void trimTrailingNewlines() {
int prevOrigEnd = firstCommonInOriginalEnd - 1; int prevOrigEnd = firstCommonInOriginalEnd - 1;
while( prevOrigEnd > lastCommonInOriginalStart while (prevOrigEnd > lastCommonInOriginalStart && prevOrigEnd > -1 &&
&& prevOrigEnd > -1 isUninterresting(originalCode, prevOrigEnd)) {
&& isUninterresting(originalCode, prevOrigEnd)){
firstCommonInOriginalEnd = prevOrigEnd; firstCommonInOriginalEnd = prevOrigEnd;
prevOrigEnd--; prevOrigEnd--;
} }
while(firstCommonInOriginalEnd > 0 && firstCommonInOriginalEnd +1 < originalCode.length() && (originalCode.charAt(firstCommonInOriginalEnd) == ' ' || originalCode.charAt(firstCommonInOriginalEnd) == '\t')){ while (firstCommonInOriginalEnd > 0 && firstCommonInOriginalEnd + 1 < originalCode.length() &&
(originalCode.charAt(firstCommonInOriginalEnd) == ' ' || originalCode.charAt(firstCommonInOriginalEnd) == '\t')) {
firstCommonInOriginalEnd++; firstCommonInOriginalEnd++;
} }
int prevSynthEnd = firstCommonInSynthEnd - 1; int prevSynthEnd = firstCommonInSynthEnd - 1;
while( prevSynthEnd > lastCommonInSynthStart while (prevSynthEnd > lastCommonInSynthStart && prevSynthEnd > -1 &&
&& prevSynthEnd > -1 isUninterresting(synthCode, prevSynthEnd)) {
&& isUninterresting(synthCode, prevSynthEnd)){
firstCommonInSynthEnd = prevSynthEnd; firstCommonInSynthEnd = prevSynthEnd;
prevSynthEnd--; prevSynthEnd--;
} }
while(firstCommonInSynthEnd > 0 && firstCommonInSynthEnd +1< synthCode.length() && (synthCode.charAt(firstCommonInSynthEnd) == ' ' || synthCode.charAt(firstCommonInSynthEnd) == '\t')){ while (firstCommonInSynthEnd > 0 && firstCommonInSynthEnd + 1 < synthCode.length() &&
(synthCode.charAt(firstCommonInSynthEnd) == ' ' || synthCode.charAt(firstCommonInSynthEnd) == '\t')) {
firstCommonInSynthEnd++; firstCommonInSynthEnd++;
} }
} }
@ -508,7 +478,6 @@ public class ChangeGenerator extends ASTVisitor {
return firstCommonInSynthEnd; return firstCommonInSynthEnd;
} }
public int calcLastCommonPositionInSynthCode() { public int calcLastCommonPositionInSynthCode() {
return findLastCommonPosition(synthCode, originalCode); return findLastCommonPosition(synthCode, originalCode);
} }
@ -517,48 +486,41 @@ public class ChangeGenerator extends ASTVisitor {
return findLastCommonPosition(originalCode, synthCode); return findLastCommonPosition(originalCode, synthCode);
} }
private int calcFirstPositionOfCommonEndInOriginalCode(int originalLimit, int synthLimit) { private int calcFirstPositionOfCommonEndInOriginalCode(int originalLimit, int synthLimit) {
StringBuilder reverseOriginalCode = new StringBuilder(originalCode).reverse();
StringBuilder reverseOriginalCode = new StringBuilder(originalCode) StringBuilder reverseSynthCode = new StringBuilder(synthCode).reverse();
.reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode)
.reverse();
int lastCommonPosition = findLastCommonPosition(reverseOriginalCode, reverseSynthCode, int lastCommonPosition = findLastCommonPosition(reverseOriginalCode, reverseSynthCode,
reverseOriginalCode.length() - originalLimit - 1, reverseSynthCode.length() - synthLimit - 1); reverseOriginalCode.length() - originalLimit - 1,
reverseSynthCode.length() - synthLimit - 1);
if (lastCommonPosition < 0 if (lastCommonPosition < 0 || lastCommonPosition >= originalCode.length()) {
|| lastCommonPosition >= originalCode.length()) {
return -1; return -1;
} }
return originalCode.length() - lastCommonPosition -1; return originalCode.length() - lastCommonPosition - 1;
} }
private int calcFirstPositionOfCommonEndInSynthCode(int synthLimit, int originalLimit) { private int calcFirstPositionOfCommonEndInSynthCode(int synthLimit, int originalLimit) {
StringBuilder reverseOriginalCode = new StringBuilder(originalCode) StringBuilder reverseOriginalCode = new StringBuilder(originalCode).reverse();
.reverse(); StringBuilder reverseSynthCode = new StringBuilder(synthCode).reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode)
.reverse();
int lastCommonPosition = findLastCommonPosition(reverseSynthCode, reverseOriginalCode, int lastCommonPosition = findLastCommonPosition(reverseSynthCode, reverseOriginalCode,
reverseSynthCode.length() - synthLimit -1, reverseOriginalCode.length() - originalLimit -1); reverseSynthCode.length() - synthLimit - 1,
reverseOriginalCode.length() - originalLimit - 1);
if (lastCommonPosition < 0 if (lastCommonPosition < 0 || lastCommonPosition >= synthCode.length()) {
|| lastCommonPosition >= synthCode.length()) {
return -1; return -1;
} }
return synthCode.length() - lastCommonPosition - 1; return synthCode.length() - lastCommonPosition - 1;
} }
private int findLastCommonPosition(StringBuilder first, StringBuilder second) {
private int findLastCommonPosition(StringBuilder first, StringBuilder second){
return findLastCommonPosition(first, second, first.length(), second.length()); return findLastCommonPosition(first, second, first.length(), second.length());
} }
private int findLastCommonPosition(StringBuilder first, StringBuilder second, int firstLimit,
private int findLastCommonPosition(StringBuilder first, StringBuilder second, int firstLimit, int secondLimit){ int secondLimit) {
int firstIndex = -1; int firstIndex = -1;
int secondIndex = -1; int secondIndex = -1;
int lastCommonIndex = -1; int lastCommonIndex = -1;
@ -567,11 +529,8 @@ public class ChangeGenerator extends ASTVisitor {
lastCommonIndex = firstIndex; lastCommonIndex = firstIndex;
firstIndex = nextInterrestingPosition(first, firstIndex); firstIndex = nextInterrestingPosition(first, firstIndex);
secondIndex = nextInterrestingPosition(second, secondIndex); secondIndex = nextInterrestingPosition(second, secondIndex);
} while (firstIndex > -1 } while (firstIndex > -1 && firstIndex <= firstLimit && secondIndex > -1 &&
&& firstIndex <= firstLimit secondIndex <= secondLimit && first.charAt(firstIndex) == second.charAt(secondIndex));
&& secondIndex > -1
&& secondIndex <= secondLimit
&& first.charAt(firstIndex) == second.charAt(secondIndex));
return lastCommonIndex; return lastCommonIndex;
} }
@ -600,63 +559,52 @@ public class ChangeGenerator extends ASTVisitor {
protected void createChange(MultiTextEdit edit, IASTNode changedNode) { protected void createChange(MultiTextEdit edit, IASTNode changedNode) {
int changeOffset = getOffsetIncludingComments(changedNode); int changeOffset = getOffsetIncludingComments(changedNode);
TextEditGroup editGroup = new TextEditGroup(Messages.ChangeGenerator_group); TextEditGroup editGroup = new TextEditGroup(Messages.ChangeGenerator_group);
for (ASTModification currentModification : modificationParent for (ASTModification currentModification : modificationParent.get(changedNode)) {
.get(changedNode)) {
if (currentModification.getAssociatedEditGroup() != null) { if (currentModification.getAssociatedEditGroup() != null) {
editGroup = currentModification.getAssociatedEditGroup(); editGroup = currentModification.getAssociatedEditGroup();
edit.addChildren(editGroup.getTextEdits()); edit.addChildren(editGroup.getTextEdits());
break; break;
} }
} }
createChange(edit, changeOffset); createChange(edit, changeOffset);
} }
private void createChange(MultiTextEdit edit, int changeOffset) { private void createChange(MultiTextEdit edit, int changeOffset) {
int i = (firstCommonInSynthEnd >= 0 ?
int i = (firstCommonInSynthEnd >= 0 ? firstCommonInOriginalEnd firstCommonInOriginalEnd : originalCode.length()) - lastCommonInOriginalStart;
: originalCode.length())
- lastCommonInOriginalStart;
if (i <= 0) { if (i <= 0) {
String insertCode = synthCode.substring( String insertCode = synthCode.substring(lastCommonInSynthStart,
lastCommonInSynthStart, firstCommonInSynthEnd); firstCommonInSynthEnd);
InsertEdit iEdit = new InsertEdit(changeOffset InsertEdit iEdit = new InsertEdit(changeOffset + lastCommonInOriginalStart,
+ lastCommonInOriginalStart, insertCode); insertCode);
edit.addChild(iEdit); edit.addChild(iEdit);
} else if ((firstCommonInSynthEnd >= 0 ? firstCommonInSynthEnd } else if ((firstCommonInSynthEnd >= 0 ?
: synthCode.length()) firstCommonInSynthEnd : synthCode.length()) - lastCommonInSynthStart <= 0) {
- lastCommonInSynthStart <= 0) {
int correction = 0; int correction = 0;
if (lastCommonInSynthStart > firstCommonInSynthEnd) { if (lastCommonInSynthStart > firstCommonInSynthEnd) {
correction = lastCommonInSynthStart correction = lastCommonInSynthStart - firstCommonInSynthEnd;
- firstCommonInSynthEnd;
} }
DeleteEdit dEdit = new DeleteEdit(changeOffset DeleteEdit dEdit = new DeleteEdit(changeOffset + lastCommonInOriginalStart,
+ lastCommonInOriginalStart, firstCommonInOriginalEnd - lastCommonInOriginalStart + correction);
firstCommonInOriginalEnd
- lastCommonInOriginalStart + correction);
edit.addChild(dEdit); edit.addChild(dEdit);
} else { } else {
String replacementCode = getReplacementCode( String replacementCode = getReplacementCode(lastCommonInSynthStart,
lastCommonInSynthStart, firstCommonInSynthEnd); firstCommonInSynthEnd);
ReplaceEdit rEdit = new ReplaceEdit( ReplaceEdit rEdit = new ReplaceEdit(
changeOffset changeOffset + Math.max(lastCommonInOriginalStart, 0),
+ Math.max(lastCommonInOriginalStart, 0), (firstCommonInOriginalEnd >= 0 ?
(firstCommonInOriginalEnd >= 0 ? firstCommonInOriginalEnd firstCommonInOriginalEnd :
: originalCode.length()) originalCode.length()) - Math.max(lastCommonInOriginalStart, 0),
- Math.max(lastCommonInOriginalStart, 0),
replacementCode); replacementCode);
edit.addChild(rEdit); edit.addChild(rEdit);
} }
} }
private String getReplacementCode(int lastCommonPositionInSynth, private String getReplacementCode(int lastCommonPositionInSynth, int firstOfCommonEndInSynth) {
int firstOfCommonEndInSynth) {
int replacementStart = Math.max(lastCommonPositionInSynth, 0); int replacementStart = Math.max(lastCommonPositionInSynth, 0);
int replacementEnd = (firstOfCommonEndInSynth >= 0 ? firstOfCommonEndInSynth int replacementEnd = (firstOfCommonEndInSynth >= 0 ?
: synthCode.length()); firstOfCommonEndInSynth : synthCode.length());
if (replacementStart < replacementEnd) { if (replacementStart < replacementEnd) {
return synthCode.substring(replacementStart, replacementEnd); return synthCode.substring(replacementStart, replacementEnd);
} }

View file

@ -37,15 +37,12 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap; import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/** /**
*
* Visits the nodes in consideration of {@link ASTModification}s. * Visits the nodes in consideration of {@link ASTModification}s.
* *
* @since 5.0 * @since 5.0
* @author Emanuel Graf IFS * @author Emanuel Graf IFS
*
*/ */
public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor { public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
private static final String DEFAULT_INDENTATION = ""; //$NON-NLS-1$ private static final String DEFAULT_INDENTATION = ""; //$NON-NLS-1$
private final ASTModificationStore modificationStore; private final ASTModificationStore modificationStore;
private final String fileScope; private final String fileScope;
@ -74,15 +71,14 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
shouldVisitProblems = delegateVisitor.shouldVisitProblems; shouldVisitProblems = delegateVisitor.shouldVisitProblems;
shouldVisitTypeIds = delegateVisitor.shouldVisitTypeIds; shouldVisitTypeIds = delegateVisitor.shouldVisitTypeIds;
shouldVisitArrayModifiers= delegateVisitor.shouldVisitArrayModifiers; shouldVisitArrayModifiers= delegateVisitor.shouldVisitArrayModifiers;
} }
public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, NodeCommentMap nodeMap) { public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, NodeCommentMap nodeMap) {
this(modStore, DEFAULT_INDENTATION, null, nodeMap); this(modStore, DEFAULT_INDENTATION, null, nodeMap);
} }
public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, String givenIndentation,
String givenIndentation, String fileScope, NodeCommentMap commentMap) { String fileScope, NodeCommentMap commentMap) {
super(givenIndentation, commentMap); super(givenIndentation, commentMap);
this.modificationStore = modStore; this.modificationStore = modStore;
this.fileScope = fileScope; this.fileScope = fileScope;
@ -98,13 +94,12 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
} }
@Override @Override
protected IASTDeclarator getParameterDeclarator( protected IASTDeclarator getParameterDeclarator(IASTParameterDeclaration parameterDeclaration) {
IASTParameterDeclaration parameterDeclaration) {
IASTDeclarator newDecl = parameterDeclaration.getDeclarator(); IASTDeclarator newDecl = parameterDeclaration.getDeclarator();
if(stack.getModifiedNodes().contains(newDecl)){ if (stack.getModifiedNodes().contains(newDecl)) {
for(ASTModification currentModification : stack.getModificationsForNode(newDecl)){ for (ASTModification currentModification : stack.getModificationsForNode(newDecl)) {
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE && currentModification.getTargetNode() == parameterDeclaration){ if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE &&
currentModification.getTargetNode() == parameterDeclaration) {
newDecl = (IASTDeclarator) currentModification.getNewNode(); newDecl = (IASTDeclarator) currentModification.getNewNode();
} }
} }
@ -115,9 +110,10 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
@Override @Override
protected IASTName getParameterName(IASTDeclarator declarator) { protected IASTName getParameterName(IASTDeclarator declarator) {
IASTName newName = declarator.getName(); IASTName newName = declarator.getName();
if(stack.getModifiedNodes().contains(newName)){ if (stack.getModifiedNodes().contains(newName)) {
for(ASTModification currentModification : stack.getModificationsForNode(newName)){ for (ASTModification currentModification : stack.getModificationsForNode(newName)) {
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE && currentModification.getTargetNode() == newName){ if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE &&
currentModification.getTargetNode() == newName) {
newName = (IASTName) currentModification.getNewNode(); newName = (IASTName) currentModification.getNewNode();
} }
} }
@ -329,14 +325,12 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
@Override @Override
public int visit(IASTTranslationUnit tu) { public int visit(IASTTranslationUnit tu) {
ASTModificationHelper helper = new ASTModificationHelper( ASTModificationHelper helper = new ASTModificationHelper(stack);
stack); IASTDeclaration[] declarations = helper.createModifiedChildArray(tu, tu.getDeclarations(),
IASTDeclaration.class, commentMap);
IASTDeclaration[] declarations = helper.createModifiedChildArray(tu, tu.getDeclarations(), IASTDeclaration.class, commentMap);
for (IASTDeclaration currentDeclaration : declarations) { for (IASTDeclaration currentDeclaration : declarations) {
currentDeclaration.accept(this); currentDeclaration.accept(this);
} }
return PROCESS_SKIP; return PROCESS_SKIP;
} }
@ -357,28 +351,28 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
} }
} }
//Check all insert before and append modifications for the current node. If necessary put it onto the stack. // Check all insert before and append modifications for the current node.
// If necessary put it onto the stack.
for (IASTNode currentModifiedNode : stack.getModifiedNodes()) { for (IASTNode currentModifiedNode : stack.getModifiedNodes()) {
for (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) { for (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) {
if(currentMod.getNewNode() == node){ if (currentMod.getNewNode() == node) {
if(currentMod.getKind() != ModificationKind.REPLACE) { if (currentMod.getKind() != ModificationKind.REPLACE) {
stack.pushScope(currentModifiedNode); stack.pushScope(currentModifiedNode);
return PROCESS_CONTINUE; return PROCESS_CONTINUE;
} }
} }
} }
} }
//Check all replace modifications for the current node. Visit the replacing node if found. // Check all replace modifications for the current node. Visit the replacing node if found.
for (IASTNode currentModifiedNode : stack.getModifiedNodes()) { for (IASTNode currentModifiedNode : stack.getModifiedNodes()) {
for (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) { for (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) {
if(currentMod.getTargetNode() == node && currentMod.getKind() == ModificationKind.REPLACE){ if (currentMod.getTargetNode() == node && currentMod.getKind() == ModificationKind.REPLACE) {
if(currentMod.getNewNode() != null){ if (currentMod.getNewNode() != null) {
stack.pushScope(node); stack.pushScope(node);
currentMod.getNewNode().accept(this); currentMod.getNewNode().accept(this);
stack.popScope(node); stack.popScope(node);
return PROCESS_SKIP; return PROCESS_SKIP;
} } else {
else{
return PROCESS_SKIP; return PROCESS_SKIP;
} }
} }
@ -389,7 +383,6 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
} }
private String getCorrespondingFile(IASTNode node) { private String getCorrespondingFile(IASTNode node) {
if (node.getFileLocation() != null) { if (node.getFileLocation() != null) {
return node.getFileLocation().getFileName(); return node.getFileLocation().getFileName();
} }
@ -398,11 +391,8 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
return getCorrespondingFile(node.getParent()); return getCorrespondingFile(node.getParent());
} }
for (IASTNode modifiedNode : modificationStore.getRootModifications() for (IASTNode modifiedNode : modificationStore.getRootModifications().getModifiedNodes()) {
.getModifiedNodes()) { for (ASTModification modification : modificationStore.getRootModifications().getModificationsForNode(modifiedNode)) {
for (ASTModification modification : modificationStore
.getRootModifications().getModificationsForNode(
modifiedNode)) {
if (modification.getNewNode() == node) { if (modification.getNewNode() == node) {
return getCorrespondingFile(modification.getTargetNode()); return getCorrespondingFile(modification.getTargetNode());
} }

View file

@ -30,17 +30,13 @@ import org.eclipse.osgi.util.NLS;
* A Change for creating a new file with the given name, content and encoding at the specified path. * A Change for creating a new file with the given name, content and encoding at the specified path.
* *
* @author Emanuel Graf * @author Emanuel Graf
*
*/ */
public class CreateFileChange extends Change { public class CreateFileChange extends Change {
private String name; private String name;
private final IPath path; private final IPath path;
private final String source; private final String source;
private final String encoding; private final String encoding;
public CreateFileChange(String name, IPath path, String source, String encoding) { public CreateFileChange(String name, IPath path, String source, String encoding) {
super(); super();
this.name = name; this.name = name;
@ -55,13 +51,12 @@ public class CreateFileChange extends Change {
@Override @Override
public Object getModifiedElement() { public Object getModifiedElement() {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
return file;
} }
@Override @Override
public String getName() { public String getName() {
if(name == null) { if (name == null) {
return NLS.bind(Messages.CreateFileChange_CreateFile, path.toOSString()); return NLS.bind(Messages.CreateFileChange_CreateFile, path.toOSString());
} }
return name; return name;
@ -72,8 +67,8 @@ public class CreateFileChange extends Change {
} }
@Override @Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, public RefactoringStatus isValid(IProgressMonitor pm)
OperationCanceledException { throws CoreException, OperationCanceledException {
RefactoringStatus result= new RefactoringStatus(); RefactoringStatus result= new RefactoringStatus();
IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path); IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
@ -84,8 +79,7 @@ public class CreateFileChange extends Change {
} }
if (file.exists()) { if (file.exists()) {
result.addFatalError( NLS.bind(Messages.CreateFileChange_FileExists, result.addFatalError(NLS.bind(Messages.CreateFileChange_FileExists, file.getFullPath().toString()));
file.getFullPath().toString()));
return result; return result;
} }
return result; return result;
@ -96,14 +90,12 @@ public class CreateFileChange extends Change {
IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path); IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
InputStream is = new ByteArrayInputStream(source.getBytes()); InputStream is = new ByteArrayInputStream(source.getBytes());
file.create(is, false, new SubProgressMonitor(pm, 1)); file.create(is, false, new SubProgressMonitor(pm, 1));
if(encoding != null) { if (encoding != null) {
file.setCharset(encoding, new SubProgressMonitor(pm,1)); file.setCharset(encoding, new SubProgressMonitor(pm,1));
} }
return new DeleteFileChange(file.getFullPath()); return new DeleteFileChange(file.getFullPath());
} }
public String getSource() { public String getSource() {
return source; return source;
} }
@ -116,5 +108,4 @@ public class CreateFileChange extends Change {
public String toString() { public String toString() {
return getName(); return getName();
} }
} }

View file

@ -38,7 +38,6 @@ public class ModificationCollector {
if (!rewriters.containsKey(ast)) { if (!rewriters.containsKey(ast)) {
rewriters.put(ast, ASTRewrite.create(ast)); rewriters.put(ast, ASTRewrite.create(ast));
} }
return rewriters.get(ast); return rewriters.get(ast);
} }