Example usage for org.eclipse.jdt.core.dom ASTParser K_STATEMENTS

List of usage examples for org.eclipse.jdt.core.dom ASTParser K_STATEMENTS

Introduction

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

Prototype

int K_STATEMENTS

To view the source code for org.eclipse.jdt.core.dom ASTParser K_STATEMENTS.

Click Source Link

Document

Kind constant used to request that the source be parsed as a sequence of statements.

Usage

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

License:Open Source License

private ASTNode parseSourceCode(int kind) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    Map<String, String> parserOptions = JavaCore.getOptions();
    parserOptions.put(CompilerOptions.OPTION_Source, this.sourceLevel);
    parser.setCompilerOptions(parserOptions);

    switch (kind & K_MASK) {
    case K_COMPILATION_UNIT:
        return parseSourceCode(parser, ASTParser.K_COMPILATION_UNIT, true);
    case K_CLASS_BODY_DECLARATIONS:
        return parseSourceCode(parser, ASTParser.K_CLASS_BODY_DECLARATIONS, false);
    case K_STATEMENTS:
        return parseSourceCode(parser, ASTParser.K_STATEMENTS, false);
    case K_EXPRESSION:
        return parseSourceCode(parser, ASTParser.K_EXPRESSION, false);
    case K_UNKNOWN:
        int[] parserModes = { ASTParser.K_COMPILATION_UNIT, ASTParser.K_EXPRESSION,
                ASTParser.K_CLASS_BODY_DECLARATIONS, ASTParser.K_STATEMENTS };
        for (int parserMode : parserModes) {
            ASTNode astNode = parseSourceCode(parser, parserMode, false);
            if (astNode != null)
                return astNode;
            parser.setCompilerOptions(parserOptions); // parser loses compiler options after every use
        }/* ww w  . jav a 2  s  . c om*/
        return null;
    default:
        throw new IllegalArgumentException();
    }
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAbstractAstNodeModelAdapter.java

License:Open Source License

/**
 * Creates a {@link Type} from the given name, owned by the given AST.
 *///from w w  w . j  a va 2  s . co m
protected Type getTypeFromString(AST ast, String name) {
    if (name == null) {
        return ast.newPrimitiveType(PrimitiveType.VOID);
    }
    PrimitiveType.Code primitiveTypeCode = PrimitiveType.toCode(name);
    if (primitiveTypeCode != null) {
        return ast.newPrimitiveType(primitiveTypeCode);
    }

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_STATEMENTS);
    parser.setSource((name + " a;").toCharArray());

    Block block = (Block) parser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType());
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Creates a new appropriate {@link Type} from the given <code>value</code>.
 * <p>/*w w w .  java2  s. c  o m*/
 * Note that if <code>value</code> is <code>null</code> returns
 * {@link PrimitiveType#VOID}.
 * 
 * @param ast
 *            {@link AST} of the {@link ASTNode ASTElement} needing a new
 *            Type
 * @param value
 *            the name of the {@link Type} to be created.
 * @param canBePrimitiveType
 *            if <code>true</code> try to create a primitive from the
 *            given <code>value</code> if possible, otherwise create a new
 *            Type without checking primitives
 * @author Luiza
 * 
 * @flowerModelElementId _zVs8hZiOEd6aNMdNFvR5WQ
 */
public static Type getJavaTypeFromString(AST ast, String value, boolean canBePrimitiveType) {
    if (canBePrimitiveType) {
        PrimitiveType.Code primitiveTypeCode = null;
        if (value == null)
            primitiveTypeCode = PrimitiveType.VOID;
        else {
            primitiveTypeCode = PrimitiveType.toCode(value);
        }
        if (primitiveTypeCode != null)
            return ast.newPrimitiveType(primitiveTypeCode);
    }

    // not a primitive
    ASTParser statementParser = ASTParser.newParser(AST.JLS3);
    statementParser.setKind(ASTParser.K_STATEMENTS);
    statementParser.setSource((value + " a;").toCharArray()); // try to parse a variable declaration

    Block block = (Block) statementParser.createAST(null);
    VariableDeclarationStatement declaration = (VariableDeclarationStatement) block.statements().get(0);
    return (Type) ASTNode.copySubtree(ast, declaration.getType()); // detach the type from the parent node
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.JavaSyncUtils.java

License:Open Source License

/**
 * Creates a new block and adds it as body to the given {@link MethodDeclaration}.
 * //from w  w w  .j  ava 2s  .c o  m
 * @param md - the {@link MethodDeclaration} that requires a new body block.
 * @param blockString - the {@link String} that will form the block content.
 * 
 * @author Luiza
 */
public static void generateBodyForMethod(MethodDeclaration md, String blockString) {
    AST ast = md.getAST();
    ASTParser statementParser = ASTParser.newParser(AST.JLS3);
    statementParser.setKind(ASTParser.K_STATEMENTS);
    // parse the block
    statementParser.setSource(blockString.toCharArray());
    Block block = (Block) statementParser.createAST(null);
    block = (Block) ASTNode.copySubtree(ast, block);

    md.setBody(block);
}

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

License:Apache License

/** Runs the Google Java formatter on the given source, with only the given ranges specified. */
private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) {
    try {/*from ww  w .  j a  v a  2s.  c om*/
        boolean includeComments = (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS;
        kind &= ~CodeFormatter.F_INCLUDE_COMMENTS;
        SnippetKind snippetKind;
        switch (kind) {
        case ASTParser.K_EXPRESSION:
            snippetKind = SnippetKind.EXPRESSION;
            break;
        case ASTParser.K_STATEMENTS:
            snippetKind = SnippetKind.STATEMENTS;
            break;
        case ASTParser.K_CLASS_BODY_DECLARATIONS:
            snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS;
            break;
        case ASTParser.K_COMPILATION_UNIT:
            snippetKind = SnippetKind.COMPILATION_UNIT;
            break;
        default:
            throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind));
        }
        List<Replacement> replacements = new SnippetFormatter().format(snippetKind, source,
                rangesFromRegions(regions), initialIndent, includeComments);
        if (idempotent(source, regions, replacements)) {
            // Do not create edits if there's no diff.
            return null;
        }
        // Convert replacements to text edits.
        return editFromReplacements(replacements);
    } catch (IllegalArgumentException | FormatterException exception) {
        // Do not format on errors.
        return null;
    }
}

From source file:com.kodebeagle.javaparser.JavaASTParser.java

License:Apache License

/**
 * Return an ASTNode given the content/*from w w w  .j  a va2s  .c o m*/
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content, final ParseType parseType) {
    final ASTParser parser = ASTParser.newParser(AST.JLS8);
    final int astKind;
    switch (parseType) {
    case CLASS_BODY:
    case METHOD:
        astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
        break;
    case COMPILATION_UNIT:
        astKind = ASTParser.K_COMPILATION_UNIT;
        break;
    case EXPRESSION:
        astKind = ASTParser.K_EXPRESSION;
        break;
    case STATEMENTS:
        astKind = ASTParser.K_STATEMENTS;
        break;
    default:
        astKind = ASTParser.K_COMPILATION_UNIT;
    }
    parser.setKind(astKind);

    final Map<String, String> options = new Hashtable<String, String>();
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
    if (useJavadocs) {
        options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
    }
    parser.setCompilerOptions(options);
    parser.setSource(content);
    parser.setResolveBindings(useBindings);
    parser.setBindingsRecovery(useBindings);
    parser.setStatementsRecovery(true);

    if (parseType != ParseType.METHOD) {
        return parser.createAST(null);
    } else {
        final ASTNode cu = parser.createAST(null);
        return getFirstMethodDeclaration(cu);
    }
}

From source file:net.atos.optimus.common.tools.jdt.ASTHelper.java

License:Open Source License

/**
 * Return the hashCode of a Java method body.
 * //from w ww .j  a  v a  2s.c om
 * @param methodBody
 *            The method body as a String
 * @return the hashCode of a Java method body
 */
public static int methodBodyHashCode(String methodBody) {

    // Create an ASTParser from this expected body
    astp.setSource(methodBody.toCharArray());
    astp.setKind(ASTParser.K_STATEMENTS);

    // Create an AST tree from this method body
    Block b = (Block) astp.createAST(null);

    return methodBodyHashCode(b);
}

From source file:org.eclipse.jet.internal.runtime.model.jdt.JavaLoader.java

License:Open Source License

/**
 * @param kind/*from   w  w  w. j  a va2 s.com*/
 * @return
 */
private int getKind(String kind) {
    if ("classbodydeclarations".equalsIgnoreCase(kind)) { //$NON-NLS-1$
        return ASTParser.K_CLASS_BODY_DECLARATIONS;
    } else if ("expression".equals(kind)) { //$NON-NLS-1$
        return ASTParser.K_EXPRESSION;

    } else if ("statements".equals(kind)) { //$NON-NLS-1$
        return ASTParser.K_STATEMENTS;
    } else {
        return ASTParser.K_COMPILATION_UNIT;
    }

}

From source file:org.eclipse.jet.internal.taglib.java.ImportTag.java

License:Open Source License

public String doFunction(TagInfo tc, JET2Context context, String bodyContent) throws JET2TagException {
    final ImportManager importManager = JavaActionsUtil.getImportManager(getOut());
    ASTParser parser = ASTParser.newParser(AST.JLS3);

    // create a jface Document to track positions of replaceable text...
    final IDocument document = new Document();
    document.set(bodyContent);//from w  w w  .j a v  a  2 s.  c o m

    // create a Java statement with the type declaration
    String varDeclStatement = bodyContent + " x;"; //$NON-NLS-1$
    // ... and get an AST for it ...
    parser.setSource(varDeclStatement.toCharArray());
    parser.setKind(ASTParser.K_STATEMENTS);
    Block syntheticBlock = (Block) parser.createAST(null);

    // visit the AST, looking for Java 'simple types'
    syntheticBlock.accept(new ASTVisitor() {
        public boolean visit(SimpleType node) {
            // register the fully qualified name with the import manager
            final String fullyQualifiedName = node.getName().getFullyQualifiedName();
            importManager.addImport(fullyQualifiedName);
            try {
                // register the position so we can replace it later, once we have
                // recorded the positions of all the qualified names...
                document.addPosition(
                        new Position(node.getName().getStartPosition(), node.getName().getLength()));
            } catch (BadLocationException e) {
                // should not happen, ignore
            }
            return super.visit(node);
        }
    });

    // Now run through all saved positions, and replace the original text with
    // the short name from the import manager...
    try {
        final Position[] positions = document.getPositions(IDocument.DEFAULT_CATEGORY);
        for (int i = 0; i < positions.length; i++) {
            String qualifiedName = document.get(positions[i].offset, positions[i].length);
            document.replace(positions[i].offset, positions[i].length,
                    importManager.getImportedName(qualifiedName));
        }
    } catch (BadPositionCategoryException e) {
        // should not happen, ignore
    } catch (BadLocationException e) {
        // should not happen, ignore
    }

    return document.get();
}

From source file:org.eclipse.objectteams.otdt.ui.tests.dom.rewrite.ASTRewritingModifyingTeamTest.java

License:Open Source License

public void test0004() throws Exception {

    // generate some AST:
    String generated = "public team class MyTeam {\n" + "   protected class DisposeWatcher playedBy Item {\n"
            + "       void bar() { nop(); }\n" + "   }\n" + "}\n";

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_STATEMENTS);
    parser.setSource(generated.toCharArray());

    Block block = (Block) parser.createAST(null);
    TypeDeclarationStatement st = (TypeDeclarationStatement) block.statements().get(0);
    TypeDeclaration decl = (TypeDeclaration) st.getDeclaration();
    ASTNode[] myNodes = (ASTNode[]) decl.bodyDeclarations().toArray(new ASTNode[1]);

    // create a CU to copy into:
    String existing = "public team class MyTeam {\n" + "   protected class OtherRole {}\n"
            + "   void foo() { System.out.println(this); }\n" + "}\n";
    parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(existing.toCharArray());
    CompilationUnit _astCU = (CompilationUnit) parser.createAST(null);
    TypeDeclaration teamDecl = (TypeDeclaration) _astCU.types().get(0);

    // copy generated into CU:
    _astCU.recordModifications();/* w  ww  .  j  av a  2s  . c  o m*/
    teamDecl.bodyDeclarations().add(ASTNode.copySubtree(_astCU.getAST(), myNodes[0]));

    // apply change:
    Document doc = new Document(existing);
    TextEdit edits = _astCU.rewrite(doc, null);
    edits.apply(doc);

    // compare result with expected:
    String newSource = doc.get();
    String expected = "public team class MyTeam {\n" + "   protected class OtherRole {}\n"
            + "   void foo() { System.out.println(this); }\n"
            + "    protected class DisposeWatcher playedBy Item {\n" + "        void bar() {\n"
            + "            nop();\n" + "        }\n" + "    }\n" + "}\n";
    assertEquals(expected, newSource);
}