Java Code Examples for org.eclipse.jdt.core.dom.ASTParser#setKind()

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setKind() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ValidationTestBase.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
protected CompilationUnit prepareAST(String javaFile) throws IOException {
	File projectRoot = new File(VALIDATION_EXAMPLES_ROOT).getAbsoluteFile();
	File sourceFile = new File(projectRoot.getCanonicalPath() + getValidationExamplesPackage() + javaFile);

	ASTParser parser = ASTParser.newParser(AST.JLS8);
	char[] content = SharedUtils.getFileContents(sourceFile);

	String[] classpath = {};
	String[] sourcepath = { projectRoot.getCanonicalPath(), new File(API_SRC_LOC).getCanonicalPath() };
	String[] encodings = { "UTF-8", "UTF-8" };

	parser.setSource(content);

	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setUnitName(sourceFile.getName());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setEnvironment(classpath, sourcepath, encodings, true);

	return (CompilationUnit) parser.createAST(null);
}
 
Example 2
Source File: SORecommender.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private HashMap<String, HashSet<String>> parseKCUnit(String snippet) throws IOException {
	HashMap<String, HashSet<String>> tokens = new HashMap<String, HashSet<String>>();
	ASTParser parser = ASTParser.newParser(AST.JLS9);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(snippet.toCharArray());
	parser.setResolveBindings(true);
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	parser.setCompilerOptions(options);
	try {
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);
		MyASTVisitor myVisitor = new MyASTVisitor();
		cu.accept(myVisitor);
		tokens = myVisitor.getTokens();
	} catch (Exception exc) {
		logger.error("JDT parsing error");
	}
	return tokens;
}
 
Example 3
Source File: BoaAstIntrinsics.java    From compiler with Apache License 2.0 5 votes vote down vote up
@FunctionSpec(name = "parse", returnType = "ASTRoot", formalParameters = { "string" })
public static ASTRoot parse(final String s) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(s.toCharArray());

	@SuppressWarnings("rawtypes")
	final Map options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
	parser.setCompilerOptions(options);

	final ASTRoot.Builder ast = ASTRoot.newBuilder();
	try {
		final org.eclipse.jdt.core.dom.CompilationUnit cu = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);
		final JavaErrorCheckVisitor errorCheck = new JavaErrorCheckVisitor();
		cu.accept(errorCheck);

		if (!errorCheck.hasError) {
			final JavaVisitor visitor = new JavaVisitor(s);
			ast.addNamespaces(visitor.getNamespaces(cu));
		}
	} catch (final Exception e) {
		// do nothing
	}

	return ast.build();
}
 
Example 4
Source File: CompilationUnitParser.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public CompilationUnit parse(ICompilationUnit unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    parser.setProject(unit.getJavaProject());
    parser.setUnitName(unit.getPath().toString());
    return (CompilationUnit) parser.createAST(null);
}
 
Example 5
Source File: APIUsageExtractor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
private Set<Slice> generateExamples() {
	Set<Slice> slices = new HashSet<>();

	File srcFile = new File(srcPath);
	String[] testPaths = getTestFiles(srcFile).parallelStream().map(File::getAbsolutePath).toArray(String[]::new);
	String[] folderPaths = getAllFiles(srcFile).parallelStream().map(File::getParentFile).map(File::getAbsolutePath).toArray(String[]::new);

	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setEnvironment(null, folderPaths, null, true);
	parser.setResolveBindings(true);
	Map<String, String> options = new Hashtable<>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	parser.setCompilerOptions(options);
	parser.setBindingsRecovery(true);
	parser.createASTs(testPaths, null, new String[]{}, new FileASTRequestor() {
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit javaUnit) {
			APIMethodVisitor visitor = new APIMethodVisitor();
			javaUnit.accept(visitor);
			slices.addAll(visitor.getSlices());
		}
	}, null);
	return slices;
}
 
Example 6
Source File: ASTGenerator.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static ASTNode genAST(String source, int type){
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(source.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	return astParser.createAST(null);
}
 
Example 7
Source File: JavaFileParser.java    From buck with Apache License 2.0 5 votes vote down vote up
private CompilationUnit makeCompilationUnitFromSource(String code) {
  ASTParser parser = ASTParser.newParser(jlsLevel);
  parser.setSource(code.toCharArray());
  parser.setKind(ASTParser.K_COMPILATION_UNIT);

  Map<String, String> options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(javaVersion, options);
  parser.setCompilerOptions(options);

  return (CompilationUnit) parser.createAST(/* monitor */ null);
}
 
Example 8
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding findTypeBinding(IType currentType) throws JavaModelException{
  final ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  parser.setSource(currentType.getCompilationUnit());
  parser.setResolveBindings(true);
  CompilationUnit unit = (CompilationUnit) parser.createAST(null);
  return ASTNodes.getTypeBinding(unit, currentType);
}
 
Example 9
Source File: JavaParser.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public AST generate(String filename, String source, String[] srcFolders) {
	AST ast = new AST();
	ast.setFileName(filename);
	ast.setSource(source);

	ASTParser parser = ASTParser.newParser(org.eclipse.jdt.core.dom.AST.JLS10);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setBindingsRecovery(true);
	parser.setCompilerOptions(JavaCore.getOptions());
	parser.setUnitName(filename);
	parser.setSource(source.toCharArray());

	parser.setEnvironment(null, srcFolders, null, true);
	
	CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	FileVisitor visitor = new FileVisitor();
	cu.accept(visitor);

	ast.setImports(visitor.getImports());
	ast.setPackageDeclaration(visitor.getPackageName());
	ast.setTypes(visitor.getTypes());
	ast.setLanguage(Language.JAVA);

	return ast;
}
 
Example 10
Source File: ReferencedClassesParser.java    From BUILD_file_generator with Apache License 2.0 5 votes vote down vote up
private static ASTParser createCompilationUnitParser() {
  ASTParser parser = ASTParser.newParser(AST.JLS8);
  Map options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
  parser.setCompilerOptions(options);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  return parser;
}
 
Example 11
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<ClassObject> parseAST(ICompilationUnit iCompilationUnit) {
	ASTInformationGenerator.setCurrentITypeRoot(iCompilationUnit);
	IFile iFile = (IFile)iCompilationUnit.getResource();
       ASTParser parser = ASTParser.newParser(JLS);
       parser.setKind(ASTParser.K_COMPILATION_UNIT);
       parser.setSource(iCompilationUnit);
       parser.setResolveBindings(true); // we need bindings later on
       CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
       
       return parseAST(compilationUnit, iFile);
}
 
Example 12
Source File: SurroundWithTemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean isNewContext() {

	final String templateVariableRegEx= "\\$\\{[^\\}]*\\}"; //$NON-NLS-1$

	String template= fTemplate.getPattern();
	int currentPosition= template.indexOf($_LINE_SELECTION);
	int insertionPosition= -1;
	while (currentPosition != -1) {
		insertionPosition= currentPosition;
		template= template.replaceFirst(templateVariableRegEx, ""); //$NON-NLS-1$
		currentPosition= template.indexOf($_LINE_SELECTION);
	}
	template= template.replaceAll(templateVariableRegEx, ""); //$NON-NLS-1$

	AST ast= getAst();
	ASTParser parser= ASTParser.newParser(ast.apiLevel());
	parser.setSource(template.toCharArray());
	parser.setProject(fCurrentProject);
	parser.setKind(ASTParser.K_STATEMENTS);
	ASTNode root= parser.createAST(null);
	if (((Block)root).statements().isEmpty()) {
		parser= ASTParser.newParser(ast.apiLevel());
		parser.setSource(template.toCharArray());
		parser.setProject(fCurrentProject);
		parser.setKind(ASTParser.K_EXPRESSION);
		root= parser.createAST(null);
	}

	final int lineSelectionPosition= insertionPosition;
	root.accept(new GenericVisitor() {
		@Override
		public void endVisit(Block node) {
			super.endVisit(node);
			if (fTemplateNode == null && node.getStartPosition() <= lineSelectionPosition && node.getLength() + node.getStartPosition() >= lineSelectionPosition) {
				fTemplateNode= node;
			}
		}
	});

	if (fTemplateNode != null && ASTNodes.getParent(fTemplateNode, MethodDeclaration.class) != null) {
		return true;
	}

	return false;
}
 
Example 13
Source File: JavaASTExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Get the AST of a file, including additional source paths to resolve
 * cross-file bindings. It is assumed that a CompilationUnit will be
 * returned. A heuristic is used to set the file's path variable.
 * <p>
 * Note: this may only yield a big improvement if the above heuristic fails
 * and srcPaths contains the correct source path.
 *
 * @param file
 * @param srcPaths
 *            for binding resolution
 * @return the compilation unit of the file
 * @throws IOException
 */
public final CompilationUnit getAST(final File file,
		final Set<String> srcPaths) throws IOException {
	final String sourceFile = FileUtils.readFileToString(file);
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	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(sourceFile.toCharArray()); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	parser.setUnitName(file.getAbsolutePath());

	// Heuristic to retrieve source file path
	final String srcFilePath;
	if (file.getAbsolutePath().contains("/src")) {
		srcFilePath = file.getAbsolutePath().substring(0,
				file.getAbsolutePath().indexOf("src", 0) + 3);
	} else {
		srcFilePath = "";
	}

	// Add file to source paths if not already present
	srcPaths.add(srcFilePath);

	final String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths
			.size()]);
	final String[] classPathEntries = new String[0];
	parser.setEnvironment(classPathEntries, sourcePathEntries, null, true);

	final CompilationUnit compilationUnit = (CompilationUnit) parser
			.createAST(null);
	return compilationUnit;
}
 
Example 14
Source File: JavaASTExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Get the AST of a file, including additional source paths to resolve
 * cross-file bindings. It is assumed that a CompilationUnit will be
 * returned. A heuristic is used to set the file's path variable.
 * <p>
 * Note: this may only yield a big improvement if the above heuristic fails
 * and srcPaths contains the correct source path.
 *
 * @param file
 * @param srcPaths
 *            for binding resolution
 * @return the compilation unit of the file
 * @throws IOException
 */
public final CompilationUnit getAST(final File file,
		final Set<String> srcPaths) throws IOException {
	final String sourceFile = FileUtils.readFileToString(file);
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	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(sourceFile.toCharArray()); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	parser.setUnitName(file.getAbsolutePath());

	// Heuristic to retrieve source file path
	final String srcFilePath;
	if (file.getAbsolutePath().contains("/src")) {
		srcFilePath = file.getAbsolutePath().substring(0,
				file.getAbsolutePath().indexOf("src", 0) + 3);
	} else {
		srcFilePath = "";
	}

	// Add file to source paths if not already present
	srcPaths.add(srcFilePath);

	final String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths
			.size()]);
	final String[] classPathEntries = new String[0];
	parser.setEnvironment(classPathEntries, sourcePathEntries, null, true);

	final CompilationUnit compilationUnit = (CompilationUnit) parser
			.createAST(null);
	return compilationUnit;
}
 
Example 15
Source File: JavaParser.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public static ElementInfoPool parse(String srcDir) {
    ElementInfoPool elementInfoPool = new ElementInfoPool(srcDir);

    Collection<File> javaFiles = FileUtils.listFiles(new File(srcDir), new String[]{"java"}, true);
    Set<String> srcPathSet = new HashSet<>();
    Set<String> srcFolderSet = new HashSet<>();
    for (File javaFile : javaFiles) {
        String srcPath = javaFile.getAbsolutePath();
        String srcFolderPath = javaFile.getParentFile().getAbsolutePath();
        srcPathSet.add(srcPath);
        srcFolderSet.add(srcFolderPath);
    }
    String[] srcPaths = new String[srcPathSet.size()];
    srcPathSet.toArray(srcPaths);
    NameResolver.setSrcPathSet(srcPathSet);
    String[] srcFolderPaths = new String[srcFolderSet.size()];
    srcFolderSet.toArray(srcFolderPaths);

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setEnvironment(null, srcFolderPaths, null, true);
    parser.setResolveBindings(true);
    Map<String, String> options = new Hashtable<>();
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
    parser.setCompilerOptions(options);
    parser.setBindingsRecovery(true);
    System.out.println(javaFiles.size());
    parser.createASTs(srcPaths, null, new String[]{}, new FileASTRequestor() {
        @Override
        public void acceptAST(String sourceFilePath, CompilationUnit javaUnit) {
            try {
                javaUnit.accept(new JavaASTVisitor(elementInfoPool, FileUtils.readFileToString(new File(sourceFilePath))));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, null);

    return elementInfoPool;
}
 
Example 16
Source File: JavaASTExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @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); // set source
	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);
	}
}
 
Example 17
Source File: CreateTypeMemberOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
	if (this.createdNode == null) {
		this.source = removeIndentAndNewLines(this.source, cu);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(this.source.toCharArray());
		parser.setProject(getCompilationUnit().getJavaProject());
		parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
		ASTNode node = parser.createAST(this.progressMonitor);
		String createdNodeSource;
		if (node.getNodeType() != ASTNode.TYPE_DECLARATION) {
			createdNodeSource = generateSyntaxIncorrectAST();
			if (this.createdNode == null)
				throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
		} else {
			TypeDeclaration typeDeclaration = (TypeDeclaration) node;
			if ((typeDeclaration.getFlags() & ASTNode.MALFORMED) != 0) {
				createdNodeSource = generateSyntaxIncorrectAST();
				if (this.createdNode == null)
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
			} else {
				List bodyDeclarations = typeDeclaration.bodyDeclarations();
				if (bodyDeclarations.size() == 0) {
					throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS));
				}
				this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
				createdNodeSource = this.source;
			}
		}
		if (this.alteredName != null) {
			SimpleName newName = this.createdNode.getAST().newSimpleName(this.alteredName);
			SimpleName oldName = rename(this.createdNode, newName);
			int nameStart = oldName.getStartPosition();
			int nameEnd = nameStart + oldName.getLength();
			StringBuffer newSource = new StringBuffer();
			if (this.source.equals(createdNodeSource)) {
				newSource.append(createdNodeSource.substring(0, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd));
			} else {
				// syntactically incorrect source
				int createdNodeStart = this.createdNode.getStartPosition();
				int createdNodeEnd = createdNodeStart + this.createdNode.getLength();
				newSource.append(createdNodeSource.substring(createdNodeStart, nameStart));
				newSource.append(this.alteredName);
				newSource.append(createdNodeSource.substring(nameEnd, createdNodeEnd));

			}
			this.source = newSource.toString();
		}
	}
	if (rewriter == null) return this.createdNode;
	// return a string place holder (instead of the created node) so has to not lose comments and formatting
	return rewriter.createStringPlaceholder(this.source, this.createdNode.getNodeType());
}
 
Example 18
Source File: JavaASTParser.java    From KodeBeagle with Apache License 2.0 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @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 HashMap<>();
    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);
    }
}
 
Example 19
Source File: JavaASTExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @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); // set source
	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);
	}
}
 
Example 20
Source File: JavaASTExtractor.java    From api-mining with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @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); // set source
	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);
	}
}