Example usage for org.eclipse.jdt.core.dom EnumDeclaration bodyDeclarations

List of usage examples for org.eclipse.jdt.core.dom EnumDeclaration bodyDeclarations

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom EnumDeclaration bodyDeclarations.

Prototype

public List bodyDeclarations() 

Source Link

Document

Returns the live ordered list of body declarations of this type declaration.

Usage

From source file:at.bestsolution.fxide.jdt.corext.dom.ASTFlattener.java

License:Open Source License

@Override
public boolean visit(EnumDeclaration node) {
    if (node.getJavadoc() != null) {
        node.getJavadoc().accept(this);
    }//  w w  w .j  a  v a 2 s.  c om
    printModifiers(node.modifiers());
    this.fBuffer.append("enum ");//$NON-NLS-1$
    node.getName().accept(this);
    this.fBuffer.append(" ");//$NON-NLS-1$
    if (!node.superInterfaceTypes().isEmpty()) {
        this.fBuffer.append("implements ");//$NON-NLS-1$
        for (Iterator<Type> it = node.superInterfaceTypes().iterator(); it.hasNext();) {
            Type t = it.next();
            t.accept(this);
            if (it.hasNext()) {
                this.fBuffer.append(", ");//$NON-NLS-1$
            }
        }
        this.fBuffer.append(" ");//$NON-NLS-1$
    }
    this.fBuffer.append("{");//$NON-NLS-1$
    for (Iterator<EnumConstantDeclaration> it = node.enumConstants().iterator(); it.hasNext();) {
        EnumConstantDeclaration d = it.next();
        d.accept(this);
        // enum constant declarations do not include punctuation
        if (it.hasNext()) {
            // enum constant declarations are separated by commas
            this.fBuffer.append(", ");//$NON-NLS-1$
        }
    }
    if (!node.bodyDeclarations().isEmpty()) {
        this.fBuffer.append("; ");//$NON-NLS-1$
        for (Iterator<BodyDeclaration> it = node.bodyDeclarations().iterator(); it.hasNext();) {
            BodyDeclaration d = it.next();
            d.accept(this);
            // other body declarations include trailing punctuation
        }
    }
    this.fBuffer.append("}");//$NON-NLS-1$
    return false;
}

From source file:coloredide.utils.CopiedNaiveASTFlattener.java

License:Open Source License

public boolean visit(EnumDeclaration node) {
    if (node.getJavadoc() != null) {
        node.getJavadoc().accept(this);
    }/*w w w  .ja va 2s  . c o  m*/
    printIndent();
    printModifiers(node.modifiers());
    this.buffer.append("enum ");//$NON-NLS-1$
    node.getName().accept(this);
    this.buffer.append(" ");//$NON-NLS-1$
    if (!node.superInterfaceTypes().isEmpty()) {
        this.buffer.append("implements ");//$NON-NLS-1$
        for (Iterator it = node.superInterfaceTypes().iterator(); it.hasNext();) {
            Type t = (Type) it.next();
            t.accept(this);
            if (it.hasNext()) {
                this.buffer.append(", ");//$NON-NLS-1$
            }
        }
        this.buffer.append(" ");//$NON-NLS-1$
    }
    this.buffer.append("{");//$NON-NLS-1$
    for (Iterator it = node.enumConstants().iterator(); it.hasNext();) {
        EnumConstantDeclaration d = (EnumConstantDeclaration) it.next();
        d.accept(this);
        // enum constant declarations do not include punctuation
        if (it.hasNext()) {
            // enum constant declarations are separated by commas
            this.buffer.append(", ");//$NON-NLS-1$
        }
    }
    if (!node.bodyDeclarations().isEmpty()) {
        this.buffer.append("; ");//$NON-NLS-1$
        for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext();) {
            BodyDeclaration d = (BodyDeclaration) it.next();
            d.accept(this);
            // other body declarations include trailing punctuation
        }
    }
    this.buffer.append("}\n");//$NON-NLS-1$
    return false;
}

From source file:com.bsiag.eclipse.jdt.java.formatter.LineBreaksPreparator.java

License:Open Source License

@Override
public boolean visit(EnumDeclaration node) {
    handleBracedCode(node, node.getName(), this.options.brace_position_for_enum_declaration,
            this.options.indent_body_declarations_compare_to_enum_declaration_header,
            this.options.insert_new_line_in_empty_enum_declaration);
    handleBodyDeclarations(node.bodyDeclarations());

    List<EnumConstantDeclaration> enumConstants = node.enumConstants();
    for (int i = 0; i < enumConstants.size(); i++) {
        EnumConstantDeclaration declaration = enumConstants.get(i);
        if (declaration.getJavadoc() != null)
            this.tm.firstTokenIn(declaration, TokenNameCOMMENT_JAVADOC).breakBefore();
        if (declaration.getAnonymousClassDeclaration() != null && i < enumConstants.size() - 1)
            this.tm.firstTokenAfter(declaration, TokenNameCOMMA).breakAfter();
    }//from  ww w.  j a v  a2 s  . com

    // put breaks after semicolons
    int index = enumConstants.isEmpty() ? this.tm.firstIndexAfter(node.getName(), TokenNameLBRACE) + 1
            : this.tm.firstIndexAfter(enumConstants.get(enumConstants.size() - 1), -1);
    for (;; index++) {
        Token token = this.tm.get(index);
        if (token.isComment())
            continue;
        if (token.tokenType == TokenNameSEMICOLON)
            token.breakAfter();
        else
            break;
    }

    this.declarationModifierVisited = false;
    return true;
}

From source file:com.bsiag.eclipse.jdt.java.formatter.linewrap.WrapPreparator.java

License:Open Source License

@Override
public boolean visit(EnumDeclaration node) {
    List<EnumConstantDeclaration> enumConstants = node.enumConstants();
    if (!enumConstants.isEmpty()) {
        for (EnumConstantDeclaration constant : enumConstants)
            this.wrapIndexes.add(this.tm.firstIndexIn(constant, -1));
        this.wrapParentIndex = this.tm.firstIndexBefore(enumConstants.get(0), TokenNameLBRACE);
        this.wrapGroupEnd = this.tm.lastIndexIn(enumConstants.get(enumConstants.size() - 1), -1);
        handleWrap(this.options.alignment_for_enum_constants, node);
    }// w w w .j  av a2s. c  o m

    List<Type> superInterfaceTypes = node.superInterfaceTypes();
    if (!superInterfaceTypes.isEmpty()) {
        this.wrapIndexes.add(this.tm.firstIndexBefore(superInterfaceTypes.get(0), TokenNameimplements));
        for (Type type : superInterfaceTypes)
            this.wrapIndexes.add(this.tm.firstIndexIn(type, -1));
        this.wrapParentIndex = this.tm.lastIndexIn(node.getName(), -1);
        this.wrapGroupEnd = this.tm.lastIndexIn(superInterfaceTypes.get(superInterfaceTypes.size() - 1), -1);
        this.wrapPenalties.add(PREFERRED);
        handleWrap(this.options.alignment_for_superinterfaces_in_enum_declaration, node);
    }

    if (this.options.align_type_members_on_columns)
        this.fieldAligner.prepareAlign(node.bodyDeclarations());

    return true;
}

From source file:com.github.parzonka.ccms.engine.SortElementsOperation.java

License:Open Source License

private ASTRewrite sortCompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit ast,
        final TextEditGroup group) {
    ast.accept(new ASTVisitor() {
        @Override//www. j  av  a  2 s. com
        public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) {
            final List<AbstractTypeDeclaration> types = compilationUnit.types();
            for (final Iterator<AbstractTypeDeclaration> iter = types.iterator(); iter.hasNext();) {
                final AbstractTypeDeclaration typeDeclaration = iter.next();
                typeDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(typeDeclaration.getStartPosition()));
                compilationUnit.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(typeDeclaration)));
            }
            return true;
        }

        @Override
        public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) {
            final List bodyDeclarations = annotationTypeDeclaration.bodyDeclarations();
            for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
                final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
                bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(bodyDeclaration.getStartPosition()));
                annotationTypeDeclaration.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(bodyDeclaration)));
            }
            return true;
        }

        @Override
        public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) {
            final List bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
            for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
                final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
                bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(bodyDeclaration.getStartPosition()));
                anonymousClassDeclaration.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(bodyDeclaration)));
            }
            return true;
        }

        @Override
        public boolean visit(TypeDeclaration typeDeclaration) {
            final List bodyDeclarations = typeDeclaration.bodyDeclarations();
            for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
                final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
                bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(bodyDeclaration.getStartPosition()));
                typeDeclaration.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(bodyDeclaration)));
            }
            return true;
        }

        @Override
        public boolean visit(EnumDeclaration enumDeclaration) {
            final List bodyDeclarations = enumDeclaration.bodyDeclarations();
            for (final Iterator iter = bodyDeclarations.iterator(); iter.hasNext();) {
                final BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
                bodyDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(bodyDeclaration.getStartPosition()));
                enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(bodyDeclaration)));
            }
            final List enumConstants = enumDeclaration.enumConstants();
            for (final Iterator iter = enumConstants.iterator(); iter.hasNext();) {
                final EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) iter.next();
                enumConstantDeclaration.setProperty(CompilationUnitSorter.RELATIVE_ORDER,
                        new Integer(enumConstantDeclaration.getStartPosition()));
                enumDeclaration.setProperty(CONTAINS_MALFORMED_NODES,
                        Boolean.valueOf(isMalformed(enumConstantDeclaration)));
            }
            return true;
        }
    });

    final ASTRewrite rewriter = ASTRewrite.create(ast.getAST());
    final boolean[] hasChanges = new boolean[] { false };

    ast.accept(new ASTVisitor() {

        /**
         * This
         *
         * @param elements
         * @param listRewrite
         */
        private void sortElements(List<BodyDeclaration> elements, ListRewrite listRewrite) {
            if (elements.size() == 0)
                return;

            final List<BodyDeclaration> myCopy = new ArrayList<BodyDeclaration>();
            myCopy.addAll(elements);

            // orderexperiment
            final List<Signature> methods = new ArrayList<Signature>();
            for (final BodyDeclaration bd : myCopy) {
                if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) {
                    methods.add(new Signature((MethodDeclaration) bd));
                }
            }
            Collections.sort(methods, ((BodyDeclarationComparator) SortElementsOperation.this.comparator)
                    .getMethodDeclarationComparator());
            logger.info("Sorting of methods based on appearance:");
            int j = 0;
            for (final Signature sig : methods) {
                logger.info("Method [{}] : {}", ++j, sig);
            }

            Collections.sort(myCopy, SortElementsOperation.this.comparator);

            logger.info("Final sorting order just before the AST-Rewrite:");
            for (final BodyDeclaration bd : myCopy) {
                if (bd.getNodeType() == ASTNode.METHOD_DECLARATION) {
                    logger.info("{}", new Signature((MethodDeclaration) bd));
                } else {
                    logger.info("{}", bd.toString());
                }
            }

            for (int i = 0; i < elements.size(); i++) {
                final BodyDeclaration oldNode = elements.get(i);

                final BodyDeclaration newNode = myCopy.get(i);

                if (oldNode != newNode) {
                    if (oldNode.getNodeType() == ASTNode.METHOD_DECLARATION
                            && newNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
                        final Signature oldMethodSignature = new Signature((MethodDeclaration) oldNode);
                        final Signature newMethodSignature = new Signature((MethodDeclaration) newNode);
                        logger.trace("Swapping [{}]for [{}]", oldMethodSignature, newMethodSignature);
                    } else {
                        logger.trace("Swapping [{}]for [{}]", oldNode.getNodeType(), newNode.getNodeType());
                    }
                    listRewrite.replace(oldNode, rewriter.createMoveTarget(newNode), group);
                    hasChanges[0] = true;
                }
            }
        }

        @Override
        public boolean visit(org.eclipse.jdt.core.dom.CompilationUnit compilationUnit) {
            if (checkMalformedNodes(compilationUnit)) {
                logger.warn("Malformed nodes. Aborting sorting of current element.");
                return true;
            }

            sortElements(compilationUnit.types(), rewriter.getListRewrite(compilationUnit,
                    org.eclipse.jdt.core.dom.CompilationUnit.TYPES_PROPERTY));
            return true;
        }

        @Override
        public boolean visit(AnnotationTypeDeclaration annotationTypeDeclaration) {
            if (checkMalformedNodes(annotationTypeDeclaration)) {
                logger.warn("Malformed nodes. Aborting sorting of current element.");
                return true;
            }

            sortElements(annotationTypeDeclaration.bodyDeclarations(), rewriter.getListRewrite(
                    annotationTypeDeclaration, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY));
            return true;
        }

        @Override
        public boolean visit(AnonymousClassDeclaration anonymousClassDeclaration) {
            if (checkMalformedNodes(anonymousClassDeclaration)) {
                logger.warn("Malformed nodes. Aborting sorting of current element.");
                return true;
            }

            sortElements(anonymousClassDeclaration.bodyDeclarations(), rewriter.getListRewrite(
                    anonymousClassDeclaration, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY));
            return true;
        }

        @Override
        public boolean visit(TypeDeclaration typeDeclaration) {
            if (checkMalformedNodes(typeDeclaration)) {
                logger.warn("Malformed nodes. Aborting sorting of current element.");
                return true;
            }

            sortElements(typeDeclaration.bodyDeclarations(),
                    rewriter.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY));
            return true;
        }

        @Override
        public boolean visit(EnumDeclaration enumDeclaration) {
            if (checkMalformedNodes(enumDeclaration)) {
                return true; // abort sorting of current element
            }

            sortElements(enumDeclaration.bodyDeclarations(),
                    rewriter.getListRewrite(enumDeclaration, EnumDeclaration.BODY_DECLARATIONS_PROPERTY));
            sortElements(enumDeclaration.enumConstants(),
                    rewriter.getListRewrite(enumDeclaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY));
            return true;
        }
    });

    if (!hasChanges[0])
        return null;

    return rewriter;
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

License:Open Source License

private static int numberOfConstructors(org.eclipse.jdt.core.dom.ASTNode node) {
    int count = 0;
    if (node instanceof org.eclipse.jdt.core.dom.TypeDeclaration) {
        org.eclipse.jdt.core.dom.TypeDeclaration typeDecl = (org.eclipse.jdt.core.dom.TypeDeclaration) node;
        for (org.eclipse.jdt.core.dom.MethodDeclaration methodDecl : typeDecl.getMethods()) {
            if (methodDecl.isConstructor()) {
                count++;/*from   ww  w.  ja  v  a 2s. com*/
            }
        }
        return count;
    }
    if (node instanceof EnumDeclaration) {
        EnumDeclaration enumDecl = (EnumDeclaration) node;
        for (Object child : (List<?>) enumDecl.bodyDeclarations()) {
            if (child instanceof org.eclipse.jdt.core.dom.MethodDeclaration) {
                org.eclipse.jdt.core.dom.MethodDeclaration methodDecl = (org.eclipse.jdt.core.dom.MethodDeclaration) child;
                if (methodDecl.isConstructor()) {
                    count++;
                }
            }
        }
        return count;
    }
    throw new UnsupportedOperationException("not implemented: " + node.getClass());
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean visit(org.eclipse.jdt.core.dom.EnumDeclaration node) {
    SimpleIdentifier name = translateSimpleName(node.getName());
    // implements
    ImplementsClause implementsClause;//from  w w  w.j ava 2s . com
    {
        List<TypeName> interfaces = Lists.newArrayList();
        // add Comparable
        interfaces.add(typeName("Comparable", typeName(name)));
        // add declared interfaces
        if (!node.superInterfaceTypes().isEmpty()) {
            for (Object javaInterface : node.superInterfaceTypes()) {
                interfaces.add((TypeName) translate((org.eclipse.jdt.core.dom.ASTNode) javaInterface));
            }
        }
        // create ImplementsClause
        implementsClause = new ImplementsClause(null, interfaces);
    }
    // members
    List<ClassMember> members = Lists.newArrayList();
    {
        // constants
        List<Expression> valuesList = Lists.newArrayList();
        for (Object javaConst : node.enumConstants()) {
            org.eclipse.jdt.core.dom.EnumConstantDeclaration javaEnumConst = (org.eclipse.jdt.core.dom.EnumConstantDeclaration) javaConst;
            members.add((FieldDeclaration) translate(javaEnumConst));
            valuesList.add(identifier(javaEnumConst.getName().getIdentifier()));
        }
        // values
        members.add(fieldDeclaration(true, Keyword.FINAL, listType(typeName(name), 1),
                variableDeclaration("values", listLiteral(valuesList))));
        // body declarations
        members.add(fieldDeclaration(eolDocComment(ENUM_NAME_FIELD_COMMENT), false, Keyword.FINAL,
                typeName("String"), variableDeclaration(ENUM_NAME_FIELD_NAME)));
        members.add(fieldDeclaration(eolDocComment(ENUM_ORDINAL_FIELD_COMMENT), false, Keyword.FINAL,
                typeName("int"), variableDeclaration(ENUM_ORDINAL_FIELD_NAME)));
        boolean hasConstructor = false;
        for (Iterator<?> I = node.bodyDeclarations().iterator(); I.hasNext();) {
            org.eclipse.jdt.core.dom.BodyDeclaration javaBodyDecl = (org.eclipse.jdt.core.dom.BodyDeclaration) I
                    .next();
            constructorImpl = null;
            ClassMember member = translate(javaBodyDecl);
            members.add(member);
            if (constructorImpl != null) {
                members.add(constructorImpl);
            }
            if (javaBodyDecl instanceof org.eclipse.jdt.core.dom.MethodDeclaration) {
                if (((org.eclipse.jdt.core.dom.MethodDeclaration) javaBodyDecl).isConstructor()) {
                    hasConstructor = true;
                }
            }
        }
        // add default constructor, use artificial constructor
        if (!hasConstructor) {
            org.eclipse.jdt.core.dom.MethodDeclaration ac = node.getAST().newMethodDeclaration();
            try {
                ac.setConstructor(true);
                ac.setName(node.getAST().newSimpleName(name.getName()));
                ac.setBody(node.getAST().newBlock());
                node.bodyDeclarations().add(ac);
                ConstructorDeclaration innerConstructor = translate(ac);
                members.add(innerConstructor);
                if (constructorImpl != null) {
                    members.add(constructorImpl);
                }
            } finally {
                node.bodyDeclarations().remove(ac);
            }
        }
        // compareTo()
        members.add(methodDeclaration(typeName("int"), identifier("compareTo"),
                formalParameterList(simpleFormalParameter(typeName(name), "other")),
                expressionFunctionBody(binaryExpression(identifier(ENUM_ORDINAL_FIELD_NAME), TokenType.MINUS,
                        propertyAccess(identifier("other"), identifier(ENUM_ORDINAL_FIELD_NAME))))));
        // toString()
        members.add(methodDeclaration(typeName("String"), identifier("toString"), formalParameterList(),
                expressionFunctionBody(identifier(ENUM_NAME_FIELD_NAME))));
    }
    return done(classDeclaration(translateJavadoc(node), name, null, null, implementsClause, members));
}

From source file:com.google.devtools.j2cpp.gen.CppImplementationGenerator.java

License:Open Source License

@Override
protected void generate(EnumDeclaration node) {
    @SuppressWarnings("unchecked")
    List<EnumConstantDeclaration> constants = node.enumConstants(); // safe by definition
    List<MethodDeclaration> methods = Lists.newArrayList();
    List<FieldDeclaration> fields = Lists.newArrayList();
    MethodDeclaration initializeMethod = null;
    @SuppressWarnings("unchecked")
    List<BodyDeclaration> declarations = node.bodyDeclarations(); // safe by definition
    for (BodyDeclaration decl : declarations) {
        if (decl instanceof FieldDeclaration) {
            fields.add((FieldDeclaration) decl);
        } else if (decl instanceof MethodDeclaration) {
            MethodDeclaration md = (MethodDeclaration) decl;
            if (md.getName().getIdentifier().equals("initialize")) {
                initializeMethod = md;/*from   w w  w  . jav  a  2  s  .  c  o m*/
            } else {
                methods.add(md);
            }
        }
    }
    syncLineNumbers(node.getName()); // avoid doc-comment

    String typeName = NameTable.getFullName(node);
    for (EnumConstantDeclaration constant : constants) {
        printf("static %s *%s_%s;\n", typeName, typeName, NameTable.getName(constant.getName()));
    }
    printf("IOSObjectArray *%s_values;\n", typeName);
    newline();

    printf("@implementation %s\n\n", typeName);
    printStaticVars(fields);

    for (EnumConstantDeclaration constant : constants) {
        String name = NameTable.getName(constant.getName());
        printf("+ (%s *)%s {\n", typeName, name);
        printf("  return %s_%s;\n", typeName, name);
        println("}");
    }
    newline();

    // Enum constants needs to implement NSCopying.  Being singletons, they
    // can just return self, as long the retain count is incremented.
    String selfString = Options.useReferenceCounting() ? "[self retain]" : "self";
    printf("- (id)copyWithZone:(NSZone *)zone {\n  return %s;\n}\n\n", selfString);

    printProperties(fields.toArray(new FieldDeclaration[0]));
    printMethods(methods);

    printf("+ (void)initialize {\n  if (self == [%s class]) {\n", typeName);
    for (int i = 0; i < constants.size(); i++) {
        EnumConstantDeclaration constant = constants.get(i);
        @SuppressWarnings("unchecked")
        List<Expression> args = constant.arguments(); // safe by definition
        String name = NameTable.getName(constant.getName());
        String constantTypeName = NameTable.getFullName(Types.getMethodBinding(constant).getDeclaringClass());
        printf("    %s_%s = [[%s alloc] init", typeName, name, constantTypeName);
        boolean isSimpleEnum = constantTypeName.equals(typeName);

        // Common-case: no extra fields and no constant anonymous classes.
        if (args.isEmpty() && isSimpleEnum) {
            printf("WithNSString:@\"%s_%s\" withInt:%d];\n", typeName.replace("Enum", ""), name, i);
        } else {
            String argString = CppStatementGenerator.generateArguments(Types.getMethodBinding(constant), args,
                    fieldHiders, getBuilder().getCurrentLine());
            print(argString);
            if (args.isEmpty()) {
                print("With");
            } else {
                print(" with");
            }
            printf("NSString:@\"%s_%s\" withInt:%d];\n", typeName.replace("Enum", ""), name, i);
        }
    }
    printf("    %s_values = [[IOSObjectArray alloc] initWithObjects:(id[]){ ", typeName);
    for (EnumConstantDeclaration constant : constants) {
        printf("%s_%s, ", typeName, NameTable.getName(constant.getName()));
    }
    printf("nil } count:%d type:[IOSClass classWithClass:[%s class]]];\n", constants.size(), typeName);
    if (initializeMethod != null) {
        @SuppressWarnings("unchecked")
        List<Statement> stmts = initializeMethod.getBody().statements(); // safe by definition
        for (Statement s : stmts) {
            printf("    %s",
                    CppStatementGenerator.generate(s, fieldHiders, false, getBuilder().getCurrentLine()));
        }
    }
    println("  }\n}\n");

    // Print generated values and valueOf methods.
    println("+ (IOSObjectArray *)values {");
    printf("  return [IOSObjectArray arrayWithArray:%s_values];\n", typeName);
    println("}\n");
    printf("+ (%s *)valueOfWithNSString:(NSString *)name {\n", typeName);
    printf("  for (int i = 0; i < [%s_values count]; i++) {\n", typeName);
    printf("    %s *e = [%s_values objectAtIndex:i];\n", typeName, typeName);
    printf("    if ([name isEqual:[e name]]) {\n");
    printf("      return e;\n");
    printf("    }\n");
    printf("  }\n");
    printf("  @throw [[JavaLangIllegalArgumentException alloc] initWithNSString:name];\n");
    printf("  return nil;\n");
    println("}\n");

    println("@end");
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* www.  j  a  v  a 2 s .  c om*/
public void endVisit(EnumDeclaration node) {
    ITypeBinding binding = node.resolveBinding();
    List<BodyDeclaration> body = node.bodyDeclarations();
    eliminateDeadCode(binding, body);
    generateMissingMethods(node.getAST(), binding, body);
    if (deadCodeMap.isDeadClass(Types.getSignature(node.resolveBinding()))) {
        // Dead enum means none of the constants are ever used, so they can all be deleted.
        node.enumConstants().clear();
    }
    finishElimination();
}

From source file:com.google.googlejavaformat.java.JavaInputAstVisitor.java

License:Apache License

/** Visitor method for {@link EnumDeclaration}s. */
@Override/*from   w  ww.ja va2 s .  c  om*/
public boolean visit(EnumDeclaration node) {
    sync(node);
    builder.open(ZERO);
    visitAndBreakModifiers(node.modifiers(), Direction.VERTICAL, Optional.<BreakTag>absent());
    builder.open(plusFour);
    token("enum");
    builder.breakOp(" ");
    visit(node.getName());
    builder.close();
    builder.close();
    if (!node.superInterfaceTypes().isEmpty()) {
        builder.open(plusFour);
        builder.breakOp(" ");
        builder.open(plusFour);
        token("implements");
        builder.breakOp(" ");
        builder.open(ZERO);
        boolean first = true;
        for (Type superInterfaceType : (List<Type>) node.superInterfaceTypes()) {
            if (!first) {
                token(",");
                builder.breakToFill(" ");
            }
            superInterfaceType.accept(this);
            first = false;
        }
        builder.close();
        builder.close();
        builder.close();
    }
    builder.space();
    tokenBreakTrailingComment("{", plusTwo);
    if (node.enumConstants().isEmpty() && node.bodyDeclarations().isEmpty()) {
        builder.open(ZERO);
        builder.blankLineWanted(BlankLineWanted.NO);
        token("}");
        builder.close();
    } else {
        builder.open(plusTwo);
        builder.blankLineWanted(BlankLineWanted.NO);
        builder.forcedBreak();
        builder.open(ZERO);
        boolean first = true;
        for (EnumConstantDeclaration enumConstant : (List<EnumConstantDeclaration>) node.enumConstants()) {
            if (!first) {
                token(",");
                builder.forcedBreak();
            }
            visit(enumConstant);
            first = false;
        }
        if (builder.peekToken().or("").equals(",")) {
            token(",");
            builder.forcedBreak(); // The ";" goes on its own line.
        }
        builder.close();
        builder.close();
        builder.open(ZERO);
        if (node.bodyDeclarations().isEmpty()) {
            builder.guessToken(";");
        } else {
            token(";");
            builder.forcedBreak();
            addBodyDeclarations(node.bodyDeclarations(), BracesOrNot.NO, FirstDeclarationsOrNot.NO);
        }
        builder.forcedBreak();
        builder.blankLineWanted(BlankLineWanted.NO);
        token("}", plusTwo);
        builder.close();
    }
    builder.guessToken(";");
    return false;
}