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

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#createAST() . 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: CamelJavaFileParser.java    From eip-designer with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the routeFile given while building the instance and fill the model.
 * @param model The EIP Model to fill with parsed elements from routeFile.
 * @throws InvalidArgumentException if given file is not a valid Spring integration file
 */
public void parseAndFillModel(EIPModel model) throws Exception {
   // Read source content.
   routeSource = parseRouteClass();
   
   // Parse and get the compilation unit.
   ASTParser parser = ASTParser.newParser(AST.JLS8);
   parser.setKind(ASTParser.K_COMPILATION_UNIT);
   parser.setSource(routeSource.toCharArray());
   parser.setResolveBindings(false);
   routeCU = (CompilationUnit) parser.createAST(null);
   
   // Visit and build a comment map before parsing.
   for (Object comment : routeCU.getCommentList()) {
      ((Comment) comment).accept(this);
   }
   
   // Initialize and build a route.
   route = EipFactory.eINSTANCE.createRoute();
   model.getOwnedRoutes().add(route);
   
   // 
   routeCU.accept(this);
}
 
Example 2
Source File: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Javadoc getJavaDoc() {
	if (context == null || context.eResource() == null || context.eResource().getResourceSet() == null)
		return null;
	Object classpathURIContext = ((XtextResourceSet) context.eResource().getResourceSet()).getClasspathURIContext();
	if (classpathURIContext instanceof IJavaProject) {
		IJavaProject javaProject = (IJavaProject) classpathURIContext;
		@SuppressWarnings("all")
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setProject(javaProject);
		Map<String, String> options = javaProject.getOptions(true);
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
		parser.setCompilerOptions(options);
		String source = rawJavaDoc + "class C{}"; //$NON-NLS-1$
		parser.setSource(source.toCharArray());
		CompilationUnit root = (CompilationUnit) parser.createAST(null);
		if (root == null)
			return null;
		List<AbstractTypeDeclaration> types = root.types();
		if (types.size() != 1)
			return null;
		AbstractTypeDeclaration type = types.get(0);
		return type.getJavadoc();
	}
	return null;
}
 
Example 3
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 6 votes vote down vote up
protected static void dumpJava(final String content) {
	final ASTParser parser = ASTParser.newParser(astLevel);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(content.toCharArray());

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

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	try {
		final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
		final ASTDumper dumper = new ASTDumper(cex);
		dumper.dump(cu);
		cex.close();
	} catch (final Exception e) {}
}
 
Example 4
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 5
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression createExpression(String expr) {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_EXPRESSION);
	parser.setResolveBindings(true);
	parser.setSource(expr.toCharArray());
	
	org.eclipse.jdt.core.dom.ASTNode astNode = parser.createAST(new NullProgressMonitor());
	return (Expression) astNode;
}
 
Example 6
Source File: PlantUmlGenerator.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private CompilationUnit getSuperClassCU(Type superClass) {
	ICompilationUnit element = (ICompilationUnit) superClass.resolveBinding().getTypeDeclaration().getJavaElement()
			.getParent();

	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setSource(element);

	return (CompilationUnit) parser.createAST(null);
}
 
Example 7
Source File: MethodEvolution.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<String> getStringRepresentation(IMethod method, ProjectVersion version) {
	List<String> stringRepresentation = null;
	if(method != null) {
		ICompilationUnit iCompilationUnit = method.getCompilationUnit();
		ASTParser parser = ASTParser.newParser(ASTReader.JLS);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(iCompilationUnit);
		parser.setResolveBindings(true);
		CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
		IType declaringType = method.getDeclaringType();
		TypeDeclaration typeDeclaration = (TypeDeclaration)compilationUnit.findDeclaringNode(declaringType.getKey());
		MethodDeclaration matchingMethodDeclaration = null;
		for(MethodDeclaration methodDeclaration : typeDeclaration.getMethods()) {
			IMethod resolvedMethod = (IMethod)methodDeclaration.resolveBinding().getJavaElement();
			if(resolvedMethod.isSimilar(method)) {
				matchingMethodDeclaration = methodDeclaration;
				break;
			}
		}
		if(matchingMethodDeclaration != null && matchingMethodDeclaration.getBody() != null) {
			methodCodeMap.put(version, matchingMethodDeclaration.toString());
			ASTInformationGenerator.setCurrentITypeRoot(iCompilationUnit);
			MethodBodyObject methodBody = new MethodBodyObject(matchingMethodDeclaration.getBody());
			stringRepresentation = methodBody.stringRepresentation();
		}
	}
	return stringRepresentation;
}
 
Example 8
Source File: PasteAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static List<ParsedCu> parseCus(IJavaProject javaProject, String compilerCompliance, String text) {
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	if (javaProject != null) {
		parser.setProject(javaProject);
	} else if (compilerCompliance != null) {
		Map<String, String> options= JavaCore.getOptions();
		JavaModelUtil.setComplianceOptions(options, compilerCompliance);
		parser.setCompilerOptions(options);
	}
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	CompilationUnit unit= (CompilationUnit) parser.createAST(null);

	if (unit.types().size() > 0)
		return parseAsTypes(text, unit);

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
	ASTNode root= parser.createAST(null);
	if (root instanceof TypeDeclaration) {
		List<BodyDeclaration> bodyDeclarations= ((TypeDeclaration) root).bodyDeclarations();
		if (bodyDeclarations.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_CLASS_BODY_DECLARATIONS, null, null));
	}

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	root= parser.createAST(null);
	if (root instanceof Block) {
		List<Statement> statements= ((Block) root).statements();
		if (statements.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_STATEMENTS, null, null));
	}

	return Collections.emptyList();
}
 
Example 9
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);

	IJavaProject javaProject= element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options= javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);

	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 10
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static CompilationUnit parseCompilationUnit(
    ICompilationUnit compilationUnit) {
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setResolveBindings(true);
  parser.setSource(compilationUnit);
  return (CompilationUnit) parser.createAST(null);
}
 
Example 11
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null)
		parser.setSource(getSourceCu());
	else
		parser.setSource(getSourceClassFile());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 12
Source File: PasteAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(getDestinationCu());
	CompilationUnit cuNode= (CompilationUnit) p.createAST(pm);
	ASTRewrite rewrite= ASTRewrite.create(cuNode.getAST());
	TypedSource source= null;
	for (int i= fSources.length - 1; i >= 0; i--) {
		source= fSources[i];
		final ASTNode destination= getDestinationNodeForSourceElement(fDestination, source.getType(), cuNode);
		if (destination != null) {
			if (destination instanceof CompilationUnit)
				insertToCu(rewrite, createNewNodeToInsertToCu(source, rewrite), (CompilationUnit) destination);
			else if (destination instanceof AbstractTypeDeclaration)
				insertToType(rewrite, createNewNodeToInsertToType(source, rewrite), (AbstractTypeDeclaration) destination);
		}
	}
	final CompilationUnitChange result= new CompilationUnitChange(ReorgMessages.PasteAction_change_name, getDestinationCu());
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(getDestinationCu());
		TextEdit rootEdit= rewrite.rewriteAST(buffer.getDocument(), fDestination.getJavaProject().getOptions(true));
		if (getDestinationCu().isWorkingCopy())
			result.setSaveMode(TextFileChange.LEAVE_DIRTY);
		TextChangeCompatibility.addTextEdit(result, ReorgMessages.PasteAction_edit_name, rootEdit);
	} finally {
		RefactoringFileBuffers.release(getDestinationCu());
	}
	return result;
}
 
Example 13
Source File: ProblemMarkerBuilder.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * setupParser Method that sets up the Parser and creates a visitor for a specific unit
 *
 * @param unit Unit from getUnitForParser
 */
private void setupParser(final ICompilationUnit unit) {
	final ASTParser parser = ASTParser.newParser(AST.JLS10);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(unit);
	parser.setResolveBindings(true);
	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	cu.accept(createMarkerVisitor(unit, cu));
}
 
Example 14
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String getPackageName(IJavaProject javaProject, String fileContent) {
	if (fileContent == null) {
		return "";
	}
	//TODO probably not the most efficient way to get the package name as this reads the whole file;
	char[] source = fileContent.toCharArray();
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(javaProject);
	parser.setIgnoreMethodBodies(true);
	parser.setSource(source);
	CompilationUnit ast = (CompilationUnit) parser.createAST(null);
	PackageDeclaration pkg = ast.getPackage();
	return (pkg == null || pkg.getName() == null)?"":pkg.getName().getFullyQualifiedName();
}
 
Example 15
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) {
	if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$
		return null;
	if (! typeString.trim().equals(typeString))
		return null;

	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append("interface A{"); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	p.setProject(javaProject);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, typeString.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode selected= analyzer.getFirstSelectedNode();
	if (!(selected instanceof Type))
		return null;
	Type type= (Type)selected;
	if (MethodTypesSyntaxChecker.isVoidArrayType(type))
		return null;
	IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
	if (problems.length > 0) {
		for (int i= 0; i < problems.length; i++)
			problemsCollector.add(problems[i].getMessage());
	}

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (typeString.equals(typeNodeRange))
		return type;
	else
		return null;
}
 
Example 16
Source File: JavaStructureCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IStructureComparator createStructureComparator(final Object input, char[] buffer, IDocument doc, ISharedDocumentAdapter adapter, IProgressMonitor monitor) {
	String contents;
	Map<String, String> compilerOptions= null;

	if (input instanceof IResourceProvider) {
		IResource resource= ((IResourceProvider) input).getResource();
		if (resource != null) {
			IJavaElement element= JavaCore.create(resource);
			if (element != null) {
				IJavaProject javaProject= element.getJavaProject();
				if (javaProject != null)
					compilerOptions= javaProject.getOptions(true);
			}
		}
	}
	if (compilerOptions == null)
		compilerOptions= fDefaultCompilerOptions;

	if (doc != null) {
		boolean isEditable= false;
		if (input instanceof IEditableContent)
			isEditable= ((IEditableContent) input).isEditable();

		// we hook into the root node to intercept all node changes
		JavaNode root= new RootJavaNode(doc, isEditable, input, adapter);

		if (buffer == null) {
			contents= doc.get();
			int n= contents.length();
			buffer= new char[n];
			contents.getChars(0, n, buffer, 0);
		}

		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		if (compilerOptions != null)
			parser.setCompilerOptions(compilerOptions);
		parser.setSource(buffer);
		parser.setFocalPosition(0);
		CompilationUnit cu= (CompilationUnit) parser.createAST(monitor);
		cu.accept(new JavaParseTreeBuilder(root, buffer, true));

		return root;
	}
	return null;
}
 
Example 17
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 18
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS3 JLS3} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS3}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS3 has been deprecated. This method has been replaced by {@link #getAST4()} which returns an AST
 * with JLS4 level.
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST3() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example 19
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 20
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;
}