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

@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.astwriter;
@ -18,22 +18,17 @@ import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.ASTCommenter;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/**
*
* ASTWriter main class. Generates source code from <code>IASTNode</code>. Uses a
* <codeC>hangeGeneratorWriterVisitor</code> to generate the code for the given
* nodes.
*
* ASTWriter main class. Generates source code from <code>IASTNode</code>.
* Uses a <code>hangeGeneratorWriterVisitor</code> to generate the code for the given nodes.
*
* @see ChangeGeneratorWriterVisitor
*
*
* @author Emanuel Graf
*
*/
public class ASTWriter {
private ChangeGeneratorWriterVisitor transformationVisitor;
private ASTModificationStore modificationStore = new ASTModificationStore();
private String givenIndentation = ""; //$NON-NLS-1$
/**
* Creates a <code>ASTWriter</code>.
@ -44,7 +39,7 @@ public class ASTWriter {
/**
* Creates a <code>ASTWriter</code> that indents the code.
*
*
* @param givenIndentation The indentation added to each line
*/
public ASTWriter(String givenIndentation) {
@ -53,9 +48,8 @@ public class ASTWriter {
}
/**
*
* Genereates the source code representing this node.
*
* Generates the source code representing this node.
*
* @param rootNode Node to write.
* @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>.
@ -63,36 +57,36 @@ public class ASTWriter {
public String write(IASTNode rootNode) throws ProblemRuntimeException {
return write(rootNode, null, new NodeCommentMap());
}
public String write(IASTNode rootNode, NodeCommentMap commentMap) {
return write(rootNode, null, commentMap);
}
/**
*
* Generates the source code representing this node including comments.
*
*
* @param rootNode Node to write.
* @param fileScope
* @param commentMap Node Comment Map <code>ASTCommenter</code>
* @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)
*/
public String write(IASTNode rootNode, String fileScope, NodeCommentMap commentMap) throws ProblemRuntimeException {
transformationVisitor = new ChangeGeneratorWriterVisitor(modificationStore, givenIndentation, fileScope, commentMap);
if(rootNode != null){
public String write(IASTNode rootNode, String fileScope, NodeCommentMap commentMap)
throws ProblemRuntimeException {
transformationVisitor = new ChangeGeneratorWriterVisitor(modificationStore, givenIndentation,
fileScope, commentMap);
if (rootNode != null) {
rootNode.accept(transformationVisitor);
}
String str = transformationVisitor.toString();
transformationVisitor.cleanCache();
return str;
}
public void setModificationStore(ASTModificationStore modificationStore) {
this.modificationStore = modificationStore;
}
}
}

View file

@ -1,12 +1,12 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
*******************************************************************************/
@ -39,10 +39,10 @@ import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/**
* Visits all nodes, prints leading comments and handles macro expansions. The
* source code generation is delegated to severals <code>NodeWriters</code>.
*
*
* @see NodeWriter
* @see MacroExpansionHandler
*
*
* @author Emanuel Graf IFS
*/
public class ASTWriterVisitor extends ASTVisitor {
@ -73,7 +73,7 @@ public class ASTWriterVisitor extends ASTVisitor {
shouldVisitParameterDeclarations = true;
shouldVisitTranslationUnit = true;
}
public ASTWriterVisitor(NodeCommentMap commentMap) {
this("", commentMap); //$NON-NLS-1$
}
@ -83,7 +83,6 @@ public class ASTWriterVisitor extends ASTVisitor {
scribe.setGivenIndentation(givenIndentation);
init(commentMap);
this.commentMap = commentMap;
}
private void init(NodeCommentMap commentMap) {
@ -98,30 +97,28 @@ public class ASTWriterVisitor extends ASTVisitor {
nameWriter = new NameWriter(scribe, this, commentMap);
tempParameterWriter = new TemplateParameterWriter(scribe, this, commentMap);
}
@Override
public String toString(){
public String toString() {
return scribe.toString();
}
@Override
public int leave(IASTTranslationUnit tu) {
for(IASTComment comment : commentMap.getFreestandingCommentsForNode(tu)) {
for (IASTComment comment : commentMap.getFreestandingCommentsForNode(tu)) {
scribe.print(comment.getComment());
scribe.newLine();
}
}
return super.leave(tu);
}
private void writeLeadingComments(IASTNode node) {
for(IASTComment comment : getLeadingComments(node)) {
for (IASTComment comment : getLeadingComments(node)) {
scribe.print(comment.getComment());
scribe.newLine();
}
}
}
private ArrayList<IASTComment> getLeadingComments(IASTNode node) {
ArrayList<IASTComment> leadingComments = commentMap.getLeadingCommentsForNode(node);
IASTNodeLocation[] locs = node.getNodeLocations();
@ -131,15 +128,15 @@ public class ASTWriterVisitor extends ASTVisitor {
}
return leadingComments;
}
public void visit(ASTLiteralNode lit) {
scribe.print(lit.getRawSignature());
}
@Override
public int visit(IASTName name) {
writeLeadingComments(name);
if(!macroHandler.checkisMacroExpansionNode(name)) {
if (!macroHandler.checkisMacroExpansionNode(name)) {
nameWriter.writeName(name);
}
return ASTVisitor.PROCESS_SKIP;
@ -148,18 +145,19 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTDeclSpecifier declSpec) {
writeLeadingComments(declSpec);
declSpecWriter.writeDelcSpec(declSpec);
declSpecWriter.writeDelcSpec(declSpec);
return ASTVisitor.PROCESS_SKIP;
}
@Override
public int visit(IASTExpression expression) {
writeLeadingComments(expression);
if(!macroHandler.checkisMacroExpansionNode(expression)) {
writeLeadingComments(expression);
if (!macroHandler.checkisMacroExpansionNode(expression)) {
if (expression instanceof IGNUASTCompoundStatementExpression) {
IGNUASTCompoundStatementExpression gnuCompStmtExp = (IGNUASTCompoundStatementExpression) expression;
IGNUASTCompoundStatementExpression gnuCompStmtExp =
(IGNUASTCompoundStatementExpression) expression;
gnuCompStmtExp.getCompoundStatement().accept(this);
}else {
} else {
expWriter.writeExpression(expression);
}
}
@ -169,10 +167,11 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTStatement statement) {
writeLeadingComments(statement);
if(macroHandler.isStatementWithMixedLocation(statement) && !(statement instanceof IASTCompoundStatement)){
if (macroHandler.isStatementWithMixedLocation(statement) &&
!(statement instanceof IASTCompoundStatement)) {
return statementWriter.writeMixedStatement(statement);
}
if(macroHandler.checkisMacroExpansionNode(statement)) {
if (macroHandler.checkisMacroExpansionNode(statement)) {
return ASTVisitor.PROCESS_SKIP;
}
return statementWriter.writeStatement(statement, true);
@ -181,7 +180,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTDeclaration declaration) {
writeLeadingComments(declaration);
if(!macroHandler.checkisMacroExpansionNode(declaration)) {
if (!macroHandler.checkisMacroExpansionNode(declaration)) {
declarationWriter.writeDeclaration(declaration);
}
return ASTVisitor.PROCESS_SKIP;
@ -190,7 +189,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTDeclarator declarator) {
writeLeadingComments(declarator);
if(!macroHandler.checkisMacroExpansionNode(declarator)) {
if (!macroHandler.checkisMacroExpansionNode(declarator)) {
declaratorWriter.writeDeclarator(declarator);
}
return ASTVisitor.PROCESS_SKIP;
@ -198,7 +197,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTArrayModifier amod) {
if(!macroHandler.checkisMacroExpansionNode(amod)) {
if (!macroHandler.checkisMacroExpansionNode(amod)) {
declaratorWriter.writeArrayModifier(amod);
}
return ASTVisitor.PROCESS_SKIP;
@ -207,7 +206,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTInitializer initializer) {
writeLeadingComments(initializer);
if(!macroHandler.checkisMacroExpansionNode(initializer)) {
if (!macroHandler.checkisMacroExpansionNode(initializer)) {
initializerWriter.writeInitializer(initializer);
}
return ASTVisitor.PROCESS_SKIP;
@ -216,11 +215,11 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(IASTParameterDeclaration parameterDeclaration) {
writeLeadingComments(parameterDeclaration);
if(!macroHandler.checkisMacroExpansionNode(parameterDeclaration)) {
if (!macroHandler.checkisMacroExpansionNode(parameterDeclaration)) {
parameterDeclaration.getDeclSpecifier().accept(this);
IASTDeclarator declarator = getParameterDeclarator(parameterDeclaration);
if(getParameterName(declarator).toString().length() != 0){
if (getParameterName(declarator).toString().length() != 0) {
scribe.printSpaces(1);
}
declarator.accept(this);
@ -232,15 +231,14 @@ public class ASTWriterVisitor extends ASTVisitor {
return declarator.getName();
}
protected IASTDeclarator getParameterDeclarator(
IASTParameterDeclaration parameterDeclaration) {
protected IASTDeclarator getParameterDeclarator(IASTParameterDeclaration parameterDeclaration) {
return parameterDeclaration.getDeclarator();
}
@Override
public int visit(ICPPASTNamespaceDefinition namespace) {
writeLeadingComments(namespace);
if(!macroHandler.checkisMacroExpansionNode(namespace)) {
if (!macroHandler.checkisMacroExpansionNode(namespace)) {
declarationWriter.writeDeclaration(namespace);
}
return ASTVisitor.PROCESS_SKIP;
@ -249,7 +247,7 @@ public class ASTWriterVisitor extends ASTVisitor {
@Override
public int visit(ICPPASTTemplateParameter parameter) {
writeLeadingComments(parameter);
if(!macroHandler.checkisMacroExpansionNode(parameter)) {
if (!macroHandler.checkisMacroExpansionNode(parameter)) {
tempParameterWriter.writeTemplateParameter(parameter);
}
return ASTVisitor.PROCESS_SKIP;

View file

@ -1,14 +1,14 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2010 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.astwriter;
@ -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.rewrite.commenthandler.NodeCommentMap;
/**
*
* Generates source code of declaration nodes. The actual string operations are delegated
* to the <code>Scribe</code> class.
*
*
* @see Scribe
* @see IASTDeclaration
* @author Emanuel Graf IFS
*
*/
public class DeclarationWriter extends NodeWriter{
private static final String ASM_END = ")"; //$NON-NLS-1$
private static final String ASM_START = "asm("; //$NON-NLS-1$
private static final String TEMPLATE_DECLARATION = "template<"; //$NON-NLS-1$
@ -60,15 +56,15 @@ public class DeclarationWriter extends NodeWriter{
private static final String NAMESPACE = "namespace "; //$NON-NLS-1$
private static final String USING = "using "; //$NON-NLS-1$
private boolean printSemicolon;
public DeclarationWriter(Scribe scribe, ASTVisitor visitor, NodeCommentMap commentMap) {
super(scribe, visitor, commentMap);
}
protected void writeDeclaration(IASTDeclaration declaration) throws ProblemRuntimeException{
writeDeclaration(declaration, true);
}
protected void writeDeclaration(IASTDeclaration declaration, boolean writeSemicolon) {
boolean addNewLine = true;
printSemicolon = writeSemicolon;
@ -86,7 +82,7 @@ public class DeclarationWriter extends NodeWriter{
} else if (declaration instanceof ICPPASTLinkageSpecification) {
writeLinkageSpecification((ICPPASTLinkageSpecification) declaration);
} else if (declaration instanceof ICPPASTNamespaceAlias) {
writeNamespaceAlias((ICPPASTNamespaceAlias) declaration);
writeNamespaceAlias((ICPPASTNamespaceAlias) declaration);
} else if (declaration instanceof ICPPASTTemplateDeclaration) {
writeTemplateDeclaration((ICPPASTTemplateDeclaration) declaration);
addNewLine = false;
@ -100,13 +96,13 @@ public class DeclarationWriter extends NodeWriter{
} else if (declaration instanceof ICPPASTVisibilityLabel) {
writeVisibilityLabel((ICPPASTVisibilityLabel) declaration);
}
if(hasTrailingComments(declaration)) {
if (hasTrailingComments(declaration)) {
writeTrailingComments(declaration, addNewLine);
}else if(addNewLine){
} else if (addNewLine) {
scribe.newLine();
}
if(hasFreestandingComments(declaration)){
if (hasFreestandingComments(declaration)) {
writeFreeStandingComments(declaration);
}
@ -127,7 +123,7 @@ public class DeclarationWriter extends NodeWriter{
scribe.print(':');
break;
case ICPPASTVisibilityLabel.v_public:
scribe.print(PUBLIC);
scribe.print(PUBLIC);
scribe.print(':');
break;
default:
@ -144,10 +140,10 @@ public class DeclarationWriter extends NodeWriter{
private void writeUsingDeclaration(ICPPASTUsingDeclaration usingDeclaration) {
scribe.print(USING);
if(usingDeclaration.isTypename()){
if (usingDeclaration.isTypename()) {
scribe.print(TYPENAME);
}
usingDeclaration.getName().accept(visitor);
usingDeclaration.getName().accept(visitor);
scribe.printSemicolon();
}
@ -157,14 +153,14 @@ public class DeclarationWriter extends NodeWriter{
}
protected void writeTemplateDeclaration(ICPPASTTemplateDeclaration templateDeclaration) {
if(templateDeclaration.isExported()){
if (templateDeclaration.isExported()) {
scribe.print(EXPORT);
}
scribe.print(TEMPLATE_DECLARATION);
ICPPASTTemplateParameter[] paraDecls = templateDeclaration.getTemplateParameters();
for(int i = 0; i < paraDecls.length; ++i) {
for (int i = 0; i < paraDecls.length; ++i) {
paraDecls[i].accept(visitor);
if(i + 1 < paraDecls.length) {
if (i + 1 < paraDecls.length) {
scribe.print(',');
scribe.printSpaces(1);
}
@ -174,30 +170,30 @@ public class DeclarationWriter extends NodeWriter{
templateDeclaration.getDeclaration().accept(visitor);
}
protected void writeDeclaration(ICPPASTNamespaceDefinition declaration){
protected void writeDeclaration(ICPPASTNamespaceDefinition declaration) {
printSemicolon = true;
writeNamespaceDefinition(declaration);
}
private void writeNamespaceDefinition(ICPPASTNamespaceDefinition namespaceDefinition) {
scribe.print(NAMESPACE);
namespaceDefinition.getName().accept(visitor);
if(!hasTrailingComments(namespaceDefinition.getName())) {
if (!hasTrailingComments(namespaceDefinition.getName())) {
scribe.newLine();
}
scribe.printLBrace();
scribe.newLine();
writeDeclarationsInNamespace(namespaceDefinition, namespaceDefinition.getDeclarations());
if(hasFreestandingComments(namespaceDefinition)) {
if (hasFreestandingComments(namespaceDefinition)) {
writeFreeStandingComments(namespaceDefinition);
}
scribe.printRBrace();
if(hasTrailingComments(namespaceDefinition)) {
if (hasTrailingComments(namespaceDefinition)) {
writeTrailingComments(namespaceDefinition);
}else{
scribe.newLine();
}
}
}
protected void writeDeclarationsInNamespace(ICPPASTNamespaceDefinition namespaceDefinition, IASTDeclaration[] declarations) {
@ -218,9 +214,9 @@ public class DeclarationWriter extends NodeWriter{
scribe.print( EXTERN);
scribe.print(linkageSpecification.getLiteral());
scribe.printSpaces(1);
IASTDeclaration[] declarations = linkageSpecification.getDeclarations();
if(declarations.length > 1){
if (declarations.length > 1) {
scribe.printLBrace();
scribe.decrementIndentationLevel();
scribe.newLine();
@ -229,13 +225,13 @@ public class DeclarationWriter extends NodeWriter{
}
scribe.printRBrace();
scribe.incrementIndentationLevel();
} else if(declarations.length > 0) {
} else if (declarations.length > 0) {
visitNodeIfNotNull(declarations[0]);
}
}
private void writeExplicitTemplateInstantiation(ICPPASTExplicitTemplateInstantiation explicitTemplateInstantiation) {
switch(explicitTemplateInstantiation.getModifier()){
switch(explicitTemplateInstantiation.getModifier()) {
case ICPPASTExplicitTemplateInstantiation.EXTERN:
scribe.print(EXTERN);
break;
@ -246,7 +242,7 @@ public class DeclarationWriter extends NodeWriter{
scribe.print(STATIC);
break;
}
scribe.print(TEMPLATE);
explicitTemplateInstantiation.getDeclaration().accept(visitor);
}
@ -259,7 +255,7 @@ public class DeclarationWriter extends NodeWriter{
}
private void printSemicolon() {
if(printSemicolon) {
if (printSemicolon) {
scribe.printSemicolon();
}
}
@ -269,7 +265,7 @@ public class DeclarationWriter extends NodeWriter{
declSpecifier.accept(visitor);
if (declSpecifier instanceof IASTSimpleDeclSpecifier) {
IASTSimpleDeclSpecifier simDeclSpec = (IASTSimpleDeclSpecifier) declSpecifier;
if(simDeclSpec.getType() != IASTSimpleDeclSpecifier.t_unspecified) {
if (simDeclSpec.getType() != IASTSimpleDeclSpecifier.t_unspecified) {
scribe.printSpace();
}
}else {
@ -277,12 +273,12 @@ public class DeclarationWriter extends NodeWriter{
}
IASTDeclarator declarator = ASTQueries.findOutermostDeclarator(funcDef.getDeclarator());
declarator.accept(visitor);
if (funcDef instanceof ICPPASTFunctionWithTryBlock) {
scribe.newLine();
scribe.print(Keywords.TRY);
}
if (funcDef instanceof ICPPASTFunctionDefinition) {
ICPPASTFunctionDefinition cppFuncDef= (ICPPASTFunctionDefinition) funcDef;
writeCtorChainInitializer(cppFuncDef, cppFuncDef.getMemberInitializers());
@ -290,7 +286,7 @@ public class DeclarationWriter extends NodeWriter{
scribe.newLine();
funcDef.getBody().accept(visitor);
if (funcDef instanceof ICPPASTFunctionWithTryBlock) {
ICPPASTFunctionWithTryBlock tryblock = (ICPPASTFunctionWithTryBlock) funcDef;
ICPPASTCatchHandler[] catches = tryblock.getCatchHandlers();
@ -299,17 +295,17 @@ public class DeclarationWriter extends NodeWriter{
}
}
}
protected void writeCtorChainInitializer(
ICPPASTFunctionDefinition funcDec, ICPPASTConstructorChainInitializer[] ctorInitChain) {
if(ctorInitChain.length != 0) {
protected void writeCtorChainInitializer(ICPPASTFunctionDefinition funcDec,
ICPPASTConstructorChainInitializer[] ctorInitChain) {
if (ctorInitChain.length != 0) {
scribe.newLine();
scribe.print(':');
}
for(int i = 0; i < ctorInitChain.length; ++i) {
for (int i = 0; i < ctorInitChain.length; ++i) {
ICPPASTConstructorChainInitializer initializer = ctorInitChain[i];
initializer.accept(visitor);
if(i+1 < ctorInitChain.length) {
if (i + 1 < ctorInitChain.length) {
scribe.print(COMMA_SPACE);
}
}
@ -318,24 +314,23 @@ public class DeclarationWriter extends NodeWriter{
private void writeSimpleDeclaration(IASTSimpleDeclaration simpDec) {
IASTDeclSpecifier declSpecifier = simpDec.getDeclSpecifier();
IASTDeclarator[] decls = simpDec.getDeclarators();
declSpecifier.accept(visitor);
boolean noSpace = false;
if (declSpecifier instanceof IASTSimpleDeclSpecifier) {
IASTSimpleDeclSpecifier simpleDeclSpecifier = (IASTSimpleDeclSpecifier) declSpecifier;
if(simpleDeclSpecifier.getType() == IASTSimpleDeclSpecifier.t_unspecified) {
if (simpleDeclSpecifier.getType() == IASTSimpleDeclSpecifier.t_unspecified) {
noSpace = true;
}
}
if(decls.length > 0) {
if(!noSpace) {
if (decls.length > 0) {
if (!noSpace) {
scribe.printSpace();
}
writeNodeList(decls);
}
printSemicolon();
}
}

View file

@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.astwriter;
@ -35,14 +35,12 @@ import org.eclipse.cdt.internal.core.pdom.dom.PDOMMacroReferenceName;
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.
* @author Emanuel Graf IFS
*
* @author Emanuel Graf IFS
*/
public class MacroExpansionHandler {
private int lastMacroExpOffset;
private final Scribe scribe;
private IASTTranslationUnit tu;
@ -58,7 +56,7 @@ public class MacroExpansionHandler {
protected boolean isStatementWithMixedLocation(IASTStatement node) {
IASTNodeLocation[] nodeLocations = getNodeLocations(node);
if(nodeLocations != null && nodeLocations.length > 1) {
if (nodeLocations != null && nodeLocations.length > 1) {
for (IASTNodeLocation loc : nodeLocations) {
if (loc instanceof IASTMacroExpansionLocation) {
return true;
@ -70,7 +68,7 @@ public class MacroExpansionHandler {
protected boolean macroExpansionAlreadyPrinted(IASTNode node) {
IASTNodeLocation[] locs = node.getNodeLocations();
if(locs.length ==1) {
if (locs.length ==1) {
if (locs[0] instanceof IASTMacroExpansionLocation) {
IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0];
if (macroNode.asFileLocation().getNodeOffset() == lastMacroExpOffset) {
@ -83,14 +81,14 @@ public class MacroExpansionHandler {
protected boolean checkisMacroExpansionNode(IASTNode node, boolean write) {
IASTTranslationUnit unit = node.getTranslationUnit();
if(tu == null || !tu.equals(unit)) {
if (tu == null || !tu.equals(unit)) {
initEmptyMacros(unit);
}
IASTNodeLocation[] locs = getNodeLocations(node);
if (locs != null && locs.length ==1) {
if (locs[0] instanceof IASTMacroExpansionLocation) {
IASTMacroExpansionLocation macroNode = (IASTMacroExpansionLocation) locs[0];
if (macroNode.asFileLocation().getNodeOffset() == lastMacroExpOffset) {
return true;
}
@ -122,28 +120,28 @@ public class MacroExpansionHandler {
}
return locs;
}
private void handleEmptyMacroExpansion(IASTNode node) {
if(node.getTranslationUnit() == null)return;
if (node.getTranslationUnit() == null)return;
String file = node.getContainingFilename();
List<IIndexName> exps = macroExpansion.get(file);
if(exps != null && !exps.isEmpty()) {
if (exps != null && !exps.isEmpty()) {
IASTFileLocation fileLocation = getFileLocation(node);
if(fileLocation != null) {
if (fileLocation != null) {
int nOff = fileLocation.getNodeOffset();
for (IIndexName iIndexName : exps) {
if (iIndexName instanceof PDOMMacroReferenceName) {
PDOMMacroReferenceName mName = (PDOMMacroReferenceName) iIndexName;
int eOff = mName.getFileLocation().getNodeOffset();
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$
}
}
}
}
}
}
private IASTFileLocation getFileLocation(IASTNode node) {
@ -161,29 +159,30 @@ public class MacroExpansionHandler {
if (unit != null) {
tu = unit;
IIndex index = tu.getIndex();
if(index != null) {
if (index != null) {
macroExpansion = new TreeMap<String, List<IIndexName>>();
IASTPreprocessorMacroDefinition[] md = tu.getMacroDefinitions();
TreeSet<String>paths = new TreeSet<String>();
for(IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) {
if(!is.isSystemInclude()) {
for (IASTPreprocessorIncludeStatement is :tu.getIncludeDirectives()) {
if (!is.isSystemInclude()) {
paths.add(is.getContainingFilename());
}
}
paths.add(tu.getContainingFilename());
for (IASTPreprocessorMacroDefinition iastPreprocessorMacroDefinition : md) {
if(iastPreprocessorMacroDefinition.getExpansion().length() == 0) {
if (iastPreprocessorMacroDefinition.getExpansion().length() == 0) {
try {
IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(), IndexFilter.ALL, null);
if(macroBinding.length > 0) {
IIndexMacro[] macroBinding = index.findMacros(iastPreprocessorMacroDefinition.getName().toCharArray(),
IndexFilter.ALL, null);
if (macroBinding.length > 0) {
IIndexName[] refs = index.findReferences(macroBinding[0]);
for (IIndexName iIndexName : refs) {
String filename2 = iIndexName.getFileLocation().getFileName();
List<IIndexName>fileList = macroExpansion.get(filename2);
if (paths.contains(filename2)) {
if(fileList == null) {
if (fileList == null) {
fileList = new ArrayList<IIndexName>();
macroExpansion.put(filename2, fileList);
}
@ -196,14 +195,13 @@ public class MacroExpansionHandler {
}
}
}
}else {
} else {
macroExpansion = Collections.emptyMap();
}
}
}
public void reset(){
public void reset() {
lastMacroExpOffset = -1;
}
}

View file

@ -1,14 +1,14 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.changegenerator;
@ -55,8 +55,6 @@ import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.text.edits.TextEditGroup;
public class ChangeGenerator extends ASTVisitor {
private final LinkedHashMap<String, Integer> sourceOffsets = new LinkedHashMap<String, Integer>();
public LinkedHashMap<IASTNode, List<ASTModification>> modificationParent = new LinkedHashMap<IASTNode, List<ASTModification>>();
private final LinkedHashMap<IFile, MultiTextEdit> changes = new LinkedHashMap<IFile, MultiTextEdit>();
@ -67,37 +65,23 @@ public class ChangeGenerator extends ASTVisitor {
{
shouldVisitExpressions = true;
shouldVisitStatements = true;
shouldVisitNames = true;
shouldVisitDeclarations = true;
shouldVisitDeclSpecifiers = true;
shouldVisitDeclarators = true;
shouldVisitArrayModifiers= true;
shouldVisitInitializers = true;
shouldVisitBaseSpecifiers = true;
shouldVisitNamespaces = true;
shouldVisitTemplateParameters = true;
shouldVisitParameterDeclarations = true;
shouldVisitTranslationUnit = true;
}
public ChangeGenerator(ASTModificationStore modificationStore, NodeCommentMap commentMap) {
this.modificationStore = modificationStore;
this.commentMap = commentMap;
}
public void generateChange(IASTNode rootNode) throws ProblemRuntimeException {
@ -110,7 +94,6 @@ public class ChangeGenerator extends ASTVisitor {
initParentModList();
rootNode.accept(pathProvider);
for (IFile currentFile : changes.keySet()) {
TextFileChange subchange= ASTRewriteAnalyzer.createCTextFileChange(currentFile);
subchange.setEdit(changes.get(currentFile));
change.add(subchange);
@ -118,20 +101,19 @@ public class ChangeGenerator extends ASTVisitor {
}
private void initParentModList() {
ASTModificationMap rootModifications = modificationStore
.getRootModifications();
ASTModificationMap rootModifications = modificationStore.getRootModifications();
if (rootModifications != null) {
for (IASTNode modifiedNode : rootModifications.getModifiedNodes()) {
List<ASTModification> modificationsForNode = rootModifications
.getModificationsForNode(modifiedNode);
List<ASTModification> modificationsForNode = rootModifications.getModificationsForNode(modifiedNode);
IASTNode modifiedNodeParent = determineParentToBeRewritten(modifiedNode, modificationsForNode);
List<ASTModification> list = modificationParent.get(modifiedNodeParent != null ? modifiedNodeParent : modifiedNode);
if(list != null){
List<ASTModification> list = modificationParent.get(modifiedNodeParent != null ?
modifiedNodeParent : modifiedNode);
if (list != null) {
list.addAll(modificationsForNode);
}else{
} else {
List<ASTModification> modifiableList = new ArrayList<ASTModification>(modificationsForNode);
modificationParent.put(modifiedNodeParent != null ? modifiedNodeParent : modifiedNode,
modifiableList);
modificationParent.put(modifiedNodeParent != null ?
modifiedNodeParent : modifiedNode, modifiableList);
}
}
}
@ -139,8 +121,8 @@ public class ChangeGenerator extends ASTVisitor {
private IASTNode determineParentToBeRewritten(IASTNode modifiedNode, List<ASTModification> modificationsForNode) {
IASTNode modifiedNodeParent = modifiedNode;
for(ASTModification currentModification : modificationsForNode){
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE){
for (ASTModification currentModification : modificationsForNode) {
if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE) {
modifiedNodeParent = modifiedNode.getParent();
break;
}
@ -152,21 +134,20 @@ public class ChangeGenerator extends ASTVisitor {
@Override
public int visit(IASTTranslationUnit translationUnit) {
if (hasChangedChild(translationUnit)) {
synthTreatment(translationUnit);
}
IASTFileLocation location = getFileLocationOfEmptyTranslationUnit(translationUnit);
sourceOffsets.put(location.getFileName(),
Integer.valueOf(location.getNodeOffset()));
sourceOffsets.put(location.getFileName(), Integer.valueOf(location.getNodeOffset()));
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
* that was built on an empty file you will get null 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.
* This is a workaround for a known but not jet solved problem in IASTNode. If you get
* the FileFocation of a translation unit that was built on an empty file you will get null
* 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
* @return a hopefully "unnull" FileLocation
* @return a hopefully non-{@code null} FileLocation
*/
public IASTFileLocation getFileLocationOfEmptyTranslationUnit(IASTNode node) {
IASTFileLocation fileLocation = node.getFileLocation();
@ -175,7 +156,7 @@ public class ChangeGenerator extends ASTVisitor {
if (lr != null) {
fileLocation = lr.getMappedFileLocation(0, 0);
} else {
// support for old location map
// Support for old location map
fileLocation = node.getTranslationUnit().flattenLocationsToFile(node.getNodeLocations());
}
}
@ -184,14 +165,11 @@ public class ChangeGenerator extends ASTVisitor {
@Override
public int leave(IASTTranslationUnit tu) {
return super.leave(tu);
}
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();
}
@ -212,15 +190,13 @@ public class ChangeGenerator extends ASTVisitor {
String indent = getIndent(synthNode);
ASTWriter synthWriter = new ASTWriter(indent);
synthWriter.setModificationStore(modificationStore);
String synthSource = synthWriter.write(synthNode, fileScope, commentMap);
createChange(synthNode, synthSource);
int newOffset = synthNode.getFileLocation().getNodeOffset()
+ synthNode.getFileLocation().getNodeLength();
int newOffset = synthNode.getFileLocation().getNodeOffset() + synthNode.getFileLocation().getNodeLength();
sourceOffsets.put(synthNode.getFileLocation().getFileName(), Integer.valueOf(newOffset));
}
private void synthTreatment(IASTTranslationUnit synthTU) {
@ -228,9 +204,8 @@ public class ChangeGenerator extends ASTVisitor {
synthWriter.setModificationStore(modificationStore);
for (ASTModification modification : modificationParent.get(synthTU)) {
IASTFileLocation targetLocation;
targetLocation = getFileLocationOfEmptyTranslationUnit(modification.getTargetNode());
IASTFileLocation targetLocation =
getFileLocationOfEmptyTranslationUnit(modification.getTargetNode());
String currentFile = targetLocation.getFileName();
IPath implPath = new Path(currentFile);
IFile relevantFile= ResourceLookup.selectFileForLocation(implPath, null);
@ -256,14 +231,16 @@ public class ChangeGenerator extends ASTVisitor {
newNodeCode));
break;
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();
IASTDeclaration lastDecl = tu.getDeclarations()[tu.getDeclarations().length -1];
targetLocation = lastDecl.getFileLocation();
}
String lineDelimiter = FileHelper.determineLineDelimiter(FileHelper.getIFilefromIASTNode(modification.getTargetNode()));
edit.addChild(new InsertEdit(targetLocation.getNodeOffset()
+ targetLocation.getNodeLength(),lineDelimiter + lineDelimiter + newNodeCode));
String lineDelimiter = FileHelper.determineLineDelimiter(
FileHelper.getIFilefromIASTNode(modification.getTargetNode()));
edit.addChild(new InsertEdit(targetLocation.getNodeOffset() + targetLocation.getNodeLength(),
lineDelimiter + lineDelimiter + newNodeCode));
break;
}
}
@ -291,7 +268,7 @@ public class ChangeGenerator extends ASTVisitor {
IFile sourceFile = FileHelper.getIFilefromIASTNode(node);
int nodeOffset = getOffsetIncludingComments(node);
int nodeLength = getNodeLengthIncludingComments(node);
return FileContentHelper.getContent(sourceFile, nodeOffset, nodeLength);
}
return null;
@ -300,17 +277,17 @@ public class ChangeGenerator extends ASTVisitor {
private int getNodeLengthIncludingComments(IASTNode node) {
int nodeOffset = node.getFileLocation().getNodeOffset();
int nodeLength = node.getFileLocation().getNodeLength();
ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node);
if(!comments.isEmpty()) {
if (!comments.isEmpty()) {
int startOffset = nodeOffset;
int endOffset = nodeOffset + nodeLength;
for(IASTComment comment : comments) {
for (IASTComment comment : comments) {
IASTFileLocation commentLocation = comment.getFileLocation();
if(commentLocation.getNodeOffset() < startOffset) {
if (commentLocation.getNodeOffset() < startOffset) {
startOffset = commentLocation.getNodeOffset();
}
if(commentLocation.getNodeOffset() + commentLocation.getNodeLength() >= endOffset) {
if (commentLocation.getNodeOffset() + commentLocation.getNodeLength() >= endOffset) {
endOffset = commentLocation.getNodeOffset() + commentLocation.getNodeLength();
}
}
@ -321,13 +298,13 @@ public class ChangeGenerator extends ASTVisitor {
private int getOffsetIncludingComments(IASTNode node) {
int nodeOffset = node.getFileLocation().getNodeOffset();
ArrayList<IASTComment> comments = commentMap.getAllCommentsForNode(node);
if(!comments.isEmpty()) {
if (!comments.isEmpty()) {
int startOffset = nodeOffset;
for(IASTComment comment : comments) {
for (IASTComment comment : comments) {
IASTFileLocation commentLocation = comment.getFileLocation();
if(commentLocation.getNodeOffset() < startOffset) {
if (commentLocation.getNodeOffset() < startOffset) {
startOffset = commentLocation.getNodeOffset();
}
}
@ -338,16 +315,13 @@ public class ChangeGenerator extends ASTVisitor {
private String getIndent(IASTNode nextNode) {
IASTFileLocation fileLocation = nextNode.getFileLocation();
int length = fileLocation.getNodeOffset()
- getOffsetForNodeFile(nextNode);
int length = fileLocation.getNodeOffset() - getOffsetForNodeFile(nextNode);
String originalSource = FileContentHelper.getContent(FileHelper
.getIFilefromIASTNode(nextNode),
String originalSource = FileContentHelper.getContent(FileHelper.getIFilefromIASTNode(nextNode),
getOffsetForNodeFile(nextNode), length);
StringBuilder indent = new StringBuilder(originalSource);
indent.reverse();
String lastline = indent
.substring(0, Math.max(indent.indexOf("\n"), 0)); //$NON-NLS-1$
String lastline = indent.substring(0, Math.max(indent.indexOf("\n"), 0)); //$NON-NLS-1$
if (lastline.trim().length() == 0) {
return lastline;
}
@ -355,11 +329,9 @@ public class ChangeGenerator extends ASTVisitor {
}
private boolean hasChangedChild(IASTNode parent) {
return modificationParent.containsKey(parent);
}
@Override
public int visit(IASTDeclarator declarator) {
if (hasChangedChild(declarator)) {
@ -378,10 +350,9 @@ public class ChangeGenerator extends ASTVisitor {
return super.visit(mod);
}
@Override
public int visit(ICPPASTNamespaceDefinition namespaceDefinition) {
if(hasChangedChild(namespaceDefinition)){
if (hasChangedChild(namespaceDefinition)) {
synthTreatment(namespaceDefinition);
return ASTVisitor.PROCESS_SKIP;
}
@ -443,7 +414,6 @@ public class ChangeGenerator extends ASTVisitor {
}
class CodeComparer {
private final StringBuilder originalCode;
private final StringBuilder synthCode;
private int lastCommonInSynthStart;
@ -456,38 +426,38 @@ public class ChangeGenerator extends ASTVisitor {
this.synthCode = new StringBuilder(synthCode);
calculatePositions();
}
private void calculatePositions(){
private void calculatePositions() {
lastCommonInSynthStart = calcLastCommonPositionInSynthCode();
lastCommonInOriginalStart = calcLastCommonPositionInOriginalCode();
firstCommonInSynthEnd = calcFirstPositionOfCommonEndInSynthCode(lastCommonInSynthStart, lastCommonInOriginalStart);
firstCommonInOriginalEnd = calcFirstPositionOfCommonEndInOriginalCode(lastCommonInOriginalStart, lastCommonInSynthStart);
lastCommonInOriginalStart = calcLastCommonPositionInOriginalCode();
firstCommonInSynthEnd =
calcFirstPositionOfCommonEndInSynthCode(lastCommonInSynthStart, lastCommonInOriginalStart);
firstCommonInOriginalEnd =
calcFirstPositionOfCommonEndInOriginalCode(lastCommonInOriginalStart, lastCommonInSynthStart);
trimTrailingNewlines();
}
private void trimTrailingNewlines() {
int prevOrigEnd = firstCommonInOriginalEnd - 1;
while( prevOrigEnd > lastCommonInOriginalStart
&& prevOrigEnd > -1
&& isUninterresting(originalCode, prevOrigEnd)){
while (prevOrigEnd > lastCommonInOriginalStart && prevOrigEnd > -1 &&
isUninterresting(originalCode, prevOrigEnd)) {
firstCommonInOriginalEnd = 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++;
}
int prevSynthEnd = firstCommonInSynthEnd - 1;
while( prevSynthEnd > lastCommonInSynthStart
&& prevSynthEnd > -1
&& isUninterresting(synthCode, prevSynthEnd)){
while (prevSynthEnd > lastCommonInSynthStart && prevSynthEnd > -1 &&
isUninterresting(synthCode, prevSynthEnd)) {
firstCommonInSynthEnd = 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++;
}
}
@ -495,11 +465,11 @@ public class ChangeGenerator extends ASTVisitor {
public int getLastCommonPositionInSynthCode() {
return lastCommonInSynthStart;
}
public int getLastCommonPositionInOriginalCode() {
return lastCommonInOriginalStart;
}
return lastCommonInOriginalStart;
}
public int getFirstPositionOfCommonEndInOriginalCode() {
return firstCommonInOriginalEnd;
}
@ -507,58 +477,50 @@ public class ChangeGenerator extends ASTVisitor {
public int getFirstPositionOfCommonEndInSynthCode() {
return firstCommonInSynthEnd;
}
public int calcLastCommonPositionInSynthCode() {
return findLastCommonPosition(synthCode, originalCode);
}
public int calcLastCommonPositionInOriginalCode() {
return findLastCommonPosition(originalCode, synthCode);
}
return findLastCommonPosition(originalCode, synthCode);
}
private int calcFirstPositionOfCommonEndInOriginalCode(int originalLimit, int synthLimit) {
StringBuilder reverseOriginalCode = new StringBuilder(originalCode)
.reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode)
.reverse();
StringBuilder reverseOriginalCode = new StringBuilder(originalCode).reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode).reverse();
int lastCommonPosition = findLastCommonPosition(reverseOriginalCode, reverseSynthCode,
reverseOriginalCode.length() - originalLimit - 1, reverseSynthCode.length() - synthLimit - 1);
reverseOriginalCode.length() - originalLimit - 1,
reverseSynthCode.length() - synthLimit - 1);
if (lastCommonPosition < 0
|| lastCommonPosition >= originalCode.length()) {
if (lastCommonPosition < 0 || lastCommonPosition >= originalCode.length()) {
return -1;
}
return originalCode.length() - lastCommonPosition -1;
return originalCode.length() - lastCommonPosition - 1;
}
private int calcFirstPositionOfCommonEndInSynthCode(int synthLimit, int originalLimit) {
StringBuilder reverseOriginalCode = new StringBuilder(originalCode)
.reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode)
.reverse();
StringBuilder reverseOriginalCode = new StringBuilder(originalCode).reverse();
StringBuilder reverseSynthCode = new StringBuilder(synthCode).reverse();
int lastCommonPosition = findLastCommonPosition(reverseSynthCode, reverseOriginalCode,
reverseSynthCode.length() - synthLimit -1, reverseOriginalCode.length() - originalLimit -1);
reverseSynthCode.length() - synthLimit - 1,
reverseOriginalCode.length() - originalLimit - 1);
if (lastCommonPosition < 0
|| lastCommonPosition >= synthCode.length()) {
if (lastCommonPosition < 0 || lastCommonPosition >= synthCode.length()) {
return -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());
}
private int findLastCommonPosition(StringBuilder first, StringBuilder second, int firstLimit, int secondLimit){
private int findLastCommonPosition(StringBuilder first, StringBuilder second, int firstLimit,
int secondLimit) {
int firstIndex = -1;
int secondIndex = -1;
int lastCommonIndex = -1;
@ -567,11 +529,8 @@ public class ChangeGenerator extends ASTVisitor {
lastCommonIndex = firstIndex;
firstIndex = nextInterrestingPosition(first, firstIndex);
secondIndex = nextInterrestingPosition(second, secondIndex);
} while (firstIndex > -1
&& firstIndex <= firstLimit
&& secondIndex > -1
&& secondIndex <= secondLimit
&& first.charAt(firstIndex) == second.charAt(secondIndex));
} while (firstIndex > -1 && firstIndex <= firstLimit && secondIndex > -1 &&
secondIndex <= secondLimit && first.charAt(firstIndex) == second.charAt(secondIndex));
return lastCommonIndex;
}
@ -600,63 +559,52 @@ public class ChangeGenerator extends ASTVisitor {
protected void createChange(MultiTextEdit edit, IASTNode changedNode) {
int changeOffset = getOffsetIncludingComments(changedNode);
TextEditGroup editGroup = new TextEditGroup(Messages.ChangeGenerator_group);
for (ASTModification currentModification : modificationParent
.get(changedNode)) {
for (ASTModification currentModification : modificationParent.get(changedNode)) {
if (currentModification.getAssociatedEditGroup() != null) {
editGroup = currentModification.getAssociatedEditGroup();
edit.addChildren(editGroup.getTextEdits());
break;
}
}
createChange(edit, changeOffset);
}
private void createChange(MultiTextEdit edit, int changeOffset) {
int i = (firstCommonInSynthEnd >= 0 ? firstCommonInOriginalEnd
: originalCode.length())
- lastCommonInOriginalStart;
int i = (firstCommonInSynthEnd >= 0 ?
firstCommonInOriginalEnd : originalCode.length()) - lastCommonInOriginalStart;
if (i <= 0) {
String insertCode = synthCode.substring(
lastCommonInSynthStart, firstCommonInSynthEnd);
InsertEdit iEdit = new InsertEdit(changeOffset
+ lastCommonInOriginalStart, insertCode);
String insertCode = synthCode.substring(lastCommonInSynthStart,
firstCommonInSynthEnd);
InsertEdit iEdit = new InsertEdit(changeOffset + lastCommonInOriginalStart,
insertCode);
edit.addChild(iEdit);
} else if ((firstCommonInSynthEnd >= 0 ? firstCommonInSynthEnd
: synthCode.length())
- lastCommonInSynthStart <= 0) {
} else if ((firstCommonInSynthEnd >= 0 ?
firstCommonInSynthEnd : synthCode.length()) - lastCommonInSynthStart <= 0) {
int correction = 0;
if (lastCommonInSynthStart > firstCommonInSynthEnd) {
correction = lastCommonInSynthStart
- firstCommonInSynthEnd;
correction = lastCommonInSynthStart - firstCommonInSynthEnd;
}
DeleteEdit dEdit = new DeleteEdit(changeOffset
+ lastCommonInOriginalStart,
firstCommonInOriginalEnd
- lastCommonInOriginalStart + correction);
DeleteEdit dEdit = new DeleteEdit(changeOffset + lastCommonInOriginalStart,
firstCommonInOriginalEnd - lastCommonInOriginalStart + correction);
edit.addChild(dEdit);
} else {
String replacementCode = getReplacementCode(
lastCommonInSynthStart, firstCommonInSynthEnd);
} else {
String replacementCode = getReplacementCode(lastCommonInSynthStart,
firstCommonInSynthEnd);
ReplaceEdit rEdit = new ReplaceEdit(
changeOffset
+ Math.max(lastCommonInOriginalStart, 0),
(firstCommonInOriginalEnd >= 0 ? firstCommonInOriginalEnd
: originalCode.length())
- Math.max(lastCommonInOriginalStart, 0),
changeOffset + Math.max(lastCommonInOriginalStart, 0),
(firstCommonInOriginalEnd >= 0 ?
firstCommonInOriginalEnd :
originalCode.length()) - Math.max(lastCommonInOriginalStart, 0),
replacementCode);
edit.addChild(rEdit);
}
}
private String getReplacementCode(int lastCommonPositionInSynth,
int firstOfCommonEndInSynth) {
private String getReplacementCode(int lastCommonPositionInSynth, int firstOfCommonEndInSynth) {
int replacementStart = Math.max(lastCommonPositionInSynth, 0);
int replacementEnd = (firstOfCommonEndInSynth >= 0 ? firstOfCommonEndInSynth
: synthCode.length());
int replacementEnd = (firstOfCommonEndInSynth >= 0 ?
firstOfCommonEndInSynth : synthCode.length());
if (replacementStart < replacementEnd) {
return synthCode.substring(replacementStart, replacementEnd);
}

View file

@ -1,14 +1,14 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2011 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* Markus Schorn (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.rewrite.changegenerator;
@ -37,15 +37,12 @@ import org.eclipse.cdt.internal.core.dom.rewrite.astwriter.ASTWriterVisitor;
import org.eclipse.cdt.internal.core.dom.rewrite.commenthandler.NodeCommentMap;
/**
*
* Visits the nodes in consideration of {@link ASTModification}s.
*
*
* @since 5.0
* @author Emanuel Graf IFS
*
*/
public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
private static final String DEFAULT_INDENTATION = ""; //$NON-NLS-1$
private final ASTModificationStore modificationStore;
private final String fileScope;
@ -74,15 +71,14 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
shouldVisitProblems = delegateVisitor.shouldVisitProblems;
shouldVisitTypeIds = delegateVisitor.shouldVisitTypeIds;
shouldVisitArrayModifiers= delegateVisitor.shouldVisitArrayModifiers;
}
public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, NodeCommentMap nodeMap) {
this(modStore, DEFAULT_INDENTATION, null, nodeMap);
}
public ChangeGeneratorWriterVisitor(ASTModificationStore modStore,
String givenIndentation, String fileScope, NodeCommentMap commentMap) {
public ChangeGeneratorWriterVisitor(ASTModificationStore modStore, String givenIndentation,
String fileScope, NodeCommentMap commentMap) {
super(givenIndentation, commentMap);
this.modificationStore = modStore;
this.fileScope = fileScope;
@ -98,13 +94,12 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
}
@Override
protected IASTDeclarator getParameterDeclarator(
IASTParameterDeclaration parameterDeclaration) {
protected IASTDeclarator getParameterDeclarator(IASTParameterDeclaration parameterDeclaration) {
IASTDeclarator newDecl = parameterDeclaration.getDeclarator();
if(stack.getModifiedNodes().contains(newDecl)){
for(ASTModification currentModification : stack.getModificationsForNode(newDecl)){
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE && currentModification.getTargetNode() == parameterDeclaration){
if (stack.getModifiedNodes().contains(newDecl)) {
for (ASTModification currentModification : stack.getModificationsForNode(newDecl)) {
if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE &&
currentModification.getTargetNode() == parameterDeclaration) {
newDecl = (IASTDeclarator) currentModification.getNewNode();
}
}
@ -115,9 +110,10 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
@Override
protected IASTName getParameterName(IASTDeclarator declarator) {
IASTName newName = declarator.getName();
if(stack.getModifiedNodes().contains(newName)){
for(ASTModification currentModification : stack.getModificationsForNode(newName)){
if(currentModification.getKind() == ASTModification.ModificationKind.REPLACE && currentModification.getTargetNode() == newName){
if (stack.getModifiedNodes().contains(newName)) {
for (ASTModification currentModification : stack.getModificationsForNode(newName)) {
if (currentModification.getKind() == ASTModification.ModificationKind.REPLACE &&
currentModification.getTargetNode() == newName) {
newName = (IASTName) currentModification.getNewNode();
}
}
@ -278,7 +274,7 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
}
return PROCESS_SKIP;
}
@Override
public int visit(IASTExpression expression) {
if (doBeforeEveryNode(expression) == PROCESS_CONTINUE) {
@ -329,14 +325,12 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
@Override
public int visit(IASTTranslationUnit tu) {
ASTModificationHelper helper = new ASTModificationHelper(
stack);
IASTDeclaration[] declarations = helper.createModifiedChildArray(tu, tu.getDeclarations(), IASTDeclaration.class, commentMap);
ASTModificationHelper helper = new ASTModificationHelper(stack);
IASTDeclaration[] declarations = helper.createModifiedChildArray(tu, tu.getDeclarations(),
IASTDeclaration.class, commentMap);
for (IASTDeclaration currentDeclaration : declarations) {
currentDeclaration.accept(this);
}
return PROCESS_SKIP;
}
@ -356,40 +350,39 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
return PROCESS_SKIP;
}
}
//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 (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) {
if(currentMod.getNewNode() == node){
if(currentMod.getKind() != ModificationKind.REPLACE) {
if (currentMod.getNewNode() == node) {
if (currentMod.getKind() != ModificationKind.REPLACE) {
stack.pushScope(currentModifiedNode);
return PROCESS_CONTINUE;
}
}
}
}
//Check all replace modifications for the current node. Visit the replacing node if found.
for (IASTNode currentModifiedNode : stack.getModifiedNodes()) {
// Check all replace modifications for the current node. Visit the replacing node if found.
for (IASTNode currentModifiedNode : stack.getModifiedNodes()) {
for (ASTModification currentMod : stack.getModificationsForNode(currentModifiedNode)) {
if(currentMod.getTargetNode() == node && currentMod.getKind() == ModificationKind.REPLACE){
if(currentMod.getNewNode() != null){
if (currentMod.getTargetNode() == node && currentMod.getKind() == ModificationKind.REPLACE) {
if (currentMod.getNewNode() != null) {
stack.pushScope(node);
currentMod.getNewNode().accept(this);
stack.popScope(node);
return PROCESS_SKIP;
}
else{
} else {
return PROCESS_SKIP;
}
}
}
}
return PROCESS_CONTINUE;
}
private String getCorrespondingFile(IASTNode node) {
if (node.getFileLocation() != null) {
return node.getFileLocation().getFileName();
}
@ -398,11 +391,8 @@ public class ChangeGeneratorWriterVisitor extends ASTWriterVisitor {
return getCorrespondingFile(node.getParent());
}
for (IASTNode modifiedNode : modificationStore.getRootModifications()
.getModifiedNodes()) {
for (ASTModification modification : modificationStore
.getRootModifications().getModificationsForNode(
modifiedNode)) {
for (IASTNode modifiedNode : modificationStore.getRootModifications().getModifiedNodes()) {
for (ASTModification modification : modificationStore.getRootModifications().getModificationsForNode(modifiedNode)) {
if (modification.getNewNode() == node) {
return getCorrespondingFile(modification.getTargetNode());
}

View file

@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring;
@ -28,18 +28,14 @@ import org.eclipse.osgi.util.NLS;
/**
* 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 {
private String name;
private final IPath path;
private final String source;
private final String encoding;
public CreateFileChange(String name, IPath path, String source, String encoding) {
super();
@ -48,21 +44,20 @@ public class CreateFileChange extends Change {
this.source = source;
this.encoding = encoding;
}
public CreateFileChange(IPath path, String source, String encoding) {
this(null, path, source, encoding);
}
@Override
public Object getModifiedElement() {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
return file;
return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
}
@Override
public String getName() {
if(name == null) {
return NLS.bind(Messages.CreateFileChange_CreateFile, path.toOSString());
if (name == null) {
return NLS.bind(Messages.CreateFileChange_CreateFile, path.toOSString());
}
return name;
}
@ -72,20 +67,19 @@ public class CreateFileChange extends Change {
}
@Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException,
OperationCanceledException {
public RefactoringStatus isValid(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
RefactoringStatus result= new RefactoringStatus();
IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
URI location= file.getLocationURI();
if (location == null) {
result.addFatalError(NLS.bind(Messages.CreateFileChange_UnknownLoc, file.getFullPath().toString()));
result.addFatalError(NLS.bind(Messages.CreateFileChange_UnknownLoc, file.getFullPath().toString()));
return result;
}
if (file.exists()) {
result.addFatalError( NLS.bind(Messages.CreateFileChange_FileExists,
file.getFullPath().toString()));
result.addFatalError(NLS.bind(Messages.CreateFileChange_FileExists, file.getFullPath().toString()));
return result;
}
return result;
@ -96,13 +90,11 @@ public class CreateFileChange extends Change {
IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(path);
InputStream is = new ByteArrayInputStream(source.getBytes());
file.create(is, false, new SubProgressMonitor(pm, 1));
if(encoding != null) {
if (encoding != null) {
file.setCharset(encoding, new SubProgressMonitor(pm,1));
}
return new DeleteFileChange(file.getFullPath());
}
public String getSource() {
return source;
@ -115,6 +107,5 @@ public class CreateFileChange extends Change {
@Override
public String toString() {
return getName();
}
}
}

View file

@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik
* Copyright (c) 2008, 2009 Institute for Software, HSR Hochschule fuer Technik
* Rapperswil, University of applied sciences and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Institute for Software - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.ui.refactoring;
@ -22,26 +22,25 @@ import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
/**
* A ModificationCollector can be passed through a refactoring and manages the rewriters
* A ModificationCollector can be passed through a refactoring and manages the rewriters
* and additional changes a refactoring can create.
*
*
* @author Mirko Stocker
*/
public class ModificationCollector {
// Each translation unit can have only one ASTRewrite
private final Map<IASTTranslationUnit, ASTRewrite> rewriters =
new HashMap<IASTTranslationUnit, ASTRewrite>();
new HashMap<IASTTranslationUnit, ASTRewrite>();
private Collection<CreateFileChange> changes;
public ASTRewrite rewriterForTranslationUnit(IASTTranslationUnit ast) {
if (!rewriters.containsKey(ast)) {
rewriters.put(ast, ASTRewrite.create(ast));
}
return rewriters.get(ast);
}
// Creating new files doesn't concern the rewriter, the refactorings can add them here as needed.
public void addFileChange(CreateFileChange change) {
if (changes == null) {
@ -49,19 +48,19 @@ public class ModificationCollector {
}
changes.add(change);
}
public CCompositeChange createFinalChange() {
// Synthetic changes aren't displayed and therefore don't need a name
CCompositeChange result = new CCompositeChange(""); //$NON-NLS-1$
result.markAsSynthetic();
if (changes != null)
result.addAll(changes.toArray(new Change[changes.size()]));
for (ASTRewrite each : rewriters.values()) {
result.add(each.rewriteAST());
}
return result;
}
}