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


Java ASTParser類代碼示例

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


ASTParser類屬於org.eclipse.jdt.core.dom包,在下文中一共展示了ASTParser類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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: EclipseParser

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
/**
 * Creates a new EclipseParser
 *
 * @param sourceFile String of source file to read
 * @param outJ       JSON parsed out
 * @throws IOException when file can't be opened or errors in reading/writing
 */
public EclipseParser(String sourceFile, PrintStream outJ, boolean prettyprint) throws IOException {

    File file = new File(sourceFile);
    final BufferedReader reader = new BufferedReader(new FileReader(file));
    char[] source = IOUtils.toCharArray(reader);
    reader.close();
    this.parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final JsonFactory jsonF = new JsonFactory();
    jG = jsonF.createGenerator(outJ);
    if (prettyprint) {
        jG.setPrettyPrinter(new DefaultPrettyPrinter());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ASTNode.class, new NodeSerializer());
    mapper.registerModule(module);
}
 
開發者ID:bblfsh,項目名稱:java-driver,代碼行數:31,代碼來源:eclipseParser.java

示例3: getField

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
/**
 * @param methodname
 * @return
 */
public FieldDeclaration getField(   ) {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	String s = getStaticVariable ( );
	if (s==null) return null;
	parser.setSource(s.toCharArray());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	final  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	cu.accept(new ASTVisitor() {
		public boolean visit(FieldDeclaration node) {
			field = node;
			return true;
		}
	});		 
	return field;
}
 
開發者ID:gw4e,項目名稱:gw4e.project,代碼行數:20,代碼來源:ClassExtension.java

示例4: getGraphWalkerClassAnnotation

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
/**
 * @return
 */
public NormalAnnotation getGraphWalkerClassAnnotation() {
	String source = getSource ();
	if(source==null) return null;
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setSource(source.toCharArray());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	cu.accept(new ASTVisitor() {
		public boolean visit(NormalAnnotation node) {
			annotation = node;
			return true;
		}
	});
	if (this.generateAnnotation) return annotation;
	return null;
}
 
開發者ID:gw4e,項目名稱:gw4e.project,代碼行數:20,代碼來源:ClassExtension.java

示例5: getGeneratedClassAnnotation

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
public NormalAnnotation getGeneratedClassAnnotation() {
	String source = getGeneratedAnnotationSource ();
	if(source==null) return null;
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setSource(source.toCharArray());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	cu.accept(new ASTVisitor() {
		public boolean visit(NormalAnnotation node) {
			annotation = node;
			return true;
		}
	});
    return annotation;
	 
}
 
開發者ID:gw4e,項目名稱:gw4e.project,代碼行數:17,代碼來源:ClassExtension.java

示例6: parse

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
public void parse() throws ParseException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    Map<String, String> options = JavaCore.getOptions();
    options.put("org.eclipse.jdt.core.compiler.source", "1.8");
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setUnitName("Program.java");
    parser.setEnvironment(new String[] { classpath != null? classpath : "" },
            new String[] { "" }, new String[] { "UTF-8" }, true);
    parser.setResolveBindings(true);
    cu = (CompilationUnit) parser.createAST(null);

    List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p ->
                                        p.isError() &&
                                        p.getID() != IProblem.PublicClassMustMatchFileName && // we use "Program.java"
                                        p.getID() != IProblem.ParameterMismatch // Evidence varargs
                                    ).collect(Collectors.toList());
    if (problems.size() > 0)
        throw new ParseException(problems);
}
 
開發者ID:capergroup,項目名稱:bayou,代碼行數:22,代碼來源:Parser.java

示例7: toGroovyTypeModel

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
public TypeModel toGroovyTypeModel(String source) {
    source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();");
    source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();");
    source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();");

    ASTParser parser = ASTParser.newParser(JLS8);
    parser.setSource(source.toCharArray());
    parser.setKind(K_COMPILATION_UNIT);
    parser.setCompilerOptions(compilerOptions());

    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    astProxy.setTarget(cu.getAST());

    TypeVisitor visitor = testClassVisitorSupplier.get();
    cu.accept(visitor);
    return visitor.typeModel();
}
 
開發者ID:opaluchlukasz,項目名稱:junit2spock,代碼行數:18,代碼來源:Spocker.java

示例8: getRecoveredAST

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
	CompilationUnit ast = SharedASTProvider.getInstance().getAST(fCompilationUnit, null);
	if (ast != null) {
		recoveredDocument.set(document.get());
		return ast;
	}

	char[] content= document.get().toCharArray();

	// clear prefix to avoid compile errors
	int index= offset - 1;
	while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
		content[index]= ' ';
		index--;
	}

	recoveredDocument.set(new String(content));

	final ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);
	parser.setSource(content);
	parser.setUnitName(fCompilationUnit.getElementName());
	parser.setProject(fCompilationUnit.getJavaProject());
	return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:27,代碼來源:OverrideCompletionProposal.java

示例9: getParameterTypeNamesForSeeTag

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) {
	try {
		ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setProject(overridden.getJavaProject());
		IBinding[] bindings = parser.createBindings(new IJavaElement[] { overridden }, null);
		if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) {
			return getParameterTypeNamesForSeeTag((IMethodBinding) bindings[0]);
		}
	} catch (IllegalStateException e) {
		// method does not exist
	}
	// fall back code. Not good for generic methods!
	String[] paramTypes = overridden.getParameterTypes();
	String[] paramTypeNames = new String[paramTypes.length];
	for (int i = 0; i < paramTypes.length; i++) {
		paramTypeNames[i] = Signature.toString(Signature.getTypeErasure(paramTypes[i]));
	}
	return paramTypeNames;
}
 
開發者ID:eclipse,項目名稱:eclipse.jdt.ls,代碼行數:20,代碼來源:StubUtility.java

示例10: 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

示例11: 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

示例12: isValidExpression

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

示例13: isValidVarargsExpression

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
public static boolean isValidVarargsExpression(String string) {
  String trimmed = string.trim();
  if ("".equals(trimmed)) // speed up for a common case //$NON-NLS-1$
  return true;
  StringBuffer cuBuff = new StringBuffer();
  cuBuff.append("class A{ {m("); // $NON-NLS-1$
  int offset = cuBuff.length();
  cuBuff.append(trimmed).append(");}}"); // $NON-NLS-1$
  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[] selectedNodes = analyzer.getSelectedNodes();
  if (selectedNodes.length == 0) return false;
  for (int i = 0; i < selectedNodes.length; i++) {
    if (!(selectedNodes[i] instanceof Expression)) return false;
  }
  return true;
}
 
開發者ID:eclipse,項目名稱:che,代碼行數:22,代碼來源:ChangeSignatureProcessor.java

示例14: _processUnit

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
private void _processUnit(ICompilationUnit cu)
	throws JavaModelException, MalformedTreeException, BadLocationException {

	// Parse the javacode to be able to modify it
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setSource(cu);

	// Create a copy of the CompilationUnit to work on
	CompilationUnit copyOfUnit = (CompilationUnit)parser.createAST(null);

	MemberComparator comparator = new MemberComparator();

	// This helper method will sort our java code with the given comparator
	TextEdit edits = CompilationUnitSorter.sort(copyOfUnit, comparator, 0, null, null);

	// The sort method gives us null if there weren't any changes
	if (edits != null) {
		ICompilationUnit workingCopy = cu.getWorkingCopy(new WorkingCopyOwner() {}, null);

		workingCopy.applyTextEdit(edits, null);

		// Commit changes
		workingCopy.commitWorkingCopy(true, null);
	}
}
 
開發者ID:Ixenit,項目名稱:eclipsemembersort,代碼行數:26,代碼來源:SortHandler.java

示例15: Parse

import org.eclipse.jdt.core.dom.ASTParser; //導入依賴的package包/類
private CompilationUnit Parse(String contentFile, String fileName) throws Exception
{
	File file = new File(fileName);
	IFile[] files = WorkspaceRoot.findFilesForLocationURI(file.toURI(), IResource.FILE);
	
	if (files.length > 1)
		throw new Exception("Ambigous parse request for file: " + fileName);
	else if (files.length == 0)
		throw new Exception("File is not part of the enlistment: " + fileName);
	
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(contentFile.toCharArray());
	parser.setUnitName(files[0].getName());
	parser.setProject(JavaCore.create(files[0].getProject()));
	parser.setResolveBindings(true);
	
	CompilationUnit cu = (CompilationUnit)parser.createAST(null);
	return cu;
}
 
開發者ID:Microsoft,項目名稱:vsminecraft,代碼行數:21,代碼來源:JavaParser.java


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