Java 类org.eclipse.jdt.core.dom.ASTParser 实例源码

项目:gw4e.project    文件:ClassExtension.java   
/**
 * @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;
}
项目:gw4e.project    文件:ClassExtension.java   
/**
 * @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;
}
项目:sahagin-java    文件:SrcTreeGenerator.java   
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);
}
项目:gw4e.project    文件:ClassExtension.java   
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;

}
项目:bayou    文件:Parser.java   
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);
}
项目:junit2spock    文件:Spocker.java   
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();
}
项目:java-driver    文件:eclipseParser.java   
/**
 * 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);
}
项目:eclipse.jdt.ls    文件:OverrideCompletionProposal.java   
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());
}
项目:eclipse.jdt.ls    文件:StubUtility.java   
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;
}
项目:code    文件:WorkspaceUtilities.java   
/**
 * 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;
}
项目:code    文件:WorkspaceUtilities.java   
/**
 * 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;
}
项目:code    文件:WorkspaceUtilities.java   
/**
 * 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;
}
项目:j2objc    文件:JdtParser.java   
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);
}
项目:che    文件:ChangeSignatureProcessor.java   
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)));
}
项目:che    文件:ChangeSignatureProcessor.java   
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;
}
项目:eclipsemembersort    文件:SortHandler.java   
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);
    }
}
项目:vsminecraft    文件:JavaParser.java   
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;
}
项目:gwt-eclipse-plugin    文件:JavaASTUtils.java   
public static ITypeBinding resolveType(IJavaProject javaProject,
    String qualifiedTypeName) throws JavaModelException {
  IType type = javaProject.findType(qualifiedTypeName);
  if (type == null || !type.exists()) {
    return null;
  }

  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setProject(javaProject);
  IBinding[] bindings = parser.createBindings(new IJavaElement[] {type}, null);
  if (bindings == null) {
    return null;
  }

  return (ITypeBinding) bindings[0];
}
项目:PerformanceHat    文件:AstCompilationUnitDecorator.java   
private CompilationUnit createAst() {
   // advise the parser to parse the code following to the Java Language Specification, Fourth Edition
   @SuppressWarnings("deprecation")
   // TODO: remove warning 
final ASTParser parser = ASTParser.newParser(AST.JLS4);

   // tells the parser, that it has to expect an ICompilationUnit as input
   parser.setKind(ASTParser.K_COMPILATION_UNIT);

   parser.setSource(compilationUnit);

   // binding service has to be explicitly requested at parse times
   parser.setResolveBindings(true);

   return (CompilationUnit) parser.createAST(new NullProgressMonitor());
 }
项目:compiler    文件:Java7BaseTest.java   
protected static void dumpJava(final String content) {
final ASTParser parser = ASTParser.newParser(astLevel);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(content.toCharArray());

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

final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

      try {
          final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
          final ASTDumper dumper = new ASTDumper(cex);
          dumper.dump(cu);
          cex.close();
      } catch (final Exception e) {}
  }
项目:compiler    文件:Java7BaseTest.java   
protected static String parseJava(final String content) {
    final ASTParser parser = ASTParser.newParser(astLevel);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(content.toCharArray());

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

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    final ASTRoot.Builder ast = ASTRoot.newBuilder();
    try {
        ast.addNamespaces(visitor.getNamespaces(cu));
        for (final String s : visitor.getImports())
            ast.addImports(s);
    } catch (final Exception e) {
        System.err.println(e);
        e.printStackTrace();
        return "";
    }

    return JsonFormat.printToString(ast.build());
}
项目:Java-RSRepair    文件:ParserContext.java   
public ParserContext(HashMap<String, HashSet<String>> scope, 
                       HashMap<String, DocumentASTRewrite> sourceFileContents,
                     String[] classpaths, String[] sourcepaths, String[] sourceFilesArray, 
                     LineCoverage faultyLineCoverage, LineCoverage seedLineCoverage, 
                     Statements faultyStatements, Statements seedStatements){

this.parser = ASTParser.newParser(AST.JLS8);

    this.scope = scope;
    this.sourceFileContents = sourceFileContents;
    this.classpaths = classpaths;
    this.sourcepaths = sourcepaths;
    this.sourceFilesArray = sourceFilesArray;
    this.faultyLineCoverage = faultyLineCoverage;
    this.seedLineCoverage = seedLineCoverage;
    this.faultyStatements = faultyStatements;
    this.seedStatements = seedStatements;
  }
项目:eip-designer    文件:CamelJavaFileParser.java   
/**
 * Parse the routeFile given while building the instance and fill the model.
 * @param model The EIP Model to fill with parsed elements from routeFile.
 * @throws InvalidArgumentException if given file is not a valid Spring integration file
 */
public void parseAndFillModel(EIPModel model) throws Exception {
   // Read source content.
   routeSource = parseRouteClass();

   // Parse and get the compilation unit.
   ASTParser parser = ASTParser.newParser(AST.JLS8);
   parser.setKind(ASTParser.K_COMPILATION_UNIT);
   parser.setSource(routeSource.toCharArray());
   parser.setResolveBindings(false);
   routeCU = (CompilationUnit) parser.createAST(null);

   // Visit and build a comment map before parsing.
   for (Object comment : routeCU.getCommentList()) {
      ((Comment) comment).accept(this);
   }

   // Initialize and build a route.
   route = EipFactory.eINSTANCE.createRoute();
   model.getOwnedRoutes().add(route);

   // 
   routeCU.accept(this);
}
项目:txtUML    文件:ModelTest.java   
private CompilationUnit prepareAST(String javaFile) throws IOException {
    File projectRoot = new File(VALIDATION_EXAMPLES_ROOT).getAbsoluteFile();
    File sourceFile = new File(projectRoot.getCanonicalPath() + VALIDATION_EXAMPLES_PACKAGE + javaFile);

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    char[] content = SharedUtils.getFileContents(sourceFile);

    String[] classpath = {};
    String[] sourcepath = { projectRoot.getCanonicalPath(), new File(API_SRC_LOC).getCanonicalPath() };
    String[] encodings = { "UTF-8", "UTF-8" };

    parser.setSource(content);

    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setUnitName(sourceFile.getName());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setEnvironment(classpath, sourcepath, encodings, true);

    return (CompilationUnit) parser.createAST(null);
}
项目:txtUML    文件:SharedUtils.java   
/**
 * Parses the specified Java source file located in the given Java project.
 * 
 * @param sourceFile
 *            The specified Java source file.
 * @param project
 *            The given Java project.
 * @return The parsed compilation unit.
 * @throws IOException
 *             Thrown when I/O error occurs during reading the file.
 * @throws JavaModelException
 */
public static CompilationUnit parseJavaSource(File sourceFile, IJavaProject project)
        throws IOException, JavaModelException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    char[] content = SharedUtils.getFileContents(sourceFile);

    parser.setSource(content);
    parser.setProject(project);

    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setUnitName(sourceFile.getName());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    return compilationUnit;
}
项目:Eclipse-Postfix-Code-Completion    文件:ChangeSignatureProcessor.java   
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)));
}
项目:Eclipse-Postfix-Code-Completion    文件:ChangeSignatureProcessor.java   
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;
}
项目:Eclipse-Postfix-Code-Completion    文件:TypedSource.java   
private static String getFieldSource(IField field, SourceTuple tuple) throws CoreException {
    if (Flags.isEnum(field.getFlags())) {
        String source= field.getSource();
        if (source != null)
            return source;
    } else {
        if (tuple.node == null) {
            ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            parser.setSource(tuple.unit);
            tuple.node= (CompilationUnit) parser.createAST(null);
        }
        FieldDeclaration declaration= ASTNodeSearchUtil.getFieldDeclarationNode(field, tuple.node);
        if (declaration.fragments().size() == 1)
            return getSourceOfDeclararationNode(field, tuple.unit);
        VariableDeclarationFragment declarationFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, tuple.node);
        IBuffer buffer= tuple.unit.getBuffer();
        StringBuffer buff= new StringBuffer();
        buff.append(buffer.getText(declaration.getStartPosition(), ((ASTNode) declaration.fragments().get(0)).getStartPosition() - declaration.getStartPosition()));
        buff.append(buffer.getText(declarationFragment.getStartPosition(), declarationFragment.getLength()));
        buff.append(";"); //$NON-NLS-1$
        return buff.toString();
    }
    return ""; //$NON-NLS-1$
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:NewTypeWizardPage.java   
/**
 * Uses the New Java file template from the code template page to generate a
 * compilation unit with the given type content.
 * 
 * @param cu The new created compilation unit
 * @param typeContent The content of the type, including signature and type
 * body.
 * @param lineDelimiter The line delimiter to be used.
 * @return String Returns the result of evaluating the new file template
 * with the given type content.
 * @throws CoreException when fetching the file comment fails or fetching the content for the
 *             new compilation unit fails
 * @since 2.1
 */
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
    String fileComment= getFileComment(cu, lineDelimiter);
    String typeComment= getTypeComment(cu, lineDelimiter);
    IPackageFragment pack= (IPackageFragment) cu.getParent();
    String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
    if (content != null) {
        ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(cu.getJavaProject());
        parser.setSource(content.toCharArray());
        CompilationUnit unit= (CompilationUnit) parser.createAST(null);
        if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
            return content;
        }
    }
    StringBuffer buf= new StringBuffer();
    if (!pack.isDefaultPackage()) {
        buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
    }
    buf.append(lineDelimiter).append(lineDelimiter);
    if (typeComment != null) {
        buf.append(typeComment).append(lineDelimiter);
    }
    buf.append(typeContent);
    return buf.toString();
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ClassPathDetector.java   
private void visitCompilationUnit(IFile file) {
    ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
    if (cu != null) {
        ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setSource(cu);
        parser.setFocalPosition(0);
        CompilationUnit root= (CompilationUnit)parser.createAST(null);
        PackageDeclaration packDecl= root.getPackage();

        IPath packPath= file.getParent().getFullPath();
        String cuName= file.getName();
        if (packDecl == null) {
            addToMap(fSourceFolders, packPath, new Path(cuName));
        } else {
            IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
            IPath folderPath= getFolderPath(packPath, relPath);
            if (folderPath != null) {
                addToMap(fSourceFolders, folderPath, relPath.append(cuName));
            }
        }
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:NewTypeWizardPage.java   
/**
 * Uses the New Java file template from the code template page to generate a
 * compilation unit with the given type content.
 * 
 * @param cu The new created compilation unit
 * @param typeContent The content of the type, including signature and type
 * body.
 * @param lineDelimiter The line delimiter to be used.
 * @return String Returns the result of evaluating the new file template
 * with the given type content.
 * @throws CoreException when fetching the file comment fails or fetching the content for the
 *             new compilation unit fails
 * @since 2.1
 */
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
    String fileComment= getFileComment(cu, lineDelimiter);
    String typeComment= getTypeComment(cu, lineDelimiter);
    IPackageFragment pack= (IPackageFragment) cu.getParent();
    String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
    if (content != null) {
        ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setProject(cu.getJavaProject());
        parser.setSource(content.toCharArray());
        CompilationUnit unit= (CompilationUnit) parser.createAST(null);
        if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
            return content;
        }
    }
    StringBuffer buf= new StringBuffer();
    if (!pack.isDefaultPackage()) {
        buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
    }
    buf.append(lineDelimiter).append(lineDelimiter);
    if (typeComment != null) {
        buf.append(typeComment).append(lineDelimiter);
    }
    buf.append(typeContent);
    return buf.toString();
}
项目:Eclipse-Postfix-Code-Completion    文件:OverrideCompletionProposal.java   
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
    CompilationUnit ast= SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_ACTIVE_ONLY, 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(ASTProvider.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());
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaHistoryActionImpl.java   
static CompilationUnit parsePartialCompilationUnit(ICompilationUnit unit) {

        if (unit == null) {
            throw new IllegalArgumentException();
        }
        try {
            ASTParser c= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
            c.setSource(unit);
            c.setFocalPosition(0);
            c.setResolveBindings(false);
            c.setWorkingCopyOwner(null);
            ASTNode result= c.createAST(null);
            return (CompilationUnit) result;
        } catch (IllegalStateException e) {
            // convert ASTParser's complaints into old form
            throw new IllegalArgumentException();
        }
    }
项目:Eclipse-Postfix-Code-Completion    文件:ClassPathDetector.java   
private void visitCompilationUnit(IFile file) {
    ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
    if (cu != null) {
        ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
        parser.setSource(cu);
        parser.setFocalPosition(0);
        CompilationUnit root= (CompilationUnit)parser.createAST(null);
        PackageDeclaration packDecl= root.getPackage();

        IPath packPath= file.getParent().getFullPath();
        String cuName= file.getName();
        if (packDecl == null) {
            addToMap(fSourceFolders, packPath, new Path(cuName));
        } else {
            IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
            IPath folderPath= getFolderPath(packPath, relPath);
            if (folderPath != null) {
                addToMap(fSourceFolders, folderPath, relPath.append(cuName));
            }
        }
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:CreateTypeMemberOperation.java   
/**
 * Generates an <code>ASTNode</code> based on the source of this operation
 * when there is likely a syntax error in the source.
 * Returns the source used to generate this node.
 */
protected String generateSyntaxIncorrectAST() {
    //create some dummy source to generate an ast node
    StringBuffer buff = new StringBuffer();
    IType type = getType();
    String lineSeparator = org.eclipse.jdt.internal.core.util.Util.getLineSeparator(this.source, type == null ? null : type.getJavaProject());
    buff.append(lineSeparator + " public class A {" + lineSeparator); //$NON-NLS-1$
    buff.append(this.source);
    buff.append(lineSeparator).append('}');
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(buff.toString().toCharArray());
    CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
    TypeDeclaration typeDeclaration = (TypeDeclaration) compilationUnit.types().iterator().next();
    List bodyDeclarations = typeDeclaration.bodyDeclarations();
    if (bodyDeclarations.size() != 0)
        this.createdNode = (ASTNode) bodyDeclarations.iterator().next();
    return buff.toString();
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaStatementPostfixContext.java   
private void initDomAST() {
        if (isReadOnly())
            return;

        ASTParser parser= ASTParser.newParser(AST.JLS8);
        parser.setSource(getCompilationUnit());
        parser.setResolveBindings(true);
        org.eclipse.jdt.core.dom.ASTNode domAst = parser.createAST(new NullProgressMonitor());

//      org.eclipse.jdt.core.dom.AST ast = domAst.getAST();

        NodeFinder nf = new NodeFinder(domAst, getCompletionOffset(), 1);
        org.eclipse.jdt.core.dom.ASTNode cv = nf.getCoveringNode();

        bodyDeclaration = ASTResolving.findParentBodyDeclaration(cv);
        parentDeclaration = ASTResolving.findParentType(cv);
        domInitialized = true;
    }
项目:codemodify    文件:DefaultCodeModifier.java   
@Override
public void modify(ICompilationUnit cu, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, modifiers.size() + 1);

    // parse compilation unit
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(cu);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(subMonitor.split(1));

    for (ICompilationUnitModifier compilationUnitModifier : modifiers) {
        compilationUnitModifier.modifyCompilationUnit(astRoot, subMonitor.split(1));
    }

}
项目:ChangeScribe    文件:JParser.java   
public void parse() {
    if (this.member != null) {
        if (this.member instanceof IType) {
            this.elements.add(this.unit.findDeclaringNode(((IType)this.member).getKey()));
        }
        else if (this.member instanceof IMethod) {
            final ASTParser parser = ASTParser.newParser(4);
            parser.setProject(((IMethod)this.member).getJavaProject());
            parser.setResolveBindings(true);
            final IBinding binding = parser.createBindings(new IJavaElement[] { (IMethod)this.member }, (IProgressMonitor)null)[0];
            if (binding instanceof IMethodBinding) {
                final ASTNode method = this.unit.findDeclaringNode(((IMethodBinding)binding).getKey());
                this.elements.add(method);
            }
        }
    }
    else {
        for (final Object o : this.unit.types()) {
            if (!(o instanceof TypeDeclaration)) {
                continue;
            }
            this.elements.add((ASTNode)o);
        }
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:OverrideCompletionProposal.java   
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
    CompilationUnit ast= SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_ACTIVE_ONLY, 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(ASTProvider.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());
}
项目:dominoes    文件:FileNode.java   
private void extractPackage(Repository _repo) throws MissingObjectException, IOException{
    ObjectLoader newFile = _repo.open(this.newObjId);
    String newData = readStream(newFile.openStream());


    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(newData.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Hashtable<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED);
    parser.setCompilerOptions(options);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

        public boolean visit(PackageDeclaration _package){
            packageName = _package.getName().getFullyQualifiedName();
            return false;
        }
    });
}