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

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setSource() . 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: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isValidExpression(String string){
	String trimmed= string.trim();
	if ("".equals(trimmed)) //speed up for a common case //$NON-NLS-1$
		return false;
	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append(CONST_CLASS_DECL)
		  .append("Object") //$NON-NLS-1$
		  .append(CONST_ASSIGN);
	int offset= cuBuff.length();
	cuBuff.append(trimmed)
		  .append(CONST_CLOSE);
	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, trimmed.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode selected= analyzer.getFirstSelectedNode();
	return (selected instanceof Expression) &&
			trimmed.equals(cuBuff.substring(cu.getExtendedStartPosition(selected), cu.getExtendedStartPosition(selected) + cu.getExtendedLength(selected)));
}
 
Example 2
Source File: EclipseASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ASTParserFactory.ASTParserWrapper createJavaParser(final Object context) {
  if ((context instanceof IJavaElement)) {
    final IJavaProject project = ((IJavaElement)context).getJavaProject();
    final String projlevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
    final ASTParser parser = this.createDefaultJavaParser(projlevel);
    if ((context instanceof IJavaProject)) {
      parser.setProject(project);
      this.tweakOptions(parser, project);
    } else {
      if ((context instanceof ICompilationUnit)) {
        parser.setSource(((ICompilationUnit)context));
        this.tweakOptions(parser, ((ICompilationUnit)context).getJavaProject());
      }
    }
    return new ASTParserFactory.ASTParserWrapper(projlevel, parser);
  }
  return super.createJavaParser(context);
}
 
Example 3
Source File: TypeCheckingEvolution.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinJavaProject(IJavaProject javaProject, TypeCheckElimination elimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	try {
		IPackageFragmentRoot[] iPackageFragmentRoots = javaProject.getPackageFragmentRoots();
		for(IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) {
			IJavaElement[] children = iPackageFragmentRoot.getChildren();
			for(IJavaElement child : children) {
				if(child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
					IPackageFragment iPackageFragment = (IPackageFragment)child;
					ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits();
					for(ICompilationUnit iCompilationUnit : iCompilationUnits) {
						ASTParser parser = ASTParser.newParser(ASTReader.JLS);
				        parser.setKind(ASTParser.K_COMPILATION_UNIT);
				        parser.setSource(iCompilationUnit);
				        parser.setResolveBindings(true); // we need bindings later on
				        CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
						typeCheckEliminations.addAll(generateTypeCheckEliminationsWithinCompilationUnit(compilationUnit, elimination));
					}
				}
			}
		}
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
	return typeCheckEliminations;
}
 
Example 4
Source File: Utils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private static CompilationUnit getCompilationUnit(IBinding binding) {
	try {
		ICompilationUnit unit = (ICompilationUnit) binding.getJavaElement()
				.getAncestor(IJavaElement.COMPILATION_UNIT);
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(unit);
		parser.setResolveBindings(true);
		CompilationUnit cu = (CompilationUnit) parser.createAST(null);
		return cu;
	} catch (Exception ex) {
		return null;
	}
}
 
Example 5
Source File: JavaASTUtilsTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setSource(testClass.getCompilationUnit());
  ast = parser.createAST(null);
}
 
Example 6
Source File: RemoteServiceValidatorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode newAST(ICompilationUnit syncInterface) {
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setResolveBindings(true);
  parser.setProject(syncInterface.getJavaProject());
  parser.setSource(syncInterface);
  return parser.createAST(null);
}
 
Example 7
Source File: JsniParserTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testParseMethodDeclaration() {
  // Have JDT parse the compilation unit
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(getTestProject());
  parser.setResolveBindings(false);
  parser.setSource(testClass.getCompilationUnit());
  CompilationUnit root = (CompilationUnit) parser.createAST(null);

  // Find the JSNI method and parse it
  TypeDeclaration typeDecl = (TypeDeclaration) root.types().get(0);
  MethodDeclaration jsniMethod = typeDecl.getMethods()[0];
  JavaValidationResult result = JsniParser.parse(jsniMethod);

  // Verify the Java refs
  List<JsniJavaRef> refs = result.getJavaRefs();
  assertEquals(3, refs.size());
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.A$B::getNumber()")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::getSum(II)")));
  assertTrue(refs.contains(JsniJavaRef.parse("@com.hello.client.JsniParserTest::counter")));

  // Verify the problems
  List<GWTJavaProblem> problems = result.getProblems();
  assertEquals(1, problems.size());
  GWTJavaProblem problem = problems.get(0);
  assertEquals(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, problem.getProblemType());
  IRegion expectedProblemRegion = RegionConverter.convertWindowsRegion(184, 0, testClass.getContents());
  assertEquals(expectedProblemRegion.getOffset(), problem.getSourceStart());
}
 
Example 8
Source File: WizardUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the list of types in the given compilation unit.
 */
private synchronized static List<?> getTypes(ICompilationUnit compilationUnit) {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setResolveBindings(true);
	parser.setSource(compilationUnit);
	CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	return cu.types();
}
 
Example 9
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 10
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 11
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * generate {@code CompilationUnit} from {@code ICompilationUnit}
 * 
 * @param icu
 * @return
 */
public static CompilationUnit genASTFromICU(ICompilationUnit icu) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu);
	astParser.setKind(ASTParser.K_COMPILATION_UNIT);
	astParser.setResolveBindings(true);
	return (CompilationUnit) astParser.createAST(null);
}
 
Example 12
Source File: AbstractQuickfixTestCase.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void testQuickfix(InputStream testdataStream, AbstractASTResolution quickfix)
        throws Exception {
  QuickfixTestData[] testdata = getTestData(testdataStream);

  for (int i = 0; i < testdata.length; i++) {

    org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(testdata[i].input);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(doc.get().toCharArray());
    CompilationUnit compUnit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
    compUnit.recordModifications();
    IRegion region = doc.getLineInformation(testdata[i].line);

    int markerStartOffset = region.getOffset() + testdata[i].position;

    System.out.println("Invoke quickfix " + quickfix.getClass() + " with markerStartOffset="
            + markerStartOffset);

    compUnit.accept(quickfix.handleGetCorrectingASTVisitor(region, markerStartOffset));

    Map<String, String> options = new HashMap<>();
    options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
    options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
    options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES,
            "true");
    options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH,
            "true");

    TextEdit edit = compUnit.rewrite(doc, options);
    edit.apply(doc);

    assertEquals(testdata[i].result, doc.get());
  }

}
 
Example 13
Source File: UnusedImportsNodeCollectorTest.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private List<String> getUnusedImports(String source) {
  ASTParser parser = ASTParser.newParser(AST.JLS8);
  parser.setSource(source.toCharArray());
  CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);

  UnusedImportsNodeCollector importsCollector = new UnusedImportsNodeCollector();
  compilationUnit.accept(importsCollector);
  List<ImportDeclaration> unusedImportsDeclarations = importsCollector.getUnusedImports();
  List<String> unusedImports = new ArrayList<>();
  for (ImportDeclaration importDeclaration : unusedImportsDeclarations) {
    unusedImports.add(importDeclaration.getName().toString());
  }
  return unusedImports;
}
 
Example 14
Source File: SortElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Method processElement.
 * @param unit
 * @param source
 */
private String processElement(ICompilationUnit unit, char[] source) {
	Document document = new Document(new String(source));
	CompilerOptions options = new CompilerOptions(unit.getJavaProject().getOptions(true));
	ASTParser parser = ASTParser.newParser(this.apiLevel);
	parser.setCompilerOptions(options.getMap());
	parser.setSource(source);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setResolveBindings(false);
	org.eclipse.jdt.core.dom.CompilationUnit ast = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);

	ASTRewrite rewriter= sortCompilationUnit(ast, null);
	if (rewriter == null)
		return document.get();

	TextEdit edits = rewriter.rewriteAST(document, unit.getJavaProject().getOptions(true));

	RangeMarker[] markers = null;
	if (this.positions != null) {
		markers = new RangeMarker[this.positions.length];
		for (int i = 0, max = this.positions.length; i < max; i++) {
			markers[i]= new RangeMarker(this.positions[i], 0);
			insert(edits, markers[i]);
		}
	}
	try {
		edits.apply(document, TextEdit.UPDATE_REGIONS);
		if (this.positions != null) {
			for (int i= 0, max = markers.length; i < max; i++) {
				this.positions[i]= markers[i].getOffset();
			}
		}
	} catch (BadLocationException e) {
		// ignore
	}
	return document.get();
}
 
Example 15
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 16
Source File: JavadocContentAccess2.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) {
	Assert.isNotNull(element);
	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 17
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 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: IssueReportFix.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns the Java method body that contains the error.
 * 
 * @return method body as {@link String}
 */
private String getMethodBody() {
	String methodBody = "";
	ICompilationUnit sourceUnit = null;
	try {
		sourceUnit = QuickFixUtils.getCompilationUnitFromMarker(marker);
		final ASTParser parser = ASTParser.newParser(AST.JLS11);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setSource(sourceUnit);
		final CompilationUnit unit = (CompilationUnit) parser.createAST(null);
		HashMap<Integer, MethodDeclaration> methodMap = new HashMap<>();

		unit.accept(new ASTVisitor() {
			@Override
			public boolean visit(final MethodDeclaration node) {
				methodMap.put(unit.getLineNumber(node.getStartPosition()), node);
				return true;
			}
		});

		int errorLineNumber = (int) marker.getAttribute(IMarker.LINE_NUMBER);
		ArrayList<Integer> methodStartLineNumber = new ArrayList<>(methodMap.keySet());
		Collections.sort(methodStartLineNumber);

		if (errorLineNumber < methodStartLineNumber.get(0)) {
			// error in the variable declarations
		} else if (errorLineNumber > methodStartLineNumber.get(methodStartLineNumber.size() - 1)) {
			methodBody = methodMap.get(methodStartLineNumber.get(methodStartLineNumber.size() - 1)).toString();
		} else {
			for (int i = 0; i < methodStartLineNumber.size() - 1; i++) {
				int start = methodStartLineNumber.get(i);
				int end = methodStartLineNumber.get(i + 1);

				if (errorLineNumber > start && errorLineNumber < end) {
					methodBody = methodMap.get(methodStartLineNumber.get(i)).toString();
					break;
				}
			}
		}

	}
	catch (CoreException e) {
		Activator.getDefault().logError(e);
	}

	return methodBody;
}
 
Example 20
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#JLS4 JLS4} 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#JLS4}
 * 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 JLS4 has been deprecated. This method has been replaced by {@link #getAST8()} which returns an AST
 * with JLS8 level.
 * @since 3.7.1
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST4() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS4 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS4);
		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);
}