### Eclipse Workspace Patch 1.0 #P org.eclipse.jdt.core Index: formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java =================================================================== RCS file: /cvsroot/eclipse/org.eclipse.jdt.core/formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java,v retrieving revision 1.77 diff -u -r1.77 DefaultCodeFormatterConstants.java --- formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java 21 Nov 2006 15:32:31 -0000 1.77 +++ formatter/org/eclipse/jdt/core/formatter/DefaultCodeFormatterConstants.java 2 Feb 2007 01:28:54 -0000 @@ -585,11 +585,52 @@ * @see #TRUE * @see #FALSE * @since 3.1 + * @deprecated Use multiple settings for each kind of comments. See {@link #FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT}, + * {@link #FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT} and {@link #FORMATTER_COMMENT_FORMAT_LINE_COMMENT}. */ public final static String FORMATTER_COMMENT_FORMAT = "org.eclipse.jdt.core.formatter.comment.format_comments"; //$NON-NLS-1$ /** *
+ * FORMATTER / Option to control whether single line comments are formatted + * - option id: "org.eclipse.jdt.core.formatter.comment.format_line_comments" + * - possible values: { TRUE, FALSE } + * - default: TRUE + *+ * @see #TRUE + * @see #FALSE + * @since 3.3 + */ + public final static String FORMATTER_COMMENT_FORMAT_LINE_COMMENT = "org.eclipse.jdt.core.formatter.comment.format_line_comments"; //$NON-NLS-1$ + + /** + *
+ * FORMATTER / Option to control whether multiple comments are formatted + * - option id: "org.eclipse.jdt.core.formatter.comment.format_block_comments" + * - possible values: { TRUE, FALSE } + * - default: TRUE + *+ * @see #TRUE + * @see #FALSE + * @since 3.3 + */ + public final static String FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT = "org.eclipse.jdt.core.formatter.comment.format_block_comments"; //$NON-NLS-1$ + + /** + *
+ * FORMATTER / Option to control whether javadoc comments are formatted + * - option id: "org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" + * - possible values: { TRUE, FALSE } + * - default: TRUE + *+ * @see #TRUE + * @see #FALSE + * @since 3.3 + */ + public final static String FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT = "org.eclipse.jdt.core.formatter.comment.format_javadoc_comments"; //$NON-NLS-1$ + + /** + *
* FORMATTER / Option to control whether the header comment of a Java source file is formatted * - option id: "org.eclipse.jdt.core.formatter.comment.format_header" * - possible values: { TRUE, FALSE } Index: formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor2.java =================================================================== RCS file: formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor2.java diff -N formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor2.java --- formatter/org/eclipse/jdt/internal/formatter/CodeFormatterVisitor2.java 11 Jan 2007 16:04:34 -0000 1.21 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,3403 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2002, 2006 IBM Corporation 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: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.formatter; - -import java.util.List; -import java.util.Map; - -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.compiler.InvalidInputException; -import org.eclipse.jdt.core.dom.*; -import org.eclipse.jdt.core.dom.PrefixExpression.Operator; -import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; -import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; -import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; -import org.eclipse.jdt.internal.compiler.parser.Scanner; -import org.eclipse.jdt.internal.compiler.parser.TerminalTokens; -import org.eclipse.jdt.internal.formatter.align.Alignment; -import org.eclipse.jdt.internal.formatter.align.Alignment2; -import org.eclipse.jdt.internal.formatter.align.AlignmentException; -import org.eclipse.text.edits.TextEdit; - -/** - * This class is responsible for formatting a valid java source code. - * @since 3.2 - */ -public class CodeFormatterVisitor2 extends ASTVisitor { - public final static boolean DEBUG = false; - - private static final int[] CLOSING_GENERICS_EXPECTEDTOKENS = new int[] { - TerminalTokens.TokenNameRIGHT_SHIFT, - TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT, - TerminalTokens.TokenNameGREATER - }; - private static final int[] NUMBER_LITERALS_EXPECTEDTOKENS = new int[] { - TerminalTokens.TokenNameIntegerLiteral, - TerminalTokens.TokenNameLongLiteral, - TerminalTokens.TokenNameFloatingPointLiteral, - TerminalTokens.TokenNameDoubleLiteral - }; - /* - * Set of expected tokens type for a single type reference. - * This array needs to be SORTED. - */ - private static final int[] PRIMITIVE_TYPE_EXPECTEDTOKENS = new int[] { - TerminalTokens.TokenNameboolean, - TerminalTokens.TokenNamebyte, - TerminalTokens.TokenNamechar, - TerminalTokens.TokenNamedouble, - TerminalTokens.TokenNamefloat, - TerminalTokens.TokenNameint, - TerminalTokens.TokenNamelong, - TerminalTokens.TokenNameshort, - TerminalTokens.TokenNamevoid - }; - private Scanner localScanner; - - public DefaultCodeFormatterOptions preferences; - - public Scribe2 scribe; - - public CodeFormatterVisitor2(DefaultCodeFormatterOptions preferences, Map settings, int offset, int length, CompilationUnit unit) { - long sourceLevel = settings == null - ? ClassFileConstants.JDK1_3 - : CompilerOptions.versionToJdkLevel(settings.get(JavaCore.COMPILER_SOURCE)); - this.localScanner = new Scanner(true, false, false/*nls*/, sourceLevel/*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); - - this.preferences = preferences; - this.scribe = new Scribe2(this, sourceLevel, offset, length, unit); - } - - private boolean commentStartsBlock(int start, int end) { - this.localScanner.resetTo(start, end); - try { - if (this.localScanner.getNextToken() == TerminalTokens.TokenNameLBRACE) { - switch(this.localScanner.getNextToken()) { - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - case TerminalTokens.TokenNameCOMMENT_LINE : - return true; - } - } - } catch(InvalidInputException e) { - // ignore - } - return false; - } - - - public static int extractInfixExpressionOperator(InfixExpression node) { - final InfixExpression.Operator infixOperator = node.getOperator(); - if (infixOperator == InfixExpression.Operator.AND) { - return TerminalTokens.TokenNameAND; - } else if (infixOperator == InfixExpression.Operator.CONDITIONAL_AND) { - return TerminalTokens.TokenNameAND_AND; - } else if (infixOperator == InfixExpression.Operator.CONDITIONAL_OR) { - return TerminalTokens.TokenNameOR_OR; - } else if (infixOperator == InfixExpression.Operator.DIVIDE) { - return TerminalTokens.TokenNameDIVIDE; - } else if (infixOperator == InfixExpression.Operator.EQUALS) { - return TerminalTokens.TokenNameEQUAL_EQUAL; - } else if (infixOperator == InfixExpression.Operator.GREATER) { - return TerminalTokens.TokenNameGREATER; - } else if (infixOperator == InfixExpression.Operator.GREATER_EQUALS) { - return TerminalTokens.TokenNameGREATER_EQUAL; - } else if (infixOperator == InfixExpression.Operator.LEFT_SHIFT) { - return TerminalTokens.TokenNameLEFT_SHIFT; - } else if (infixOperator == InfixExpression.Operator.LESS) { - return TerminalTokens.TokenNameLESS; - } else if (infixOperator == InfixExpression.Operator.LESS_EQUALS) { - return TerminalTokens.TokenNameLESS_EQUAL; - } else if (infixOperator == InfixExpression.Operator.MINUS) { - return TerminalTokens.TokenNameMINUS; - } else if (infixOperator == InfixExpression.Operator.NOT_EQUALS) { - return TerminalTokens.TokenNameNOT_EQUAL; - } else if (infixOperator == InfixExpression.Operator.OR) { - return TerminalTokens.TokenNameOR; - } else if (infixOperator == InfixExpression.Operator.PLUS) { - return TerminalTokens.TokenNamePLUS; - } else if (infixOperator == InfixExpression.Operator.REMAINDER) { - return TerminalTokens.TokenNameREMAINDER; - } else if (infixOperator == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) { - return TerminalTokens.TokenNameRIGHT_SHIFT; - } else if (infixOperator == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED) { - return TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT; - } else if (infixOperator == InfixExpression.Operator.TIMES) { - return TerminalTokens.TokenNameMULTIPLY; - } else { - return TerminalTokens.TokenNameXOR; - } - } - - private final TextEdit failedToFormat() { - if (DEBUG) { - System.out.println("COULD NOT FORMAT \n" + this.scribe.scanner); //$NON-NLS-1$ - System.out.println(this.scribe); - } - return null; - } - - /** - * @see org.eclipse.jdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String) - */ - public TextEdit format(String string, AbstractTypeDeclaration typeDeclaration) { - // reset the scribe - this.scribe.reset(); - - long startTime = System.currentTimeMillis(); - - final char[] compilationUnitSource = string.toCharArray(); - - this.localScanner.setSource(compilationUnitSource); - this.scribe.initializeScanner(compilationUnitSource); - - try { - this.scribe.lastNumberOfNewLines = 1; - formatTypeMembers(typeDeclaration.bodyDeclarations(), false); - } catch(AbortFormatting e){ - return failedToFormat(); - } - if (DEBUG){ - System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$ - } - return this.scribe.getRootEdit(); - } - - /** - * @see org.eclipse.jdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String) - */ - public TextEdit format(String string, Block block) { - // reset the scribe - this.scribe.reset(); - - long startTime = System.currentTimeMillis(); - - final char[] compilationUnitSource = string.toCharArray(); - - this.localScanner.setSource(compilationUnitSource); - this.scribe.initializeScanner(compilationUnitSource); - - if ((block.getFlags() & ASTNode.MALFORMED) != 0) { - return failedToFormat(); - } - - try { - formatStatements(block.statements(), false); - if (hasComments()) { - this.scribe.printNewLine(); - } - this.scribe.printComment(); - } catch(AbortFormatting e){ - return failedToFormat(); - } - if (DEBUG){ - System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$ - } - return this.scribe.getRootEdit(); - } - - /** - * @see org.eclipse.jdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String) - */ - public TextEdit format(String string, CompilationUnit compilationUnit) { - // reset the scribe - this.scribe.reset(); - - if ((compilationUnit.getFlags() & ASTNode.MALFORMED) != 0) { - return failedToFormat(); - } - - long startTime = System.currentTimeMillis(); - - final char[] compilationUnitSource = string.toCharArray(); - - this.localScanner.setSource(compilationUnitSource); - this.scribe.initializeScanner(compilationUnitSource); - - try { - compilationUnit.accept(this); - } catch(AbortFormatting e){ - return failedToFormat(); - } - if (DEBUG){ - System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$ - } - return this.scribe.getRootEdit(); - } - - /** - * @see org.eclipse.jdt.core.formatter.CodeFormatter#format(int, String, int, int, int, String) - */ - public TextEdit format(String string, Expression expression) { - // reset the scribe - this.scribe.reset(); - - long startTime = System.currentTimeMillis(); - - final char[] compilationUnitSource = string.toCharArray(); - - this.localScanner.setSource(compilationUnitSource); - this.scribe.initializeScanner(compilationUnitSource); - - if ((expression.getFlags() & ASTNode.MALFORMED) != 0) { - return failedToFormat(); - } - try { - expression.accept(this); - this.scribe.printComment(); - } catch(AbortFormatting e){ - return failedToFormat(); - } - if (DEBUG){ - System.out.println("Formatting time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$ - } - return this.scribe.getRootEdit(); - } - - private void format( - AbstractTypeDeclaration memberTypeDeclaration, - boolean isChunkStart, - boolean isFirstClassBodyDeclaration) { - - if (isFirstClassBodyDeclaration) { - int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration; - if (newLinesBeforeFirstClassBodyDeclaration > 0) { - this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration); - } - } else { - int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0; - if (newLineBeforeChunk > 0) { - this.scribe.printEmptyLines(newLineBeforeChunk); - } - final int newLinesBeforeMember = this.preferences.blank_lines_before_member_type; - if (newLinesBeforeMember > 0) { - this.scribe.printEmptyLines(newLinesBeforeMember); - } - } - memberTypeDeclaration.accept(this); - } - - private void format(FieldDeclaration fieldDeclaration, boolean isChunkStart, boolean isFirstClassBodyDeclaration) { - if (isFirstClassBodyDeclaration) { - int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration; - if (newLinesBeforeFirstClassBodyDeclaration > 0) { - this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration); - } - } else { - int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0; - if (newLineBeforeChunk > 0) { - this.scribe.printEmptyLines(newLineBeforeChunk); - } - final int newLinesBeforeField = this.preferences.blank_lines_before_field; - if (newLinesBeforeField > 0) { - this.scribe.printEmptyLines(newLinesBeforeField); - } - } - Alignment2 memberAlignment = this.scribe.getMemberAlignment(); - - this.scribe.printComment(); - final List modifiers = fieldDeclaration.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - fieldDeclaration.getType().accept(this); - - List fragments = fieldDeclaration.fragments(); - final int fragmentsLength = fragments.size(); - if (fragmentsLength > 1) { - // multiple field declaration - Alignment2 multiFieldDeclarationsAlignment =this.scribe.createAlignment( - "multiple_field",//$NON-NLS-1$ - this.preferences.alignment_for_multiple_fields, - fragmentsLength - 1, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(multiFieldDeclarationsAlignment); - - boolean ok = false; - do { - try { - for (int i = 0; i < fragmentsLength; i++) { - VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(i); - /* - * Field name - */ - if (i == 0) { - this.scribe.alignFragment(memberAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false); - } - - /* - * Check for extra dimensions - */ - final int extraDimensions = fragment.getExtraDimensions(); - if (extraDimensions != 0) { - for (int index = 0; index < extraDimensions; index++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - - /* - * Field initialization - */ - final Expression initialization = fragment.getInitializer(); - if (initialization != null) { - if (i == 0) { - this.scribe.alignFragment(memberAlignment, 1); - } - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - Alignment2 assignmentAlignment = this.scribe.createAlignment("fieldDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok2 = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - initialization.accept(this); - ok2 = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok2); - this.scribe.exitAlignment(assignmentAlignment, true); - } - - if (i != fragmentsLength - 1) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_multiple_field_declarations); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(multiFieldDeclarationsAlignment, i); - - if (this.preferences.insert_space_after_comma_in_multiple_field_declarations) { - this.scribe.space(); - } - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.alignFragment(memberAlignment, 2); - this.scribe.printTrailingComment(); - } - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(multiFieldDeclarationsAlignment, true); - } else { - // single field declaration - this.scribe.alignFragment(memberAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(0); - final int extraDimensions = fragment.getExtraDimensions(); - if (extraDimensions != 0) { - for (int i = 0; i < extraDimensions; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - final Expression initialization = fragment.getInitializer(); - if (initialization != null) { - this.scribe.alignFragment(memberAlignment, 1); - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - Alignment2 assignmentAlignment = this.scribe.createAlignment("fieldDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - initialization.accept(this); - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(assignmentAlignment, true); - } - - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - - if (memberAlignment != null) { - this.scribe.alignFragment(memberAlignment, 2); - this.scribe.printTrailingComment(); - } else { - this.scribe.space(); - this.scribe.printTrailingComment(); - } - } - } - private void format( - BodyDeclaration bodyDeclaration, - boolean isChunkStart, - boolean isFirstClassBodyDeclaration) { - - if (isFirstClassBodyDeclaration) { - int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration; - if (newLinesBeforeFirstClassBodyDeclaration > 0) { - this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration); - } - } else { - final int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0; - if (newLineBeforeChunk > 0) { - this.scribe.printEmptyLines(newLineBeforeChunk); - } - } - final int newLinesBeforeMethod = this.preferences.blank_lines_before_method; - if (newLinesBeforeMethod > 0 && !isFirstClassBodyDeclaration) { - this.scribe.printEmptyLines(newLinesBeforeMethod); - } else if (this.scribe.line != 0 || this.scribe.column != 1) { - this.scribe.printNewLine(); - } - bodyDeclaration.accept(this); - } - - private void formatAction(final int line, final Statement action, boolean insertLineForSingleStatement) { - if (action != null) { - switch(action.getNodeType()) { - case ASTNode.BLOCK : - formatLeftCurlyBrace(line, this.preferences.brace_position_for_block); - action.accept(this); - break; - case ASTNode.EMPTY_STATEMENT : - this.scribe.indent(); - action.accept(this); - this.scribe.unIndent(); - break; - default : - this.scribe.printNewLine(); - this.scribe.indent(); - action.accept(this); - this.scribe.unIndent(); - if (insertLineForSingleStatement) { - this.scribe.printNewLine(); - } - } - } - } - - private void formatBlock(Block block, String block_brace_position, boolean insertSpaceBeforeOpeningBrace) { - formatOpeningBrace(block_brace_position, insertSpaceBeforeOpeningBrace); - final List statements = block.statements(); - final int statementsLength = statements.size(); - if (statementsLength != 0) { - this.scribe.printNewLine(); - if (this.preferences.indent_statements_compare_to_block) { - this.scribe.indent(); - } - formatStatements(statements, true); - this.scribe.printComment(); - - if (this.preferences.indent_statements_compare_to_block) { - this.scribe.unIndent(); - } - } else { - if (this.preferences.insert_new_line_in_empty_block) { - this.scribe.printNewLine(); - } - if (this.preferences.indent_statements_compare_to_block) { - this.scribe.indent(); - } - this.scribe.printComment(); - - if (this.preferences.indent_statements_compare_to_block) { - this.scribe.unIndent(); - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(block_brace_position)) { - this.scribe.unIndent(); - } - } - - private void formatEmptyTypeDeclaration(boolean isFirst) { - boolean hasSemiColon = isNextToken(TerminalTokens.TokenNameSEMICOLON); - while(isNextToken(TerminalTokens.TokenNameSEMICOLON)) { - this.scribe.printComment(); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - } - if (hasSemiColon && isFirst) { - this.scribe.printNewLine(); - } - } - - - private void formatLeftCurlyBrace(final int line, final String bracePosition) { - /* - * deal with (quite unexpected) comments right before lcurly - */ - this.scribe.printComment(); - if (DefaultCodeFormatterConstants.NEXT_LINE_ON_WRAP.equals(bracePosition) - && (this.scribe.line > line || this.scribe.column >= this.preferences.page_width)) - { - this.scribe.printNewLine(); - } - } - - private void formatLocalDeclaration(VariableDeclarationExpression declarationExpression, boolean insertSpaceBeforeComma, boolean insertSpaceAfterComma) { - final List modifiers = declarationExpression.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - declarationExpression.getType().accept(this); - - formatVariableDeclarationFragments(declarationExpression.fragments(), insertSpaceBeforeComma, insertSpaceAfterComma); - } - - private void formatVariableDeclarationFragments(final List fragments, boolean insertSpaceBeforeComma, boolean insertSpaceAfterComma) { - final int fragmentsLength = fragments.size(); - if (fragmentsLength > 1) { - // multiple field declaration - Alignment2 multiFieldDeclarationsAlignment =this.scribe.createAlignment( - "multiple_field",//$NON-NLS-1$ - this.preferences.alignment_for_multiple_fields, - fragmentsLength - 1, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(multiFieldDeclarationsAlignment); - - boolean ok = false; - do { - try { - for (int i = 0; i < fragmentsLength; i++) { - VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(i); - /* - * Field name - */ - if (i == 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false); - } - - /* - * Check for extra dimensions - */ - final int extraDimensions = fragment.getExtraDimensions(); - if (extraDimensions != 0) { - for (int index = 0; index < extraDimensions; index++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - - /* - * Field initialization - */ - final Expression initialization = fragment.getInitializer(); - if (initialization != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - Alignment2 assignmentAlignment = this.scribe.createAlignment("fieldDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok2 = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - initialization.accept(this); - ok2 = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok2); - this.scribe.exitAlignment(assignmentAlignment, true); - } - - if (i != fragmentsLength - 1) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, insertSpaceBeforeComma); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(multiFieldDeclarationsAlignment, i); - - if (insertSpaceAfterComma) { - this.scribe.space(); - } - } - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(multiFieldDeclarationsAlignment, true); - } else { - // single field declaration - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(0); - final int extraDimensions = fragment.getExtraDimensions(); - if (extraDimensions != 0) { - for (int i = 0; i < extraDimensions; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - final Expression initialization = fragment.getInitializer(); - if (initialization != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - Alignment2 assignmentAlignment = this.scribe.createAlignment("localDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - initialization.accept(this); - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(assignmentAlignment, true); - } - } - } - - private void formatOpeningBrace(String bracePosition, boolean insertSpaceBeforeBrace) { - if (DefaultCodeFormatterConstants.NEXT_LINE.equals(bracePosition)) { - this.scribe.printNewLine(); - } else if (DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(bracePosition)) { - this.scribe.printNewLine(); - this.scribe.indent(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, insertSpaceBeforeBrace); - - this.scribe.printTrailingComment(); - } - - private void formatStatements(final List statements, boolean insertNewLineAfterLastStatement) { - final int statementsLength = statements.size(); - if (statementsLength > 1) { - Statement previousStatement = (Statement) statements.get(0); - previousStatement.accept(this); - final int previousStatementNodeType = previousStatement.getNodeType(); - for (int i = 1; i < statementsLength - 1; i++) { - final Statement statement = (Statement) statements.get(i); - final int statementNodeType = statement.getNodeType(); - if ((previousStatementNodeType == ASTNode.EMPTY_STATEMENT - && statementNodeType != ASTNode.EMPTY_STATEMENT) - || (previousStatementNodeType != ASTNode.EMPTY_STATEMENT - && statementNodeType != ASTNode.EMPTY_STATEMENT)) { - this.scribe.printNewLine(); - } - statement.accept(this); - previousStatement = statement; - } - final Statement statement = ((Statement) statements.get(statementsLength - 1)); - final int statementNodeType = statement.getNodeType(); - if ((previousStatementNodeType == ASTNode.EMPTY_STATEMENT - && statementNodeType != ASTNode.EMPTY_STATEMENT) - || (previousStatementNodeType != ASTNode.EMPTY_STATEMENT - && statementNodeType != ASTNode.EMPTY_STATEMENT)) { - this.scribe.printNewLine(); - } - statement.accept(this); - } else { - ((Statement) statements.get(0)).accept(this); - } - if (insertNewLineAfterLastStatement) { - this.scribe.printNewLine(); - } - } - - private void formatTypeMembers(List bodyDeclarations, boolean insertLineAfterLastMember) { - Alignment2 memberAlignment = this.scribe.createMemberAlignment("typeMembers", this.preferences.align_type_members_on_columns ? Alignment.M_MULTICOLUMN : Alignment.M_NO_ALIGNMENT, 3, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterMemberAlignment(memberAlignment); - boolean isChunkStart = false; - boolean ok = false; - int startIndex = 0; - do { - try { - for (int i = startIndex, max = bodyDeclarations.size(); i < max; i++) { - BodyDeclaration bodyDeclaration = (BodyDeclaration) bodyDeclarations.get(i); - switch(bodyDeclaration.getNodeType()) { - case ASTNode.FIELD_DECLARATION : - isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_FIELD, i, this.scribe.scanner.currentPosition); - FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration; - format(fieldDeclaration, isChunkStart, i == 0); - break; - case ASTNode.INITIALIZER : - isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_FIELD, i, this.scribe.scanner.currentPosition); - int newLineBeforeChunk = isChunkStart ? this.preferences.blank_lines_before_new_chunk : 0; - if (newLineBeforeChunk > 0 && i != 0) { - this.scribe.printEmptyLines(newLineBeforeChunk); - } else if (i == 0) { - int newLinesBeforeFirstClassBodyDeclaration = this.preferences.blank_lines_before_first_class_body_declaration; - if (newLinesBeforeFirstClassBodyDeclaration > 0) { - this.scribe.printEmptyLines(newLinesBeforeFirstClassBodyDeclaration); - } - } - bodyDeclaration.accept(this); - break; - case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION : - case ASTNode.METHOD_DECLARATION : - isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_METHOD, i, this.scribe.scanner.currentPosition); - format(bodyDeclaration, isChunkStart, i == 0); - break; - case ASTNode.TYPE_DECLARATION : - case ASTNode.ENUM_DECLARATION : - case ASTNode.ANNOTATION_TYPE_DECLARATION : - isChunkStart = memberAlignment.checkChunkStart(Alignment.CHUNK_TYPE, i, this.scribe.scanner.currentPosition); - format((AbstractTypeDeclaration)bodyDeclaration, isChunkStart, i == 0); - } - if (isNextToken(TerminalTokens.TokenNameSEMICOLON)) { - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - } - if (i < max - 1 || insertLineAfterLastMember) { - this.scribe.printNewLine(); - } - // realign to the proper value - if (this.scribe.memberAlignment != null) { - // select the last alignment - this.scribe.indentationLevel = this.scribe.memberAlignment.originalIndentationLevel; - } - } - ok = true; - } catch(AlignmentException e){ - startIndex = memberAlignment.chunkStartIndex; - this.scribe.redoMemberAlignment(e); - } - } while (!ok); - this.scribe.printComment(); - this.scribe.exitMemberAlignment(memberAlignment); - } - - private void formatTypeOpeningBrace(String bracePosition, boolean insertSpaceBeforeBrace, boolean insertNewLine, ASTNode node) { - formatOpeningBrace(bracePosition, insertSpaceBeforeBrace); - if (!insertNewLine) { - switch(node.getNodeType()) { - case ASTNode.ENUM_DECLARATION : - insertNewLine = this.preferences.insert_new_line_in_empty_enum_declaration; - break; - case ASTNode.ENUM_CONSTANT_DECLARATION : - insertNewLine = this.preferences.insert_new_line_in_empty_enum_constant; - break; - case ASTNode.ANONYMOUS_CLASS_DECLARATION : - insertNewLine = this.preferences.insert_new_line_in_empty_anonymous_type_declaration; - break; - case ASTNode.ANNOTATION_TYPE_DECLARATION : - insertNewLine = this.preferences.insert_new_line_in_empty_annotation_declaration; - break; - default: - insertNewLine = this.preferences.insert_new_line_in_empty_type_declaration; - } - } - if (insertNewLine) { - this.scribe.printNewLine(); - } - } - - - private boolean hasComments() { - - this.localScanner.resetTo(this.scribe.scanner.startPosition, this.scribe.scannerEndPosition - 1); - try { - switch(this.localScanner.getNextToken()) { - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - case TerminalTokens.TokenNameCOMMENT_LINE : - return true; - } - } catch(InvalidInputException e) { - // ignore - } - return false; - } - - private boolean isClosingGenericToken() { - this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1); - try { - int token = this.localScanner.getNextToken(); - loop: while(true) { - switch(token) { - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - case TerminalTokens.TokenNameCOMMENT_LINE : - token = this.localScanner.getNextToken(); - continue loop; - default: - break loop; - } - } - switch(token) { - case TerminalTokens.TokenNameGREATER : - case TerminalTokens.TokenNameRIGHT_SHIFT : - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT : - return true; - } - } catch(InvalidInputException e) { - // ignore - } - return false; - } - - private boolean isGuardClause(Block block, List statements) { - if (commentStartsBlock(block.getStartPosition(), block.getStartPosition() + block.getLength() - 1)) return false; - final int statementsLength = statements.size(); - if (statementsLength != 1) return false; - switch(((Statement) statements.get(0)).getNodeType()) { - case ASTNode.RETURN_STATEMENT : - case ASTNode.THROW_STATEMENT : - return true; - } - return false; - } - - private boolean isNextToken(int tokenName) { - this.localScanner.resetTo(this.scribe.scanner.currentPosition, this.scribe.scannerEndPosition - 1); - try { - int token = this.localScanner.getNextToken(); - loop: while(true) { - switch(token) { - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - case TerminalTokens.TokenNameCOMMENT_LINE : - token = this.localScanner.getNextToken(); - continue loop; - default: - break loop; - } - } - return token == tokenName; - } catch(InvalidInputException e) { - // ignore - } - return false; - } - - public boolean visit(AnnotationTypeDeclaration node) { - this.scribe.printComment(); - final int line = this.scribe.line; - - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameAT, this.preferences.insert_space_before_at_in_annotation_type_declaration); - this.scribe.printNextToken(TerminalTokens.TokenNameinterface, this.preferences.insert_space_after_at_in_annotation_type_declaration); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - - String class_declaration_brace; - boolean space_before_opening_brace; - class_declaration_brace = this.preferences.brace_position_for_annotation_type_declaration; - space_before_opening_brace = this.preferences.insert_space_before_opening_brace_in_annotation_type_declaration; - - formatLeftCurlyBrace(line, class_declaration_brace); - final List bodyDeclarations = node.bodyDeclarations(); - formatTypeOpeningBrace(class_declaration_brace, space_before_opening_brace, bodyDeclarations.size() != 0, node); - - boolean indent_body_declarations_compare_to_header = this.preferences.indent_body_declarations_compare_to_annotation_declaration_header; - if (indent_body_declarations_compare_to_header) { - this.scribe.indent(); - } - - formatTypeMembers(bodyDeclarations, true); - - if (indent_body_declarations_compare_to_header) { - this.scribe.unIndent(); - } - - if (this.preferences.insert_new_line_in_empty_annotation_declaration) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (class_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - if (hasComments()) { - this.scribe.printNewLine(); - } - return false; - } - - public boolean visit(AnnotationTypeMemberDeclaration node) { - /* - * Print comments to get proper line number - */ - this.scribe.printComment(); - List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - /* - * Print the method return type - */ - node.getType().accept(this); - /* - * Print the method name - */ - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_annotation_type_member_declaration); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_annotation_type_member_declaration); - - Expression defaultValue = node.getDefault(); - if (defaultValue != null) { - this.scribe.printNextToken(TerminalTokens.TokenNamedefault, true); - this.scribe.space(); - defaultValue.accept(this); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(AnonymousClassDeclaration node) { - /* - * Type body - */ - String anonymous_type_declaration_brace_position = this.preferences.brace_position_for_anonymous_type_declaration; - - final List bodyDeclarations = node.bodyDeclarations(); - formatTypeOpeningBrace(anonymous_type_declaration_brace_position, this.preferences.insert_space_before_opening_brace_in_anonymous_type_declaration, bodyDeclarations.size() != 0, node); - - this.scribe.indent(); - - formatTypeMembers(bodyDeclarations, true); - - this.scribe.unIndent(); - if (this.preferences.insert_new_line_in_empty_anonymous_type_declaration) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - if (anonymous_type_declaration_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - return false; - } - - public boolean visit(ArrayAccess node) { - node.getArray().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, this.preferences.insert_space_before_opening_bracket_in_array_reference); - if (this.preferences.insert_space_after_opening_bracket_in_array_reference) { - this.scribe.space(); - } - node.getIndex().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_before_closing_bracket_in_array_reference); - return false; - } - - public boolean visit(ArrayCreation node) { - this.scribe.printNextToken(TerminalTokens.TokenNamenew); - this.scribe.space(); - final ArrayType type = node.getType(); - final List dimensions = node.dimensions(); - final int dimensionsLength = dimensions.size(); - - final int arrayTypeDimensions = type.getDimensions(); - type.getElementType().accept(this); - if (dimensionsLength != 0) { - for (int i = 0; i < dimensionsLength; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, this.preferences.insert_space_before_opening_bracket_in_array_allocation_expression); - Expression dimension = (Expression) dimensions.get(i); - if (dimension != null) { - if (this.preferences.insert_space_after_opening_bracket_in_array_allocation_expression) { - this.scribe.space(); - } - dimension.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_before_closing_bracket_in_array_allocation_expression); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_brackets_in_array_allocation_expression); - } - } - for (int i = 0, max = arrayTypeDimensions - dimensionsLength; i < max; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, this.preferences.insert_space_before_opening_bracket_in_array_allocation_expression); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_brackets_in_array_allocation_expression); - } - } else { - for (int i = 0; i < arrayTypeDimensions; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET, this.preferences.insert_space_before_opening_bracket_in_array_allocation_expression); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET, this.preferences.insert_space_between_empty_brackets_in_array_allocation_expression); - } - } - - final ArrayInitializer initializer = node.getInitializer(); - if (initializer != null) { - initializer.accept(this); - } - - return false; - } - - public boolean visit(ArrayInitializer node) { - final List expressions = node.expressions(); - final int expressionsLength = expressions.size(); - if (expressionsLength != 0) { - final String array_initializer_brace_position = this.preferences.brace_position_for_array_initializer; - formatOpeningBrace(array_initializer_brace_position, this.preferences.insert_space_before_opening_brace_in_array_initializer); - - final boolean insert_new_line_after_opening_brace = this.preferences.insert_new_line_after_opening_brace_in_array_initializer; - if (expressionsLength > 1) { - if (insert_new_line_after_opening_brace) { - this.scribe.printNewLine(); - } - Alignment2 arrayInitializerAlignment = this.scribe.createAlignment( - "array_initializer",//$NON-NLS-1$ - this.preferences.alignment_for_expressions_in_array_initializer, - Alignment.R_OUTERMOST, - expressionsLength, - this.scribe.scanner.currentPosition, - this.preferences.continuation_indentation_for_array_initializer, - true); - - if (insert_new_line_after_opening_brace) { - arrayInitializerAlignment.fragmentIndentations[0] = arrayInitializerAlignment.breakIndentationLevel; - } - - this.scribe.enterAlignment(arrayInitializerAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(arrayInitializerAlignment, 0); - if (this.preferences.insert_space_after_opening_brace_in_array_initializer) { - this.scribe.space(); - } - ((Expression) expressions.get(0)).accept(this); - for (int i = 1; i < expressionsLength; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(arrayInitializerAlignment, i); - if (this.preferences.insert_space_after_comma_in_array_initializer) { - this.scribe.space(); - } - ((Expression) expressions.get(i)).accept(this); - if (i == expressionsLength - 1) { - if (isNextToken(TerminalTokens.TokenNameCOMMA)) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer); - this.scribe.printTrailingComment(); - } - } - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(arrayInitializerAlignment, true); - } else { - if (insert_new_line_after_opening_brace) { - this.scribe.printNewLine(); - this.scribe.indent(); - } - // we don't need to use an alignment - if (this.preferences.insert_space_after_opening_brace_in_array_initializer) { - this.scribe.space(); - } else { - this.scribe.needSpace = false; - } - ((Expression) expressions.get(0)).accept(this); - if (isNextToken(TerminalTokens.TokenNameCOMMA)) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_array_initializer); - this.scribe.printTrailingComment(); - } - if (insert_new_line_after_opening_brace) { - this.scribe.unIndent(); - } - } - if (this.preferences.insert_new_line_before_closing_brace_in_array_initializer) { - this.scribe.printNewLine(); - } else if (this.preferences.insert_space_before_closing_brace_in_array_initializer) { - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, false); - if (array_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - } else { - boolean keepEmptyArrayInitializerOnTheSameLine = this.preferences.keep_empty_array_initializer_on_one_line; - String array_initializer_brace_position = this.preferences.brace_position_for_array_initializer; - if (keepEmptyArrayInitializerOnTheSameLine) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, this.preferences.insert_space_before_opening_brace_in_array_initializer); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, this.preferences.insert_space_between_empty_braces_in_array_initializer); - } else { - formatOpeningBrace(array_initializer_brace_position, this.preferences.insert_space_before_opening_brace_in_array_initializer); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, false); - if (array_initializer_brace_position.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - } - } - return false; - } - - public boolean visit(ArrayType node) { - node.getComponentType().accept(this); - if (this.preferences.insert_space_before_opening_bracket_in_array_type_reference) { - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - if (this.preferences.insert_space_between_brackets_in_array_type_reference) { - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - return false; - } - - public boolean visit(AssertStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNameassert); - this.scribe.space(); - node.getExpression().accept(this); - - Expression message = node.getMessage(); - if (message != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_assert); - if (this.preferences.insert_space_after_colon_in_assert) { - this.scribe.space(); - } - message.accept(this); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(Assignment node) { - node.getLeftHandSide().accept(this); - Assignment.Operator operator = node.getOperator(); - if (operator == Assignment.Operator.ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.MINUS_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameMINUS_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.PLUS_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNamePLUS_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.TIMES_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameMULTIPLY_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.DIVIDE_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameDIVIDE_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.REMAINDER_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameREMAINDER_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.LEFT_SHIFT_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameLEFT_SHIFT_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameRIGHT_SHIFT_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.BIT_AND_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameAND_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else if (operator == Assignment.Operator.BIT_OR_ASSIGN) { - this.scribe.printNextToken(TerminalTokens.TokenNameOR_EQUAL, this.preferences.insert_space_before_assignment_operator); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameXOR_EQUAL, this.preferences.insert_space_before_assignment_operator); - } - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - - Alignment2 assignmentAlignment = this.scribe.createAlignment("assignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - node.getRightHandSide().accept(this); - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(assignmentAlignment, true); - return false; - } - - public boolean visit(Block node) { - formatBlock(node, this.preferences.brace_position_for_block, this.preferences.insert_space_before_opening_brace_in_block); - return false; - } - - public boolean visit(BooleanLiteral node) { - if (node.booleanValue()) { - this.scribe.printNextToken(TerminalTokens.TokenNametrue); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNamefalse); - } - return false; - } - - public boolean visit(BreakStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamebreak); - if (node.getLabel() != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(CastExpression node) { - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN); - if (this.preferences.insert_space_after_opening_paren_in_cast) { - this.scribe.space(); - } - node.getType().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_cast); - if (this.preferences.insert_space_after_closing_paren_in_cast) { - this.scribe.space(); - } - node.getExpression().accept(this); - return false; - } - - public boolean visit(CharacterLiteral node) { - this.scribe.printNextToken(TerminalTokens.TokenNameCharacterLiteral); - return false; - } - - public boolean visit(ClassInstanceCreation node) { - Expression expression = node.getExpression(); - if (expression != null) { - expression.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - this.scribe.printNextToken(TerminalTokens.TokenNamenew); - final List typeArguments = node.typeArguments(); - final int length = typeArguments.size(); - if (length != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_arguments); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - for (int i = 0; i < length - 1; i++) { - ((Type) typeArguments.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_arguments); - if (this.preferences.insert_space_after_comma_in_type_arguments) { - this.scribe.space(); - } - } - ((Type) typeArguments.get(length - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_arguments); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - } else { - this.scribe.space(); - } - - node.getType().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation); - - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - - if (argumentsLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_invocation) { - this.scribe.space(); - } - Alignment2 argumentsAlignment =this.scribe.createAlignment( - "allocation",//$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_allocation_expression, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_allocation_expression); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_allocation_expression) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation); - } - final AnonymousClassDeclaration classDeclaration = node.getAnonymousClassDeclaration(); - if (classDeclaration != null) { - classDeclaration.accept(this); - } - return false; - } - - public boolean visit(CompilationUnit node) { - // fake new line to handle empty lines before package declaration or import declarations - this.scribe.lastNumberOfNewLines = 1; - /* - * Package declaration - */ - final PackageDeclaration packageDeclaration = node.getPackage(); - final boolean hasPackage = packageDeclaration != null; - if (hasPackage) { - if (hasComments()) { - this.scribe.printComment(); - } - int blankLinesBeforePackage = this.preferences.blank_lines_before_package; - if (blankLinesBeforePackage > 0) { - this.scribe.printEmptyLines(blankLinesBeforePackage); - } - - final List annotations = packageDeclaration.annotations(); - if (annotations.size() != 0) { - this.scribe.printModifiers(annotations, this); - this.scribe.space(); - } - // dump the package keyword - this.scribe.printNextToken(TerminalTokens.TokenNamepackage); - this.scribe.space(); - packageDeclaration.getName().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - int blankLinesAfterPackage = this.preferences.blank_lines_after_package; - if (blankLinesAfterPackage > 0) { - this.scribe.printEmptyLines(blankLinesAfterPackage); - } else { - this.scribe.printNewLine(); - } - } else { - this.scribe.printComment(); - } - - /* - * Import statements - */ - final List imports = node.imports(); - final int importsLength = imports.size(); - if (importsLength != 0) { - if (hasPackage) { - int blankLinesBeforeImports = this.preferences.blank_lines_before_imports; - if (blankLinesBeforeImports > 0) { - this.scribe.printEmptyLines(blankLinesBeforeImports); - } - } - for (int i = 0; i < importsLength; i++) { - ((ImportDeclaration) imports.get(i)).accept(this); - } - - int blankLinesAfterImports = this.preferences.blank_lines_after_imports; - if (blankLinesAfterImports > 0) { - this.scribe.printEmptyLines(blankLinesAfterImports); - } - } - - formatEmptyTypeDeclaration(true); - - int blankLineBetweenTypeDeclarations = this.preferences.blank_lines_between_type_declarations; - /* - * Type declarations - */ - final List types = node.types(); - final int typesLength = types.size(); - if (typesLength != 0) { - for (int i = 0; i < typesLength - 1; i++) { - ((AbstractTypeDeclaration) types.get(i)).accept(this); - formatEmptyTypeDeclaration(false); - if (blankLineBetweenTypeDeclarations != 0) { - this.scribe.printEmptyLines(blankLineBetweenTypeDeclarations); - } else { - this.scribe.printNewLine(); - } - } - ((AbstractTypeDeclaration) types.get(typesLength - 1)).accept(this); - } - this.scribe.printEndOfCompilationUnit(); - return false; - } - - public boolean visit(ConditionalExpression node) { - node.getExpression().accept(this); - - Alignment2 conditionalExpressionAlignment =this.scribe.createAlignment( - "conditionalExpression", //$NON-NLS-1$ - this.preferences.alignment_for_conditional_expression, - 2, - this.scribe.scanner.currentPosition); - - this.scribe.enterAlignment(conditionalExpressionAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(conditionalExpressionAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameQUESTION, this.preferences.insert_space_before_question_in_conditional); - - if (this.preferences.insert_space_after_question_in_conditional) { - this.scribe.space(); - } - node.getThenExpression().accept(this); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(conditionalExpressionAlignment, 1); - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_conditional); - - if (this.preferences.insert_space_after_colon_in_conditional) { - this.scribe.space(); - } - node.getElseExpression().accept(this); - - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(conditionalExpressionAlignment, true); - return false; - } - - public boolean visit(ConstructorInvocation node) { - final List typeArguments = node.typeArguments(); - final int typeArgumentsLength = typeArguments.size(); - if (typeArgumentsLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_arguments); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - for (int i = 0; i < typeArgumentsLength - 1; i++) { - ((Type) typeArguments.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_arguments); - if (this.preferences.insert_space_after_comma_in_type_arguments) { - this.scribe.space(); - } - } - ((Type) typeArguments.get(typeArgumentsLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_arguments); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - } - - this.scribe.printNextToken(TerminalTokens.TokenNamethis); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation); - - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - if (argumentsLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_invocation) { - this.scribe.space(); - } - Alignment2 argumentsAlignment =this.scribe.createAlignment( - "explicit_constructor_call",//$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_explicit_constructor_call, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_explicit_constructor_call_arguments); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_explicit_constructor_call_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(ContinueStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamecontinue); - if (node.getLabel() != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(DoStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamedo); - final int line = this.scribe.line; - - final Statement action = node.getBody(); - if (action != null) { - switch(action.getNodeType()) { - case ASTNode.BLOCK : - formatLeftCurlyBrace(line, this.preferences.brace_position_for_block); - action.accept(this); - break; - case ASTNode.EMPTY_STATEMENT : - action.accept(this); - break; - default : - this.scribe.printNewLine(); - this.scribe.indent(); - action.accept(this); - this.scribe.unIndent(); - this.scribe.printNewLine(); - } - } - - if (this.preferences.insert_new_line_before_while_in_do_statement) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNamewhile, this.preferences.insert_space_after_closing_brace_in_block); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_while); - - if (this.preferences.insert_space_after_opening_paren_in_while) { - this.scribe.space(); - } - - node.getExpression().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_while); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(EmptyStatement node) { - if (this.preferences.put_empty_statement_on_new_line) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(EnhancedForStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamefor); - final int line = this.scribe.line; - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_for); - - if (this.preferences.insert_space_after_opening_paren_in_for) { - this.scribe.space(); - } - node.getParameter().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_for); - if (this.preferences.insert_space_after_colon_in_for) { - this.scribe.space(); - } - node.getExpression().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_for); - - formatAction(line, node.getBody(), false); - return false; - } - - public boolean visit(EnumConstantDeclaration node) { - this.scribe.printComment(); - final int line = this.scribe.line; - - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - if (isNextToken(TerminalTokens.TokenNameLPAREN)) { - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_enum_constant); - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - if (argumentsLength != 0) { - Alignment2 argumentsAlignment = this.scribe.createAlignment( - "enumConstantArguments",//$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_enum_constant, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - if (this.preferences.insert_space_after_opening_paren_in_enum_constant) { - this.scribe.space(); - } - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_enum_constant_arguments); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_enum_constant_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_enum_constant); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_enum_constant); - } - } - - final AnonymousClassDeclaration anonymousClassDeclaration = node.getAnonymousClassDeclaration(); - if (anonymousClassDeclaration != null) { - final List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations(); - String enum_constant_brace = this.preferences.brace_position_for_enum_constant; - - formatLeftCurlyBrace(line, enum_constant_brace); - formatTypeOpeningBrace(enum_constant_brace, this.preferences.insert_space_before_opening_brace_in_enum_constant, bodyDeclarations.size() != 0, node); - - if (this.preferences.indent_body_declarations_compare_to_enum_constant_header) { - this.scribe.indent(); - } - - formatTypeMembers(bodyDeclarations, true); - - if (this.preferences.indent_body_declarations_compare_to_enum_constant_header) { - this.scribe.unIndent(); - } - - if (this.preferences.insert_new_line_in_empty_enum_constant) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - if (enum_constant_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - if (hasComments()) { - this.scribe.printNewLine(); - } - } - return false; - } - - - public boolean visit(EnumDeclaration node) { - /* - * Print comments to get proper line number - */ - this.scribe.printComment(); - final int line = this.scribe.line; - - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - this.scribe.printNextToken(TerminalTokens.TokenNameenum, true); - - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - - /* - * Super Interfaces - */ - final List superInterfaces = node.superInterfaceTypes(); - final int superInterfacesLength = superInterfaces.size(); - if (superInterfacesLength != 0) { - Alignment2 interfaceAlignment =this.scribe.createAlignment( - "superInterfaces",//$NON-NLS-1$ - this.preferences.alignment_for_superinterfaces_in_enum_declaration, - superInterfacesLength+1, // implements token is first fragment - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(interfaceAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(interfaceAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameimplements, true); - for (int i = 0; i < superInterfacesLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_superinterfaces); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(interfaceAlignment, i+1); - if (this.preferences.insert_space_after_comma_in_superinterfaces) { - this.scribe.space(); - } - ((Type) superInterfaces.get(i)).accept(this); - } else { - this.scribe.alignFragment(interfaceAlignment, i+1); - this.scribe.space(); - ((Type) superInterfaces.get(i)).accept(this); - } - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(interfaceAlignment, true); - } - - final String bracePosition = this.preferences.brace_position_for_enum_declaration; - - final List enumConstants = node.enumConstants(); - final int enumConstantsLength = enumConstants.size(); - - formatLeftCurlyBrace(line, bracePosition); - formatTypeOpeningBrace(bracePosition, this.preferences.insert_space_before_opening_brace_in_enum_declaration, (enumConstantsLength + node.bodyDeclarations().size()) != 0, node); - - final boolean indent_body_declarations_compare_to_header = this.preferences.indent_body_declarations_compare_to_enum_declaration_header; - if (indent_body_declarations_compare_to_header) { - this.scribe.indent(); - } - - if (enumConstantsLength != 0) { - if (enumConstantsLength > 1) { - Alignment2 enumConstantsAlignment = this.scribe.createAlignment( - "enumConstants",//$NON-NLS-1$ - this.preferences.alignment_for_enum_constants, - enumConstantsLength, - this.scribe.scanner.currentPosition, - 0, // we don't want to indent enum constants when splitting to a new line - false); - this.scribe.enterAlignment(enumConstantsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < enumConstantsLength; i++) { - this.scribe.alignFragment(enumConstantsAlignment, i); - final EnumConstantDeclaration enumConstantDeclaration = ((EnumConstantDeclaration) enumConstants.get(i)); - enumConstantDeclaration.accept(this); - if (isNextToken(TerminalTokens.TokenNameCOMMA)) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_enum_declarations); - if (this.preferences.insert_space_after_comma_in_enum_declarations) { - this.scribe.space(); - } - this.scribe.printTrailingComment(); - if (enumConstantDeclaration.getAnonymousClassDeclaration() != null) { - this.scribe.printNewLine(); - } - } - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(enumConstantsAlignment, true); - } else { - final EnumConstantDeclaration enumConstantDeclaration = ((EnumConstantDeclaration) enumConstants.get(0)); - enumConstantDeclaration.accept(this); - if (isNextToken(TerminalTokens.TokenNameCOMMA)) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_enum_declarations); - if (this.preferences.insert_space_after_comma_in_enum_declarations) { - this.scribe.space(); - } - this.scribe.printTrailingComment(); - if (enumConstantDeclaration.getAnonymousClassDeclaration() != null) { - this.scribe.printNewLine(); - } - } - } - } - if (isNextToken(TerminalTokens.TokenNameSEMICOLON)) { - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - } - if (enumConstantsLength != 0) { - this.scribe.printNewLine(); - } - - formatTypeMembers(node.bodyDeclarations(), true); - - if (indent_body_declarations_compare_to_header) { - this.scribe.unIndent(); - } - - if (this.preferences.insert_new_line_in_empty_enum_declaration) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (bracePosition.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - if (hasComments()) { - this.scribe.printNewLine(); - } - return false; - } - - public boolean visit(ExpressionStatement node) { - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(FieldAccess node) { - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - return false; - } - - public boolean visit(ForStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamefor); - final int line = this.scribe.line; - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_for); - - if (this.preferences.insert_space_after_opening_paren_in_for) { - this.scribe.space(); - } - final List initializers = node.initializers(); - final int initializersLength = initializers.size(); - if (initializersLength != 0) { - for (int i = 0; i < initializersLength; i++) { - Expression initializer = (Expression) initializers.get(i); - switch(initializer.getNodeType()) { - case ASTNode.VARIABLE_DECLARATION_EXPRESSION : - formatLocalDeclaration((VariableDeclarationExpression) initializer, this.preferences.insert_space_before_comma_in_for_inits, this.preferences.insert_space_after_comma_in_for_inits); - break; - default: - initializer.accept(this); - if (i >= 0 && (i < initializersLength - 1)) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_for_inits); - if (this.preferences.insert_space_after_comma_in_for_inits) { - this.scribe.space(); - } - this.scribe.printTrailingComment(); - } - } - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon_in_for); - final Expression condition = node.getExpression(); - if (condition != null) { - if (this.preferences.insert_space_after_semicolon_in_for) { - this.scribe.space(); - } - condition.accept(this); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon_in_for); - final List updaters = node.updaters(); - final int updatersLength = updaters.size(); - if (updatersLength != 0) { - if (this.preferences.insert_space_after_semicolon_in_for) { - this.scribe.space(); - } - for (int i = 0; i < updatersLength; i++) { - ((Expression) updaters.get(i)).accept(this); - if (i != updatersLength - 1) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_for_increments); - if (this.preferences.insert_space_after_comma_in_for_increments) { - this.scribe.space(); - } - this.scribe.printTrailingComment(); - } - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_for); - - formatAction(line, node.getBody(), false); - return false; - } - - public boolean visit(IfStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNameif); - final int line = this.scribe.line; - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_if); - if (this.preferences.insert_space_after_opening_paren_in_if) { - this.scribe.space(); - } - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_if); - - final Statement thenStatement = node.getThenStatement(); - final Statement elseStatement = node.getElseStatement(); - - boolean thenStatementIsBlock = false; - if (thenStatement != null) { - if (thenStatement instanceof Block) { - final Block block = (Block) thenStatement; - thenStatementIsBlock = true; - final List statements = block.statements(); - if (isGuardClause(block, statements) && elseStatement == null && this.preferences.keep_guardian_clause_on_one_line) { - /* - * Need a specific formatting for guard clauses - * guard clauses are block with a single return or throw - * statement - */ - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACE, this.preferences.insert_space_before_opening_brace_in_block); - this.scribe.space(); - ((Statement) statements.get(0)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE, true); - this.scribe.printTrailingComment(); - } else { - formatLeftCurlyBrace(line, this.preferences.brace_position_for_block); - thenStatement.accept(this); - if (elseStatement != null && (this.preferences.insert_new_line_before_else_in_if_statement)) { - this.scribe.printNewLine(); - } - } - } else if (elseStatement == null && this.preferences.keep_simple_if_on_one_line) { - Alignment2 compactIfAlignment = this.scribe.createAlignment( - "compactIf", //$NON-NLS-1$ - this.preferences.alignment_for_compact_if, - Alignment.R_OUTERMOST, - 1, - this.scribe.scanner.currentPosition, - 1, - false); - this.scribe.enterAlignment(compactIfAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(compactIfAlignment, 0); - this.scribe.space(); - thenStatement.accept(this); - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(compactIfAlignment, true); - } else if (this.preferences.keep_then_statement_on_same_line) { - this.scribe.space(); - thenStatement.accept(this); - if (elseStatement != null) { - this.scribe.printNewLine(); - } - } else { - this.scribe.printTrailingComment(); - this.scribe.printNewLine(); - this.scribe.indent(); - thenStatement.accept(this); - if (elseStatement != null) { - this.scribe.printNewLine(); - } - this.scribe.unIndent(); - } - } - - if (elseStatement != null) { - if (thenStatementIsBlock) { - this.scribe.printNextToken(TerminalTokens.TokenNameelse, this.preferences.insert_space_after_closing_brace_in_block); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameelse, true); - } - if (elseStatement instanceof Block) { - elseStatement.accept(this); - } else if (elseStatement instanceof IfStatement) { - if (!this.preferences.compact_else_if) { - this.scribe.printNewLine(); - this.scribe.indent(); - } - this.scribe.space(); - elseStatement.accept(this); - if (!this.preferences.compact_else_if) { - this.scribe.unIndent(); - } - } else if (this.preferences.keep_else_statement_on_same_line) { - this.scribe.space(); - elseStatement.accept(this); - } else { - this.scribe.printNewLine(); - this.scribe.indent(); - elseStatement.accept(this); - this.scribe.unIndent(); - } - } - return false; - } - - public boolean visit(ImportDeclaration node) { - this.scribe.printNextToken(TerminalTokens.TokenNameimport); - this.scribe.space(); - if (node.isStatic()) { - this.scribe.printNextToken(TerminalTokens.TokenNamestatic); - this.scribe.space(); - } - node.getName().accept(this); - if (node.isOnDemand()) { - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - this.scribe.printNextToken(TerminalTokens.TokenNameMULTIPLY); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - this.scribe.printNewLine(); - return false; - } - - public boolean visit(InfixExpression node) { - // active line wrapping - final InfixExpressionWrappingBuilder builder = new InfixExpressionWrappingBuilder(); - node.accept(builder); - final int fragmentsSize = builder.getFragmentsCounter(); - this.scribe.printComment(); - Alignment2 binaryExpressionAlignment = this.scribe.createAlignment("binaryExpressionAlignment", this.preferences.alignment_for_binary_expression, Alignment.R_OUTERMOST, fragmentsSize, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(binaryExpressionAlignment); - boolean ok = false; - List fragments = builder.fragments; - int[] operators = builder.getOperators(); -/* do { - try { - final boolean alignAfterOperator = false; - if (alignAfterOperator) { - for (int i = 0; i < fragmentsSize - 1; i++) { - this.scribe.alignFragment(binaryExpressionAlignment, i); - ((Expression) fragments.get(i)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - // a new line has been inserted by printTrailingComment() - this.scribe.indentationLevel = binaryExpressionAlignment.breakIndentationLevel; - } - this.scribe.printNextToken(operators[i], this.preferences.insert_space_before_binary_operator); - if (operators[i] == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS)) { - // the next character is a minus (unary operator) - this.scribe.space(); - } - if (this.preferences.insert_space_after_binary_operator) { - this.scribe.space(); - } - } - this.scribe.alignFragment(binaryExpressionAlignment, fragmentsSize - 1); - ((Expression) fragments.get(fragmentsSize - 1)).accept(this); - this.scribe.printTrailingComment(); - } else { - this.scribe.alignFragment(binaryExpressionAlignment, 0); - ((Expression) fragments.get(0)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - for (int i = 1; i < fragmentsSize - 1; i++) { - this.scribe.alignFragment(binaryExpressionAlignment, i); - this.scribe.printNextToken(operators[i - 1], this.preferences.insert_space_before_binary_operator); - if (operators[i] == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS)) { - // the next character is a minus (unary operator) - this.scribe.space(); - } - if (this.preferences.insert_space_after_binary_operator) { - this.scribe.space(); - } - ((Expression) fragments.get(i)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - } - this.scribe.alignFragment(binaryExpressionAlignment, fragmentsSize - 1); - this.scribe.printNextToken(operators[fragmentsSize - 2], this.preferences.insert_space_before_binary_operator); - if (operators[fragmentsSize - 2] == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS)) { - // the next character is a minus (unary operator) - this.scribe.space(); - } - if (this.preferences.insert_space_after_binary_operator) { - this.scribe.space(); - } - ((Expression) fragments.get(fragmentsSize - 1)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - } - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(binaryExpressionAlignment, true);*/ - do { - try { - for (int i = 0; i < fragmentsSize - 1; i++) { - ((Expression) fragments.get(i)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - this.scribe.alignFragment(binaryExpressionAlignment, i); - this.scribe.printNextToken(operators[i], this.preferences.insert_space_before_binary_operator); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - if ( this.preferences.insert_space_after_binary_operator - || (operators[i] == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS))) { - // the next character is a minus (unary operator) or the preference is set to true - this.scribe.space(); - } - } - ((Expression) fragments.get(fragmentsSize - 1)).accept(this); - this.scribe.printTrailingComment(); - if (this.scribe.lastNumberOfNewLines == 1) { - if (binaryExpressionAlignment.couldBreak() && binaryExpressionAlignment.wasSplit) { - binaryExpressionAlignment.performFragmentEffect(); - } - } - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(binaryExpressionAlignment, true); -/* leftOperand.accept(this); - final int operator = extractInfixExpressionOperator(node); - this.scribe.printNextToken(operator, this.preferences.insert_space_before_binary_operator); - if ( this.preferences.insert_space_after_binary_operator - || (operator == TerminalTokens.TokenNameMINUS && isNextToken(TerminalTokens.TokenNameMINUS))) { - // the next character is a minus (unary operator) or the preference is set to true - this.scribe.space(); - } - rightOperand.accept(this);*/ - return false; - } - - public boolean visit(Initializer node) { - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - node.getBody().accept(this); - return false; - } - - public boolean visit(InstanceofExpression node) { - node.getLeftOperand().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameinstanceof, true); - this.scribe.space(); - node.getRightOperand().accept(this); - return false; - } - - public boolean visit(LabeledStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_labeled_statement); - if (this.preferences.insert_space_after_colon_in_labeled_statement) { - this.scribe.space(); - } - node.getBody().accept(this); - return false; - } - - public boolean visit(MarkerAnnotation node) { - this.scribe.printNextToken(TerminalTokens.TokenNameAT); - if (this.preferences.insert_space_after_at_in_annotation) { - this.scribe.space(); - } - node.getTypeName().accept(this); - return false; - } - - public boolean visit(MemberValuePair node) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - node.getValue().accept(this); - return false; - } - - public boolean visit(MethodDeclaration node) { - if ((node.getFlags() & ASTNode.MALFORMED) != 0) { - this.scribe.printComment(); - this.scribe.printIndentationIfNecessary(); - this.scribe.scanner.resetTo(node.getStartPosition() + node.getLength(), this.scribe.scannerEndPosition); - this.scribe.needSpace = true; - this.scribe.printTrailingComment(); - switch(this.scribe.scanner.source[this.scribe.scanner.currentPosition]) { - case '\n' : - this.scribe.scanner.currentPosition++; - this.scribe.lastNumberOfNewLines = 1; - break; - case '\r' : - this.scribe.scanner.currentPosition++; - if (this.scribe.scanner.source[this.scribe.scanner.currentPosition] == '\n') { - this.scribe.scanner.currentPosition++; - } - this.scribe.lastNumberOfNewLines = 1; - } - return false; - } - /* - * Print comments to get proper line number - */ - this.scribe.printComment(); - final int line = this.scribe.line; - - final List modifiers = node.modifiers(); - final int modifiersLength = modifiers.size(); - if (modifiersLength != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - final List typeParameters = node.typeParameters(); - final int typeParametersLength = typeParameters.size(); - if (typeParametersLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_parameters); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_parameters) { - this.scribe.space(); - } - for (int i = 0; i < typeParametersLength - 1; i++) { - ((TypeParameter) typeParameters.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_parameters); - if (this.preferences.insert_space_after_comma_in_type_parameters) { - this.scribe.space(); - } - } - ((TypeParameter) typeParameters.get(typeParametersLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_parameters); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_parameters) { - this.scribe.space(); - } - } - - final Type returnType = node.getReturnType2(); - if (returnType != null) { - returnType.accept(this); - } - /* - * Print the method name - */ - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - - boolean spaceBeforeParen = this.preferences.insert_space_before_opening_paren_in_method_declaration; - if (node.isConstructor()) { - spaceBeforeParen = this.preferences.insert_space_before_opening_paren_in_constructor_declaration; - } - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, spaceBeforeParen); - - final List parameters = node.parameters(); - final int parametersLength = parameters.size(); - if (parametersLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_declaration) { - this.scribe.space(); - } - Alignment2 parametersAlignment = this.scribe.createAlignment( - "methodParameters",//$NON-NLS-1$ - this.preferences.alignment_for_parameters_in_method_declaration, - parametersLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(parametersAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < parametersLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_declaration_parameters); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(parametersAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_method_declaration_parameters) { - this.scribe.space(); - } - ((SingleVariableDeclaration) parameters.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(parametersAlignment, true); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_declaration); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_declaration); - } - /* - * Check for extra dimensions - */ - final int extraDimensions = node.getExtraDimensions(); - if (extraDimensions != 0) { - for (int i = 0; i < extraDimensions; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - - final List thrownExceptions = node.thrownExceptions(); - final int thrownExceptionsLength = thrownExceptions.size(); - if (thrownExceptionsLength != 0) { - Alignment2 throwsAlignment = this.scribe.createAlignment( - "throws",//$NON-NLS-1$ - node.isConstructor() - ? this.preferences.alignment_for_throws_clause_in_constructor_declaration - : this.preferences.alignment_for_throws_clause_in_method_declaration, - thrownExceptionsLength, // throws is the first token - this.scribe.scanner.currentPosition); - - this.scribe.enterAlignment(throwsAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(throwsAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNamethrows, true); - - for (int i = 0; i < thrownExceptionsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_declaration_throws); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(throwsAlignment, i); - if (this.preferences.insert_space_after_comma_in_method_declaration_throws) { - this.scribe.space(); - } - } else { - this.scribe.space(); - } - ((Name) thrownExceptions.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(throwsAlignment, true); - } - - final Block body = node.getBody(); - if (body != null) { - /* - * Method body - */ - String method_declaration_brace = this.preferences.brace_position_for_method_declaration; - formatLeftCurlyBrace(line, method_declaration_brace); - formatOpeningBrace(method_declaration_brace, this.preferences.insert_space_before_opening_brace_in_method_declaration); - final int numberOfBlankLinesAtBeginningOfMethodBody = this.preferences.blank_lines_at_beginning_of_method_body; - if (numberOfBlankLinesAtBeginningOfMethodBody > 0) { - this.scribe.printEmptyLines(numberOfBlankLinesAtBeginningOfMethodBody); - } - final List statements = body.statements(); - final int statementsLength = statements.size(); - if (statementsLength != 0) { - this.scribe.printNewLine(); - if (this.preferences.indent_statements_compare_to_body) { - this.scribe.indent(); - } - formatStatements(statements, true); - this.scribe.printComment(); - if (this.preferences.indent_statements_compare_to_body) { - this.scribe.unIndent(); - } - } else if (this.preferences.insert_new_line_in_empty_method_body) { - this.scribe.printNewLine(); - if (this.preferences.indent_statements_compare_to_body) { - this.scribe.indent(); - } - this.scribe.printComment(); - if (this.preferences.indent_statements_compare_to_body) { - this.scribe.unIndent(); - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (method_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - } else { - // no method body - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - } - return false; - } - - public boolean visit(MethodInvocation node) { - MethodInvocationFragmentBuilder builder = new MethodInvocationFragmentBuilder(); - node.accept(builder); - - final List fragments = builder.fragments(); - final int fragmentsLength = fragments.size(); - if (fragmentsLength >= 3) { - // manage cascading method invocations - // check the first fragment - final Expression firstFragment = (Expression) fragments.get(0); - switch(firstFragment.getNodeType()) { - case ASTNode.METHOD_INVOCATION : - formatSingleMethodInvocation((MethodInvocation) firstFragment); - break; - default: - firstFragment.accept(this); - } - Alignment2 cascadingMessageSendAlignment = - this.scribe.createAlignment( - "cascadingMessageSendAlignment", //$NON-NLS-1$ - this.preferences.alignment_for_selector_in_method_invocation, - Alignment.R_INNERMOST, - fragmentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(cascadingMessageSendAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(cascadingMessageSendAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - for (int i = 1; i < fragmentsLength - 1; i++) { - MethodInvocation currentMethodInvocation = (MethodInvocation) fragments.get(i); - formatSingleMethodInvocation(currentMethodInvocation); - this.scribe.alignFragment(cascadingMessageSendAlignment, i); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - MethodInvocation currentMethodInvocation = (MethodInvocation) fragments.get(fragmentsLength - 1); - formatSingleMethodInvocation(currentMethodInvocation); - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(cascadingMessageSendAlignment, true); - } else { - Expression expression = node.getExpression(); - if (expression != null) { - expression.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - formatSingleMethodInvocation(node); - } - return false; - } - - private void formatSingleMethodInvocation(MethodInvocation node) { - final List typeArguments = node.typeArguments(); - final int typeArgumentsLength = typeArguments.size(); - if (typeArgumentsLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_arguments); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - for (int i = 0; i < typeArgumentsLength - 1; i++) { - ((Type) typeArguments.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_arguments); - if (this.preferences.insert_space_after_comma_in_type_arguments) { - this.scribe.space(); - } - } - ((Type) typeArguments.get(typeArgumentsLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_arguments); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); // selector - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation); - - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - if (argumentsLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_invocation) { - this.scribe.space(); - } - if (argumentsLength > 1) { - Alignment2 argumentsAlignment = this.scribe.createAlignment( - "messageArguments", //$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_method_invocation, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - } else { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments); - this.scribe.printTrailingComment(); - } - if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation); - } - } - - public boolean visit(NormalAnnotation node) { - this.scribe.printNextToken(TerminalTokens.TokenNameAT); - if (this.preferences.insert_space_after_at_in_annotation) { - this.scribe.space(); - } - node.getTypeName().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_annotation); - if (this.preferences.insert_space_after_opening_paren_in_annotation) { - this.scribe.space(); - } - final List memberValuePairs = node.values(); - final int memberValuePairsLength = memberValuePairs.size(); - if (memberValuePairs.size() != 0) { - for (int i = 0; i < memberValuePairsLength - 1; i++) { - ((MemberValuePair) memberValuePairs.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_annotation); - if (this.preferences.insert_space_after_comma_in_annotation) { - this.scribe.space(); - } - } - ((MemberValuePair) memberValuePairs.get(memberValuePairsLength - 1)).accept(this); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_annotation); - return false; - } - - public boolean visit(NullLiteral node) { - this.scribe.printNextToken(TerminalTokens.TokenNamenull); - return false; - } - - public boolean visit(NumberLiteral node) { - if (isNextToken(TerminalTokens.TokenNameMINUS)) { - this.scribe.printNextToken(TerminalTokens.TokenNameMINUS, this.preferences.insert_space_before_unary_operator); - if (this.preferences.insert_space_after_unary_operator) { - this.scribe.space(); - } - } - this.scribe.printNextToken(NUMBER_LITERALS_EXPECTEDTOKENS); - return false; - } - - public boolean visit(ParameterizedType node) { - node.getType().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_parameterized_type_reference); - if (this.preferences.insert_space_after_opening_angle_bracket_in_parameterized_type_reference) { - this.scribe.space(); - } - final List typeArguments = node.typeArguments(); - final int typeArgumentsLength = typeArguments.size(); - for (int i = 0; i < typeArgumentsLength - 1; i++) { - ((Type) typeArguments.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_parameterized_type_reference); - if (this.preferences.insert_space_after_comma_in_parameterized_type_reference) { - this.scribe.space(); - } - } - ((Type) typeArguments.get(typeArgumentsLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_parameterized_type_reference); - } - return false; - } - - public boolean visit(ParenthesizedExpression node) { - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_parenthesized_expression); - if (this.preferences.insert_space_after_opening_paren_in_parenthesized_expression) { - this.scribe.space(); - } - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_parenthesized_expression); - return false; - } - - public boolean visit(PostfixExpression node) { - node.getOperand().accept(this); - int operator = node.getOperator() == PostfixExpression.Operator.INCREMENT - ? TerminalTokens.TokenNamePLUS_PLUS : TerminalTokens.TokenNameMINUS_MINUS; - this.scribe.printNextToken(operator, this.preferences.insert_space_before_postfix_operator); - if (this.preferences.insert_space_after_postfix_operator) { - this.scribe.space(); - } - return false; - } - - public boolean visit(PrefixExpression node) { - int operator; - boolean insertSpaceBeforeOperator; - boolean insertSpaceAfterOperator; - final Operator operator2 = node.getOperator(); - if (operator2 == PrefixExpression.Operator.INCREMENT) { - operator = TerminalTokens.TokenNamePLUS_PLUS; - insertSpaceBeforeOperator = this.preferences.insert_space_before_prefix_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_prefix_operator; - } else if (operator2 == PrefixExpression.Operator.DECREMENT) { - operator = TerminalTokens.TokenNameMINUS_MINUS; - insertSpaceBeforeOperator = this.preferences.insert_space_before_prefix_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_prefix_operator; - } else if (operator2 == PrefixExpression.Operator.COMPLEMENT) { - operator = TerminalTokens.TokenNameTWIDDLE; - insertSpaceBeforeOperator = this.preferences.insert_space_before_unary_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_unary_operator; - } else if (operator2 == PrefixExpression.Operator.MINUS) { - operator = TerminalTokens.TokenNameMINUS; - insertSpaceBeforeOperator = this.preferences.insert_space_before_unary_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_unary_operator; - } else if (operator2 == PrefixExpression.Operator.NOT) { - operator = TerminalTokens.TokenNameNOT; - insertSpaceBeforeOperator = this.preferences.insert_space_before_unary_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_unary_operator; - } else { - operator = TerminalTokens.TokenNamePLUS; - insertSpaceBeforeOperator = this.preferences.insert_space_before_unary_operator; - insertSpaceAfterOperator = this.preferences.insert_space_after_unary_operator; - } - - this.scribe.printNextToken(operator, insertSpaceBeforeOperator); - if (insertSpaceAfterOperator) { - this.scribe.space(); - } - node.getOperand().accept(this); - return false; - } - - public boolean visit(PrimitiveType node) { - this.scribe.printNextToken(PRIMITIVE_TYPE_EXPECTEDTOKENS); - return false; - } - - public boolean visit(QualifiedName node) { - node.getQualifier().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - node.getName().accept(this); - return false; - } - - public boolean visit(QualifiedType node) { - node.getQualifier().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - node.getName().accept(this); - return false; - } - - public boolean visit(ReturnStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamereturn); - final Expression expression = node.getExpression(); - if (expression != null) { - switch(expression.getNodeType()) { - case ASTNode.PARENTHESIZED_EXPRESSION : - if (this.preferences.insert_space_before_parenthesized_expression_in_return) { - this.scribe.space(); - } - break; - default: - this.scribe.space(); - } - expression.accept(this); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(SimpleName node) { - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - return false; - } - - public boolean visit(SimpleType node) { - node.getName().accept(this); - return false; - } - - public boolean visit(SingleMemberAnnotation node) { - this.scribe.printNextToken(TerminalTokens.TokenNameAT); - if (this.preferences.insert_space_after_at_in_annotation) { - this.scribe.space(); - } - node.getTypeName().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_annotation); - if (this.preferences.insert_space_after_opening_paren_in_annotation) { - this.scribe.space(); - } - node.getValue().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_annotation); - return false; - } - - public boolean visit(SingleVariableDeclaration node) { - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - node.getType().accept(this); - - if (node.isVarargs()) { - this.scribe.printNextToken(TerminalTokens.TokenNameELLIPSIS, this.preferences.insert_space_before_ellipsis); - if (this.preferences.insert_space_after_ellipsis) { - this.scribe.space(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, false); - } else { - /* - * Print the argument name - */ - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - } - - final int extraDimensions = node.getExtraDimensions(); - if (extraDimensions != 0) { - for (int i = 0; i < extraDimensions; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameLBRACKET); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACKET); - } - } - final Expression initialization = node.getInitializer(); - if (initialization != null) { - this.scribe.printNextToken(TerminalTokens.TokenNameEQUAL, this.preferences.insert_space_before_assignment_operator); - if (this.preferences.insert_space_after_assignment_operator) { - this.scribe.space(); - } - Alignment2 assignmentAlignment = this.scribe.createAlignment("localDeclarationAssignmentAlignment", this.preferences.alignment_for_assignment, 1, this.scribe.scanner.currentPosition); //$NON-NLS-1$ - this.scribe.enterAlignment(assignmentAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(assignmentAlignment, 0); - initialization.accept(this); - ok = true; - } catch(AlignmentException e){ - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(assignmentAlignment, true); - } - return false; - } - - public boolean visit(StringLiteral node) { - this.scribe.checkNLSTag(node.getStartPosition()); - this.scribe.printNextToken(TerminalTokens.TokenNameStringLiteral); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(SuperConstructorInvocation node) { - final Expression qualification = node.getExpression(); - if (qualification != null) { - qualification.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - final List typeArguments = node.typeArguments(); - final int typeArgumentsLength = typeArguments.size(); - if (typeArgumentsLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_arguments); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - for (int i = 0; i < typeArgumentsLength - 1; i++) { - ((Type) typeArguments.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_arguments); - if (this.preferences.insert_space_after_comma_in_type_arguments) { - this.scribe.space(); - } - } - ((Type) typeArguments.get(typeArgumentsLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_arguments); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_arguments) { - this.scribe.space(); - } - } - - this.scribe.printNextToken(TerminalTokens.TokenNamesuper); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation); - - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - if (argumentsLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_invocation) { - this.scribe.space(); - } - Alignment2 argumentsAlignment =this.scribe.createAlignment( - "explicit_constructor_call",//$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_explicit_constructor_call, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_explicit_constructor_call_arguments); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_explicit_constructor_call_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation); - } - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(SuperFieldAccess node) { - final Name qualifier = node.getQualifier(); - if (qualifier != null) { - qualifier.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - this.scribe.printNextToken(TerminalTokens.TokenNamesuper); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - return false; - } - - public boolean visit(SuperMethodInvocation node) { - final Name qualifier = node.getQualifier(); - if (qualifier != null) { - qualifier.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - this.scribe.printNextToken(TerminalTokens.TokenNamesuper); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_method_invocation); - - final List arguments = node.arguments(); - final int argumentsLength = arguments.size(); - if (argumentsLength != 0) { - if (this.preferences.insert_space_after_opening_paren_in_method_invocation) { - this.scribe.space(); - } - if (argumentsLength > 1) { - Alignment2 argumentsAlignment = this.scribe.createAlignment( - "messageArguments", //$NON-NLS-1$ - this.preferences.alignment_for_arguments_in_method_invocation, - argumentsLength, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(argumentsAlignment); - boolean ok = false; - do { - try { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments); - this.scribe.printTrailingComment(); - } - this.scribe.alignFragment(argumentsAlignment, i); - if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(argumentsAlignment, true); - } else { - for (int i = 0; i < argumentsLength; i++) { - if (i > 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_method_invocation_arguments); - this.scribe.printTrailingComment(); - } - if (i > 0 && this.preferences.insert_space_after_comma_in_method_invocation_arguments) { - this.scribe.space(); - } - ((Expression) arguments.get(i)).accept(this); - } - } - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_method_invocation); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_between_empty_parens_in_method_invocation); - } - return false; - } - - public boolean visit(SwitchCase node) { - Expression constant = node.getExpression(); - if (constant == null) { - this.scribe.printNextToken(TerminalTokens.TokenNamedefault); - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_default); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNamecase); - this.scribe.space(); - constant.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOLON, this.preferences.insert_space_before_colon_in_case); - } - return false; - } - - public boolean visit(SwitchStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNameswitch); - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_switch); - - if (this.preferences.insert_space_after_opening_paren_in_switch) { - this.scribe.space(); - } - - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_switch); - /* - * Type body - */ - String switch_brace = this.preferences.brace_position_for_switch; - formatOpeningBrace(switch_brace, this.preferences.insert_space_before_opening_brace_in_switch); - this.scribe.printNewLine(); - - if (this.preferences.indent_switchstatements_compare_to_switch) { - this.scribe.indent(); - } - final List statements = node.statements(); - final int statementsLength = statements.size(); - boolean wasACase = false; - boolean wasAStatement = false; - if (statementsLength != 0) { - for (int i = 0; i < statementsLength; i++) { - final Statement statement = (Statement) statements.get(i); - if (statement instanceof SwitchCase) { - if (wasACase) { - this.scribe.printNewLine(); - } - if ((wasACase && this.preferences.indent_switchstatements_compare_to_cases) - || (wasAStatement && this.preferences.indent_switchstatements_compare_to_cases)) { - this.scribe.unIndent(); - } - statement.accept(this); - this.scribe.printTrailingComment(); - wasACase = true; - wasAStatement = false; - if (this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.indent(); - } - } else if (statement instanceof BreakStatement) { - if (this.preferences.indent_breaks_compare_to_cases) { - if (wasAStatement && !this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.indent(); - } - } else { - if (wasAStatement) { - if (this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.unIndent(); - } - } - if (wasACase && this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.unIndent(); - } - } - if (wasACase) { - this.scribe.printNewLine(); - } - statement.accept(this); - if (this.preferences.indent_breaks_compare_to_cases) { - this.scribe.unIndent(); - } - wasACase = false; - wasAStatement = false; - } else if (statement instanceof Block) { - String bracePosition; - if (wasACase) { - if (this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.unIndent(); - } - bracePosition = this.preferences.brace_position_for_block_in_case; - formatBlock((Block) statement, bracePosition, this.preferences.insert_space_after_colon_in_case); - if (this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.indent(); - } - } else { - bracePosition = this.preferences.brace_position_for_block; - formatBlock((Block) statement, bracePosition, this.preferences.insert_space_before_opening_brace_in_block); - } - wasAStatement = true; - wasACase = false; - } else { - this.scribe.printNewLine(); - statement.accept(this); - wasAStatement = true; - wasACase = false; - } - if (!wasACase) { - this.scribe.printNewLine(); - } - this.scribe.printComment(); - } - } - - if ((wasACase || wasAStatement) && this.preferences.indent_switchstatements_compare_to_cases) { - this.scribe.unIndent(); - } - if (this.preferences.indent_switchstatements_compare_to_switch) { - this.scribe.unIndent(); - } - this.scribe.printNewLine(); - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (switch_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - return false; - } - - public boolean visit(SynchronizedStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamesynchronized); - - final int line = this.scribe.line; - - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_synchronized); - - if (this.preferences.insert_space_after_opening_paren_in_synchronized) { - this.scribe.space(); - } - node.getExpression().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_synchronized); - - formatLeftCurlyBrace(line, this.preferences.brace_position_for_block); - node.getBody().accept(this); - return false; - } - - public boolean visit(ThisExpression node) { - final Name qualifier = node.getQualifier(); - if (qualifier != null) { - qualifier.accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - } - this.scribe.printNextToken(TerminalTokens.TokenNamethis); - return false; - } - - public boolean visit(ThrowStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamethrow); - this.scribe.space(); - node.getExpression().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(TryStatement node) { - - this.scribe.printNextToken(TerminalTokens.TokenNametry); - node.getBody().accept(this); - final List catchClauses = node.catchClauses(); - final int catchClausesLength = catchClauses.size(); - if (catchClausesLength != 0) { - for (int i = 0; i < catchClausesLength; i++) { - if (this.preferences.insert_new_line_before_catch_in_try_statement) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNamecatch, this.preferences.insert_space_after_closing_brace_in_block); - final int line = this.scribe.line; - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_catch); - - if (this.preferences.insert_space_after_opening_paren_in_catch) { - this.scribe.space(); - } - - final CatchClause catchClause = ((CatchClause) catchClauses.get(i)); - catchClause.getException().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_catch); - - formatLeftCurlyBrace(line, this.preferences.brace_position_for_block); - catchClause.getBody().accept(this); - } - } - final Block finallyBlock = node.getFinally(); - if (finallyBlock != null) { - if (this.preferences.insert_new_line_before_finally_in_try_statement) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNamefinally, this.preferences.insert_space_after_closing_brace_in_block); - finallyBlock.accept(this); - } - return false; - } - - public boolean visit(TypeDeclaration node) { - /* - * Print comments to get proper line number - */ - this.scribe.printComment(); - final int line = this.scribe.line; - - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - final boolean isInterface = node.isInterface(); - if (isInterface) { - this.scribe.printNextToken(TerminalTokens.TokenNameinterface, true); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameclass, true); - } - - this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); - - final List typeParameters = node.typeParameters(); - final int typeParametersLength = typeParameters.size(); - if (typeParametersLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameLESS, this.preferences.insert_space_before_opening_angle_bracket_in_type_parameters); - if (this.preferences.insert_space_after_opening_angle_bracket_in_type_parameters) { - this.scribe.space(); - } - for (int i = 0; i < typeParametersLength - 1; i++) { - ((TypeParameter) typeParameters.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_type_parameters); - if (this.preferences.insert_space_after_comma_in_type_parameters) { - this.scribe.space(); - } - } - ((TypeParameter) typeParameters.get(typeParametersLength - 1)).accept(this); - if (isClosingGenericToken()) { - this.scribe.printNextToken(CLOSING_GENERICS_EXPECTEDTOKENS, this.preferences.insert_space_before_closing_angle_bracket_in_type_parameters); - } - if (this.preferences.insert_space_after_closing_angle_bracket_in_type_parameters) { - this.scribe.space(); - } - } - /* - * Superclass - */ - final Type superclass = node.getSuperclassType(); - if (superclass != null) { - Alignment2 superclassAlignment =this.scribe.createAlignment( - "superclass", //$NON-NLS-1$ - this.preferences.alignment_for_superclass_in_type_declaration, - 2, - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(superclassAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(superclassAlignment, 0); - this.scribe.printNextToken(TerminalTokens.TokenNameextends, true); - this.scribe.alignFragment(superclassAlignment, 1); - this.scribe.space(); - superclass.accept(this); - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(superclassAlignment, true); - } - - /* - * Super Interfaces - */ - final List superInterfaces = node.superInterfaceTypes(); - final int superInterfacesLength = superInterfaces.size(); - if (superInterfacesLength != 0) { - Alignment2 interfaceAlignment = this.scribe.createAlignment( - "superInterfaces",//$NON-NLS-1$ - this.preferences.alignment_for_superinterfaces_in_type_declaration, - superInterfacesLength+1, // implements token is first fragment - this.scribe.scanner.currentPosition); - this.scribe.enterAlignment(interfaceAlignment); - boolean ok = false; - do { - try { - this.scribe.alignFragment(interfaceAlignment, 0); - if (isInterface) { - this.scribe.printNextToken(TerminalTokens.TokenNameextends, true); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNameimplements, true); - } - this.scribe.alignFragment(interfaceAlignment, 1); - this.scribe.space(); - ((Type) superInterfaces.get(0)).accept(this); - for (int i = 1; i < superInterfacesLength; i++) { - this.scribe.printNextToken(TerminalTokens.TokenNameCOMMA, this.preferences.insert_space_before_comma_in_superinterfaces); - this.scribe.printTrailingComment(); - this.scribe.alignFragment(interfaceAlignment, i+1); - if (this.preferences.insert_space_after_comma_in_superinterfaces) { - this.scribe.space(); - } - ((Type) superInterfaces.get(i)).accept(this); - } - ok = true; - } catch (AlignmentException e) { - this.scribe.redoAlignment(e); - } - } while (!ok); - this.scribe.exitAlignment(interfaceAlignment, true); - } - - final String class_declaration_brace = this.preferences.brace_position_for_type_declaration; - final boolean space_before_opening_brace = this.preferences.insert_space_before_opening_brace_in_type_declaration; - - formatLeftCurlyBrace(line, class_declaration_brace); - final List bodyDeclarations = node.bodyDeclarations(); - formatTypeOpeningBrace(class_declaration_brace, space_before_opening_brace, bodyDeclarations.size() != 0, node); - - final boolean indent_body_declarations_compare_to_header = this.preferences.indent_body_declarations_compare_to_type_header; - - if (indent_body_declarations_compare_to_header) { - this.scribe.indent(); - } - - formatTypeMembers(bodyDeclarations, true); - - if (indent_body_declarations_compare_to_header) { - this.scribe.unIndent(); - } - - if (this.preferences.insert_new_line_in_empty_type_declaration) { - this.scribe.printNewLine(); - } - this.scribe.printNextToken(TerminalTokens.TokenNameRBRACE); - this.scribe.printTrailingComment(); - if (class_declaration_brace.equals(DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED)) { - this.scribe.unIndent(); - } - if (hasComments()) { - this.scribe.printNewLine(); - } - return false; - } - - public boolean visit(TypeDeclarationStatement node) { - node.getDeclaration().accept(this); - return false; - } - - public boolean visit(TypeLiteral node) { - node.getType().accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameDOT); - this.scribe.printNextToken(TerminalTokens.TokenNameclass); - return false; - } - - public boolean visit(TypeParameter node) { - node.getName().accept(this); - final List bounds = node.typeBounds(); - final int boundsLength = bounds.size(); - if (boundsLength != 0) { - this.scribe.printNextToken(TerminalTokens.TokenNameextends, true); - this.scribe.space(); - ((Type) bounds.get(0)).accept(this); - if (boundsLength > 1) { - this.scribe.printNextToken(TerminalTokens.TokenNameAND, this.preferences.insert_space_before_and_in_type_parameter); - if (this.preferences.insert_space_after_and_in_type_parameter) { - this.scribe.space(); - } - for (int i = 1; i < boundsLength - 1; i++) { - ((Type) bounds.get(i)).accept(this); - this.scribe.printNextToken(TerminalTokens.TokenNameAND, this.preferences.insert_space_before_and_in_type_parameter); - if (this.preferences.insert_space_after_and_in_type_parameter) { - this.scribe.space(); - } - } - ((Type) bounds.get(boundsLength - 1)).accept(this); - } - } - return false; - } - - public boolean visit(VariableDeclarationExpression node) { - formatLocalDeclaration(node, this.preferences.insert_space_before_comma_in_multiple_local_declarations, this.preferences.insert_space_after_comma_in_multiple_local_declarations); - return false; - } - - public boolean visit(VariableDeclarationStatement node) { - final List modifiers = node.modifiers(); - if (modifiers.size() != 0) { - this.scribe.printModifiers(modifiers, this); - this.scribe.space(); - } - - node.getType().accept(this); - - formatVariableDeclarationFragments(node.fragments(), this.preferences.insert_space_before_comma_in_multiple_local_declarations, this.preferences.insert_space_after_comma_in_multiple_local_declarations); - this.scribe.printNextToken(TerminalTokens.TokenNameSEMICOLON, this.preferences.insert_space_before_semicolon); - this.scribe.printTrailingComment(); - return false; - } - - public boolean visit(WhileStatement node) { - this.scribe.printNextToken(TerminalTokens.TokenNamewhile); - final int line = this.scribe.line; - this.scribe.printNextToken(TerminalTokens.TokenNameLPAREN, this.preferences.insert_space_before_opening_paren_in_while); - - if (this.preferences.insert_space_after_opening_paren_in_while) { - this.scribe.space(); - } - node.getExpression().accept(this); - - this.scribe.printNextToken(TerminalTokens.TokenNameRPAREN, this.preferences.insert_space_before_closing_paren_in_while); - - formatAction(line, node.getBody(),false); - return false; - } - - public boolean visit(WildcardType node) { - this.scribe.printNextToken(TerminalTokens.TokenNameQUESTION, this.preferences.insert_space_before_question_in_wilcard); - final Type bound = node.getBound(); - if (bound != null) { - if (node.isUpperBound()) { - this.scribe.printNextToken(TerminalTokens.TokenNameextends, true); - } else { - this.scribe.printNextToken(TerminalTokens.TokenNamesuper, true); - } - this.scribe.space(); - bound.accept(this); - } else if (this.preferences.insert_space_after_question_in_wilcard) { - this.scribe.space(); - } - return false; - } - -} Index: formatter/org/eclipse/jdt/internal/formatter/InfixExpressionWrappingBuilder.java =================================================================== RCS file: formatter/org/eclipse/jdt/internal/formatter/InfixExpressionWrappingBuilder.java diff -N formatter/org/eclipse/jdt/internal/formatter/InfixExpressionWrappingBuilder.java --- formatter/org/eclipse/jdt/internal/formatter/InfixExpressionWrappingBuilder.java 10 May 2006 18:03:51 -0000 1.5 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation 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: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.formatter; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.InfixExpression; - -public class InfixExpressionWrappingBuilder extends ASTVisitor { - private final static int DEFAULT_SIZE = 10; - ArrayList fragments = new ArrayList(); - int[] operators = new int[DEFAULT_SIZE]; - int operatorCounter = 0; - - public int getFragmentsCounter() { - return this.fragments.size(); - } - - public int[] getOperators() { - if (operators.length != operatorCounter) { - // resize - System.arraycopy(this.operators, 0, (this.operators = new int[this.operatorCounter]), 0, this.operatorCounter); - } - return this.operators; - } - private boolean isSplittable(Expression expression) { -// if (expression instanceof InfixExpression) { -// InfixExpression infixExpression = (InfixExpression) expression; -// return infixExpression.getLeftOperand() instanceof InfixExpression -// || infixExpression.getRightOperand() instanceof InfixExpression; -// } -// return false; - return true; - } - public boolean visit(InfixExpression node) { - final Expression leftOperand = node.getLeftOperand(); - final Expression rightOperand = node.getRightOperand(); - if (leftOperand.getNodeType() == ASTNode.INFIX_EXPRESSION && isSplittable(leftOperand)) { - leftOperand.accept(this); - } else { - this.fragments.add(leftOperand); - } - if (operatorCounter == this.operators.length) { - // need to resize - System.arraycopy(this.operators, 0, (this.operators = new int[this.operatorCounter * 2]), 0, this.operatorCounter); - } - final int extractInfixExpressionOperator = CodeFormatterVisitor2.extractInfixExpressionOperator(node); - this.operators[this.operatorCounter++] = extractInfixExpressionOperator; - if (rightOperand.getNodeType() == ASTNode.INFIX_EXPRESSION && isSplittable(leftOperand)) { - rightOperand.accept(this); - } else { - this.fragments.add(rightOperand); - } - final List extendedOperands = node.extendedOperands(); - final int extendedOperandsLength = extendedOperands.size(); - if (extendedOperandsLength != 0) { - for (int i = 0; i < extendedOperandsLength; i++) { - if (operatorCounter == this.operators.length) { - // need to resize - System.arraycopy(this.operators, 0, (this.operators = new int[this.operatorCounter * 2]), 0, this.operatorCounter); - } - this.operators[this.operatorCounter++] = extractInfixExpressionOperator; - final Expression extendedOperand = ((Expression) extendedOperands.get(i)); - if (extendedOperand instanceof InfixExpression) { - extendedOperand.accept(this); - } else { - this.fragments.add(extendedOperand); - } - } - } - return false; - } - -} Index: formatter/org/eclipse/jdt/internal/formatter/Location2.java =================================================================== RCS file: formatter/org/eclipse/jdt/internal/formatter/Location2.java diff -N formatter/org/eclipse/jdt/internal/formatter/Location2.java --- formatter/org/eclipse/jdt/internal/formatter/Location2.java 8 Sep 2005 20:30:23 -0000 1.1 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation 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: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.formatter; - -/** - * A location maintains positional information both in original source and in the output source. - * It remembers source offsets, line/column and indentation level. - * @since 2.1 - */ -public class Location2 { - - public int inputOffset; - public int outputLine; - public int outputColumn; - public int outputIndentationLevel; - public boolean needSpace; - public boolean pendingSpace; - public int nlsTagCounter; - public int numberOfIndentations; - - // chunk management - public int lastNumberOfNewLines; - - // edits management - int editsIndex; - OptimizedReplaceEdit textEdit; - - public Location2(Scribe2 scribe, int sourceRestart){ - update(scribe, sourceRestart); - } - - public void update(Scribe2 scribe, int sourceRestart){ - this.outputColumn = scribe.column; - this.outputLine = scribe.line; - this.inputOffset = sourceRestart; - this.outputIndentationLevel = scribe.indentationLevel; - this.lastNumberOfNewLines = scribe.lastNumberOfNewLines; - this.needSpace = scribe.needSpace; - this.pendingSpace = scribe.pendingSpace; - this.editsIndex = scribe.editsIndex; - this.nlsTagCounter = scribe.nlsTagCounter; - this.numberOfIndentations = scribe.numberOfIndentations; - textEdit = scribe.getLastEdit(); - } -} Index: formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java =================================================================== RCS file: /cvsroot/eclipse/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java,v retrieving revision 1.58 diff -u -r1.58 DefaultCodeFormatter.java --- formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java 24 Nov 2006 01:32:03 -0000 1.58 +++ formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatter.java 2 Feb 2007 01:28:55 -0000 @@ -16,11 +16,6 @@ import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.internal.compiler.ast.ASTNode; @@ -45,7 +40,7 @@ public static final boolean DEBUG = false; private static Scanner ProbingScanner; - public static boolean USE_NEW_FORMATTER = false; + private static final MultiTextEdit DEFAULT_EMPTY_EDIT = new MultiTextEdit(); /** * Creates a comment region for a specific document partition type. @@ -68,11 +63,11 @@ } return null; } + private CodeSnippetParsingUtil codeSnippetParsingUtil; private Map defaultCompilerOptions; private CodeFormatterVisitor newCodeFormatter; - private CodeFormatterVisitor2 newCodeFormatter2; private Map options; private DefaultCodeFormatterOptions preferences; @@ -174,24 +169,6 @@ } private TextEdit formatClassBodyDeclarations(String source, int indentationLevel, String lineSeparator, int offset, int length) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - return this.newCodeFormatter2.format(source, (AbstractTypeDeclaration) node); - } ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true); if (bodyDeclarations == null) { @@ -202,7 +179,17 @@ } private TextEdit formatComment(int kind, String source, int indentationLevel, String lineSeparator, int offset, int length) { - final boolean isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT)); + boolean isFormattingComments = false; + switch (kind) { + case CodeFormatter.K_SINGLE_LINE_COMMENT: + isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT)); + break; + case CodeFormatter.K_MULTI_LINE_COMMENT: + isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT)); + break; + case CodeFormatter.K_JAVA_DOC: + isFormattingComments = DefaultCodeFormatterConstants.TRUE.equals(this.options.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT)); + } if (isFormattingComments) { if (lineSeparator != null) { this.preferences.line_separator = lineSeparator; @@ -216,28 +203,10 @@ return this.newCodeFormatter.format(source, region); } } - return new MultiTextEdit(); + return DEFAULT_EMPTY_EDIT; } private TextEdit formatCompilationUnit(String source, int indentationLevel, String lineSeparator, int offset, int length) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_COMPILATION_UNIT); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - return this.newCodeFormatter2.format(source, (CompilationUnit) node); - } CompilationUnitDeclaration compilationUnitDeclaration = this.codeSnippetParsingUtil.parseCompilationUnit(source.toCharArray(), getDefaultCompilerOptions(), true); if (lineSeparator != null) { @@ -253,27 +222,6 @@ } private TextEdit formatExpression(String source, int indentationLevel, String lineSeparator, int offset, int length) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_EXPRESSION); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (node.getNodeType() == org.eclipse.jdt.core.dom.ASTNode.COMPILATION_UNIT) return null; - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - - return this.newCodeFormatter2.format(source, (org.eclipse.jdt.core.dom.Expression) node); - } - Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true); if (expression == null) { @@ -284,26 +232,6 @@ } private TextEdit formatStatements(String source, int indentationLevel, String lineSeparator, int offset, int length) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_STATEMENTS); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - - return this.newCodeFormatter2.format(source, (Block) node); - } - ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false); if (constructorDeclaration.statements == null) { @@ -458,97 +386,21 @@ // probe for expression Expression expression = this.codeSnippetParsingUtil.parseExpression(source.toCharArray(), getDefaultCompilerOptions(), true); if (expression != null) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_EXPRESSION); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (node.getNodeType() == org.eclipse.jdt.core.dom.ASTNode.COMPILATION_UNIT) return null; - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - - TextEdit textEdit = this.newCodeFormatter2.format(source, (org.eclipse.jdt.core.dom.Expression) node); - return textEdit; - } return internalFormatExpression(source, indentationLevel, lineSeparator, expression, offset, length); } // probe for body declarations (fields, methods, constructors) ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true); if (bodyDeclarations != null) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - return this.newCodeFormatter2.format(source, (AbstractTypeDeclaration) node); - } return internalFormatClassBodyDeclarations(source, indentationLevel, lineSeparator, bodyDeclarations, offset, length); } // probe for statements ConstructorDeclaration constructorDeclaration = this.codeSnippetParsingUtil.parseStatements(source.toCharArray(), getDefaultCompilerOptions(), true, false); if (constructorDeclaration.statements != null) { - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_STATEMENTS); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - - return this.newCodeFormatter2.format(source, (Block) node); - } return internalFormatStatements(source, indentationLevel, lineSeparator, constructorDeclaration, offset, length); } - if (USE_NEW_FORMATTER) { - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setSource(source.toCharArray()); - parser.setKind(ASTParser.K_COMPILATION_UNIT); - parser.setCompilerOptions(getDefaultCompilerOptions()); - parser.setResolveBindings(false); - parser.setUnitName(""); //$NON-NLS-1$ - org.eclipse.jdt.core.dom.ASTNode node = parser.createAST(null); - if (lineSeparator != null) { - this.preferences.line_separator = lineSeparator; - } else { - this.preferences.line_separator = Util.LINE_SEPARATOR; - } - this.preferences.initial_indentation_level = indentationLevel; - - this.newCodeFormatter2 = new CodeFormatterVisitor2(this.preferences, this.options, offset, length, (CompilationUnit) node.getRoot()); - return this.newCodeFormatter2.format(source, (CompilationUnit) node); - } // this has to be a compilation unit return formatCompilationUnit(source, indentationLevel, lineSeparator, offset, length); } Index: formatter/org/eclipse/jdt/internal/formatter/Scribe2.java =================================================================== RCS file: formatter/org/eclipse/jdt/internal/formatter/Scribe2.java diff -N formatter/org/eclipse/jdt/internal/formatter/Scribe2.java --- formatter/org/eclipse/jdt/internal/formatter/Scribe2.java 24 Nov 2006 01:32:03 -0000 1.11 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,1506 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation 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: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.formatter; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.eclipse.jdt.core.compiler.CharOperation; -import org.eclipse.jdt.core.compiler.InvalidInputException; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.Comment; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.internal.compiler.parser.Scanner; -import org.eclipse.jdt.internal.compiler.parser.ScannerHelper; -import org.eclipse.jdt.internal.compiler.parser.TerminalTokens; -import org.eclipse.jdt.internal.compiler.util.Util; -import org.eclipse.jdt.internal.formatter.align.Alignment; -import org.eclipse.jdt.internal.formatter.align.Alignment2; -import org.eclipse.jdt.internal.formatter.align.AlignmentException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; - -/** - * This class is responsible for dumping formatted source - * @since 2.1 - */ -public class Scribe2 { private static final int INITIAL_SIZE = 100; - - private boolean checkLineWrapping; - /** one-based column */ - public int column; - private List comments; - - // Most specific alignment. - public Alignment2 currentAlignment; - public int currentToken; - - // edits management - private OptimizedReplaceEdit[] edits; - public int editsIndex; - - public CodeFormatterVisitor2 formatter; - public int indentationLevel; - public int lastNumberOfNewLines; - public int line; - - private String lineSeparator; - public Alignment2 memberAlignment; - public boolean needSpace = false; - - public int nlsTagCounter; - public int pageWidth; - public boolean pendingSpace = false; - - public Scanner scanner; - public int scannerEndPosition; - public int tabLength; - public int indentationSize; - private int textRegionEnd; - private int textRegionStart; - public int tabChar; - public int numberOfIndentations; - private boolean useTabsOnlyForLeadingIndents; - CompilationUnit unit; - - /** indent empty lines*/ - private final boolean indentEmptyLines; - - Scribe2(CodeFormatterVisitor2 formatter, long sourceLevel, int offset, int length, CompilationUnit unit) { - this.scanner = new Scanner(true, true, false/*nls*/, sourceLevel/*sourceLevel*/, null/*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); - this.formatter = formatter; - this.pageWidth = formatter.preferences.page_width; - this.tabLength = formatter.preferences.tab_size; - this.indentationLevel= 0; // initialize properly - this.numberOfIndentations = 0; - this.useTabsOnlyForLeadingIndents = formatter.preferences.use_tabs_only_for_leading_indentations; - this.indentEmptyLines = formatter.preferences.indent_empty_lines; - this.tabChar = formatter.preferences.tab_char; - if (this.tabChar == DefaultCodeFormatterOptions.MIXED) { - this.indentationSize = formatter.preferences.indentation_size; - } else { - this.indentationSize = this.tabLength; - } - this.lineSeparator = formatter.preferences.line_separator; - this.indentationLevel = formatter.preferences.initial_indentation_level * this.indentationSize; - this.textRegionStart = offset; - this.textRegionEnd = offset + length - 1; - if (unit != null) { - this.unit = unit; - this.comments = unit.getCommentList(); - } - reset(); - } - - private final void addDeleteEdit(int start, int end) { - if (this.edits.length == this.editsIndex) { - // resize - resize(); - } - addOptimizedReplaceEdit(start, end - start + 1, Util.EMPTY_STRING); - } - - public final void addInsertEdit(int insertPosition, String insertedString) { - if (this.edits.length == this.editsIndex) { - // resize - resize(); - } - addOptimizedReplaceEdit(insertPosition, 0, insertedString); - } - - private final void addOptimizedReplaceEdit(int offset, int length, String replacement) { - if (this.editsIndex > 0) { - // try to merge last two edits - final OptimizedReplaceEdit previous = this.edits[this.editsIndex-1]; - final int previousOffset = previous.offset; - final int previousLength = previous.length; - final int endOffsetOfPreviousEdit = previousOffset + previousLength; - final int replacementLength = replacement.length(); - final String previousReplacement = previous.replacement; - final int previousReplacementLength = previousReplacement.length(); - if (previousOffset == offset && previousLength == length && (replacementLength == 0 || previousReplacementLength == 0)) { - if (this.currentAlignment != null) { - final Location2 location = this.currentAlignment.location; - if (location.editsIndex == this.editsIndex) { - location.editsIndex--; - location.textEdit = previous; - } - } - this.editsIndex--; - return; - } - if (endOffsetOfPreviousEdit == offset) { - if (length != 0) { - if (replacementLength != 0) { - this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength + length, previousReplacement + replacement); - } else if (previousLength + length == previousReplacementLength) { - // check the characters. If they are identical, we can get rid of the previous edit - boolean canBeRemoved = true; - loop: for (int i = previousOffset; i < previousOffset + previousReplacementLength; i++) { - if (scanner.source[i] != previousReplacement.charAt(i - previousOffset)) { - this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousReplacementLength, previousReplacement); - canBeRemoved = false; - break loop; - } - } - if (canBeRemoved) { - if (this.currentAlignment != null) { - final Location2 location = this.currentAlignment.location; - if (location.editsIndex == this.editsIndex) { - location.editsIndex--; - location.textEdit = previous; - } - } - this.editsIndex--; - } - } else { - this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength + length, previousReplacement); - } - } else { - if (replacementLength != 0) { - this.edits[this.editsIndex - 1] = new OptimizedReplaceEdit(previousOffset, previousLength, previousReplacement + replacement); - } - } - } else { - this.edits[this.editsIndex++] = new OptimizedReplaceEdit(offset, length, replacement); - } - } else { - this.edits[this.editsIndex++] = new OptimizedReplaceEdit(offset, length, replacement); - } - } - - public final void addReplaceEdit(int start, int end, String replacement) { - if (this.edits.length == this.editsIndex) { - // resize - resize(); - } - addOptimizedReplaceEdit(start, end - start + 1, replacement); - } - - public void alignFragment(Alignment2 alignment, int fragmentIndex){ - alignment.fragmentIndex = fragmentIndex; - alignment.checkColumn(); - alignment.performFragmentEffect(); - } - - public void checkNLSTag(int sourceStart) { - if (hasNLSTag(sourceStart)) { - this.nlsTagCounter++; - } - } - public void consumeNextToken() { - printComment(); - try { - this.currentToken = this.scanner.getNextToken(); - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - public Alignment2 createAlignment(String name, int mode, int count, int sourceRestart){ - return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart); - } - - public Alignment2 createAlignment(String name, int mode, int count, int sourceRestart, boolean adjust){ - return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, adjust); - } - - public Alignment2 createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart){ - return createAlignment(name, mode, tieBreakRule, count, sourceRestart, this.formatter.preferences.continuation_indentation, false); - } - - public Alignment2 createAlignment(String name, int mode, int count, int sourceRestart, int continuationIndent, boolean adjust){ - return createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart, continuationIndent, adjust); - } - - public Alignment2 createAlignment(String name, int mode, int tieBreakRule, int count, int sourceRestart, int continuationIndent, boolean adjust){ - Alignment2 alignment = new Alignment2(name, mode, tieBreakRule, this, count, sourceRestart, continuationIndent); - // adjust break indentation - if (adjust && this.memberAlignment != null) { - Alignment2 current = this.memberAlignment; - while (current.enclosing != null) { - current = current.enclosing; - } - if ((current.mode & Alignment.M_MULTICOLUMN) != 0) { - final int indentSize = this.indentationSize; - switch(current.chunkKind) { - case Alignment.CHUNK_METHOD : - case Alignment.CHUNK_TYPE : - if ((mode & Alignment.M_INDENT_BY_ONE) != 0) { - alignment.breakIndentationLevel = this.indentationLevel + indentSize; - } else { - alignment.breakIndentationLevel = this.indentationLevel + continuationIndent * indentSize; - } - alignment.update(); - break; - case Alignment.CHUNK_FIELD : - if ((mode & Alignment.M_INDENT_BY_ONE) != 0) { - alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize; - } else { - alignment.breakIndentationLevel = current.originalIndentationLevel + continuationIndent * indentSize; - } - alignment.update(); - break; - } - } else { - switch(current.mode & Alignment.SPLIT_MASK) { - case Alignment.M_COMPACT_SPLIT : - case Alignment.M_COMPACT_FIRST_BREAK_SPLIT : - case Alignment.M_NEXT_PER_LINE_SPLIT : - case Alignment.M_NEXT_SHIFTED_SPLIT : - case Alignment.M_ONE_PER_LINE_SPLIT : - final int indentSize = this.indentationSize; - switch(current.chunkKind) { - case Alignment.CHUNK_METHOD : - case Alignment.CHUNK_TYPE : - if ((mode & Alignment.M_INDENT_BY_ONE) != 0) { - alignment.breakIndentationLevel = this.indentationLevel + indentSize; - } else { - alignment.breakIndentationLevel = this.indentationLevel + continuationIndent * indentSize; - } - alignment.update(); - break; - case Alignment.CHUNK_FIELD : - if ((mode & Alignment.M_INDENT_BY_ONE) != 0) { - alignment.breakIndentationLevel = current.originalIndentationLevel + indentSize; - } else { - alignment.breakIndentationLevel = current.originalIndentationLevel + continuationIndent * indentSize; - } - alignment.update(); - break; - } - break; - } - } - } - return alignment; - } - - public Alignment2 createMemberAlignment(String name, int mode, int count, int sourceRestart) { - Alignment2 mAlignment = createAlignment(name, mode, Alignment.R_INNERMOST, count, sourceRestart); - mAlignment.breakIndentationLevel = this.indentationLevel; - return mAlignment; - } - - public void enterAlignment(Alignment2 alignment){ - alignment.enclosing = this.currentAlignment; - this.currentAlignment = alignment; - } - - public void enterMemberAlignment(Alignment2 alignment) { - alignment.enclosing = this.memberAlignment; - this.memberAlignment = alignment; - } - - public void exitAlignment(Alignment2 alignment, boolean discardAlignment){ - Alignment2 current = this.currentAlignment; - while (current != null){ - if (current == alignment) break; - current = current.enclosing; - } - if (current == null) { - throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ - } - this.indentationLevel = alignment.location.outputIndentationLevel; - this.numberOfIndentations = alignment.location.numberOfIndentations; - if (discardAlignment){ - this.currentAlignment = alignment.enclosing; - } - } - - public void exitMemberAlignment(Alignment2 alignment){ - Alignment2 current = this.memberAlignment; - while (current != null){ - if (current == alignment) break; - current = current.enclosing; - } - if (current == null) { - throw new AbortFormatting("could not find matching alignment: "+alignment); //$NON-NLS-1$ - } - this.indentationLevel = current.location.outputIndentationLevel; - this.numberOfIndentations = current.location.numberOfIndentations; - this.memberAlignment = current.enclosing; - } - - public Alignment2 getAlignment(String name){ - if (this.currentAlignment != null) { - return this.currentAlignment.getAlignment(name); - } - return null; - } - - /** - * Answer actual indentation level based on true column position - * @return int - */ - public int getColumnIndentationLevel() { - return this.column - 1; - } - - public String getEmptyLines(int linesNumber) { - if (this.nlsTagCounter > 0) { - return Util.EMPTY_STRING; - } - StringBuffer buffer = new StringBuffer(); - if (lastNumberOfNewLines == 0) { - linesNumber++; // add an extra line breaks - for (int i = 0; i < linesNumber; i++) { - if (indentEmptyLines) printIndentationIfNecessary(buffer); - buffer.append(this.lineSeparator); - } - lastNumberOfNewLines += linesNumber; - line += linesNumber; - column = 1; - needSpace = false; - this.pendingSpace = false; - } else if (lastNumberOfNewLines == 1) { - for (int i = 0; i < linesNumber; i++) { - if (indentEmptyLines) printIndentationIfNecessary(buffer); - buffer.append(this.lineSeparator); - } - lastNumberOfNewLines += linesNumber; - line += linesNumber; - column = 1; - needSpace = false; - this.pendingSpace = false; - } else { - if ((lastNumberOfNewLines - 1) >= linesNumber) { - // there is no need to add new lines - return Util.EMPTY_STRING; - } - final int realNewLineNumber = linesNumber - lastNumberOfNewLines + 1; - for (int i = 0; i < realNewLineNumber; i++) { - if (indentEmptyLines) printIndentationIfNecessary(buffer); - buffer.append(this.lineSeparator); - } - lastNumberOfNewLines += realNewLineNumber; - line += realNewLineNumber; - column = 1; - needSpace = false; - this.pendingSpace = false; - } - return String.valueOf(buffer); - } - - public OptimizedReplaceEdit getLastEdit() { - if (this.editsIndex > 0) { - return this.edits[this.editsIndex - 1]; - } - return null; - } - Alignment2 getMemberAlignment() { - return this.memberAlignment; - } - - public String getNewLine() { - if (this.nlsTagCounter > 0) { - return Util.EMPTY_STRING; - } - if (lastNumberOfNewLines >= 1) { - column = 1; // ensure that the scribe is at the beginning of a new line - return Util.EMPTY_STRING; - } - line++; - lastNumberOfNewLines = 1; - column = 1; - needSpace = false; - this.pendingSpace = false; - return this.lineSeparator; - } - - /** - * Answer next indentation level based on column estimated position - * (if column is not indented, then use indentationLevel) - */ - public int getNextIndentationLevel(int someColumn) { - int indent = someColumn - 1; - if (indent == 0) - return this.indentationLevel; - if (this.tabChar == DefaultCodeFormatterOptions.TAB) { - if (this.useTabsOnlyForLeadingIndents) { - return indent; - } - int rem = indent % this.indentationSize; - int addition = rem == 0 ? 0 : this.indentationSize - rem; // round to superior - return indent + addition; - } else { - return indent; - } - } - - private String getPreserveEmptyLines(int count) { - if (count > 0) { - if (this.formatter.preferences.number_of_empty_lines_to_preserve != 0) { - int linesToPreserve = Math.min(count, this.formatter.preferences.number_of_empty_lines_to_preserve); - return this.getEmptyLines(linesToPreserve); - } else { - return getNewLine(); - } - } - return Util.EMPTY_STRING; - } - - public TextEdit getRootEdit() { - MultiTextEdit edit = null; - int length = this.textRegionEnd - this.textRegionStart + 1; - if (this.textRegionStart <= 0) { - if (length <= 0) { - edit = new MultiTextEdit(0, 0); - } else { - edit = new MultiTextEdit(0, this.textRegionEnd + 1); - } - } else { - edit = new MultiTextEdit(this.textRegionStart, this.textRegionEnd - this.textRegionStart + 1); - } - for (int i= 0, max = this.editsIndex; i < max; i++) { - OptimizedReplaceEdit currentEdit = edits[i]; - if (isValidEdit(currentEdit)) { - edit.addChild(new ReplaceEdit(currentEdit.offset, currentEdit.length, currentEdit.replacement)); - } - } - this.edits = null; - return edit; - } - - public void handleLineTooLong() { - // search for closest breakable alignment, using tiebreak rules - // look for outermost breakable one - int relativeDepth = 0, outerMostDepth = -1; - Alignment2 targetAlignment = this.currentAlignment; - while (targetAlignment != null){ - if (targetAlignment.tieBreakRule == Alignment.R_OUTERMOST && targetAlignment.couldBreak()){ - outerMostDepth = relativeDepth; - } - targetAlignment = targetAlignment.enclosing; - relativeDepth++; - } - if (outerMostDepth >= 0) { - throw new AlignmentException(AlignmentException.LINE_TOO_LONG, outerMostDepth); - } - // look for innermost breakable one - relativeDepth = 0; - targetAlignment = this.currentAlignment; - while (targetAlignment != null){ - if (targetAlignment.couldBreak()){ - throw new AlignmentException(AlignmentException.LINE_TOO_LONG, relativeDepth); - } - targetAlignment = targetAlignment.enclosing; - relativeDepth++; - } - // did not find any breakable location - proceed - } - - /* - * Check if there is a NLS tag on this line. If yes, return true, returns false otherwise. - */ - private boolean hasNLSTag(int sourceStart) { - final Comment comment = this.unit.getAST().newBlockComment(); - comment.setSourceRange(sourceStart, 1); - int index = Collections.binarySearch(this.comments, comment, new Comparator() { - public int compare(Object o1, Object o2) { - Comment comment1 = (Comment) o1; - Comment comment2 = (Comment) o2; - return comment1.getStartPosition() - comment2.getStartPosition(); - } - }); - final int lineNumber = this.unit.getLineNumber(sourceStart); - if (index < 0) { - index = -index - 1; - final int commentLength = this.comments.size(); - for (int i = index; i < commentLength; i++) { - Comment currentComment = (Comment) comments.get(i); - final int start = currentComment.getStartPosition(); - if (this.unit.getLineNumber(start) == lineNumber) { - if (currentComment.isLineComment()) { - return CharOperation.indexOf(Scanner.TAG_PREFIX, this.scanner.source, true, start) != -1; - } - } else { - return false; - } - } - } - return false; - } - - public void indent() { - this.indentationLevel += this.indentationSize; - this.numberOfIndentations++; - } - - /** - * @param compilationUnitSource - */ - public void initializeScanner(char[] compilationUnitSource) { - this.scanner.setSource(compilationUnitSource); - this.scannerEndPosition = compilationUnitSource.length; - this.scanner.resetTo(0, this.scannerEndPosition); - this.edits = new OptimizedReplaceEdit[INITIAL_SIZE]; - } - - private boolean isValidEdit(OptimizedReplaceEdit edit) { - final int editLength= edit.length; - final int editReplacementLength= edit.replacement.length(); - final int editOffset= edit.offset; - if (editLength != 0) { - if (this.textRegionStart <= editOffset && (editOffset + editLength - 1) <= this.textRegionEnd) { - if (editReplacementLength != 0 && editLength == editReplacementLength) { - for (int i = editOffset, max = editOffset + editLength; i < max; i++) { - if (scanner.source[i] != edit.replacement.charAt(i - editOffset)) { - return true; - } - } - return false; - } else { - return true; - } - } else if (editOffset + editLength == this.textRegionStart) { - int i = editOffset; - for (int max = editOffset + editLength; i < max; i++) { - int replacementStringIndex = i - editOffset; - if (replacementStringIndex >= editReplacementLength || scanner.source[i] != edit.replacement.charAt(replacementStringIndex)) { - break; - } - } - if (i - editOffset != editReplacementLength && i != editOffset + editLength - 1) { - edit.offset = textRegionStart; - edit.length = 0; - edit.replacement = edit.replacement.substring(i - editOffset); - return true; - } - } - } else if (this.textRegionStart <= editOffset && editOffset <= this.textRegionEnd) { - return true; - } else if (editOffset == this.scannerEndPosition && editOffset == this.textRegionEnd + 1) { - return true; - } - return false; - } - - private void preserveEmptyLines(int count, int insertPosition) { - if (count > 0) { - if (this.formatter.preferences.number_of_empty_lines_to_preserve != 0) { - int linesToPreserve = Math.min(count, this.formatter.preferences.number_of_empty_lines_to_preserve); - this.printEmptyLines(linesToPreserve, insertPosition); - } else { - printNewLine(insertPosition); - } - } - } - - private void print(char[] s, boolean considerSpaceIfAny) { - if (checkLineWrapping && s.length + column > this.pageWidth) { - handleLineTooLong(); - } - this.lastNumberOfNewLines = 0; - printIndentationIfNecessary(); - if (considerSpaceIfAny) { - this.space(); - } - if (this.pendingSpace) { - this.addInsertEdit(this.scanner.getCurrentTokenStartPosition(), " "); //$NON-NLS-1$ - } - this.pendingSpace = false; - this.needSpace = false; - column += s.length; - needSpace = true; - } - - private void printBlockComment(char[] s, boolean isJavadoc) { - int currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition(); - int currentTokenEndPosition = this.scanner.getCurrentTokenEndPosition() + 1; - - this.scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition - 1); - int currentCharacter; - boolean isNewLine = false; - int start = currentTokenStartPosition; - int nextCharacterStart = currentTokenStartPosition; - printIndentationIfNecessary(); - if (this.pendingSpace) { - this.addInsertEdit(currentTokenStartPosition, " "); //$NON-NLS-1$ - } - this.needSpace = false; - this.pendingSpace = false; - int previousStart = currentTokenStartPosition; - - while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = this.scanner.getNextChar()) != -1) { - nextCharacterStart = this.scanner.currentPosition; - - switch(currentCharacter) { - case '\r' : - start = previousStart; - isNewLine = true; - if (this.scanner.getNextChar('\n')) { - currentCharacter = '\n'; - nextCharacterStart = this.scanner.currentPosition; - } - break; - case '\n' : - start = previousStart; - isNewLine = true; - break; - default: - if (isNewLine) { - if (ScannerHelper.isWhitespace((char) currentCharacter)) { - int previousStartPosition = this.scanner.currentPosition; - while(currentCharacter != -1 && currentCharacter != '\r' && currentCharacter != '\n' && ScannerHelper.isWhitespace((char) currentCharacter)) { - previousStart = nextCharacterStart; - previousStartPosition = this.scanner.currentPosition; - currentCharacter = this.scanner.getNextChar(); - nextCharacterStart = this.scanner.currentPosition; - } - if (currentCharacter == '\r' || currentCharacter == '\n') { - nextCharacterStart = previousStartPosition; - } - } - this.column = 1; - this.line++; - - StringBuffer buffer = new StringBuffer(); - buffer.append(this.lineSeparator); - printIndentationIfNecessary(buffer); - buffer.append(' '); - - addReplaceEdit(start, previousStart - 1, String.valueOf(buffer)); - } else { - this.column += (nextCharacterStart - previousStart); - } - isNewLine = false; - } - previousStart = nextCharacterStart; - this.scanner.currentPosition = nextCharacterStart; - } - this.lastNumberOfNewLines = 0; - needSpace = false; - this.scanner.resetTo(currentTokenEndPosition, this.scannerEndPosition - 1); - if (isJavadoc) { - printNewLine(); - } - } - - public void printEndOfCompilationUnit() { - try { - // if we have a space between two tokens we ensure it will be dumped in the formatted string - int currentTokenStartPosition = this.scanner.currentPosition; - boolean hasComment = false; - boolean hasLineComment = false; - boolean hasWhitespace = false; - int count = 0; - while (true) { - this.currentToken = this.scanner.getNextToken(); - switch(this.currentToken) { - case TerminalTokens.TokenNameWHITESPACE : - char[] whiteSpaces = this.scanner.getCurrentTokenSource(); - count = 0; - for (int i = 0, max = whiteSpaces.length; i < max; i++) { - switch(whiteSpaces[i]) { - case '\r' : - if ((i + 1) < max) { - if (whiteSpaces[i + 1] == '\n') { - i++; - } - } - count++; - break; - case '\n' : - count++; - } - } - if (count == 0) { - hasWhitespace = true; - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else if (hasComment) { - if (count == 1) { - this.printNewLine(this.scanner.getCurrentTokenStartPosition()); - } else { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else if (hasLineComment) { - this.preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition()); - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else { - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = true; - count = 0; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = false; - hasComment = true; - count = 0; - break; - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printBlockComment(this.scanner.getRawTokenSource(), true); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = false; - hasComment = true; - count = 0; - break; - case TerminalTokens.TokenNameSEMICOLON : - char[] currentTokenSource = this.scanner.getRawTokenSource(); - this.print(currentTokenSource, this.formatter.preferences.insert_space_before_semicolon); - break; - case TerminalTokens.TokenNameEOF : - if (count >= 1 || this.formatter.preferences.insert_new_line_at_end_of_file_if_missing) { - this.printNewLine(this.scannerEndPosition); - } - return; - default : - // step back one token - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - public void printComment() { - try { - // if we have a space between two tokens we ensure it will be dumped in the formatted string - int currentTokenStartPosition = this.scanner.currentPosition; - boolean hasComment = false; - boolean hasLineComment = false; - boolean hasWhitespace = false; - int count = 0; - while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { - switch(this.currentToken) { - case TerminalTokens.TokenNameWHITESPACE : - char[] whiteSpaces = this.scanner.getCurrentTokenSource(); - count = 0; - for (int i = 0, max = whiteSpaces.length; i < max; i++) { - switch(whiteSpaces[i]) { - case '\r' : - if ((i + 1) < max) { - if (whiteSpaces[i + 1] == '\n') { - i++; - } - } - count++; - break; - case '\n' : - count++; - } - } - if (count == 0) { - hasWhitespace = true; - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else if (hasComment) { - if (count == 1) { - this.printNewLine(this.scanner.getCurrentTokenStartPosition()); - } else { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else if (hasLineComment) { - this.preserveEmptyLines(count, this.scanner.getCurrentTokenStartPosition()); - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } else if (count != 0 && this.formatter.preferences.number_of_empty_lines_to_preserve != 0) { - addReplaceEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition(), this.getPreserveEmptyLines(count - 1)); - } else { - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = true; - count = 0; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = false; - hasComment = true; - count = 0; - break; - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - if (count >= 1) { - if (count > 1) { - preserveEmptyLines(count - 1, this.scanner.getCurrentTokenStartPosition()); - } else if (count == 1) { - printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - } else if (hasWhitespace) { - space(); - } - hasWhitespace = false; - this.printBlockComment(this.scanner.getRawTokenSource(), true); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = false; - hasComment = true; - count = 0; - break; - default : - // step back one token - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - private void printCommentLine(char[] s) { - int currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition(); - int currentTokenEndPosition = this.scanner.getCurrentTokenEndPosition() + 1; - if (CharOperation.indexOf(Scanner.TAG_PREFIX, this.scanner.source, true, currentTokenStartPosition) != -1) { - this.nlsTagCounter = 0; - } - this.scanner.resetTo(currentTokenStartPosition, currentTokenEndPosition - 1); - int currentCharacter; - int start = currentTokenStartPosition; - int nextCharacterStart = currentTokenStartPosition; - printIndentationIfNecessary(); - if (this.pendingSpace) { - this.addInsertEdit(currentTokenStartPosition, " "); //$NON-NLS-1$ - } - this.needSpace = false; - this.pendingSpace = false; - int previousStart = currentTokenStartPosition; - - loop: while (nextCharacterStart <= currentTokenEndPosition && (currentCharacter = this.scanner.getNextChar()) != -1) { - nextCharacterStart = this.scanner.currentPosition; - - switch(currentCharacter) { - case '\r' : - start = previousStart; - break loop; - case '\n' : - start = previousStart; - break loop; - } - previousStart = nextCharacterStart; - } - if (start != currentTokenStartPosition) { - addReplaceEdit(start, currentTokenEndPosition - 1, lineSeparator); - } - line++; - column = 1; - needSpace = false; - this.pendingSpace = false; - lastNumberOfNewLines = 1; - // realign to the proper value - if (this.currentAlignment != null) { - if (this.memberAlignment != null) { - // select the last alignment - if (this.currentAlignment.location.inputOffset > this.memberAlignment.location.inputOffset) { - if (this.currentAlignment.couldBreak() && this.currentAlignment.wasSplit) { - this.currentAlignment.performFragmentEffect(); - } - } else { - this.indentationLevel = Math.max(this.indentationLevel, this.memberAlignment.breakIndentationLevel); - } - } else if (this.currentAlignment.couldBreak() && this.currentAlignment.wasSplit) { - this.currentAlignment.performFragmentEffect(); - } - } - this.scanner.resetTo(currentTokenEndPosition, this.scannerEndPosition - 1); - } - public void printEmptyLines(int linesNumber) { - this.printEmptyLines(linesNumber, this.scanner.getCurrentTokenEndPosition() + 1); - } - - private void printEmptyLines(int linesNumber, int insertPosition) { - final String buffer = getEmptyLines(linesNumber); - if (Util.EMPTY_STRING == buffer) return; - - addInsertEdit(insertPosition, buffer); - } - - void printIndentationIfNecessary() { - StringBuffer buffer = new StringBuffer(); - printIndentationIfNecessary(buffer); - if (buffer.length() > 0) { - addInsertEdit(this.scanner.getCurrentTokenStartPosition(), buffer.toString()); - this.pendingSpace = false; - } - } - - private void printIndentationIfNecessary(StringBuffer buffer) { - switch(this.tabChar) { - case DefaultCodeFormatterOptions.TAB : - boolean useTabsForLeadingIndents = this.useTabsOnlyForLeadingIndents; - int numberOfLeadingIndents = this.numberOfIndentations; - int indentationsAsTab = 0; - if (useTabsForLeadingIndents) { - while (this.column <= this.indentationLevel) { - if (indentationsAsTab < numberOfLeadingIndents) { - buffer.append('\t'); - indentationsAsTab++; - this.lastNumberOfNewLines = 0; - int complement = this.tabLength - ((this.column - 1) % this.tabLength); // amount of space - this.column += complement; - this.needSpace = false; - } else { - buffer.append(' '); - this.column++; - this.needSpace = false; - } - } - } else { - while (this.column <= this.indentationLevel) { - buffer.append('\t'); - this.lastNumberOfNewLines = 0; - int complement = this.tabLength - ((this.column - 1) % this.tabLength); // amount of space - this.column += complement; - this.needSpace = false; - } - } - break; - case DefaultCodeFormatterOptions.SPACE : - while (this.column <= this.indentationLevel) { - buffer.append(' '); - this.column++; - this.needSpace = false; - } - break; - case DefaultCodeFormatterOptions.MIXED : - useTabsForLeadingIndents = this.useTabsOnlyForLeadingIndents; - numberOfLeadingIndents = this.numberOfIndentations; - indentationsAsTab = 0; - if (useTabsForLeadingIndents) { - final int columnForLeadingIndents = numberOfLeadingIndents * this.indentationSize; - while (this.column <= this.indentationLevel) { - if (this.column <= columnForLeadingIndents) { - if ((this.column - 1 + this.tabLength) <= this.indentationLevel) { - buffer.append('\t'); - this.column += this.tabLength; - } else if ((this.column - 1 + this.indentationSize) <= this.indentationLevel) { - // print one indentation - for (int i = 0, max = this.indentationSize; i < max; i++) { - buffer.append(' '); - this.column++; - } - } else { - buffer.append(' '); - this.column++; - } - } else { - for (int i = this.column, max = this.indentationLevel; i <= max; i++) { - buffer.append(' '); - this.column++; - } - } - this.needSpace = false; - } - } else { - while (this.column <= this.indentationLevel) { - if ((this.column - 1 + this.tabLength) <= this.indentationLevel) { - buffer.append('\t'); - this.column += this.tabLength; - } else if ((this.column - 1 + this.indentationSize) <= this.indentationLevel) { - // print one indentation - for (int i = 0, max = this.indentationSize; i < max; i++) { - buffer.append(' '); - this.column++; - } - } else { - buffer.append(' '); - this.column++; - } - this.needSpace = false; - } - } - break; - } - } - - /** - * @param modifiers list of IExtendedModifiers - * @param visitor - */ - public void printModifiers(List modifiers, ASTVisitor visitor) { - try { - int modifiersIndex = 0; - boolean isFirstModifier = true; - int currentTokenStartPosition = this.scanner.currentPosition; - boolean hasComment = false; - while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { - switch(this.currentToken) { - case TerminalTokens.TokenNamepublic : - case TerminalTokens.TokenNameprotected : - case TerminalTokens.TokenNameprivate : - case TerminalTokens.TokenNamestatic : - case TerminalTokens.TokenNameabstract : - case TerminalTokens.TokenNamefinal : - case TerminalTokens.TokenNamenative : - case TerminalTokens.TokenNamesynchronized : - case TerminalTokens.TokenNametransient : - case TerminalTokens.TokenNamevolatile : - case TerminalTokens.TokenNamestrictfp : - this.print(this.scanner.getRawTokenSource(), !isFirstModifier); - isFirstModifier = false; - currentTokenStartPosition = this.scanner.currentPosition; - modifiersIndex++; - break; - case TerminalTokens.TokenNameAT : - if (!isFirstModifier) { - this.space(); - } - this.scanner.resetTo(this.scanner.getCurrentTokenStartPosition(), this.scannerEndPosition - 1); - ((Annotation) modifiers.get(modifiersIndex)).accept(visitor); - if (this.formatter.preferences.insert_new_line_after_annotation) { - this.printNewLine(); - } - isFirstModifier = false; - currentTokenStartPosition = this.scanner.currentPosition; - modifiersIndex++; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - hasComment = true; - break; - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - this.printBlockComment(this.scanner.getRawTokenSource(), true); - currentTokenStartPosition = this.scanner.currentPosition; - hasComment = true; - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameWHITESPACE : - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - int count = 0; - char[] whiteSpaces = this.scanner.getCurrentTokenSource(); - for (int i = 0, max = whiteSpaces.length; i < max; i++) { - switch(whiteSpaces[i]) { - case '\r' : - if ((i + 1) < max) { - if (whiteSpaces[i + 1] == '\n') { - i++; - } - } - count++; - break; - case '\n' : - count++; - } - } - if (count >= 1 && hasComment) { - printNewLine(); - } - currentTokenStartPosition = this.scanner.currentPosition; - hasComment = false; - break; - default: - // step back one token - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - public void printNewLine() { - if (this.nlsTagCounter > 0) { - return; - } - if (lastNumberOfNewLines >= 1) { - column = 1; // ensure that the scribe is at the beginning of a new line - return; - } - addInsertEdit(this.scanner.getCurrentTokenEndPosition() + 1, this.lineSeparator); - line++; - lastNumberOfNewLines = 1; - column = 1; - needSpace = false; - this.pendingSpace = false; - } - - public void printNewLine(int insertPosition) { - if (this.nlsTagCounter > 0) { - return; - } - if (lastNumberOfNewLines >= 1) { - column = 1; // ensure that the scribe is at the beginning of a new line - return; - } - addInsertEdit(insertPosition, this.lineSeparator); - line++; - lastNumberOfNewLines = 1; - column = 1; - needSpace = false; - this.pendingSpace = false; - } - - public void printNextToken(int expectedTokenType){ - printNextToken(expectedTokenType, false); - } - - public void printNextToken(int expectedTokenType, boolean considerSpaceIfAny){ - printComment(); - try { - this.currentToken = this.scanner.getNextToken(); - char[] currentTokenSource = this.scanner.getRawTokenSource(); - if (expectedTokenType != this.currentToken) { - throw new AbortFormatting("unexpected token type, expecting:"+expectedTokenType+", actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ - } - this.print(currentTokenSource, considerSpaceIfAny); - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - public void printNextToken(int[] expectedTokenTypes) { - printNextToken(expectedTokenTypes, false); - } - - public void printNextToken(int[] expectedTokenTypes, boolean considerSpaceIfAny){ - printComment(); - try { - this.currentToken = this.scanner.getNextToken(); - char[] currentTokenSource = this.scanner.getRawTokenSource(); - if (Arrays.binarySearch(expectedTokenTypes, this.currentToken) < 0) { - StringBuffer expectations = new StringBuffer(5); - for (int i = 0; i < expectedTokenTypes.length; i++){ - if (i > 0) { - expectations.append(','); - } - expectations.append(expectedTokenTypes[i]); - } - throw new AbortFormatting("unexpected token type, expecting:["+expectations.toString()+"], actual:"+this.currentToken);//$NON-NLS-1$//$NON-NLS-2$ - } - this.print(currentTokenSource, considerSpaceIfAny); - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - public void printArrayQualifiedReference(int numberOfTokens, int sourceEnd) { - int currentTokenStartPosition = this.scanner.currentPosition; - int numberOfIdentifiers = 0; - try { - do { - this.printComment(); - switch(this.currentToken = this.scanner.getNextToken()) { - case TerminalTokens.TokenNameEOF : - return; - case TerminalTokens.TokenNameWHITESPACE : - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameIdentifier : - this.print(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - if (++ numberOfIdentifiers == numberOfTokens) { - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - break; - case TerminalTokens.TokenNameDOT : - this.print(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - break; - default: - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } while (this.scanner.currentPosition <= sourceEnd); - } catch(InvalidInputException e) { - throw new AbortFormatting(e); - } - } -/* - public void printQualifiedReference(Name name) { - final int sourceEnd = name.getStartPosition() + name.getLength() - 1; - int currentTokenStartPosition = this.scanner.currentPosition; - try { - do { - this.printComment(); - switch(this.currentToken = this.scanner.getNextToken()) { - case TerminalTokens.TokenNameEOF : - return; - case TerminalTokens.TokenNameWHITESPACE : - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - case TerminalTokens.TokenNameCOMMENT_JAVADOC : - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - break; - case TerminalTokens.TokenNameIdentifier : - case TerminalTokens.TokenNameDOT : - this.print(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - break; - default: - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } while (this.scanner.currentPosition <= sourceEnd); - } catch(InvalidInputException e) { - throw new AbortFormatting(e); - } - } -*/ - private void printRule(StringBuffer stringBuffer) { - for (int i = 0; i < this.pageWidth; i++){ - if ((i % this.tabLength) == 0) { - stringBuffer.append('+'); - } else { - stringBuffer.append('-'); - } - } - stringBuffer.append(this.lineSeparator); - - for (int i = 0; i < (pageWidth / tabLength); i++) { - stringBuffer.append(i); - stringBuffer.append('\t'); - } - } - - public void printTrailingComment() { - try { - // if we have a space between two tokens we ensure it will be dumped in the formatted string - int currentTokenStartPosition = this.scanner.currentPosition; - boolean hasWhitespaces = false; - boolean hasComment = false; - boolean hasLineComment = false; - while ((this.currentToken = this.scanner.getNextToken()) != TerminalTokens.TokenNameEOF) { - switch(this.currentToken) { - case TerminalTokens.TokenNameWHITESPACE : - int count = 0; - char[] whiteSpaces = this.scanner.getCurrentTokenSource(); - for (int i = 0, max = whiteSpaces.length; i < max; i++) { - switch(whiteSpaces[i]) { - case '\r' : - if ((i + 1) < max) { - if (whiteSpaces[i + 1] == '\n') { - i++; - } - } - count++; - break; - case '\n' : - count++; - } - } - if (hasLineComment) { - if (count >= 1) { - currentTokenStartPosition = this.scanner.getCurrentTokenStartPosition(); - this.preserveEmptyLines(count, currentTokenStartPosition); - addDeleteEdit(currentTokenStartPosition, this.scanner.getCurrentTokenEndPosition()); - this.scanner.resetTo(this.scanner.currentPosition, this.scannerEndPosition - 1); - return; - } else { - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } else if (count >= 1) { - if (hasComment) { - this.printNewLine(this.scanner.getCurrentTokenStartPosition()); - } - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } else { - hasWhitespaces = true; - currentTokenStartPosition = this.scanner.currentPosition; - addDeleteEdit(this.scanner.getCurrentTokenStartPosition(), this.scanner.getCurrentTokenEndPosition()); - } - break; - case TerminalTokens.TokenNameCOMMENT_LINE : - if (hasWhitespaces) { - space(); - } - this.printCommentLine(this.scanner.getRawTokenSource()); - currentTokenStartPosition = this.scanner.currentPosition; - hasLineComment = true; - break; - case TerminalTokens.TokenNameCOMMENT_BLOCK : - if (hasWhitespaces) { - space(); - } - this.printBlockComment(this.scanner.getRawTokenSource(), false); - currentTokenStartPosition = this.scanner.currentPosition; - hasComment = true; - break; - default : - // step back one token - this.scanner.resetTo(currentTokenStartPosition, this.scannerEndPosition - 1); - return; - } - } - } catch (InvalidInputException e) { - throw new AbortFormatting(e); - } - } - - void redoAlignment(AlignmentException e){ - if (e.relativeDepth > 0) { // if exception targets a distinct context - e.relativeDepth--; // record fact that current context got traversed - this.currentAlignment = this.currentAlignment.enclosing; // pop currentLocation - throw e; // rethrow - } - // reset scribe/scanner to restart at this given location - this.resetAt(this.currentAlignment.location); - this.scanner.resetTo(this.currentAlignment.location.inputOffset, this.scanner.eofPosition); - // clean alignment chunkKind so it will think it is a new chunk again - this.currentAlignment.chunkKind = 0; - } - - void redoMemberAlignment(AlignmentException e){ - // reset scribe/scanner to restart at this given location - this.resetAt(this.memberAlignment.location); - this.scanner.resetTo(this.memberAlignment.location.inputOffset, this.scanner.eofPosition); - // clean alignment chunkKind so it will think it is a new chunk again - this.memberAlignment.chunkKind = 0; - } - - public void reset() { - this.checkLineWrapping = true; - this.line = 0; - this.column = 1; - this.editsIndex = 0; - this.nlsTagCounter = 0; - } - - private void resetAt(Location2 location) { - this.line = location.outputLine; - this.column = location.outputColumn; - this.indentationLevel = location.outputIndentationLevel; - this.numberOfIndentations = location.numberOfIndentations; - this.lastNumberOfNewLines = location.lastNumberOfNewLines; - this.needSpace = location.needSpace; - this.pendingSpace = location.pendingSpace; - this.editsIndex = location.editsIndex; - this.nlsTagCounter = location.nlsTagCounter; - if (this.editsIndex > 0) { - this.edits[this.editsIndex - 1] = location.textEdit; - } - } - - private void resize() { - System.arraycopy(this.edits, 0, (this.edits = new OptimizedReplaceEdit[this.editsIndex * 2]), 0, this.editsIndex); - } - - public void space() { - if (!this.needSpace) return; - this.lastNumberOfNewLines = 0; - this.pendingSpace = true; - this.column++; - this.needSpace = false; - } - - public String toString() { - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer - .append("(page width = " + this.pageWidth + ") - (tabChar = ");//$NON-NLS-1$//$NON-NLS-2$ - switch(this.tabChar) { - case DefaultCodeFormatterOptions.TAB : - stringBuffer.append("TAB");//$NON-NLS-1$ - break; - case DefaultCodeFormatterOptions.SPACE : - stringBuffer.append("SPACE");//$NON-NLS-1$ - break; - default : - stringBuffer.append("MIXED");//$NON-NLS-1$ - } - stringBuffer - .append(") - (tabSize = " + this.tabLength + ")")//$NON-NLS-1$//$NON-NLS-2$ - .append(this.lineSeparator) - .append("(line = " + this.line + ") - (column = " + this.column + ") - (identationLevel = " + this.indentationLevel + ")") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - .append(this.lineSeparator) - .append("(needSpace = " + this.needSpace + ") - (lastNumberOfNewLines = " + this.lastNumberOfNewLines + ") - (checkLineWrapping = " + this.checkLineWrapping + ")") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - .append(this.lineSeparator) - .append("==================================================================================") //$NON-NLS-1$ - .append(this.lineSeparator); - printRule(stringBuffer); - return stringBuffer.toString(); - } - - public void unIndent() { - this.indentationLevel -= this.indentationSize; - this.numberOfIndentations--; - } -} Index: formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java =================================================================== RCS file: /cvsroot/eclipse/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java,v retrieving revision 1.78 diff -u -r1.78 DefaultCodeFormatterOptions.java --- formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java 21 Nov 2006 00:39:17 -0000 1.78 +++ formatter/org/eclipse/jdt/internal/formatter/DefaultCodeFormatterOptions.java 2 Feb 2007 01:28:57 -0000 @@ -97,7 +97,9 @@ public int blank_lines_at_beginning_of_method_body; public boolean comment_clear_blank_lines; - public boolean comment_format; + public boolean comment_format_javadoc_comment; + public boolean comment_format_line_comment; + public boolean comment_format_block_comment; public boolean comment_format_header; public boolean comment_format_html; public boolean comment_format_source; @@ -354,7 +356,9 @@ options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION, this.brace_position_for_type_declaration); options.put(DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH, this.brace_position_for_switch); options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_CLEAR_BLANK_LINES, this.comment_clear_blank_lines ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); - options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT, this.comment_format ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); + options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, this.comment_format_javadoc_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); + options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, this.comment_format_line_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); + options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT, this.comment_format_block_comment ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER, this.comment_format_header ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HTML, this.comment_format_html ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); options.put(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_SOURCE, this.comment_format_source ? DefaultCodeFormatterConstants.TRUE : DefaultCodeFormatterConstants.FALSE); @@ -1019,10 +1023,18 @@ if (commentClearBlankLinesOption != null) { this.comment_clear_blank_lines = DefaultCodeFormatterConstants.TRUE.equals(commentClearBlankLinesOption); } - final Object commentFormatOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT); - if (commentFormatOption != null) { - this.comment_format = DefaultCodeFormatterConstants.TRUE.equals(commentFormatOption); - } + final Object commentFormatJavadocCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT); + if (commentFormatJavadocCommentOption != null) { + this.comment_format_javadoc_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatJavadocCommentOption); + } + final Object commentFormatBlockCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT); + if (commentFormatBlockCommentOption != null) { + this.comment_format_block_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatBlockCommentOption); + } + final Object commentFormatLineCommentOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT); + if (commentFormatLineCommentOption != null) { + this.comment_format_line_comment = DefaultCodeFormatterConstants.TRUE.equals(commentFormatLineCommentOption); + } final Object commentFormatHeaderOption = settings.get(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_HEADER); if (commentFormatHeaderOption != null) { this.comment_format_header = DefaultCodeFormatterConstants.TRUE.equals(commentFormatHeaderOption); @@ -1895,7 +1907,9 @@ this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE; this.comment_clear_blank_lines = false; - this.comment_format = true; + this.comment_format_block_comment = true; + this.comment_format_javadoc_comment = true; + this.comment_format_line_comment = true; this.comment_format_header = false; this.comment_format_html = true; this.comment_format_source = true; @@ -2151,7 +2165,9 @@ this.brace_position_for_type_declaration = DefaultCodeFormatterConstants.END_OF_LINE; this.brace_position_for_switch = DefaultCodeFormatterConstants.END_OF_LINE; this.comment_clear_blank_lines = false; - this.comment_format = true; + this.comment_format_block_comment = true; + this.comment_format_javadoc_comment = true; + this.comment_format_line_comment = true; this.comment_format_header = false; this.comment_format_html = true; this.comment_format_source = true; Index: model/org/eclipse/jdt/internal/core/JavaModelManager.java =================================================================== RCS file: /cvsroot/eclipse/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java,v retrieving revision 1.352 diff -u -r1.352 JavaModelManager.java --- model/org/eclipse/jdt/internal/core/JavaModelManager.java 31 Jan 2007 20:01:58 -0000 1.352 +++ model/org/eclipse/jdt/internal/core/JavaModelManager.java 2 Feb 2007 01:28:59 -0000 @@ -60,7 +60,6 @@ import org.eclipse.jdt.internal.core.util.Util; import org.eclipse.jdt.internal.core.util.WeakHashSet; import org.eclipse.jdt.internal.core.util.WeakHashSetOfCharArray; -import org.eclipse.jdt.internal.formatter.DefaultCodeFormatter; import org.osgi.service.prefs.BackingStoreException; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -194,8 +193,6 @@ public static final String CONTAINER_INITIALIZER_PERF = JavaCore.PLUGIN_ID + "/perf/containerinitializer" ; //$NON-NLS-1$ public static final String RECONCILE_PERF = JavaCore.PLUGIN_ID + "/perf/reconcile" ; //$NON-NLS-1$ - private static final String ENABLE_NEW_FORMATTER = JavaCore.PLUGIN_ID + "/formatter/enable_new" ; //$NON-NLS-1$ - private final static String INDEXED_SECONDARY_TYPES = "#@*_indexing secondary cache_*@#"; //$NON-NLS-1$ public static boolean PERF_VARIABLE_INITIALIZER = false; @@ -1263,9 +1260,6 @@ option = Platform.getDebugOption(SOURCE_MAPPER_DEBUG_VERBOSE); if(option != null) SourceMapper.VERBOSE = option.equalsIgnoreCase(TRUE) ; - - option = Platform.getDebugOption(ENABLE_NEW_FORMATTER); - if(option != null) DefaultCodeFormatter.USE_NEW_FORMATTER = option.equalsIgnoreCase(TRUE) ; } // configure performance options Index: formatter/org/eclipse/jdt/internal/formatter/align/Alignment2.java =================================================================== RCS file: formatter/org/eclipse/jdt/internal/formatter/align/Alignment2.java diff -N formatter/org/eclipse/jdt/internal/formatter/align/Alignment2.java --- formatter/org/eclipse/jdt/internal/formatter/align/Alignment2.java 23 Oct 2006 16:41:07 -0000 1.3 +++ /dev/null 1 Jan 1970 00:00:00 -0000 @@ -1,417 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation 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: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.formatter.align; - -import org.eclipse.jdt.internal.formatter.Location2; -import org.eclipse.jdt.internal.formatter.Scribe2; - -/** - * Alignment management - * - * @since 2.1 - */ -public class Alignment2 { - - // name of alignment - public String name; - - // link to enclosing alignment - public Alignment2 enclosing; - - // start location of this alignment - public Location2 location; - - // indentation management - public int fragmentIndex; - public int fragmentCount; - public int[] fragmentIndentations; - public boolean needRedoColumnAlignment; - - // chunk management - public int chunkStartIndex; - public int chunkKind; - - // break management - public int originalIndentationLevel; - public int breakIndentationLevel; - public int shiftBreakIndentationLevel; - public int[] fragmentBreaks; - public boolean wasSplit; - - public Scribe2 scribe; - - /* - * Alignment modes - */ - public static final int M_FORCE = 1; // if bit set, then alignment will be non-optional (default is optional) - public static final int M_INDENT_ON_COLUMN = 2; // if bit set, broken fragments will be aligned on current location column (default is to break at current indentation level) - public static final int M_INDENT_BY_ONE = 4; // if bit set, broken fragments will be indented one level below current (not using continuation indentation) - - // split modes can be combined either with M_FORCE or M_INDENT_ON_COLUMN - - /** foobar(#fragment1, #fragment2,
#fragment1A | #fragment2A | #fragment3A | #very-long-fragment4A |
#fragment1B | #long-fragment2B | #fragment3B | #fragment4B |
#very-long-fragment1C | #fragment2C | #fragment3C | #fragment4C |