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

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

Introduction

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

Prototype

int K_EXPRESSION

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

Click Source Link

Document

Kind constant used to request that the source be parsed as a single expression.

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
        }/*from   w w  w. j a  v  a 2  s .  co  m*/
        return null;
    default:
        throw new IllegalArgumentException();
    }
}

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

License:Open Source License

/**
 * Creates an {@link Expression} from the given string, owned by the given AST. 
 *///from   w ww .ja v  a2 s  .  com
protected Expression getExpressionFromString(AST ast, String expression) {
    if (expression == null) {
        return null;
    }
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_EXPRESSION);
    parser.setSource(expression.toCharArray());
    ASTNode node = parser.createAST(null);
    return (Expression) ASTNode.copySubtree(ast, node);
}

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

License:Open Source License

@Override
protected void setASTFeatureValue(EStructuralFeature feature, FieldDeclaration astElement, Object value)
        throws CodeSyncException {
    if (astElement == null)
        throw new IllegalArgumentException("astElement null ");
    AST ast = astElement.getAST();//from w w w  . j av  a2 s .  c o  m
    switch (feature.getFeatureID()) {
    case UMLPackage.NAMED_ELEMENT__NAME:
        if (astElement.fragments().size() == 0)
            throw new IllegalArgumentException("bad assumption size always >0");
        if (value == null)
            throw new IllegalArgumentException("setting name to null value ");
        ((VariableDeclarationFragment) astElement.fragments().get(0))
                .setName(ast.newSimpleName((String) value));
        break;
    case UMLPackage.TYPED_ELEMENT__TYPE:
        String newType = value != null ? ((Type) value).getName() : null;
        if (newType == null)
            throw new IllegalArgumentException("Field has type null: " + astElement);
        parentForwardJavaClass_OwnedFields.parentForwardJavaType.parentForwardJavaSrcDir_Files
                .createImportDeclarationIfNeeded((Type) value);
        astElement.setType(JavaSyncUtils.getJavaTypeFromString(ast, newType, true));
        break;
    case UMLPackage.PROPERTY__DEFAULT_VALUE:
        String newDefaultValue = (LiteralString) value == null ? null : ((LiteralString) value).getValue();
        Expression e = null;
        if (newDefaultValue != null && !newDefaultValue.equals("")) {
            ASTParser expressionParser = ASTParser.newParser(AST.JLS3);
            expressionParser.setKind(ASTParser.K_EXPRESSION);
            expressionParser.setSource(newDefaultValue.toCharArray());
            e = (Expression) expressionParser.createAST(null);
            e = (Expression) ASTNode.copySubtree(ast, e);
        }
        ((VariableDeclarationFragment) astElement.fragments().get(0)).setInitializer(e);
        break;
    default:
        super.setASTFeatureValue(feature, astElement, value);
    }
}

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

License:Open Source License

/**
 * Parse the given {@link String value} into a java expression.
 * //from  w  w  w  .j a v  a2 s  . co m
 * @author Luiza
 */
private static Expression makeExpression(AST ast, String value) {
    ASTParser expressionParser = ASTParser.newParser(AST.JLS3);
    expressionParser.setKind(ASTParser.K_EXPRESSION);
    expressionParser.setSource(value.toCharArray());
    Expression expression = (Expression) expressionParser.createAST(null);
    return (Expression) ASTNode.copySubtree(ast, expression);
}

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 va 2 s .  c o m*/
        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  v  a  2s  .c  om*/
 *
 * @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:edu.illinois.keshmesh.transformer.core.LCK02JFixer.java

License:Open Source License

@Override
public Change createChange(IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException {
    ITextFileBufferManager textFileBufferManager = null;
    try {// w w  w.  java  2s  .  c  om
        //Retrieving the Document out of IPath
        textFileBufferManager = FileBuffers.getTextFileBufferManager();
        textFileBufferManager.connect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
        ITextFileBuffer textFileBuffer = textFileBufferManager.getTextFileBuffer(bugPosition.getSourcePath(),
                LocationKind.IFILE);
        IDocument document = textFileBuffer.getDocument();
        try {
            Logger.log(document.get(bugPosition.getFirstOffset(), bugPosition.getLength()));
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }
        // Parsing the Document
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(document.get().toCharArray());
        parser.setResolveBindings(true);
        CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(progressMonitor);

        //Rewriting the AST
        int bugLineOffset = document.getLineInformation(bugPosition.getFirstLine() - 1).getOffset();
        int bugLineLength = document.getLineInformation(bugPosition.getFirstLine() - 1).getLength();
        String bugLineContent = document.get(bugLineOffset, bugLineLength);
        String syncCommand = "synchronized";

        int syncIndex = bugLineContent.indexOf(syncCommand);
        int start_comment_index = bugLineContent.indexOf("/*");
        int end_comment_index = bugLineContent.indexOf("*/");
        String temp_bugLineContent = bugLineContent;
        int temp_syncIndex = syncIndex;
        int temp_beginIndex = 0;

        // there is a possibility of having synchronized word within comments
        while (start_comment_index >= 0 && end_comment_index > 0 && temp_bugLineContent.length() > 0
                && temp_syncIndex > start_comment_index) {
            temp_beginIndex += (end_comment_index + 2);
            temp_bugLineContent = temp_bugLineContent.substring(end_comment_index + 2);
            temp_syncIndex = temp_bugLineContent.indexOf(syncCommand);
            start_comment_index = temp_bugLineContent.indexOf("/*");
            end_comment_index = temp_bugLineContent.indexOf("*/");
            syncIndex = temp_beginIndex + temp_syncIndex;
        }

        String bugLineContentAfterSynch = bugLineContent.substring(syncIndex + syncCommand.length());
        int openParenthesisIndex = bugLineContentAfterSynch.indexOf('(') + syncIndex + syncCommand.length();
        int myFirstOffset = bugLineOffset + syncIndex;
        int index = openParenthesisIndex;
        int pcounter = 1;
        while (pcounter != 0 && index < bugLineLength) {
            index++;
            if (bugLineContent.charAt(index) == ')') {
                pcounter--;
            } else if (bugLineContent.charAt(index) == '(') {
                pcounter++;
            }
        }

        int myLastOffset = bugLineOffset + index;
        ASTNode monitorNode = NodeFinder.perform(compilationUnit, myFirstOffset,
                myLastOffset - myFirstOffset + 1);
        SynchronizedStatement synchronizedStatement = (SynchronizedStatement) monitorNode;
        AST ast = synchronizedStatement.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        ASTParser expressionParser = ASTParser.newParser(AST.JLS3);
        expressionParser.setKind(ASTParser.K_EXPRESSION);
        expressionParser
                .setSource(CollectionUtils.getTheOnlyElementOf(fixInformation.getTypeNames()).toCharArray());
        ASTNode astNode = expressionParser.createAST(progressMonitor);
        rewriter.set(synchronizedStatement, SynchronizedStatement.EXPRESSION_PROPERTY, astNode, null);
        TextEdit textEdit = rewriter.rewriteAST(document, null);
        try {
            textEdit.apply(document);
        } catch (MalformedTreeException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }

        //Committing changes to the source file
        textFileBuffer.commit(progressMonitor, true);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    } finally {
        textFileBufferManager.disconnect(bugPosition.getSourcePath(), LocationKind.LOCATION, progressMonitor);
    }
    return null;
}

From source file:org.asup.dk.compiler.rpj.writer.JDTCallableUnitWriter.java

License:Open Source License

private Expression buildExpression(String expression) {

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_EXPRESSION);

    parser.setSource(expression.toCharArray());
    ASTNode node = parser.createAST(null);
    if (node.getLength() == 0)
        throw new IntegratedLanguageExpressionRuntimeException("Invalid java conversion: " + expression);

    Expression jdtExpression = (Expression) node;

    return (Expression) ASTNode.copySubtree(getAST(), jdtExpression);
}

From source file:org.asup.dk.compiler.rpj.writer.JDTCallableUnitWriter.java

License:Open Source License

private Expression buildExpression(AST ast, QExpression expression, Class<?> target) {

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_EXPRESSION);

    JDTExpressionStringBuilder builder = getCompilationUnit().getContext()
            .make(JDTExpressionStringBuilder.class);
    builder.setTarget(target);/*  ww  w  . ja v a 2s .c om*/
    expression.accept(builder);
    String value = builder.getResult();

    parser.setSource(value.toCharArray());
    ASTNode node = parser.createAST(null);
    if (node.getLength() == 0)
        throw new IntegratedLanguageExpressionRuntimeException("Invalid java conversion: " + value);

    Expression jdtExpression = (Expression) node;

    return (Expression) ASTNode.copySubtree(ast, jdtExpression);
}

From source file:org.asup.dk.compiler.rpj.writer.JDTStatementWriter.java

License:Open Source License

private Expression buildExpression(AST ast, QExpression expression, Class<?> target) {

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_EXPRESSION);

    JDTExpressionStringBuilder builder = compilationUnit.getContext().make(JDTExpressionStringBuilder.class);
    builder.setTarget(target);//from  www.ja va  2  s .c  om
    expression.accept(builder);
    String value = builder.getResult();

    parser.setSource(value.toCharArray());
    ASTNode node = parser.createAST(null);
    if (node.getLength() == 0)
        throw new IntegratedLanguageExpressionRuntimeException("Invalid java conversion: " + value);

    Expression jdtExpression = (Expression) node;

    return (Expression) ASTNode.copySubtree(ast, jdtExpression);
}