當前位置: 首頁>>代碼示例>>Java>>正文


Java ASTParser.createASTs方法代碼示例

本文整理匯總了Java中org.eclipse.jdt.core.dom.ASTParser.createASTs方法的典型用法代碼示例。如果您正苦於以下問題:Java ASTParser.createASTs方法的具體用法?Java ASTParser.createASTs怎麽用?Java ASTParser.createASTs使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.eclipse.jdt.core.dom.ASTParser的用法示例。


在下文中一共展示了ASTParser.createASTs方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: parseAST

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
private static void parseAST(String[] srcFiles, Charset srcCharset,
        String[] classPathEntries, FileASTRequestor requestor) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    Map<String, String> options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(classPathEntries, null, null, true);
    String[] srcEncodings = new String[srcFiles.length];
    for (int i = 0; i < srcEncodings.length; i++) {
        srcEncodings[i] = srcCharset.name();
    }
    parser.createASTs(
            srcFiles, srcEncodings, new String[]{}, requestor, null);
}
 
開發者ID:SahaginOrg,項目名稱:sahagin-java,代碼行數:18,代碼來源:SrcTreeGenerator.java

示例2: parseCompilationUnits

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
/**
 * Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
 * source code.
 * 
 * @param compilationUnits the list of compilation units to parse
 * @return the mapping from compilation unit to the AST roots of each
 */
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
	if (compilationUnits == null) {
		throw new CrystalRuntimeException("null list of compilation units");
	}

	ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
	final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setResolveBindings(true);
	parser.setProject(WorkspaceUtilities.javaProject);
	parser.createASTs(compUnits, new String[0], new ASTRequestor() {
		@Override
           public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
			parsedCompilationUnits.put(unit, node);
		}

		@Override
           public final void acceptBinding(final String key, final IBinding binding) {
			// Do nothing
		}
	}, null);
	return parsedCompilationUnits;
}
 
開發者ID:aroog,項目名稱:code,代碼行數:31,代碼來源:WorkspaceUtilities.java

示例3: parseFiles

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
public void parseFiles(List<InputFile> files, final Handler handler) {
  // We need the whole SourceFile to correctly handle a parsed ADT, so we keep track of it here.
  final Map<String, InputFile> reverseMap = new LinkedHashMap<String, InputFile>();
  for (InputFile file: files) {
    reverseMap.put(file.getPath(), file);
  }

  ASTParser parser = newASTParser();
  FileASTRequestor astRequestor = new FileASTRequestor() {
    @Override
    public void acceptAST(String sourceFilePath, CompilationUnit ast) {
      logger.fine("acceptAST: " + sourceFilePath);
      int errors = ErrorUtil.errorCount();
      checkCompilationErrors(sourceFilePath, ast);
      if (errors == ErrorUtil.errorCount()) {
        handler.handleParsedUnit(reverseMap.get(sourceFilePath), ast);
      }
    }
  };
  // JDT fails to resolve all secondary bindings unless there are the same
  // number of "binding key" strings as source files. It doesn't appear to
  // matter what the binding key strings should be (as long as they're non-
  // null), so the paths array is reused.
  String[] paths = reverseMap.keySet().toArray(new String[reverseMap.size()]);
  parser.createASTs(paths, getEncodings(paths.length), paths, astRequestor, null);
}
 
開發者ID:Sellegit,項目名稱:j2objc,代碼行數:27,代碼來源:JdtParser.java

示例4: analyze

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
public void analyze(File rootFolder, List<String> javaFiles, final SDModel model) {
	postProcessReferences = new HashMap<RastNode, List<String>>();
	postProcessSupertypes = new HashMap<RastNode, List<String>>();
	final String projectRoot = rootFolder.getPath();
	final String[] emptyArray = new String[0];
	
	String[] filesArray = new String[javaFiles.size()];
	for (int i = 0; i < filesArray.length; i++) {
		filesArray[i] = rootFolder + File.separator + javaFiles.get(i).replaceAll("/", systemFileSeparator);
	}
	final String[] sourceFolders = this.inferSourceFolders(filesArray);
	final ASTParser parser = buildAstParser(sourceFolders);
	
	FileASTRequestor fileASTRequestor = new FileASTRequestor() {
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit ast) {
			String relativePath = sourceFilePath.substring(projectRoot.length() + 1).replaceAll(systemFileSeparator, "/");
			// IProblem[] problems = ast.getProblems();
			// if (problems.length > 0) {
			// System.out.println("problems");
			// }
			//
			try {
				char[] charArray = Util.getFileCharContent(new File(sourceFilePath), null);
				processCompilationUnit(relativePath, charArray, ast, model);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			// catch (DuplicateEntityException e) {
			// debug e;
			// }
		}
	};
	parser.createASTs((String[]) filesArray, null, emptyArray, fileASTRequestor, null);
	
	postProcessReferences(model, postProcessReferences);
	postProcessReferences = null;
	postProcessSupertypes(model);
	postProcessSupertypes = null;
}
 
開發者ID:aserg-ufmg,項目名稱:RefDiff,代碼行數:41,代碼來源:SDModelBuilder.java

示例5: generateExamples

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
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;
}
 
開發者ID:linzeqipku,項目名稱:SnowGraph,代碼行數:28,代碼來源:APIUsageExtractor.java

示例6: getExpectedTypeForGenericParameters

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
private ITypeBinding getExpectedTypeForGenericParameters() {
	char[][] chKeys= context.getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0) {
		return null;
	}

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(compilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0) {
		return (ITypeBinding) bindings.get(keys[0]);
	}

	return null;
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:32,代碼來源:CompletionProposalReplacementProvider.java

示例7: getExpectedType

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
/**
 * Returns the type binding of the expected type as it is contained in the
 * code completion context.
 *
 * @return the binding of the expected type
 */
private ITypeBinding getExpectedType() {
	char[][] chKeys= fInvocationContext.getCoreContext().getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0)
		return null;

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setProject(fCompilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<String, IBinding>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0)
		return (ITypeBinding) bindings.get(keys[0]);

	return null;
}
 
開發者ID:trylimits,項目名稱:Eclipse-Postfix-Code-Completion,代碼行數:36,代碼來源:LazyGenericTypeProposal.java

示例8: createCompilationUnitsForJavaFiles

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
private void createCompilationUnitsForJavaFiles(final File inputFolder) {
    // first process input folder to find java file
    processFolderToFindJavaClass(inputFolder);

    // now prepare ASTParser to process al java file found
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setStatementsRecovery(true);
    parser.setEnvironment(new String[] {
                                        inputFolder.getAbsolutePath()
    }, new String[] {
                     inputFolder.getAbsolutePath()
    }, new String[] {
                     "UTF-8"
    }, true);

    // add compiler compliance rules to convert enums
    @SuppressWarnings("unchecked")
    Hashtable<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);

    parser.setCompilerOptions(options);
    FileASTRequestor requestor = new CustomFileASTRequestor(getLog(), inputFolder.getAbsolutePath(),
                                                            sourcePathEntry);
    parser.createASTs(sourcePathEntry.keySet().toArray(new String[0]),
                      charsetEntry.toArray(new String[0]), new String[] {
                                                                         ""
                      }, requestor, null);
}
 
開發者ID:codejuicer,項目名稱:java2csharp,代碼行數:34,代碼來源:Java2CsharpMojo.java

示例9: analyze

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
private void analyze(File rootFolder, List<String> javaFiles, final SDModel.Snapshot model) {
	    postProcessReferences = new HashMap<SDEntity, List<String>>();
		postProcessSupertypes = new HashMap<SDType, List<String>>();
		postProcessClientCode = new HashMap<String, List<SourceRepresentation>>();
		final String projectRoot = rootFolder.getPath();
		final String[] emptyArray = new String[0];
		
		String[] filesArray = new String[javaFiles.size()];
		for (int i = 0; i < filesArray.length; i++) {
			filesArray[i] = rootFolder + File.separator + javaFiles.get(i).replaceAll("/", systemFileSeparator);
		}
		final String[] sourceFolders = this.inferSourceFolders(filesArray);
		final ASTParser parser = buildAstParser(sourceFolders);

		FileASTRequestor fileASTRequestor = new FileASTRequestor() { 
			@Override
			public void acceptAST(String sourceFilePath, CompilationUnit ast) {
				String relativePath = sourceFilePath.substring(projectRoot.length() + 1).replaceAll(systemFileSeparator, "/");
//				IProblem[] problems = ast.getProblems();
//				if (problems.length > 0) {
//					System.out.println("problems");
//				}
				//
				try {
					char[] charArray = Util.getFileCharContent(new File(sourceFilePath), null);
					processCompilationUnit(relativePath, charArray, ast, model);
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
//				catch (DuplicateEntityException e) {
		            // debug e;
//		        }
			}
		};
		parser.createASTs((String[]) filesArray, null, emptyArray, fileASTRequestor, null);
		
		postProcessReferences(model, postProcessReferences);
		postProcessReferences = null;
		postProcessSupertypes(model);
		postProcessSupertypes = null;
		postProcessClientCode(model);
		postProcessClientCode = null;
	}
 
開發者ID:aserg-ufmg,項目名稱:RefDiff,代碼行數:44,代碼來源:SDModelBuilder.java

示例10: parse

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
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;
}
 
開發者ID:linzeqipku,項目名稱:SnowGraph,代碼行數:44,代碼來源:JavaParser.java

示例11: createChangeManager

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
/**
 * 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();
	}
}
 
開發者ID:trylimits,項目名稱:Eclipse-Postfix-Code-Completion,代碼行數:74,代碼來源:UseSuperTypeProcessor.java

示例12: rewriteTypeOccurrences

import org.eclipse.jdt.core.dom.ASTParser; //導入方法依賴的package包/類
protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final CompilationUnitRewrite sourceRewrite, final ICompilationUnit copy, final Set<String> replacements, final RefactoringStatus status, final IProgressMonitor monitor) {
	try {
		monitor.beginTask("", 100); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.PullUpRefactoring_checking);
		final IType declaring= getDeclaringType();
		final IJavaProject project= declaring.getJavaProject();
		final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setWorkingCopyOwner(fOwner);
		parser.setResolveBindings(true);
		parser.setProject(project);
		parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
		parser.createASTs(new ICompilationUnit[] { copy}, new String[0], new ASTRequestor() {

			@Override
			public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
				try {
					final IType subType= (IType) JavaModelUtil.findInCompilationUnit(unit, declaring);
					final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(subType, node);
					if (subDeclaration != null) {
						final ITypeBinding subBinding= subDeclaration.resolveBinding();
						if (subBinding != null) {
							String name= null;
							ITypeBinding superBinding= null;
							final ITypeBinding[] superBindings= Bindings.getAllSuperTypes(subBinding);
							for (int index= 0; index < superBindings.length; index++) {
								name= superBindings[index].getName();
								if (name.startsWith(fDestinationType.getElementName()))
									superBinding= superBindings[index];
							}
							if (superBinding != null) {
								solveSuperTypeConstraints(unit, node, subType, subBinding, superBinding, new SubProgressMonitor(monitor, 80), status);
								if (!status.hasFatalError())
									rewriteTypeOccurrences(manager, this, sourceRewrite, unit, node, replacements, status, new SubProgressMonitor(monitor, 120));
							}
						}
					}
				} catch (JavaModelException exception) {
					JavaPlugin.log(exception);
					status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error));
				}
			}

			@Override
			public final void acceptBinding(final String key, final IBinding binding) {
				// Do nothing
			}
		}, new NullProgressMonitor());
	} finally {
		monitor.done();
	}
}
 
開發者ID:trylimits,項目名稱:Eclipse-Postfix-Code-Completion,代碼行數:52,代碼來源:PullUpRefactoringProcessor.java


注:本文中的org.eclipse.jdt.core.dom.ASTParser.createASTs方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。