コード例 #1
0
  private JavaElement getJavaElement(LocalVariableBinding binding) {
    LocalDeclaration local = binding.declaration;

    JavaElement parent = null;
    ReferenceContext referenceContext =
        binding.declaringScope.isLambdaSubscope()
            ? binding.declaringScope.namedMethodScope().referenceContext()
            : binding.declaringScope.referenceContext();
    if (referenceContext instanceof AbstractMethodDeclaration) {
      AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) referenceContext;
      parent = this.getJavaElementOfCompilationUnit(methodDeclaration, methodDeclaration.binding);
    } else if (referenceContext instanceof TypeDeclaration) {
      // Local variable is declared inside an initializer
      TypeDeclaration typeDeclaration = (TypeDeclaration) referenceContext;

      JavaElement type =
          this.getJavaElementOfCompilationUnit(typeDeclaration, typeDeclaration.binding);
      parent = Util.getUnresolvedJavaElement(local.sourceStart, local.sourceEnd, type);
    }
    if (parent == null) return null;

    return new LocalVariable(
        parent,
        new String(local.name),
        local.declarationSourceStart,
        local.declarationSourceEnd,
        local.sourceStart,
        local.sourceEnd,
        local.type == null
            ? Signature.createTypeSignature(binding.type.signableName(), true)
            : Util.typeSignature(local.type),
        binding.declaration.annotations,
        local.modifiers,
        local.getKind() == AbstractVariableDeclaration.PARAMETER);
  }
コード例 #2
0
ファイル: ClassFile.java プロジェクト: felixdo/groovy-eclipse
 public byte[] getBytes() throws JavaModelException {
   JavaElement pkg = (JavaElement) getParent();
   if (pkg instanceof JarPackageFragment) {
     JarPackageFragmentRoot root = (JarPackageFragmentRoot) pkg.getParent();
     ZipFile zip = null;
     try {
       zip = root.getJar();
       String entryName = Util.concatWith(((PackageFragment) pkg).names, getElementName(), '/');
       ZipEntry ze = zip.getEntry(entryName);
       if (ze != null) {
         return org.eclipse.jdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip);
       }
       throw new JavaModelException(
           new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
     } catch (IOException ioe) {
       throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
     } catch (CoreException e) {
       if (e instanceof JavaModelException) {
         throw (JavaModelException) e;
       } else {
         throw new JavaModelException(e);
       }
     } finally {
       JavaModelManager.getJavaModelManager().closeZipFile(zip);
     }
   } else {
     IFile file = (IFile) resource();
     return Util.getResourceContentsAsByteArray(file);
   }
 }
 /**
  * Sets the deltas to register the changes resulting from this operation for this source element
  * and its destination. If the operation is a cross project operation
  *
  * <ul>
  *   <li>On a copy, the delta should be rooted in the dest project
  *   <li>On a move, two deltas are generated
  *       <ul>
  *         <li>one rooted in the source project
  *         <li>one rooted in the destination project
  *       </ul>
  * </ul>
  *
  * If the operation is rooted in a single project, the delta is rooted in that project
  */
 protected void prepareDeltas(
     IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove) {
   if (Util.isExcluded(sourceElement) || Util.isExcluded(destinationElement)) return;
   IJavaProject destProject = destinationElement.getJavaProject();
   if (isMove) {
     IJavaProject sourceProject = sourceElement.getJavaProject();
     getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
     getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
   } else {
     getDeltaFor(destProject).added(destinationElement);
   }
 }
 private void updateReadOnlyPackageFragmentsForCopy(
     IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName) {
   IContainer parentFolder = (IContainer) root.resource();
   for (int i = 0, length = newFragName.length; i < length; i++) {
     String subFolderName = newFragName[i];
     parentFolder = parentFolder.getFolder(new Path(subFolderName));
     sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
     if (sourceFolder.exists() && Util.isReadOnly(sourceFolder)) {
       Util.setReadOnly(parentFolder, true);
     }
   }
 }
コード例 #5
0
  public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;

    /* ensure no concurrent write access to index */
    Index index =
        this.manager.getIndex(
            this.containerPath, true, /*reuse index file*/ false /*create if none*/);
    if (index == null) return true;
    ReadWriteMonitor monitor = index.monitor;
    if (monitor == null) return true; // index got deleted since acquired

    try {
      monitor.enterRead(); // ask permission to read
      String containerRelativePath =
          Util.relativePath(this.folderPath, this.containerPath.segmentCount());
      String[] paths = index.queryDocumentNames(containerRelativePath);
      // all file names belonging to the folder or its subfolders and that are not excluded (see
      // http://bugs.eclipse.org/bugs/show_bug.cgi?id=32607)
      if (paths != null) {
        if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
          for (int i = 0, max = paths.length; i < max; i++) {
            manager.remove(
                paths[i],
                this.containerPath); // write lock will be acquired by the remove operation
          }
        } else {
          for (int i = 0, max = paths.length; i < max; i++) {
            String documentPath = this.containerPath.toString() + '/' + paths[i];
            if (!Util.isExcluded(
                new Path(documentPath), this.inclusionPatterns, this.exclusionPatterns, false))
              manager.remove(
                  paths[i],
                  this.containerPath); // write lock will be acquired by the remove operation
          }
        }
      }
    } catch (IOException e) {
      if (JobManager.VERBOSE) {
        Util.verbose(
            "-> failed to remove "
                + this.folderPath
                + " from index because of the following exception:",
            System.err); // $NON-NLS-1$ //$NON-NLS-2$
        e.printStackTrace();
      }
      return false;
    } finally {
      monitor.exitRead(); // free read lock
    }
    return true;
  }
コード例 #6
0
  /*
   * Extract and store type signatures and arguments using unique key for parameterized types
   * and type parameters for non-generic ones
   */
  void storeTypeSignaturesAndArguments(IType type) {
    if (type.isResolved()) {
      BindingKey bindingKey = new BindingKey(type.getKey());
      if (bindingKey.isParameterizedType() || bindingKey.isRawType()) {
        String signature = bindingKey.toSignature();
        this.typeSignatures = Util.splitTypeLevelsSignature(signature);
        setTypeArguments(Util.getAllTypeArguments(this.typeSignatures));
      }
      return;
    }

    // Scan hierarchy to store type arguments at each level
    char[][][] typeParameters = new char[10][][];
    int ptr = -1;
    boolean hasParameters = false;
    try {
      IJavaElement parent = type;
      ITypeParameter[] parameters = null;
      while (parent != null && parent.getElementType() == IJavaElement.TYPE) {
        if (++ptr > typeParameters.length) {
          System.arraycopy(
              typeParameters, 0, typeParameters = new char[typeParameters.length + 10][][], 0, ptr);
        }
        IType parentType = (IType) parent;
        parameters = parentType.getTypeParameters();
        if (parameters != null) {
          int length = parameters.length;
          if (length > 0) {
            hasParameters = true;
            typeParameters[ptr] = new char[length][];
            for (int i = 0; i < length; i++)
              typeParameters[ptr][i] =
                  Signature.createTypeSignature(parameters[i].getElementName(), false)
                      .toCharArray();
          }
        }
        parent = parent.getParent();
      }
    } catch (JavaModelException jme) {
      return;
    }

    // Store type arguments if any
    if (hasParameters) {
      if (++ptr < typeParameters.length)
        System.arraycopy(typeParameters, 0, typeParameters = new char[ptr][][], 0, ptr);
      setTypeArguments(typeParameters);
    }
  }
コード例 #7
0
ファイル: ClassFile.java プロジェクト: felixdo/groovy-eclipse
 /* package */ static String simpleName(char[] className) {
   if (className == null) return null;
   String simpleName = new String(unqualifiedName(className));
   int lastDollar = simpleName.lastIndexOf('$');
   if (lastDollar != -1) return Util.localTypeName(simpleName, lastDollar, simpleName.length());
   else return simpleName;
 }
コード例 #8
0
ファイル: ClassFile.java プロジェクト: felixdo/groovy-eclipse
 public String getTypeName() {
   // Internal class file name doesn't contain ".class" file extension
   int lastDollar = this.name.lastIndexOf('$');
   return lastDollar > -1
       ? Util.localTypeName(this.name, lastDollar, this.name.length())
       : this.name;
 }
コード例 #9
0
 /**
  * Returns the registered Java like extensions. Taken from
  * org.eclipse.jdt.internal.core.util.Util.getJavaLikeExtensions
  */
 public static char[][] getGroovyLikeExtensions() {
   if (GROOVY_LIKE_EXTENSIONS == null) {
     Set<String> fileExtensions = loadGroovyFileExtensions();
     if (fileExtensions.isEmpty()) {
       // Shouldn't happen, but it seems it does.
       // See: STS-3936
       // Probably means user's workspace is already severely broken...
       // Still it is not nice to throw exceptions. So handle the case and log an error instead.
       if (!noGroovyContentTypesErrorLogged) {
         noGroovyContentTypesErrorLogged = true;
         Util.log(
             new IllegalStateException(
                 "No Groovy Content Types found. This shouldn't happen. Is the workspace metadata corrupted?"));
       }
       // Don't cache it. Maybe its only looking funky because we are looking 'too early'.
       return new char[][] {"groovy".toCharArray()};
     } else {
       int length = fileExtensions.size();
       char[][] extensions = new char[length][];
       extensions[0] = "groovy".toCharArray(); // ensure that "groovy" is first
       int index = 1;
       for (String fileExtension : fileExtensions) {
         if ("groovy".equals(fileExtension)) continue;
         extensions[index++] = fileExtension.toCharArray();
       }
       GROOVY_LIKE_EXTENSIONS = extensions;
     }
   }
   return GROOVY_LIKE_EXTENSIONS;
 }
コード例 #10
0
 /*
  * @see ITypeBinding#getSuperclass()
  */
 public synchronized ITypeBinding getSuperclass() {
   if (this.binding == null) return null;
   switch (this.binding.kind()) {
     case Binding.ARRAY_TYPE:
     case Binding.BASE_TYPE:
       return null;
     default:
       // no superclass for interface types (interface | annotation type)
       if (this.binding.isInterface()) return null;
   }
   ReferenceBinding superclass = null;
   try {
     superclass = ((ReferenceBinding) this.binding).superclass();
   } catch (RuntimeException e) {
     /* in case a method cannot be resolvable due to missing jars on the classpath
      * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871
      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
      */
     org.eclipse.jdt.internal.core.util.Util.log(
         e, "Could not retrieve superclass"); // $NON-NLS-1$
     return this.resolver.resolveWellKnownType("java.lang.Object"); // $NON-NLS-1$
   }
   if (superclass == null) {
     return null;
   }
   return this.resolver.getTypeBinding(superclass);
 }
コード例 #11
0
 /*
  * @see ITypeBinding#getDeclaredTypes()
  */
 public synchronized ITypeBinding[] getDeclaredTypes() {
   if (this.members != null) {
     return this.members;
   }
   try {
     if (isClass() || isInterface() || isEnum()) {
       ReferenceBinding referenceBinding = (ReferenceBinding) this.binding;
       ReferenceBinding[] internalMembers = referenceBinding.memberTypes();
       int length = internalMembers.length;
       if (length != 0) {
         ITypeBinding[] newMembers = new ITypeBinding[length];
         for (int i = 0; i < length; i++) {
           ITypeBinding typeBinding = this.resolver.getTypeBinding(internalMembers[i]);
           if (typeBinding == null) {
             return this.members = NO_TYPE_BINDINGS;
           }
           newMembers[i] = typeBinding;
         }
         return this.members = newMembers;
       }
     }
   } catch (RuntimeException e) {
     /* in case a method cannot be resolvable due to missing jars on the classpath
      * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871
      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
      * https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
      */
     org.eclipse.jdt.internal.core.util.Util.log(
         e, "Could not retrieve declared methods"); // $NON-NLS-1$
   }
   return this.members = NO_TYPE_BINDINGS;
 }
コード例 #12
0
  /** @see Openable#openBuffer(IProgressMonitor, Object) */
  protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    IBuffer buffer = this.owner.createBuffer(this);
    if (buffer == null) return null;

    // set the buffer source
    if (buffer.getCharacters() == null) {
      IBuffer classFileBuffer = this.classFile.getBuffer();
      if (classFileBuffer != null) {
        buffer.setContents(classFileBuffer.getCharacters());
      } else {
        // Disassemble
        IClassFileReader reader =
            ToolFactory.createDefaultClassFileReader(this.classFile, IClassFileReader.ALL);
        Disassembler disassembler = new Disassembler();
        String contents =
            disassembler.disassemble(
                reader,
                Util.getLineSeparator("", getJavaProject()),
                ClassFileBytesDisassembler.WORKING_COPY); // $NON-NLS-1$
        buffer.setContents(contents);
      }
    }

    // add buffer to buffer cache
    BufferManager bufManager = getBufferManager();
    bufManager.addBuffer(buffer);

    // listen to buffer changes
    buffer.addBufferChangedListener(this);

    return buffer;
  }
コード例 #13
0
  /**
   * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
   * necessary.
   *
   * @return an AST rewrite or null if no rewrite needed
   */
  private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
      throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
      return null; // nothing to change
    } else {
      // ensure cu is consistent (noop if already consistent)
      cu.makeConsistent(this.progressMonitor);

      // GROOVY start
      // don't use the ASTParser if not a Java compilation unit
      if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
        // ZALUUM
        // old return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        return LanguageSupportFactory.updateContent(cu, destPackageName, currPackageName, newName);
        // END ZALUUM
      }
      // GROOVY end

      this.parser.setSource(cu);
      CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
      AST ast = astCU.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);
      updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
      updatePackageStatement(astCU, destPackageName, rewrite, cu);
      return rewrite.rewriteAST();
    }
  }
コード例 #14
0
 /** @see IMethodBinding#getParameterTypes() */
 public ITypeBinding[] getParameterTypes() {
   if (this.parameterTypes != null) {
     return this.parameterTypes;
   }
   org.eclipse.jdt.internal.compiler.lookup.TypeBinding[] parameters = this.binding.parameters;
   int length = parameters == null ? 0 : parameters.length;
   if (length == 0) {
     return this.parameterTypes = NO_TYPE_BINDINGS;
   } else {
     ITypeBinding[] paramTypes = new ITypeBinding[length];
     for (int i = 0; i < length; i++) {
       final TypeBinding parameterBinding = parameters[i];
       if (parameterBinding != null) {
         ITypeBinding typeBinding = this.resolver.getTypeBinding(parameterBinding);
         if (typeBinding == null) {
           return this.parameterTypes = NO_TYPE_BINDINGS;
         }
         paramTypes[i] = typeBinding;
       } else {
         // log error
         StringBuffer message =
             new StringBuffer("Report method binding where a parameter is null:\n"); // $NON-NLS-1$
         message.append(toString());
         Util.log(new IllegalArgumentException(), message.toString());
         // report no binding since one or more parameter has no binding
         return this.parameterTypes = NO_TYPE_BINDINGS;
       }
     }
     return this.parameterTypes = paramTypes;
   }
 }
コード例 #15
0
 /**
  * Gets the module info for this compilation unit
  *
  * @param force if true, then a module info is created even if not a working copy. This occurs by
  *     temporarily turning the compilation unit into a working copy and then discarding it.
  * @return the {@link ModuleNodeInfo} for this compilation unit. Will be null if force is set to
  *     false and this unit is not a working copy. Also will be null if a problem occurs
  */
 public ModuleNodeInfo getModuleInfo(boolean force) {
   try {
     if (!isConsistent()) {
       makeConsistent(null);
     }
     boolean becameWorkingCopy = false;
     ModuleNodeMapper.getInstance().lock();
     // discard the working copy after finishing
     // if there was no working copy to begin with
     try {
       if (becameWorkingCopy = (force && !isWorkingCopy())) {
         becomeWorkingCopy(null);
       }
       PerWorkingCopyInfo info = getPerWorkingCopyInfo();
       if (info != null) {
         return ModuleNodeMapper.getInstance().get(info);
       }
     } finally {
       try {
         if (becameWorkingCopy) {
           discardWorkingCopy();
         }
       } finally {
         ModuleNodeMapper.getInstance().unlock();
       }
     }
   } catch (JavaModelException e) {
     Util.log(
         e,
         "Exception thrown when trying to get Groovy module node for "
             + this.getElementName()); // $NON-NLS-1$
   }
   // return null if not found. Means that there was a problem with build structure
   return null;
 }
コード例 #16
0
  protected boolean checkForClassFileChanges(
      IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount)
      throws CoreException {
    IResource resource = binaryDelta.getResource();
    // remember that if inclusion & exclusion patterns change then a full build is done
    boolean isExcluded =
        (md.exclusionPatterns != null || md.inclusionPatterns != null)
            && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
    switch (resource.getType()) {
      case IResource.FOLDER:
        if (isExcluded && md.inclusionPatterns == null)
          return true; // no need to go further with this delta since its children cannot be
        // included

        IResourceDelta[] children = binaryDelta.getAffectedChildren();
        for (int i = 0, l = children.length; i < l; i++)
          if (!checkForClassFileChanges(children[i], md, segmentCount)) return false;
        return true;
      case IResource.FILE:
        if (!isExcluded
            && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
          // perform full build if a managed class file has been changed
          IPath typePath =
              resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
          if (this.newState.isKnownType(typePath.toString())) {
            if (JavaBuilder.DEBUG)
              System.out.println(
                  "MUST DO FULL BUILD. Found change to class file " + typePath); // $NON-NLS-1$
            return false;
          }
          return true;
        }
    }
    return true;
  }
コード例 #17
0
  /** Returns the matching nodes that are in the given range in the source order. */
  protected ASTNode[] matchingNodes(int start, int end) {
    ArrayList nodes = null;
    Object[] keyTable = this.matchingNodes.keyTable;
    for (int i = 0, l = keyTable.length; i < l; i++) {
      ASTNode node = (ASTNode) keyTable[i];
      if (node != null && start <= node.sourceStart && node.sourceEnd <= end) {
        if (nodes == null) nodes = new ArrayList();
        nodes.add(node);
      }
    }
    if (nodes == null) return null;

    ASTNode[] result = new ASTNode[nodes.size()];
    nodes.toArray(result);

    // sort nodes by source starts
    Util.Comparer comparer =
        new Util.Comparer() {
          public int compare(Object o1, Object o2) {
            return ((ASTNode) o1).sourceStart - ((ASTNode) o2).sourceStart;
          }
        };
    Util.sort(result, comparer);
    return result;
  }
コード例 #18
0
 protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes)
     throws CoreException {
   try {
     byte[] oldBytes = Util.getResourceContentsAsByteArray(file);
     notEqual:
     if (newBytes.length == oldBytes.length) {
       for (int i = newBytes.length; --i >= 0; ) if (newBytes[i] != oldBytes[i]) break notEqual;
       return false; // bytes are identical so skip them
     }
     URI location = file.getLocationURI();
     if (location == null) return false; // unable to determine location of this class file
     String filePath = location.getSchemeSpecificPart();
     ClassFileReader reader = new ClassFileReader(oldBytes, filePath.toCharArray());
     // ignore local types since they're only visible inside a single method
     if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) {
       if (JavaBuilder.DEBUG)
         System.out.println("Type has structural changes " + fileName); // $NON-NLS-1$
       addDependentsOf(new Path(fileName), true);
       this.newState.wasStructurallyChanged(fileName);
     }
   } catch (ClassFormatException e) {
     addDependentsOf(new Path(fileName), true);
     this.newState.wasStructurallyChanged(fileName);
   }
   return true;
 }
コード例 #19
0
  public static IClasspathContainer readMavenClasspath(IJavaProject javaProject) {
    IFile file = javaProject.getProject().getFile(".che/classpath.maven");
    IClasspathEntry[] entries;
    if (file.exists()) {
      try {
        char[] chars = Util.getResourceContentsAsCharArray(file);
        String content = new String(chars);
        if (!content.isEmpty()) {
          String[] pathToJars = content.split(":");
          List<IClasspathEntry> classpathEntry = new ArrayList<>();
          for (String path : pathToJars) {
            String srcPath = path.substring(0, path.lastIndexOf('.')) + "-sources.jar";
            classpathEntry.add(
                JavaCore.newLibraryEntry(
                    new org.eclipse.core.runtime.Path(path),
                    new org.eclipse.core.runtime.Path(srcPath),
                    null));
          }
          entries = classpathEntry.toArray(new IClasspathEntry[classpathEntry.size()]);
        } else {
          entries = EMPTY;
        }
      } catch (JavaModelException e) {
        LOG.error("Can't read maven classpath.", e);
        entries = EMPTY;
      }
    } else {
      entries = EMPTY;
    }

    return new MavenClasspathContainer(entries);
  }
コード例 #20
0
  public void createPendingSourceArchives(IProgressMonitor monitor) throws CoreException {
    synchronized (this) {
      if (pendingSourceArchives == null || pendingSourceArchives.isEmpty()) return;
    }

    IProject externalSourceArchivesProject = null;
    externalSourceArchivesProject = createExternalSourceArchivesProject(monitor);
    // To avoid race condition (from addSourceArchive and removeSourceArchive, load the map elements
    // into an array and clear the map immediately.
    // The createLinkFolder being in the synchronized block can cause a deadlock and hence keep it
    // out of the synchronized block.
    Object[] arrayOfSourceArchives = null;
    synchronized (pendingSourceArchives) {
      arrayOfSourceArchives = pendingSourceArchives.toArray();
      pendingSourceArchives.clear();
    }

    for (int i = 0; i < arrayOfSourceArchives.length; i++) {
      try {
        createLinkFolder(
            (IPath) arrayOfSourceArchives[i], false, externalSourceArchivesProject, monitor);
      } catch (CoreException e) {
        Util.log(
            e,
            "Error while creating a link for external folder :"
                + arrayOfSourceArchives[i]); // $NON-NLS-1$
      }
    }
  }
コード例 #21
0
    public boolean visit(IResource resource) throws CoreException {
      if (resource.isDerived()) {
        return false;
      }

      handler.handleResourceStart(resource);

      if (resource.getType() == IResource.FILE
          && ContentTypeUtils.isGroovyLikeFileName(resource.getName())) {
        if (Util.isExcluded(resource, includes, excludes)) {
          return false;
        }

        GroovyCompilationUnit unit = (GroovyCompilationUnit) JavaCore.create((IFile) resource);
        if (unit != null && unit.isOnBuildPath()) {
          if (monitor.isCanceled()) {
            throw new OperationCanceledException();
          }
          monitor.subTask(resource.getName());
          handler.setResource((IFile) resource);
          Map<Integer, String> commentsMap = findComments(unit);
          StaticTypeCheckerRequestor requestor =
              new StaticTypeCheckerRequestor(handler, commentsMap, onlyAssertions);
          TypeInferencingVisitorWithRequestor visitor =
              new TypeInferencingVisitorFactory().createVisitor(unit);
          try {
            unit.becomeWorkingCopy(monitor);
            visitor.visitCompilationUnit(requestor);
          } finally {
            unit.discardWorkingCopy();
          }
        }
      }
      return true;
    }
コード例 #22
0
ファイル: Activator.java プロジェクト: felixdo/groovy-eclipse
 public void setPreference(IEclipsePreferences preferences, String key, List<String> vals) {
   if (preferences == null) {
     preferences = getProjectOrWorkspacePreferences(null);
   }
   String concat;
   if (vals == null) {
     concat = "";
   } else {
     // we should escape all ',' that happen to exist in the string, but
     // these should not be here since the strings were validated on entry
     StringBuilder sb = new StringBuilder();
     for (Iterator<String> valIter = vals.iterator(); valIter.hasNext(); ) {
       sb.append(valIter.next());
       if (valIter.hasNext()) {
         sb.append(",");
       }
     }
     concat = sb.toString();
   }
   preferences.put(key, concat);
   try {
     preferences.flush();
   } catch (BackingStoreException e) {
     Util.log(e);
   }
 }
コード例 #23
0
 private static void log(Exception e) {
   if (JavaCore.getPlugin() == null || JavaCore.getPlugin().getLog() == null) {
     System.err.println("Error creating Groovy language support:"); // $NON-NLS-1$
     e.printStackTrace(System.err);
   } else {
     Util.log(e, "Error creating Groovy language support"); // $NON-NLS-1$
   }
 }
 private void updateReadOnlyPackageFragmentsForMove(
     IContainer sourceFolder,
     PackageFragmentRoot root,
     String[] newFragName,
     boolean sourceFolderIsReadOnly) {
   IContainer parentFolder = (IContainer) root.resource();
   for (int i = 0, length = newFragName.length; i < length; i++) {
     String subFolderName = newFragName[i];
     parentFolder = parentFolder.getFolder(new Path(subFolderName));
     sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
     if ((sourceFolder.exists() && Util.isReadOnly(sourceFolder))
         || (i == length - 1 && sourceFolderIsReadOnly)) {
       Util.setReadOnly(parentFolder, true);
       // the source folder will be deleted anyway (move operation)
       Util.setReadOnly(sourceFolder, false);
     }
   }
 }
コード例 #25
0
ファイル: Activator.java プロジェクト: felixdo/groovy-eclipse
 public void setGroovyCompilerLevel(IProject project, String level) {
   IEclipsePreferences projectPreferences = getProjectScope(project);
   if (projectPreferences != null) {
     projectPreferences.put(GROOVY_COMPILER_LEVEL, level);
     try {
       projectPreferences.flush();
     } catch (BackingStoreException e) {
       Util.log(e);
     }
   }
 }
コード例 #26
0
 /**
  * Gets the module node for this compilation unit. Bypasses the cached module node and creates a
  * new one, which is then placed in the cache
  *
  * @return
  */
 public ModuleNodeInfo getNewModuleInfo() {
   try {
     openWhenClosed(
         createElementInfo(), false /* or should it be true... ? */, new NullProgressMonitor());
   } catch (JavaModelException e) {
     Util.log(
         e,
         "Exception thrown when trying to get Groovy module node for "
             + this.getElementName()); // $NON-NLS-1$
   }
   return getModuleInfo(true);
 }
コード例 #27
0
 private static String[] getJavaLikeExtensions() {
   char[][] exts = Util.getJavaLikeExtensions();
   if (exts != null && exts.length > 0) {
     String[] extStrs = new String[exts.length];
     for (int i = 0; i < exts.length; i++) {
       extStrs[i] = "*." + String.valueOf(exts[i]);
     }
     return extStrs;
   } else {
     return new String[] {"*.java"};
   }
 }
 /** Renames the main type in <code>cu</code>. */
 private void updateTypeName(
     ICompilationUnit cu,
     CompilationUnit astCU,
     String oldName,
     String newName,
     ASTRewrite rewriter)
     throws JavaModelException {
   if (newName != null) {
     String oldTypeName = Util.getNameWithoutJavaLikeExtension(oldName);
     String newTypeName = Util.getNameWithoutJavaLikeExtension(newName);
     AST ast = astCU.getAST();
     // update main type name
     IType[] types = cu.getTypes();
     for (int i = 0, max = types.length; i < max; i++) {
       IType currentType = types[i];
       if (currentType.getElementName().equals(oldTypeName)) {
         AbstractTypeDeclaration typeNode =
             (AbstractTypeDeclaration) ((JavaElement) currentType).findNode(astCU);
         if (typeNode != null) {
           // rename type
           rewriter.replace(typeNode.getName(), ast.newSimpleName(newTypeName), null);
           // rename constructors
           Iterator bodyDeclarations = typeNode.bodyDeclarations().iterator();
           while (bodyDeclarations.hasNext()) {
             Object bodyDeclaration = bodyDeclarations.next();
             if (bodyDeclaration instanceof MethodDeclaration) {
               MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
               if (methodDeclaration.isConstructor()) {
                 SimpleName methodName = methodDeclaration.getName();
                 if (methodName.getIdentifier().equals(oldTypeName)) {
                   rewriter.replace(methodName, ast.newSimpleName(newTypeName), null);
                 }
               }
             }
           }
         }
       }
     }
   }
 }
 /**
  * Creates any destination package fragment(s) which do not exists yet. Return true if a read-only
  * package fragment has been found among package fragments, false otherwise
  */
 private boolean createNeededPackageFragments(
     IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName, boolean moveFolder)
     throws JavaModelException {
   boolean containsReadOnlyPackageFragment = false;
   IContainer parentFolder = (IContainer) root.resource();
   JavaElementDelta projectDelta = null;
   String[] sideEffectPackageName = null;
   char[][] inclusionPatterns = root.fullInclusionPatternChars();
   char[][] exclusionPatterns = root.fullExclusionPatternChars();
   for (int i = 0; i < newFragName.length; i++) {
     String subFolderName = newFragName[i];
     sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
     IResource subFolder = parentFolder.findMember(subFolderName);
     if (subFolder == null) {
       // create deepest folder only if not a move (folder will be moved in
       // processPackageFragmentResource)
       if (!(moveFolder && i == newFragName.length - 1)) {
         createFolder(parentFolder, subFolderName, this.force);
       }
       parentFolder = parentFolder.getFolder(new Path(subFolderName));
       sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
       if (Util.isReadOnly(sourceFolder)) {
         containsReadOnlyPackageFragment = true;
       }
       IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName);
       if (i < newFragName.length - 1 // all but the last one are side effect packages
           && !Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
         if (projectDelta == null) {
           projectDelta = getDeltaFor(root.getJavaProject());
         }
         projectDelta.added(sideEffectPackage);
       }
       this.createdElements.add(sideEffectPackage);
     } else {
       parentFolder = (IContainer) subFolder;
     }
   }
   return containsReadOnlyPackageFragment;
 }
コード例 #30
0
ファイル: MemberValuePair.java プロジェクト: beefeather/ohl
 public boolean equals(Object obj) {
   if (!(obj instanceof MemberValuePair)) {
     return false;
   }
   MemberValuePair other = (MemberValuePair) obj;
   return this.valueKind == other.valueKind
       && this.memberName.equals(other.memberName)
       && (this.value == other.value
           || (this.value != null && this.value.equals(other.value))
           || (this.value instanceof Object[]
               && other.value instanceof Object[]
               && Util.equalArraysOrNull((Object[]) this.value, (Object[]) other.value)));
 }