Exemplo n.º 1
0
  protected void findMethods(
      char[] token, boolean canCompleteEmptyToken, List<IMethod> methods, int kind) {
    if (methods == null || methods.size() == 0) return;

    int length = token.length;
    String tok = new String(token);
    if (canCompleteEmptyToken || length > 0) {
      for (int i = 0; i < methods.size(); i++) {
        IMethod method = methods.get(i);
        String qname = processMethodName(method, tok);
        String name = qname;
        if (DEBUG) {
          System.out.println("Completion:" + qname); // $NON-NLS-1$
        }
        if (length <= name.length() && CharOperation.prefixEquals(token, name, false)) {
          int relevance = computeBaseRelevance();
          relevance += computeRelevanceForInterestingProposal();
          relevance += computeRelevanceForCaseMatching(token, name);
          relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no

          // accept result
          this.noProposal = false;
          if (!this.requestor.isIgnored(kind)) {
            CompletionProposal proposal = this.createProposal(kind, this.actualCompletionPosition);
            // proposal.setSignature(getSignature(typeBinding));
            // proposal.setPackageName(q);
            // proposal.setTypeName(displayName);
            proposal.setModelElement(method);
            try {
              proposal.setFlags(method.getFlags());
            } catch (ModelException e1) {
              if (DLTKCore.DEBUG) {
                e1.printStackTrace();
              }
            }
            String[] arguments = null;

            try {
              arguments = method.getParameterNames();
            } catch (ModelException e) {
              if (DLTKCore.DEBUG) {
                e.printStackTrace();
              }
            }
            if (arguments != null && arguments.length > 0) {
              proposal.setParameterNames(arguments);
            }

            proposal.setName(name);
            proposal.setCompletion(name);
            // proposal.setFlags(Flags.AccDefault);
            proposal.setRelevance(relevance);
            accept(proposal);
          }
        }
      }
    }
  }
  private void collectSuperClasses(IScriptProject project, String typeName, Set superClassSet) {

    Set typeSet = new HashSet();
    searchTypeDeclarations(project, typeName, typeSet);

    if (typeSet.isEmpty() != true) {
      IType itype;
      String[] superClasses;
      for (Iterator typeIter = typeSet.iterator(); typeIter.hasNext(); ) {
        itype = (IType) typeIter.next();
        if (itype.exists()) {
          try {
            superClasses = itype.getSuperClasses();
            if (superClasses != null) {
              for (int cnt = 0, max = superClasses.length; cnt < max; cnt++) {
                if (!superClassSet.contains(superClasses[cnt])) {
                  superClassSet.add(superClasses[cnt]);

                  collectSuperClasses(project, superClasses[cnt], superClassSet);
                }
              }
            }
          } catch (ModelException mxcn) {
            mxcn.printStackTrace();
          }
        }
      }
    }
  }
  /**
   * Search for magic variables using the @property tag
   *
   * @param types
   * @param variableName
   * @param cache
   */
  private void resolveMagicClassVariableDeclaration(
      IType[] types, String variableName, IModelAccessCache cache) {
    for (IType type : types) {
      resolveMagicClassVariableDeclaration(variableName, type, cache);
      try {
        if (evaluated.isEmpty()
            && type.getSuperClasses() != null
            && type.getSuperClasses().length > 0) {

          ITypeHierarchy hierarchy = null;
          if (cache != null) {
            hierarchy = cache.getSuperTypeHierarchy(type, null);
          }
          IType[] superClasses = PHPModelUtils.getSuperClasses(type, hierarchy);

          for (int i = 0; i < superClasses.length /* && evaluated.isEmpty() */; i++) {
            IType superClass = superClasses[i];
            resolveMagicClassVariableDeclaration(variableName, superClass, cache);
          }
        }
      } catch (ModelException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 4
0
  public static ISourceModule resolveSourceModule(FileStoreEditorInput input) {
    final ISourceModule[] modules = new ISourceModule[1];
    final IPath filePath = URIUtil.toPath(input.getURI());
    IScriptModel scriptModel = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot());
    try {
      scriptModel.accept(
          new IModelElementVisitor() {

            public boolean visit(IModelElement element) {
              boolean shouldDescend = (modules[0] == null);

              if (shouldDescend == true) {
                if (element instanceof ExternalProjectFragment) {
                  ExternalProjectFragment fragment = (ExternalProjectFragment) element;

                  try {
                    if (filePath
                            .removeLastSegments(1)
                            .toFile()
                            .getCanonicalPath()
                            .startsWith(fragment.getPath().toFile().getCanonicalPath())
                        == true) {
                      IPath folderPath =
                          new Path(filePath.removeLastSegments(1).toFile().getCanonicalPath());
                      folderPath =
                          folderPath.removeFirstSegments(
                              new Path(fragment.getPath().toFile().getCanonicalPath())
                                  .segmentCount());
                      IScriptFolder folder = fragment.getScriptFolder(folderPath);
                      if ((folder != null) && (folder.exists() == true)) {
                        ISourceModule module = folder.getSourceModule(filePath.lastSegment());
                        if (module != null) {
                          modules[0] = module;
                        }
                      }
                    }
                  } catch (IOException ixcn) {
                    ixcn.printStackTrace();
                  }

                  shouldDescend = false;
                } else {
                  shouldDescend =
                      ((element instanceof IScriptProject) || (element instanceof IScriptModel));
                }
              }

              return shouldDescend;
            }
          });
    } catch (ModelException mxcn) {
      mxcn.printStackTrace();
    }

    return modules[0];
  }
  public void installSymfony(IProgressMonitor monitor) {

    if (monitor == null) monitor = new NullProgressMonitor();

    SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;
    monitor.beginTask("Installing symfony...", 100);
    monitor.worked(10);

    IProject projectHandle = fFirstPage.getProjectHandle();
    final IScriptProject scriptProject = DLTKCore.create(projectHandle);

    File file = null;
    final List<IBuildpathEntry> entries = new ArrayList<IBuildpathEntry>();

    level = 0;

    try {

      file = new File(firstPage.getLibraryPath());
      symfonyPath = new Path(firstPage.getLibraryPath()).toString();

      if (file.isDirectory()) {

        final File[] files = file.listFiles();

        if (!scriptProject.isOpen()) {
          scriptProject.open(monitor);
        }

        if (files != null && scriptProject != null && scriptProject.isOpen()) {

          for (File f : files) {
            importFile(f, scriptProject.getProject(), entries);
          }

          BuildPathUtils.addEntriesToBuildPath(scriptProject, entries);
          monitor.worked(90);
        }
      }
    } catch (ModelException e) {
      e.printStackTrace();
      Logger.logException(e);
    } catch (Exception e) {
      e.printStackTrace();
      Logger.logException(e);
    } finally {

      monitor.worked(100);
      monitor.done();
    }
  }
Exemplo n.º 6
0
 public IScriptFolder getScriptFolder(String name) {
   try {
     IModelElement[] elements = getChildren();
     for (int i = 0; i < elements.length; i++) {
       if (elements[i].getElementName().equals(name)) {
         return (IScriptFolder) elements[i];
       }
     }
   } catch (ModelException e) {
     if (DLTKCore.DEBUG) {
       e.printStackTrace();
     }
   }
   return null;
 }
  private void initRelativeNamespace(ISourceModule sourceModule, int offset, String lastWord) {
    String nsName = lastWord;
    String fullName = lastWord;
    nsPrefix = null;
    if (lastWord.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR) > 0) {
      nsPrefix =
          lastWord.substring(0, lastWord.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR));
      nsName = nsName.substring(0, nsName.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR) + 1);

      try {
        namespaces = PHPModelUtils.getNamespaceOf(nsName, sourceModule, offset, null, null);
      } catch (ModelException e) {
        if (DLTKCore.DEBUG) {
          e.printStackTrace();
        }
      }
    } else {
      namespaces = PhpModelAccess.NULL_TYPES;
    }
    if (lastWord.startsWith(NamespaceReference.NAMESPACE_DELIMITER)) {
      nsPrefix = null;
    } else {

      currentNS = null;
      try {
        IModelElement enclosingElement = getEnclosingElement();
        if (enclosingElement != null) {
          IType type = (IType) enclosingElement.getAncestor(IModelElement.TYPE);
          if (type != null && type.getParent() instanceof IType) {
            type = (IType) type.getParent();
          }
          if (type != null && (PHPFlags.isNamespace(type.getFlags()))) {
            currentNS = type;
            fullName =
                NamespaceReference.NAMESPACE_SEPARATOR
                    + currentNS.getElementName()
                    + NamespaceReference.NAMESPACE_SEPARATOR
                    + lastWord;
          } else {

          }
        }
      } catch (ModelException e1) {
        e1.printStackTrace();
      }
      if (currentNS != null) {
        if (nsPrefix == null) {
          nsPrefix = currentNS.getElementName();
        } else {
          nsPrefix = currentNS.getElementName() + NamespaceReference.NAMESPACE_SEPARATOR + nsPrefix;
        }
      }
    }

    IDLTKSearchScope scope = SearchEngine.createSearchScope(sourceModule.getScriptProject());
    if (fullName.startsWith(NamespaceReference.NAMESPACE_DELIMITER)) {
      fullName = fullName.substring(1);
    }
    possibleNamespaces =
        PhpModelAccess.getDefault()
            .findNamespaces(null, fullName, MatchRule.PREFIX, 0, 0, scope, null);
  }
  @Override
  public Object execute(ExecutionEvent event) {

    //	Plugin.isManuallyStarted = true;

    System.out.println("ASIDECodeAnnotateHandler.java is ran ---first line");
    targetPart = HandlerUtil.getActivePart(event);

    IWorkbenchPartSite site = targetPart.getSite();
    ISelectionProvider selectionProvider = site.getSelectionProvider();
    if (selectionProvider == null) {
      return null;
    }
    ISelection selection = selectionProvider.getSelection();
    if (selection == null) {
      System.out.println("selectProject = ");
      return null;
    }
    IResource iRes = extractSelection(selection);
    if (iRes == null) {
      System.out.println("test == null");
      return null;
    }
    selectProject = iRes.getProject();
    if (selectProject == null) {
      System.out.println("selectProject == null");
      return null;
    }
    System.out.println("selectProject = " + selectProject.getName());

    // the following is temporarily added here
    pathCollector = ModelRegistry.getPathCollectorForProject(selectProject);

    if (pathCollector == null) {
      pathCollector = new PathCollector(selectProject);
    }

    paths = pathCollector.getAllPaths();

    if (paths == null) paths = Collections.synchronizedList(new ArrayList<Path>());

    System.out.println(
        "ASIDECodeAnnotateHandler.java is ran -- start iterating files of the project");
    IScriptProject scriptProject = DLTKCore.create(selectProject);
    if (scriptProject == null) {
      System.out.println("scirpt project == null");
      return null;
    }
    int count = 1;

    // gather statistics
    // GatherStatistics.NumOfWarningsInEachFile();
    // while tablename = ...

    Utils.removeAllQuestionMarkers(iRes);
    Plugin.projectResource = iRes;
    Iterator ite = Plugin.sensitive_DB_Tables.iterator();
    String currentSensitiveTableName = null;
    // commented out Nov. 27
    /*while(ite.hasNext()){
    currentSensitiveTableName = (String) ite.next();
    Plugin.CurrentSensitiveDBTable = currentSensitiveTableName;
    System.out.println("Current Table is=" + Plugin.CurrentSensitiveDBTable);*/

    String currentTableName;

    while (!Plugin.sensitive_DB_Tables_AlphRanked
        .isEmpty()) { // collect the warnings that comes from one table, one throughout iteration
                      // for each table, and put the results into the

      currentTableName = Plugin.sensitive_DB_Tables_AlphRanked.first();
      count = 1;
      Plugin.allMarkerRecords.clear();

      while (Plugin.sensitiveOperationsForCurrentIteration != null
          && Plugin.sensitiveOperationsForCurrentIteration.size() != 0) {
        count++;
        System.out.println("-----------------begin round " + count);
        System.out.println(
            "Plugin.sensitiveOperationsForCurrentIteration size =!!!"
                + Plugin.sensitiveOperationsForCurrentIteration.size());
        IScriptFolder[] folders = null;
        try {
          folders = scriptProject.getScriptFolders();
        } catch (ModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("number of folders ==" + folders.length);

        /*String pattern = "Exec";
        process(selectProject, pattern);*/

        ////////////////
        Plugin.sensitiveOperationsForAnotherIteration.clear();
        Plugin.sensitiveOperationsForAnotherIteration = new HashSet();
        //	System.out.println("at the begining point: size of current " +
        // Plugin.sensitiveOperationsForCurrentIteration.size());
        int numOfFiles = 0;
        for (IScriptFolder folder : folders) {
          String folderName = folder.getElementName();
          if (!Constants.PHPLibraryFolders.contains(folderName)) {

            ISourceModule[] sourceModules = null;
            try {
              sourceModules = folder.getSourceModules();
            } catch (ModelException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            numOfFiles += sourceModules.length;
          }
        }
        /*    for(int i = 0; i < 20; i++)
        System.out.println("files num = " + numOfFiles);*/
        System.out.println("sum of folders =" + folders.length);
        int currentFolderNum = 1;
        for (IScriptFolder folder : folders) {
          System.out.println("folder scanning = " + currentFolderNum + "/" + folders.length);
          String folderName = folder.getElementName();
          System.out.println("folder name = " + folderName);

          if (!Constants.PHPLibraryFolders.contains(folderName)) {

            ISourceModule[] sourceModules = null;
            try {
              sourceModules = folder.getSourceModules();
            } catch (ModelException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            for (ISourceModule tmpSourceModule : sourceModules) {
              System.out.println("scanning " + tmpSourceModule.getElementName());
              // if it is not the first time to run CodeAnnotate on this project, then disable the
              // scan function,
              // we have already pop the marker records from the file and displayed in Eclipse
              // already.
              if (false) {
              } // temporarily testing
              /*		if(Plugin.FIRST_TIME_RUN == false){
              	//simply display the markers based on the marker records in the file
              	String fileDir = tmpSourceModule.getResource().getFullPath().toString();
              	System.out.println("all markers size = " + Plugin.allMarkerRecords.size());
              	HashSet<MarkerRecord> markerRecordsInSingleFile = Utils.getMarkerRecordsForSingleFile(Plugin.allMarkerRecords, fileDir);
              	Utils.createMarkersForSingleFile(markerRecordsInSingleFile, tmpSourceModule);

              	HashSet<AnnotationRecord> annotationRecordsInSingleFile = Utils.getAnnotationRecordsForSingleFile(Plugin.allAnnotationRecords, fileDir);
              	Utils.createAnnotationsForSingleFile(annotationRecordsInSingleFile, tmpSourceModule);

              	System.out.println("finished creating markers for fileDir = " + fileDir + ", markerRecordsInSingleFile size = " + markerRecordsInSingleFile.size());
              }*/
              else { // start scanning the files for sensitive operations

                //			System.out.println("isourcemodule being built = " +
                // tmpSourceModule.getElementName().toLowerCase());
                //				System.out.println("full path of the source module is ---" +
                // tmpSourceModule.getResource().getFullPath().toString());

                SensitiveOperationVisitor visitor =
                    new SensitiveOperationVisitor(
                        tmpSourceModule,
                        Plugin.sensitiveOperationsForCurrentIteration,
                        Plugin.sensitiveOperationsForAnotherIteration,
                        Plugin.sensitiveOperations);
                Program root = null;
                try {
                  root = Utils.getCompilationUnit(tmpSourceModule);
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  System.err.println("root = util.getcompilationUnit() throws exception!");
                  e.printStackTrace();
                }
                //		System.out.println("begin of traverseTopDown");
                if (root == null) {
                  System.err.println(
                      "tmpSourceModule name = "
                          + tmpSourceModule.getElementName()
                          + " in "
                          + tmpSourceModule.getPath().toString());
                  System.err.println("root == null");
                  // return null;
                }
                root.traverseTopDown(visitor);

                Plugin.sensitiveOperations = visitor.getSensitiveOperations();
                Plugin.sensitiveOperationsForAnotherIteration =
                    visitor.getSensitiveOperationsForAnotherIteration();
              }
            }
          }
          currentFolderNum++;
        }
        Plugin.sensitiveOperationsForCurrentIteration.clear();
        Plugin.sensitiveOperationsForCurrentIteration = new HashSet();

        //	System.out.println("Plugin.sensitiveOperationsForAnotherIteration size after iteration ="
        // + Plugin.sensitiveOperationsForAnotherIteration.size());
        Plugin.sensitiveOperationsForCurrentIteration =
            (HashSet<SensitiveMethod>) Plugin.sensitiveOperationsForAnotherIteration.clone();
        //	System.out.println("after assignment, Plugin.sensitiveOperationsForCurrentIteratio size =
        // " + Plugin.sensitiveOperationsForCurrentIteration.size());

        /*String newRuleFileName = "newRulesForIteration" + count + "th.txt";
        InRunPluginDataSave.writeNewSensitiveRulesIntoFile(newRuleFileName, Plugin.sensitiveOperationsForCurrentIteration);

        String mappingFileName = "numOfWarningsInEachFileInIteration" + (count-1) + "th.txt";;
        InRunPluginDataSave.writeMappingBetweenWarningsAndFiles(mappingFileName, Plugin.numberOfWarningsInEachFile);

        if(count == 2){
        String newTableNamesFileName = "tableNamesEncounteredInIteration" + (count-1) + "th.txt";
        InRunPluginDataSave.writeTableNamesIntoFile(newTableNamesFileName, Plugin.allTableNames);

        String mappingFileName2 = "numOfWarningsRelatedToEachTableForIteration" + (count-1) + "th.txt";
        InRunPluginDataSave.writeMappingBetweenWarningsAndFiles(mappingFileName2, Plugin.numberOfWarningsRelatedToEachTable);
        }*/

        PostRunPluginConfig.writeMarkerRecordIntoFile(
            Plugin.allMarkerRecords, count, currentTableName);
      }

      //// newly added
      // remove the first table name in the treeset so that we focus on the next table in the next
      // iteration.
      Plugin.sensitive_DB_Tables_AlphRanked.pollFirst();
      Plugin.sensitiveOperationsForCurrentIteration = RulesUtils.getSensitiveOperations();
    }

    // commented out Nov. 27
    /*GatherStatistics.writeMarkersForEachTable(Plugin.allMarkerRecords, Plugin.CurrentSensitiveDBTable);
    Plugin.allMarkerRecords.clear();
    Plugin.allMarkerRecords = new HashSet();
    count = 1;
    Plugin.sensitiveOperationsForCurrentIteration.clear();
    Plugin.sensitiveOperationsForCurrentIteration = new HashSet();
    Plugin.sensitiveOperationsForCurrentIteration = (HashSet<SensitiveMethod>) Plugin.sensitiveOperationsForCurrentIteration_backup.clone();
    Plugin.sensitiveOperations.clear();
    Plugin.sensitiveOperations = new HashSet();
    Plugin.sensitiveOperations = (HashSet<SensitiveMethod>)Plugin.sensitiveOperations_backup.clone();
    }*/
    // above is temporarily added.

    // below are temporarily added for the analysis use
    //		GatherStatistics.filesWithoutRequiredAccessControls(Plugin.numberOfWarningsInEachFile,
    // Plugin.numberOfAccessControlsInEachFile);

    /*
     * Use a Job to attach a {@link CodeAnnotateDocumentEditListener} to
     * each and every IDocument that is related to a ICompilationUnit in the
     * selected project
     */
    /*
     * Job job = new MountListenerJob("Mount listener to Java file",
     * JavaCore.create(selectProject)); job.setPriority(Job.INTERACTIVE);
     * job.schedule();
     */

    /* Delegates all heavy lifting to {@link PathFinder} */
    /*Job heavy_job = new Job("Finding paths in Project: "
    				+ selectProject.getName()) {

    			@Override
    			protected IStatus run(final IProgressMonitor monitor) {
    				try {
    					Plugin.getDefault().getWorkbench().getDisplay()
    							.asyncExec(new Runnable() {

    								@Override
    								public void run() {
    									// PathFinder.getInstance(selectProject).run(monitor);

    								}

    							});

    				} finally {
    					monitor.done();
    				}
    				return Status.OK_STATUS;
    			}

    		};
    		heavy_job.setPriority(Job.LONG);
    		heavy_job.schedule();
    */
    System.out.println("finished scanning, marker records saved");
    // PostRunPluginConfig.config(Plugin.allMarkerRecords, Plugin.allAnnotationRecords);
    //	PostRunPluginConfig.writeMarkerRecordIntoFile(Plugin.allMarkerRecords, count);
    //		GatherStatistics.readWarningStatistics(Plugin.sensitive_DB_Tables_AlphRanked,
    // "Update_Level5.txt");
    return null;
  }
Exemplo n.º 9
0
  public IGoal[] init() {
    PHPDocClassVariableGoal typedGoal = (PHPDocClassVariableGoal) goal;
    TypeContext context = (TypeContext) typedGoal.getContext();
    String variableName = typedGoal.getVariableName();
    int offset = typedGoal.getOffset();

    IModelAccessCache cache = context.getCache();
    IType[] types =
        PHPTypeInferenceUtils.getModelElements(context.getInstanceType(), context, offset, cache);
    Map<PHPDocBlock, IField> docs = new HashMap<PHPDocBlock, IField>();
    // remove array index from field name
    if (variableName.endsWith("]")) { // $NON-NLS-1$
      int index = variableName.indexOf("["); // $NON-NLS-1$
      if (index != -1) {
        variableName = variableName.substring(0, index);
      }
    }
    if (types != null) {
      for (IType type : types) {
        try {
          // we look in whole hiearchy
          ITypeHierarchy superHierarchy;
          if (cache != null) {
            superHierarchy = cache.getSuperTypeHierarchy(type, null);
          } else {
            superHierarchy = type.newSupertypeHierarchy(null);
          }
          IType[] superTypes = superHierarchy.getAllTypes();
          for (IType superType : superTypes) {
            IField[] typeField = PHPModelUtils.getTypeField(superType, variableName, true);
            if (typeField.length > 0) {
              PHPDocBlock docBlock = PHPModelUtils.getDocBlock(typeField[0]);
              if (docBlock != null) {
                docs.put(docBlock, typeField[0]);
              }
            }
          }
        } catch (ModelException e) {
          if (DLTKCore.DEBUG) {
            e.printStackTrace();
          }
        }
      }
    }

    for (Entry<PHPDocBlock, IField> entry : docs.entrySet()) {
      PHPDocBlock doc = entry.getKey();
      IField typeField = entry.getValue();
      IType currentNamespace = PHPModelUtils.getCurrentNamespace(typeField);

      IModelElement space =
          currentNamespace != null ? currentNamespace : typeField.getSourceModule();

      for (PHPDocTag tag : doc.getTags(PHPDocTag.VAR)) {
        // do it like for
        // PHPDocumentationContentAccess#handleBlockTags(List tags):
        // variable name can be optional, but if present keep only
        // the good ones
        if (tag.getVariableReference() != null
            && !tag.getVariableReference().getName().equals(variableName)) {
          continue;
        }

        evaluated.addAll(
            Arrays.asList(
                PHPEvaluationUtils.evaluatePHPDocType(
                    tag.getTypeReferences(), space, tag.sourceStart(), null)));
      }
    }

    return IGoal.NO_GOALS;
  }
Exemplo n.º 10
0
  protected void reportAlias(
      ICompletionReporter reporter,
      String suffix,
      AbstractCompletionContext abstractContext,
      IModuleSource module,
      final Map<String, UsePart> result)
      throws BadLocationException {
    SourceRange replacementRange = getReplacementRange(abstractContext);
    String prefix = abstractContext.getPrefixWithoutProcessing();
    IDLTKSearchScope scope = createSearchScope();
    for (Iterator iterator = result.keySet().iterator(); iterator.hasNext(); ) {
      String name = (String) iterator.next();
      String fullName = result.get(name).getNamespace().getFullyQualifiedName();
      if (fullName.startsWith("\\")) {
        fullName = fullName.substring(1);
      }
      IType[] elements =
          PhpModelAccess.getDefault()
              .findTypes(null, fullName, MatchRule.PREFIX, 0, 0, scope, null);
      try {
        for (int i = 0; i < elements.length; i++) {
          String elementName = elements[i].getElementName();
          if (!PHPFlags.isNamespace(elements[i].getFlags())) {
            reportAlias(
                reporter,
                scope,
                module,
                replacementRange,
                elements[i],
                elementName,
                elementName.replace(fullName, name),
                suffix);
          } else {
            String nsname = prefix.replace(name, fullName);
            if (nsname.startsWith(elementName + SPLASH)
                && nsname.lastIndexOf(SPLASH) == elementName.length()) {
              // namespace strategy will handle this case
              continue;
            }
            IType[] typesOfNS = elements[i].getTypes();

            for (int j = 0; j < typesOfNS.length; j++) {
              reportAlias(
                  reporter,
                  scope,
                  module,
                  replacementRange,
                  typesOfNS[j],
                  elementName + SPLASH + typesOfNS[j].getElementName(),
                  (elementName + SPLASH + typesOfNS[j].getElementName()).replace(fullName, name),
                  suffix);
            }
          }
        }

        elements =
            PhpModelAccess.getDefault().findTypes(fullName, MatchRule.EXACT, 0, 0, scope, null);

        for (int i = 0; i < elements.length; i++) {
          String elementName = elements[i].getElementName();
          if (!PHPFlags.isNamespace(elements[i].getFlags())) {
            reportAlias(
                reporter, scope, module, replacementRange, elements[i], elementName, name, suffix);
          } else {
            String nsname = prefix.replace(name, fullName);
            if (nsname.startsWith(elementName + SPLASH)
                && nsname.lastIndexOf(SPLASH) == elementName.length()) {
              // namespace strategy will handle this case
              continue;
            }
            IType[] typesOfNS = elements[i].getTypes();

            for (int j = 0; j < typesOfNS.length; j++) {
              reportAlias(
                  reporter,
                  scope,
                  module,
                  replacementRange,
                  typesOfNS[j],
                  elementName + SPLASH + typesOfNS[j].getElementName(),
                  (elementName + SPLASH + typesOfNS[j].getElementName()).replace(fullName, name),
                  suffix);
            }
          }
        }
      } catch (ModelException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 11
0
 /**
  * Returns the package fragment root corresponding to a given resource path.
  *
  * @param resourcePathString path of expected package fragment root.
  * @return the {@link IProjectFragment package fragment root} which path match the given one or
  *     <code>null</code> if none was found.
  */
 public IProjectFragment projectFragment(String resourcePathString) {
   int index = -1;
   int separatorIndex = resourcePathString.indexOf(FILE_ENTRY_SEPARATOR);
   boolean isZIPFile = separatorIndex != -1;
   boolean isSpecial = resourcePathString.startsWith(IBuildpathEntry.BUILDPATH_SPECIAL);
   if (isZIPFile) {
     // internal or external jar (case 3, 4, or 5)
     String zipPath = resourcePathString.substring(0, separatorIndex);
     String relativePath = resourcePathString.substring(separatorIndex + 1);
     index = indexOf(zipPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IScriptProject project =
           DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isZIPFile) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       if (isSpecial) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       Object target =
           Model.getTarget(
               ResourcesPlugin.getWorkspace().getRoot(),
               Path.fromPortableString(
                   this.containerPaths[index] + '/' + this.relativePaths[index]),
               false);
       if (target instanceof IProject) {
         return project.getProjectFragment((IProject) target);
       }
       if (target instanceof IResource) {
         IModelElement element = DLTKCore.create((IResource) target);
         return (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
       }
       if (target instanceof IFileHandle) {
         try {
           IProjectFragment[] fragments = project.getProjectFragments();
           IFileHandle t = (IFileHandle) target;
           IPath absPath = t.getFullPath();
           for (int i = 0; i < fragments.length; ++i) {
             IProjectFragment f = fragments[i];
             if (f.isExternal()) {
               IPath pPath = f.getPath();
               if (pPath.isPrefixOf(absPath) && !Util.isExcluded(absPath, f, t.isDirectory())) {
                 return f;
               }
             }
           }
         } catch (ModelException e) {
           e.printStackTrace();
           return null;
         }
       }
     }
   }
   return null;
 }