Java Code Examples for org.eclipse.jdt.core.JavaCore#getOptions()

The following examples show how to use org.eclipse.jdt.core.JavaCore#getOptions() . 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: SourceCompiler.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static ASTParser createParser(String sourceVersion) {
		ASTParser parser = ASTParser.newParser(AST.JLS10);

		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setResolveBindings(true);
		//TODO
//		parser.setUnitName(unitName);
		parser.setBindingsRecovery(true);
		parser.setStatementsRecovery(true);

		Map options = JavaCore.getOptions();
		
		options.put(JavaCore.COMPILER_COMPLIANCE, sourceVersion);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, sourceVersion);
		options.put(JavaCore.COMPILER_SOURCE, sourceVersion);

		parser.setCompilerOptions(options);

		return parser;
	}
 
Example 2
Source File: ASTParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets all the setting to their default values.
 */
private void initializeDefaults() {
	this.astKind = K_COMPILATION_UNIT;
	this.rawSource = null;
	this.typeRoot = null;
	this.bits = 0;
	this.sourceLength = -1;
	this.sourceOffset = 0;
	this.workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
	this.unitName = null;
	this.project = null;
	this.classpaths = null;
	this.sourcepaths = null;
	this.sourcepathsEncodings = null;
	Map options = JavaCore.getOptions();
	options.remove(JavaCore.COMPILER_TASK_TAGS); // no need to parse task tags
	this.compilerOptions = options;
}
 
Example 3
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
public static CompilationUnit genASTFromSource(String icu, String[] classPath, String[] sourcePath){
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setResolveBindings(true);
		parser.setBindingsRecovery(true);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		Map<?, ?> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
		parser.setCompilerOptions(options);
 
//		String[] sources = { "C:\\Users\\pc\\workspace\\asttester\\src" }; 
//		String[] classpath = {"C:\\Program Files\\Java\\jre1.8.0_25\\lib\\rt.jar"};
 
		parser.setEnvironment(classPath, sourcePath, new String[] { "UTF-8"}, true);
		parser.setSource(icu.toCharArray());
		return (CompilationUnit) parser.createAST(null);
	}
 
Example 4
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public UMLModelASTReader(Map<String, String> javaFileContents, Set<String> repositoryDirectories) {
	this.umlModel = new UMLModel(repositoryDirectories);
	this.parser = ASTParser.newParser(AST.JLS11);
	for(String filePath : javaFileContents.keySet()) {
		Map<String, String> options = JavaCore.getOptions();
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
		parser.setCompilerOptions(options);
		parser.setResolveBindings(false);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setStatementsRecovery(true);
		parser.setSource(javaFileContents.get(filePath).toCharArray());
		if(javaFileContents.get(filePath).contains(FREE_MARKER_GENERATED)) {
			return;
		}
		CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
		processCompilationUnit(filePath, compilationUnit);
	}
}
 
Example 5
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IFormattingContext createFormattingContext() {
	IFormattingContext context= new JavaFormattingContext();

	Map<String, String> preferences;
	IJavaElement inputJavaElement= getInputJavaElement();
	IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
	if (javaProject == null)
		preferences= new HashMap<String, String>(JavaCore.getOptions());
	else
		preferences= new HashMap<String, String>(javaProject.getOptions(true));

	context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, preferences);

	return context;
}
 
Example 6
Source File: InternalNamingConventions.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static char[] removeVariablePrefixAndSuffix(
		int variableKind,
		IJavaProject javaProject,
		char[] name) {
	AssistOptions assistOptions;
	if (javaProject != null) {
		assistOptions = new AssistOptions(javaProject.getOptions(true));
	} else {
		assistOptions = new AssistOptions(JavaCore.getOptions());
	}
	
	char[][] prefixes = null;
	char[][] suffixes = null;
	switch (variableKind) {
		case VK_INSTANCE_FIELD:
			prefixes = assistOptions.fieldPrefixes;
			suffixes = assistOptions.fieldSuffixes;
			break;
		case VK_STATIC_FIELD:
			prefixes = assistOptions.staticFieldPrefixes;
			suffixes = assistOptions.staticFieldSuffixes;
			break;
		case VK_STATIC_FINAL_FIELD:
			prefixes = assistOptions.staticFinalFieldPrefixes;
			suffixes = assistOptions.staticFinalFieldSuffixes;
			break;
		case VK_LOCAL:
			prefixes = assistOptions.localPrefixes;
			suffixes = assistOptions.localSuffixes;
			break;
		case VK_PARAMETER:
			prefixes = assistOptions.argumentPrefixes;
			suffixes = assistOptions.argumentSuffixes;
			break;
	}
	
	return InternalNamingConventions.removeVariablePrefixAndSuffix(name, prefixes, suffixes, true);
}
 
Example 7
Source File: TestVMType.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void setTestJREAsDefault(String vmId) throws CoreException {
	IVMInstallType vmInstallType = JavaRuntime.getVMInstallType(VMTYPE_ID);
	IVMInstall testVMInstall = vmInstallType.findVMInstall(vmId);
	if (!testVMInstall.equals(JavaRuntime.getDefaultVMInstall())) {
		// set the 1.8 test JRE as the new default JRE
		JavaRuntime.setDefaultVMInstall(testVMInstall, new NullProgressMonitor());
		Hashtable<String, String> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(vmId, options);
		JavaCore.setOptions(options);
	}
	JDTUtils.setCompatibleVMs(VMTYPE_ID);
}
 
Example 8
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultipleLineRange() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, JavaCore.WARNING);
	javaProject.setOptions(options);
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);

	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E {\n");
	buf.append("    public boolean foo(boolean b1) {\n");
	buf.append("        if (false) {\n");
	buf.append("            return true;\n");
	buf.append("        }\n");
	buf.append("        return false;\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

	CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
	IProblem[] problems = astRoot.getProblems();
	List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
	assertEquals(1, diagnostics.size());
	Range range = diagnostics.get(0).getRange();
	assertNotEquals(range.getStart().getLine(), range.getEnd().getLine());
}
 
Example 9
Source File: AnonymousTypeCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException {
	// Construct empty body for performance concern
	// See https://github.com/microsoft/language-server-protocol/issues/1032#issuecomment-648748013
	String newBody = fSnippetSupport ? "{\n\t${0}\n}" : "{\n\n}";

	StringBuilder buf = new StringBuilder("new A()"); //$NON-NLS-1$
	buf.append(newBody);
	// use the code formatter
	String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
	final IJavaProject project = fCompilationUnit.getJavaProject();
	IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset);
	Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions();
	String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options);
	int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength();
	int p = offset;
	if (p < document.getLength()) {
		char ch = document.getChar(p);
		while (p < lineEndOffset) {
			if (ch == '(' || ch == ')' || ch == ';' || ch == ',') {
				break;
			}
			ch = document.getChar(++p);
		}
		if (ch != ';' && ch != ',' && ch != ')') {
			replacementString = replacementString + ';';
		}
	}
	int beginIndex = replacementString.indexOf('(');
	replacementString = replacementString.substring(beginIndex);
	return replacementString;
}
 
Example 10
Source File: JavaSourceViewer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFormattingContext createFormattingContext() {

	// it's ok to use instance preferences here as subclasses replace
	// with project dependent versions (see CompilationUnitEditor.AdaptedSourceViewer)
	IFormattingContext context= new JavaFormattingContext();
	Map<String, String> map= new HashMap<String, String>(JavaCore.getOptions());
	context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, map);

	return context;
}
 
Example 11
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 12
Source File: InternalASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the rewrite: The rewrite events are translated to the corresponding in text changes.
 * The given options can be null in which case the global options {@link JavaCore#getOptions() JavaCore.getOptions()}
 * will be used.
 *
 * @param document Document which describes the code of the AST that is passed in in the
 * constructor. This document is accessed read-only.
 * @param options the given options
 * @throws IllegalArgumentException if the rewrite fails
 * @return Returns the edit describing the text changes.
 */
public TextEdit rewriteAST(IDocument document, Map options) {
	TextEdit result = new MultiTextEdit();

	final CompilationUnit rootNode = getRootNode();
	if (rootNode != null) {
		TargetSourceRangeComputer xsrComputer = new TargetSourceRangeComputer() {
			/**
			 * This implementation of
			 * {@link TargetSourceRangeComputer#computeSourceRange(ASTNode)}
			 * is specialized to work in the case of internal AST rewriting, where the
			 * original AST has been modified from its original form. This means that
			 * one cannot trust that the root of the given node is the compilation unit.
			 */
			public SourceRange computeSourceRange(ASTNode node) {
				int extendedStartPosition = rootNode.getExtendedStartPosition(node);
				int extendedLength = rootNode.getExtendedLength(node);
				return new SourceRange(extendedStartPosition, extendedLength);
			}
		};
		char[] content= document.get().toCharArray();
		LineInformation lineInfo= LineInformation.create(document);
		String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
		List comments= rootNode.getCommentList();

		Map currentOptions = options == null ? JavaCore.getOptions() : options;
		ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, comments, currentOptions, xsrComputer, (RecoveryScannerData)rootNode.getStatementsRecoveryData());
		rootNode.accept(visitor);
	}
	return result;
}
 
Example 13
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public DefaultCodeFormatter(DefaultCodeFormatterOptions defaultCodeFormatterOptions, Map options) {
	if (options != null) {
		this.options = options;
		this.preferences = new DefaultCodeFormatterOptions(options);
	} else {
		this.options = JavaCore.getOptions();
		this.preferences = new DefaultCodeFormatterOptions(DefaultCodeFormatterConstants.getJavaConventionsSettings());
	}
	this.defaultCompilerOptions = getDefaultCompilerOptions();
	if (defaultCodeFormatterOptions != null) {
		this.preferences.set(defaultCodeFormatterOptions.getMap());
	}
}
 
Example 14
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
/**
 * generate {@code CompilationUnit} from source code based on the specific
 * type (e.g., {@code ASTParser.K_COMPILATION_UNIT})
 * 
 * @param icu
 * @param type
 * @return
 */
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 15
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 16
Source File: JavaCompletionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tells this processor to restrict its proposal to those element
 * visible in the actual invocation context.
 *
 * @param restrict <code>true</code> if proposals should be restricted
 */
public void restrictProposalsToVisibility(boolean restrict) {
	Hashtable<String, String> options= JavaCore.getOptions();
	Object value= options.get(VISIBILITY);
	if (value instanceof String) {
		String newValue= restrict ? ENABLED : DISABLED;
		if ( !newValue.equals(value)) {
			options.put(VISIBILITY, newValue);
			JavaCore.setOptions(options);
		}
	}
}
 
Example 17
Source File: APIVersion.java    From apidiff with MIT License 5 votes vote down vote up
public void parse(String str, File source, final Boolean ignoreTreeDiff) throws IOException {
		
		if(this.mapModifications.size() > 0 && !this.isFileModification(source,ignoreTreeDiff)){
			return;
		}
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(str.toCharArray());
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		String[] classpath = java.lang.System.getProperty("java.class.path").split(";");
		String[] sources = { source.getParentFile().getAbsolutePath() };

		Hashtable<String, String> options = JavaCore.getOptions();
		options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
		parser.setUnitName(source.getAbsolutePath());

		parser.setCompilerOptions(options);
//		parser.setEnvironment(null, sources, new String[] { "UTF-8" },	true);
		parser.setResolveBindings(true);
		parser.setBindingsRecovery(true);

//		parser.setEnvironment(classpath, sources, new String[] { "UTF-8" },	true);
//		CompilationUnit compilationUnit = null;
		try {
			parser.setEnvironment(null, null, null,	true);
			CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
			TypeDeclarationVisitor visitorType = new TypeDeclarationVisitor();
			EnumDeclarationVisitor visitorEnum = new EnumDeclarationVisitor();
			
			compilationUnit.accept(visitorType);
			compilationUnit.accept(visitorEnum);
			
			this.configureAcessiblesAndNonAccessibleTypes(visitorType);
			this.configureAcessiblesAndNonAccessibleEnums(visitorEnum);
		} catch (Exception e) {
			this.logger.error("Erro ao criar AST sem source", e);
		}

	}
 
Example 18
Source File: Translator.java    From juniversal with MIT License 4 votes vote down vote up
/**
   * Translate all source files configured for the translator.   If a user errors occurs during translation for a file
   * (e.g. a SourceNotSupported exception is thrown), an error message is output for that file, the translation
   * continues on with remaining files, and false is eventually returned from this method as the translate failed.  If
   * an internal occurs during translation (e.g. the translator has a bug), an exception is thrown.
   *
   * @return true if all files were translated without error, false if some failed
   */
  public boolean translate() {
      ASTParser parser = ASTParser.newParser(AST.JLS8);
      parser.setKind(ASTParser.K_COMPILATION_UNIT);
      //parser.setEnvironment(new String[0], new String[0], null, false);
      //TODO: Set classpath & sourcepath differently probably; this just uses the current VM (I think), but I can
      //see that it doesn't resolve everything for some reason
      parser.setEnvironment(classpath, sourcepath, null, true);
      parser.setResolveBindings(true);

      Map options = JavaCore.getOptions();
      JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
      parser.setCompilerOptions(options);

      Var<Boolean> failed = new Var<>(false);

      FileASTRequestor astRequestor = new FileASTRequestor() {
          public void acceptAST(String sourceFilePath, CompilationUnit compilationUnit) {
              SourceFile sourceFile = new SourceFile(compilationUnit, new File(sourceFilePath), sourceTabStop);

              //boolean outputErrorForFile = false;
              for (IProblem problem : compilationUnit.getProblems()) {
                  if (problem.isError()) {
                      System.err.println("Error: " + problem.getMessage());
                      System.err.println(sourceFile.getPositionDescription(problem.getSourceStart()));
                  }
              }

              // Translate each file as it's returned; if a user error occurs while translating (e.g. a
              // SourceNotSupported exception is thrown), print the message for that, note the failure, and continue
              // on
              System.out.println("Translating " + sourceFilePath);
              try {
                  translateFile(sourceFile);
              } catch (UserViewableException e) {
                  System.err.println("Error: " + e.getMessage());
                  failed.set(true);
              }
          }
      };

      parser.createASTs(getJavaFiles(), null, new String[0], astRequestor, null);

      return !failed.value();

/*
       * String source = readFile(jUniversal.getJavaProjectDirectories().get(0).getPath());
 * parser.setSource(source.toCharArray());
 *
 * CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
 *
 *
 * TypeDeclaration typeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);
 *
 * FileWriter writer; try { writer = new FileWriter(jUniversal.getOutputDirectory()); }
 * catch (IOException e) { throw new RuntimeException(e);   }
 *
 * CPPProfile profile = new CPPProfile(); // profile.setTabStop(4);
 *
 * CPPWriter cppWriter = new CPPWriter(writer, profile);
 *
 * Context context = new Context((CompilationUnit) compilationUnit.getRoot(), source, 8,
 * profile, cppWriter, OutputType.SOURCE);
 *
 * context.setPosition(typeDeclaration.getStartPosition());
 *
 * ASTWriters astWriters = new ASTWriters();
 *
 * try { context.setPosition(typeDeclaration.getStartPosition());
 * skipSpaceAndComments();
 *
 * astWriters.writeNode(typeDeclaration, context); } catch (UserViewableException e) {
 * System.err.println(e.getMessage()); System.exit(1); } catch (RuntimeException e) { if (e
 * instanceof ContextPositionMismatchException) throw e; else throw new
 * JUniversalException(e.getMessage() + "\nError occurred with context at position\n" +
 * context.getPositionDescription(context.getPosition()), e); }
 *
 * try { writer.close(); } catch (IOException e) { throw new RuntimeException(e); }
 */
  }
 
Example 19
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Converts all modifications recorded by this rewriter
 * into an object representing the corresponding text
 * edits to the given document containing the original source
 * code. The document itself is not modified.
 * <p>
 * For nodes in the original that are being replaced or deleted,
 * this rewriter computes the adjusted source ranges
 * by calling {@link TargetSourceRangeComputer#computeSourceRange(ASTNode) getExtendedSourceRangeComputer().computeSourceRange(node)}.
 * </p>
 * <p>
 * Calling this methods does not discard the modifications
 * on record. Subsequence modifications are added to the ones
 * already on record. If this method is called again later,
 * the resulting text edit object will accurately reflect
 * the net cumulative effect of all those changes.
 * </p>
 *
 * @param document original document containing source code
 * @param options the table of formatter options
 * (key type: <code>String</code>; value type: <code>String</code>);
 * or <code>null</code> to use the standard global options
 * {@link JavaCore#getOptions() JavaCore.getOptions()}
 * @return text edit object describing the changes to the
 * document corresponding to the changes recorded by this rewriter
 * @throws IllegalArgumentException An <code>IllegalArgumentException</code>
 * is thrown if the document passed does not correspond to the AST that is rewritten.
 */
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException {
	if (document == null) {
		throw new IllegalArgumentException();
	}

	ASTNode rootNode= getRootNode();
	if (rootNode == null) {
		return new MultiTextEdit(); // no changes
	}

	char[] content= document.get().toCharArray();
	LineInformation lineInfo= LineInformation.create(document);
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);

	ASTNode astRoot= rootNode.getRoot();
	List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null;
	Map currentOptions = options == null ? JavaCore.getOptions() : options;
	return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData());
}
 
Example 20
Source File: CodeFormatterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a string that represents the given number of indentation units.
 * The returned string can contain tabs and/or spaces depending on the core formatter preferences.
 *
 * @param indentationUnits
 *        the number of indentation units to generate
 * @param project
 *        the project from which to get the formatter settings,
 *        <code>null</code> if the workspace default should be used
 * @return the indent string
 */
public static String createIndentString(int indentationUnits, IJavaProject project) {
	Map<String, String> options= project != null ? project.getOptions(true) : JavaCore.getOptions();
	return ToolFactory.createCodeFormatter(options).createIndentationString(indentationUnits);
}