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

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setCompilerOptions() . 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: ASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected final ASTParser createDefaultJavaParser(final String javaVersion) {
  ASTParser parser = null;
  final Hashtable<String, String> options = JavaCore.getOptions();
  try {
    parser = ASTParser.newParser(ASTParserFactory.asJLS(javaVersion));
    JavaCore.setComplianceOptions(javaVersion, options);
  } catch (final Throwable _t) {
    if (_t instanceof IllegalArgumentException) {
      parser = ASTParser.newParser(ASTParserFactory.asJLS(this.minParserApiLevel));
      JavaCore.setComplianceOptions(this.minParserApiLevel, options);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
  parser.setCompilerOptions(options);
  parser.setStatementsRecovery(true);
  parser.setResolveBindings(true);
  parser.setBindingsRecovery(true);
  return parser;
}
 
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: SORecommender.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private HashMap<String, HashSet<String>> parseKStatements(String snippet) throws IOException {
	HashMap<String, HashSet<String>> tokens = new HashMap<String, HashSet<String>>();
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	parser.setBindingsRecovery(true);
	Map<String, String> options = JavaCore.getOptions();
	parser.setCompilerOptions(options);
	parser.setUnitName("test");
	String src = snippet;
	String[] sources = {};
	String[] classpath = { "/usr/lib/jvm/java-8-openjdk-amd64" };
	parser.setEnvironment(classpath, sources, new String[] {}, true);
	parser.setSource(src.toCharArray());
	try {
		Block block = (Block) parser.createAST(null);
		MyASTVisitor myVisitor = new MyASTVisitor();
		block.accept(myVisitor);
		tokens = myVisitor.getTokens();
	} catch (Exception exc) {
		logger.error("JDT parsing error");
	}
	return tokens;
}
 
Example 4
Source File: Utils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static ASTNode genASTFromSource(String icu, int type) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	astParser.setBindingsRecovery(true);
	return astParser.createAST(null);
}
 
Example 5
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 6
Source File: BaseBuilderGeneratorIT.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
protected CompilationUnit parseAst(char[] source) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
    parser.setCompilerOptions(options);
    CompilationUnit result = (CompilationUnit) parser.createAST(null);
    return result;
}
 
Example 7
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 8
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 9
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 10
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 5 votes vote down vote up
protected static String parseJava(final String content) {
	final StringBuilder sb = new StringBuilder();
	final FileASTRequestor r = new FileASTRequestor() {
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit cu) {
			final ASTRoot.Builder ast = ASTRoot.newBuilder();
			try {
				ast.addNamespaces(visitor.getNamespaces(cu));
			} catch (final Exception e) {
				System.err.println(e);
				e.printStackTrace();
			}

			sb.append(JsonFormat.printToString(ast.build()));
		}
	};
	Map<String, String> fileContents = new HashMap<String, String>();
	fileContents.put("", content);
	@SuppressWarnings("rawtypes")
	Map options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_COMPLIANCE, javaVersion);
	options.put(JavaCore.COMPILER_SOURCE, javaVersion);
	ASTParser parser = ASTParser.newParser(astLevel);
	parser.setCompilerOptions(options);
	parser.setEnvironment(new String[0], new String[]{}, new String[]{}, true);
	parser.setResolveBindings(true);
	parser.createASTs(fileContents, new String[]{""}, null, new String[0], r, null);

	return FileIO.normalizeEOL(sb.toString());
}
 
Example 11
Source File: JdtParser.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private ASTParser newASTParser(boolean resolveBinding) {
  ASTParser parser = ASTParser.newParser(AST_JLS_VERSION);

  parser.setCompilerOptions(compilerOptions);
  parser.setResolveBindings(resolveBinding);
  parser.setEnvironment(
      Iterables.toArray(classpathEntries, String.class), new String[0], new String[0], false);
  return parser;
}
 
Example 12
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 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 api-mining with GNU General Public License v3.0 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 17
Source File: GwtIncompatibleStripper.java    From j2cl with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static String processFile(String fileContent) {
  // Avoid parsing if there are no textual references to GwtIncompatible.
  if (!fileContent.contains("GwtIncompatible")) {
    return fileContent;
  }

  Map<String, String> compilerOptions = new HashMap<>();
  compilerOptions.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_9);
  compilerOptions.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_9);
  compilerOptions.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_9);

  // Parse the file.
  ASTParser parser = ASTParser.newParser(AST.JLS9);
  parser.setCompilerOptions(compilerOptions);
  parser.setResolveBindings(false);
  parser.setSource(fileContent.toCharArray());
  CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);

  // Find all the declarations with @GwtIncompatible.
  GwtIncompatibleNodeCollector gwtIncompatibleVisitor = new GwtIncompatibleNodeCollector();
  compilationUnit.accept(gwtIncompatibleVisitor);
  List<ASTNode> gwtIncompatibleNodes = gwtIncompatibleVisitor.getNodes();

  // Delete the gwtIncompatible nodes.
  for (ASTNode gwtIncompatibleNode : gwtIncompatibleNodes) {
    gwtIncompatibleNode.delete();
  }

  // Gets all the imports that are no longer needed.
  UnusedImportsNodeCollector unusedImportsNodeCollector = new UnusedImportsNodeCollector();
  compilationUnit.accept(unusedImportsNodeCollector);
  List<ImportDeclaration> unusedImportsNodes = unusedImportsNodeCollector.getUnusedImports();

  // Wrap all the not needed nodes inside comments in the original source
  // (so we can preserve line numbers and have accurate source maps).
  List<ASTNode> nodesToWrap = Lists.newArrayList(unusedImportsNodes);
  nodesToWrap.addAll(gwtIncompatibleNodes);
  if (nodesToWrap.isEmpty()) {
    // Nothing was changed.
    return fileContent;
  }

  // Precondition: Node ranges must not overlap and they must be sorted by position.
  StringBuilder newFileContent = new StringBuilder();
  int currentPosition = 0;
  for (ASTNode nodeToWrap : nodesToWrap) {
    int startPosition = nodeToWrap.getStartPosition();
    int endPosition = startPosition + nodeToWrap.getLength();
    checkState(
        currentPosition <= startPosition,
        "Unexpected node position: %s, must be >= %s",
        startPosition,
        currentPosition);

    newFileContent.append(fileContent, currentPosition, startPosition);

    StringBuilder strippedCodeBuilder = new StringBuilder();
    for (char c : fileContent.substring(startPosition, endPosition).toCharArray()) {
      strippedCodeBuilder.append(Character.isWhitespace(c) ? c : ' ');
    }
    newFileContent.append(strippedCodeBuilder);
    currentPosition = endPosition;
  }
  newFileContent.append(fileContent, currentPosition, fileContent.length());

  return newFileContent.toString();
}
 
Example 18
Source File: UseSuperTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_creating);
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final IJavaProject project= fSubType.getJavaProject();
		final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setWorkingCopyOwner(fOwner);
		parser.setResolveBindings(true);
		parser.setProject(project);
		parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
		if (fSubType.isBinary() || fSubType.isReadOnly()) {
			final IBinding[] bindings= parser.createBindings(new IJavaElement[] { fSubType, fSuperType }, new SubProgressMonitor(monitor, 50));
			if (bindings != null && bindings.length == 2 && bindings[0] instanceof ITypeBinding && bindings[1] instanceof ITypeBinding) {
				solveSuperTypeConstraints(null, null, fSubType, (ITypeBinding) bindings[0], (ITypeBinding) bindings[1], new SubProgressMonitor(monitor, 100), status);
				if (!status.hasFatalError())
					rewriteTypeOccurrences(manager, null, null, null, null, new HashSet<String>(), status, new SubProgressMonitor(monitor, 150));
			}
		} else {
			parser.createASTs(new ICompilationUnit[] { fSubType.getCompilationUnit() }, new String[0], new ASTRequestor() {

				@Override
				public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
					try {
						final CompilationUnitRewrite subRewrite= new CompilationUnitRewrite(fOwner, unit, node);
						final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, subRewrite.getRoot());
						if (subDeclaration != null) {
							final ITypeBinding subBinding= subDeclaration.resolveBinding();
							if (subBinding != null) {
								final ITypeBinding superBinding= findTypeInHierarchy(subBinding, fSuperType.getFullyQualifiedName('.'));
								if (superBinding != null) {
									solveSuperTypeConstraints(subRewrite.getCu(), subRewrite.getRoot(), fSubType, subBinding, superBinding, new SubProgressMonitor(monitor, 100), status);
									if (!status.hasFatalError()) {
										rewriteTypeOccurrences(manager, this, subRewrite, subRewrite.getCu(), subRewrite.getRoot(), new HashSet<String>(), status, new SubProgressMonitor(monitor, 200));
										final TextChange change= subRewrite.createChange(true);
										if (change != null)
											manager.manage(subRewrite.getCu(), change);
									}
								}
							}
						}
					} catch (CoreException exception) {
						JavaPlugin.log(exception);
						status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.UseSuperTypeProcessor_internal_error));
					}
				}

				@Override
				public final void acceptBinding(final String key, final IBinding binding) {
					// Do nothing
				}
			}, new NullProgressMonitor());
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 19
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 20
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);
    }
}