Пример #1
0
  /**
   * Update token map with a set of token/endpoint pairs in normal state.
   *
   * <p>Prefer this whenever there are multiple pairs to update, as each update (whether a single or
   * multiple) is expensive (CASSANDRA-3831).
   *
   * @param endpointTokens
   */
  public void updateNormalTokens(Multimap<InetAddress, Token> endpointTokens) {
    if (endpointTokens.isEmpty()) return;

    lock.writeLock().lock();
    try {
      boolean shouldSortTokens = false;
      for (InetAddress endpoint : endpointTokens.keySet()) {
        Collection<Token> tokens = endpointTokens.get(endpoint);

        assert tokens != null && !tokens.isEmpty();

        bootstrapTokens.removeValue(endpoint);
        tokenToEndpointMap.removeValue(endpoint);
        topology.addEndpoint(endpoint);
        leavingEndpoints.remove(endpoint);
        removeFromMoving(endpoint); // also removing this endpoint from moving

        for (Token token : tokens) {
          InetAddress prev = tokenToEndpointMap.put(token, endpoint);
          if (!endpoint.equals(prev)) {
            if (prev != null)
              logger.warn("Token {} changing ownership from {} to {}", token, prev, endpoint);
            shouldSortTokens = true;
          }
        }
      }

      if (shouldSortTokens) sortedTokens = sortTokens();
    } finally {
      lock.writeLock().unlock();
    }
  }
Пример #2
0
  public void checkRedeclarationsInInnerClassNames(@NotNull TopDownAnalysisContext c) {
    for (ClassDescriptorWithResolutionScopes classDescriptor : c.getDeclaredClasses().values()) {
      if (classDescriptor.getKind() == ClassKind.CLASS_OBJECT) {
        // Class objects should be considered during analysing redeclarations in classes
        continue;
      }

      Collection<DeclarationDescriptor> allDescriptors =
          classDescriptor.getScopeForMemberLookup().getOwnDeclaredDescriptors();

      ClassDescriptorWithResolutionScopes classObj = classDescriptor.getClassObjectDescriptor();
      if (classObj != null) {
        Collection<DeclarationDescriptor> classObjDescriptors =
            classObj.getScopeForMemberLookup().getOwnDeclaredDescriptors();
        if (!classObjDescriptors.isEmpty()) {
          allDescriptors = Lists.newArrayList(allDescriptors);
          allDescriptors.addAll(classObjDescriptors);
        }
      }

      Multimap<Name, DeclarationDescriptor> descriptorMap = HashMultimap.create();
      for (DeclarationDescriptor desc : allDescriptors) {
        if (desc instanceof ClassDescriptor || desc instanceof PropertyDescriptor) {
          descriptorMap.put(desc.getName(), desc);
        }
      }

      reportRedeclarations(descriptorMap);
    }
  }
  /**
   * 将原始数据切割后装入ThreadInfo,并以Key=WaitID,Value= ThreadInfo实体放入到Multimap<String, ThreadInfo>集合中
   * ps:Multimap 类似于Map<key,collection>, key:value-> 1:n
   *
   * @param rawDatas
   * @return
   */
  public Multimap<String, ThreadInfo> getThreadInfo(List<String[]> rawDatas) {
    Multimap<String, ThreadInfo> w_IdMap = HashMultimap.create();
    List<ThreadInfo> threadsList = Lists.newArrayList();
    for (String[] rawData : rawDatas) {
      ThreadInfo threadInfo = new ThreadInfo();
      Pattern t_id = Pattern.compile("tid=(0x[\\d\\w]+)");
      Pattern t_name = Pattern.compile("\"([\\d\\D]*)\"");
      Pattern w_Id = Pattern.compile("\\[(0x[\\d\\w]+)\\]");
      Matcher tIdMatcher = t_id.matcher(rawData[0]);
      Matcher nameMatcher = t_name.matcher(rawData[0]);
      Matcher w_IdMatcher = w_Id.matcher(rawData[0]);
      if (tIdMatcher.find()) {
        threadInfo.setThreadId(tIdMatcher.group(1));
      }

      if (nameMatcher.find()) {
        threadInfo.setThreadName(nameMatcher.group(1));
      }

      if (w_IdMatcher.find()) {
        threadInfo.setWaitThreadId(w_IdMatcher.group(1));
      }
      threadInfo.setThreadCondition(rawData[1]);
      w_IdMap.put(threadInfo.getWaitThreadId(), threadInfo);
    }
    return w_IdMap;
  }
Пример #4
0
  // Returns list with type arguments info from supertypes
  // Example:
  //     - Foo<A, B> is a subtype of Bar<A, List<B>>, Baz<Boolean, A>
  //     - input: klass = Foo, typesFromSuper = [Bar<String, List<Int>>, Baz<Boolean, CharSequence>]
  //     - output[0] = [String, CharSequence], output[1] = []
  private static List<List<TypeProjectionAndVariance>> calculateTypeArgumentsFromSuper(
      @NotNull ClassDescriptor klass, @NotNull Collection<TypeAndVariance> typesFromSuper) {
    // For each superclass of klass and its parameters, hold their mapping to klass' parameters
    // #0 of Bar ->  A
    // #1 of Bar ->  List<B>
    // #0 of Baz ->  Boolean
    // #1 of Baz ->  A
    // #0 of Foo ->  A (mapped to itself)
    // #1 of Foo ->  B (mapped to itself)
    Multimap<TypeConstructor, TypeProjection> substitution =
        SubstitutionUtils.buildDeepSubstitutionMultimap(
            TypeUtils.makeUnsubstitutedType(klass, JetScope.EMPTY));

    // for each parameter of klass, hold arguments in corresponding supertypes
    List<List<TypeProjectionAndVariance>> parameterToArgumentsFromSuper = Lists.newArrayList();
    for (TypeParameterDescriptor ignored : klass.getTypeConstructor().getParameters()) {
      parameterToArgumentsFromSuper.add(new ArrayList<TypeProjectionAndVariance>());
    }

    // Enumerate all types from super and all its parameters
    for (TypeAndVariance typeFromSuper : typesFromSuper) {
      for (TypeParameterDescriptor parameter :
          typeFromSuper.type.getConstructor().getParameters()) {
        TypeProjection argument = typeFromSuper.type.getArguments().get(parameter.getIndex());

        // for given example, this block is executed four times:
        // 1. typeFromSuper = Bar<String, List<Int>>,      parameter = "#0 of Bar",  argument =
        // String
        // 2. typeFromSuper = Bar<String, List<Int>>,      parameter = "#1 of Bar",  argument =
        // List<Int>
        // 3. typeFromSuper = Baz<Boolean, CharSequence>,  parameter = "#0 of Baz",  argument =
        // Boolean
        // 4. typeFromSuper = Baz<Boolean, CharSequence>,  parameter = "#1 of Baz",  argument =
        // CharSequence

        // if it is mapped to klass' parameter, then store it into map
        for (TypeProjection projection : substitution.get(parameter.getTypeConstructor())) {
          // 1. projection = A
          // 2. projection = List<B>
          // 3. projection = Boolean
          // 4. projection = A
          ClassifierDescriptor classifier =
              projection.getType().getConstructor().getDeclarationDescriptor();

          // this condition is true for 1 and 4, false for 2 and 3
          if (classifier instanceof TypeParameterDescriptor
              && classifier.getContainingDeclaration() == klass) {
            int parameterIndex = ((TypeParameterDescriptor) classifier).getIndex();
            Variance effectiveVariance =
                parameter.getVariance().superpose(typeFromSuper.varianceOfPosition);
            parameterToArgumentsFromSuper
                .get(parameterIndex)
                .add(new TypeProjectionAndVariance(argument, effectiveVariance));
          }
        }
      }
    }
    return parameterToArgumentsFromSuper;
  }
Пример #5
0
  private int repeatInternal(
      @NotNull PseudocodeImpl originalPseudocode,
      @Nullable Label startLabel,
      @Nullable Label finishLabel,
      int labelCount) {
    Integer startIndex =
        startLabel != null
            ? ((PseudocodeLabel) startLabel).getTargetInstructionIndex()
            : Integer.valueOf(0);
    assert startIndex != null;
    Integer finishIndex =
        finishLabel != null
            ? ((PseudocodeLabel) finishLabel).getTargetInstructionIndex()
            : Integer.valueOf(originalPseudocode.mutableInstructionList.size());
    assert finishIndex != null;

    Map<Label, Label> originalToCopy = Maps.newLinkedHashMap();
    Multimap<Instruction, Label> originalLabelsForInstruction = HashMultimap.create();
    for (PseudocodeLabel label : originalPseudocode.labels) {
      Integer index = label.getTargetInstructionIndex();
      if (index == null) continue; // label is not bounded yet
      if (label == startLabel || label == finishLabel) continue;

      if (startIndex <= index && index <= finishIndex) {
        originalToCopy.put(label, label.copy(labelCount++));
        originalLabelsForInstruction.put(getJumpTarget(label), label);
      }
    }
    for (Label label : originalToCopy.values()) {
      labels.add((PseudocodeLabel) label);
    }
    for (int index = startIndex; index < finishIndex; index++) {
      Instruction originalInstruction = originalPseudocode.mutableInstructionList.get(index);
      repeatLabelsBindingForInstruction(
          originalInstruction, originalToCopy, originalLabelsForInstruction);
      Instruction copy = copyInstruction(originalInstruction, originalToCopy);
      addInstruction(copy);
      if (originalInstruction == originalPseudocode.errorInstruction
          && copy instanceof SubroutineExitInstruction) {
        errorInstruction = (SubroutineExitInstruction) copy;
      }
      if (originalInstruction == originalPseudocode.exitInstruction
          && copy instanceof SubroutineExitInstruction) {
        exitInstruction = (SubroutineExitInstruction) copy;
      }
      if (originalInstruction == originalPseudocode.sinkInstruction
          && copy instanceof SubroutineSinkInstruction) {
        sinkInstruction = (SubroutineSinkInstruction) copy;
      }
    }
    if (finishIndex < mutableInstructionList.size()) {
      repeatLabelsBindingForInstruction(
          originalPseudocode.mutableInstructionList.get(finishIndex),
          originalToCopy,
          originalLabelsForInstruction);
    }
    return labelCount;
  }
Пример #6
0
  public String toGraphviz() {
    StringBuilder builder = new StringBuilder();

    builder.append("digraph QuantileDigest {\n").append("\tgraph [ordering=\"out\"];");

    final List<Node> nodes = new ArrayList<>();
    postOrderTraversal(
        root,
        new Callback() {
          @Override
          public boolean process(Node node) {
            nodes.add(node);
            return true;
          }
        });

    Multimap<Integer, Node> nodesByLevel =
        Multimaps.index(
            nodes,
            new Function<Node, Integer>() {
              @Override
              public Integer apply(Node input) {
                return input.level;
              }
            });

    for (Map.Entry<Integer, Collection<Node>> entry : nodesByLevel.asMap().entrySet()) {
      builder.append("\tsubgraph level_" + entry.getKey() + " {\n").append("\t\trank = same;\n");

      for (Node node : entry.getValue()) {
        builder.append(
            String.format(
                "\t\t%s [label=\"[%s..%s]@%s\\n%s\", shape=rect, style=filled,color=%s];\n",
                idFor(node),
                node.getLowerBound(),
                node.getUpperBound(),
                node.level,
                node.weightedCount,
                node.weightedCount > 0 ? "salmon2" : "white"));
      }

      builder.append("\t}\n");
    }

    for (Node node : nodes) {
      if (node.left != null) {
        builder.append(format("\t%s -> %s;\n", idFor(node), idFor(node.left)));
      }
      if (node.right != null) {
        builder.append(format("\t%s -> %s;\n", idFor(node), idFor(node.right)));
      }
    }

    builder.append("}\n");

    return builder.toString();
  }
Пример #7
0
 /** @return an endpoint to token multimap representation of tokenToEndpointMap (a copy) */
 public Multimap<InetAddress, Token> getEndpointToTokenMapForReading() {
   lock.readLock().lock();
   try {
     Multimap<InetAddress, Token> cloned = HashMultimap.create();
     for (Map.Entry<Token, InetAddress> entry : tokenToEndpointMap.entrySet())
       cloned.put(entry.getValue(), entry.getKey());
     return cloned;
   } finally {
     lock.readLock().unlock();
   }
 }
Пример #8
0
 /**
  * expand super types after scanning, for super types that were not scanned. this is helpful in
  * finding the transitive closure without scanning all 3rd party dependencies. it uses {@link
  * ReflectionUtils#getSuperTypes(Class)}.
  *
  * <p>for example, for classes A,B,C where A supertype of B, B supertype of C:
  *
  * <ul>
  *   <li>if scanning C resulted in B (B->C in store), but A was not scanned (although A supertype
  *       of B) - then getSubTypes(A) will not return C
  *   <li>if expanding supertypes, B will be expanded with A (A->B in store) - then getSubTypes(A)
  *       will return C
  * </ul>
  */
 public void expandSuperTypes() {
   if (store.keySet().contains(index(SubTypesScanner.class))) {
     Multimap<String, String> mmap = store.get(index(SubTypesScanner.class));
     Sets.SetView<String> keys = Sets.difference(mmap.keySet(), Sets.newHashSet(mmap.values()));
     Multimap<String, String> expand = HashMultimap.create();
     for (String key : keys) {
       expandSupertypes(expand, key, forName(key));
     }
     mmap.putAll(expand);
   }
 }
Пример #9
0
 /**
  * Helper used by scanXyz methods below to check whether a directory should be visited. It can be
  * skipped if it's not a directory or if it's already marked as visited in mVisitedDirs for the
  * given package type -- in which case the directory is added to the visited map.
  *
  * @param pkgType The package type being scanned.
  * @param directory The file or directory to check.
  * @return False if directory can/should be skipped. True if directory should be visited, in which
  *     case it's registered in mVisitedDirs.
  */
 private boolean shouldVisitDir(@NonNull PkgType pkgType, @NonNull File directory) {
   if (!mFileOp.isDirectory(directory)) {
     return false;
   }
   synchronized (mLocalPackages) {
     if (mVisitedDirs.containsEntry(pkgType, new LocalDirInfo.MapComparator(directory))) {
       return false;
     }
     mVisitedDirs.put(pkgType, new LocalDirInfo(mFileOp, directory));
   }
   return true;
 }
Пример #10
0
 /** merges a Reflections instance metadata into this instance */
 public Reflections merge(final Reflections reflections) {
   if (reflections.store != null) {
     for (String indexName : reflections.store.keySet()) {
       Multimap<String, String> index = reflections.store.get(indexName);
       for (String key : index.keySet()) {
         for (String string : index.get(key)) {
           store.getOrCreate(indexName).put(key, string);
         }
       }
     }
   }
   return this;
 }
Пример #11
0
  /**
   * For unique local packages. Returns the cached LocalPkgInfo for the requested type. Loads it
   * from disk if not cached.
   *
   * @param filter {@link PkgType#PKG_TOOLS} or {@link PkgType#PKG_PLATFORM_TOOLS} or {@link
   *     PkgType#PKG_DOC}.
   * @return null if the package is not installed.
   */
  @Nullable
  public LocalPkgInfo getPkgInfo(@NonNull PkgType filter) {
    if (filter != PkgType.PKG_TOOLS
        && filter != PkgType.PKG_PLATFORM_TOOLS
        && filter != PkgType.PKG_DOC
        && filter != PkgType.PKG_NDK) {
      assert false;
      return null;
    }

    LocalPkgInfo info = null;
    synchronized (mLocalPackages) {
      Collection<LocalPkgInfo> existing = mLocalPackages.get(filter);
      assert existing.size() <= 1;
      if (!existing.isEmpty()) {
        return existing.iterator().next();
      }

      File uniqueDir = new File(mSdkRoot, filter.getFolderName());

      if (!mVisitedDirs.containsEntry(filter, new LocalDirInfo.MapComparator(uniqueDir))) {
        switch (filter) {
          case PKG_TOOLS:
            info = scanTools(uniqueDir);
            break;
          case PKG_PLATFORM_TOOLS:
            info = scanPlatformTools(uniqueDir);
            break;
          case PKG_DOC:
            info = scanDoc(uniqueDir);
            break;
          case PKG_NDK:
            info = scanNdk(uniqueDir);
          default:
            break;
        }
      }

      // Whether we have found a valid pkg or not, this directory has been visited.
      mVisitedDirs.put(filter, new LocalDirInfo(mFileOp, uniqueDir));

      if (info != null) {
        mLocalPackages.put(filter, info);
      }
    }

    return info;
  }
Пример #12
0
  /**
   * Clear the tracked visited folders & the cached {@link LocalPkgInfo} for the given filter types.
   *
   * @param filters A set of PkgType constants or {@link PkgType#PKG_ALL} to clear everything.
   */
  public void clearLocalPkg(@NonNull EnumSet<PkgType> filters) {
    mLegacyBuildTools = null;

    synchronized (mLocalPackages) {
      for (PkgType filter : filters) {
        mVisitedDirs.removeAll(filter);
        mLocalPackages.removeAll(filter);
      }

      // Clear the targets if the platforms or addons are being cleared
      if (filters.contains(PkgType.PKG_PLATFORM) || filters.contains(PkgType.PKG_ADDON)) {
        mCachedMissingTargets = null;
        mCachedTargets = null;
      }
    }
  }
Пример #13
0
 private FunctionEntry add(String name, Function function) {
   final FunctionEntryImpl entry = new FunctionEntryImpl(this, name, function);
   functionMap.put(name, entry);
   if (function.getParameters().isEmpty()) {
     nullaryFunctionMapInsensitive.put(name, entry);
   }
   return entry;
 }
Пример #14
0
 private void expandSupertypes(Multimap<String, String> mmap, String key, Class<?> type) {
   for (Class<?> supertype : ReflectionUtils.getSuperTypes(type)) {
     if (mmap.put(supertype.getName(), key)) {
       if (log != null) log.debug("expanded subtype {} -> {}", supertype.getName(), key);
       expandSupertypes(mmap, supertype.getName(), supertype);
     }
   }
 }
Пример #15
0
 private void repeatLabelsBindingForInstruction(
     @NotNull Instruction originalInstruction,
     @NotNull Map<Label, Label> originalToCopy,
     @NotNull Multimap<Instruction, Label> originalLabelsForInstruction) {
   for (Label originalLabel : originalLabelsForInstruction.get(originalInstruction)) {
     bindLabel(originalToCopy.get(originalLabel));
   }
 }
Пример #16
0
    /** Stores current DC/rack assignment for ep */
    protected void addEndpoint(InetAddress ep) {
      IEndpointSnitch snitch = DatabaseDescriptor.getEndpointSnitch();
      String dc = snitch.getDatacenter(ep);
      String rack = snitch.getRack(ep);
      Pair<String, String> current = currentLocations.get(ep);
      if (current != null) {
        if (current.left.equals(dc) && current.right.equals(rack)) return;
        dcRacks.get(current.left).remove(current.right, ep);
        dcEndpoints.remove(current.left, ep);
      }

      dcEndpoints.put(dc, ep);

      if (!dcRacks.containsKey(dc)) dcRacks.put(dc, HashMultimap.<String, InetAddress>create());
      dcRacks.get(dc).put(rack, ep);

      currentLocations.put(ep, Pair.create(dc, rack));
    }
 /**
  * 按照对应关系对 aitID:threadInfo-> 1:n 对N从大到小排序 处理MulitMap中的数据,key:value->1:n 取出<key, n>
  * 对n降序排序后,取得序列后的List<Map.Entry<key, n>>
  *
  * @return
  */
 public List<Map.Entry<String, Integer>> getOrderList(Multimap<String, ThreadInfo> w_IdMap) {
   Set<String> keys = w_IdMap.keySet();
   Map<String, Integer> w_IdMappingThread = Maps.newHashMap();
   for (String key : keys) {
     Collection<ThreadInfo> values = w_IdMap.get(key);
     w_IdMappingThread.put(key, values.size());
   }
   List<Map.Entry<String, Integer>> orderList =
       new ArrayList<Map.Entry<String, Integer>>(w_IdMappingThread.entrySet());
   Collections.sort(
       orderList,
       new Comparator<Map.Entry<String, Integer>>() {
         @Override
         public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
           return o2.getValue().compareTo(o1.getValue());
         }
       });
   return orderList;
 }
Пример #18
0
  private void checkRedeclarationsInPackages(@NotNull TopDownAnalysisContext c) {
    for (MutablePackageFragmentDescriptor packageFragment :
        Sets.newHashSet(c.getPackageFragments().values())) {
      PackageViewDescriptor packageView =
          packageFragment.getContainingDeclaration().getPackage(packageFragment.getFqName());
      JetScope packageViewScope = packageView.getMemberScope();
      Multimap<Name, DeclarationDescriptor> simpleNameDescriptors =
          packageFragment.getMemberScope().getDeclaredDescriptorsAccessibleBySimpleName();
      for (Name name : simpleNameDescriptors.keySet()) {
        // Keep only properties with no receiver
        Collection<DeclarationDescriptor> descriptors =
            Collections2.filter(
                simpleNameDescriptors.get(name),
                new Predicate<DeclarationDescriptor>() {
                  @Override
                  public boolean apply(@Nullable DeclarationDescriptor descriptor) {
                    if (descriptor instanceof PropertyDescriptor) {
                      PropertyDescriptor propertyDescriptor = (PropertyDescriptor) descriptor;
                      return propertyDescriptor.getReceiverParameter() == null;
                    }
                    return true;
                  }
                });
        ContainerUtil.addIfNotNull(descriptors, packageViewScope.getPackage(name));

        if (descriptors.size() > 1) {
          for (DeclarationDescriptor declarationDescriptor : descriptors) {
            for (PsiElement declaration : getDeclarationsByDescriptor(declarationDescriptor)) {
              assert declaration != null
                  : "Null declaration for descriptor: "
                      + declarationDescriptor
                      + " "
                      + (declarationDescriptor != null
                          ? DescriptorRenderer.FQ_NAMES_IN_TYPES.render(declarationDescriptor)
                          : "");
              trace.report(
                  REDECLARATION.on(declaration, declarationDescriptor.getName().asString()));
            }
          }
        }
      }
    }
  }
 /** 按照要求打印结果 */
 public void printStackInfo(Multimap<String, ThreadInfo> w_IdMap) {
   List<Map.Entry<String, Integer>> orderList = getOrderList(w_IdMap);
   for (Map.Entry<String, Integer> entry : orderList) {
     logger.info(entry.getKey() + "," + entry.getValue()); // 输出wait_id 对应个数
     Collection<ThreadInfo> threads = w_IdMap.get(entry.getKey()); // 输出wait_id对应的ThreadInfo集合
     for (ThreadInfo thread : threads) {
       logger.info("{}", thread);
     }
     logger.info("");
   }
 }
Пример #20
0
  /**
   * Check the tracked visited folders to see if anything has changed for the requested filter
   * types. This does not refresh or reload any package information.
   *
   * @param filters A set of PkgType constants or {@link PkgType#PKG_ALL} to clear everything.
   */
  public boolean hasChanged(@NonNull EnumSet<PkgType> filters) {
    for (PkgType filter : filters) {
      Collection<LocalDirInfo> dirInfos;
      synchronized (mLocalPackages) {
        dirInfos = mVisitedDirs.get(filter);
        for (LocalDirInfo dirInfo : dirInfos) {
          if (dirInfo.hasChanged()) {
            return true;
          }
        }
      }
    }

    return false;
  }
Пример #21
0
  private void reportRedeclarations(@NotNull Multimap<Name, DeclarationDescriptor> descriptorMap) {
    Set<Pair<PsiElement, Name>> redeclarations = Sets.newHashSet();
    for (Name name : descriptorMap.keySet()) {
      Collection<DeclarationDescriptor> descriptors = descriptorMap.get(name);
      if (descriptors.size() > 1) {
        // We mustn't compare PropertyDescriptor with PropertyDescriptor because we do this at
        // OverloadResolver
        for (DeclarationDescriptor descriptor : descriptors) {
          if (descriptor instanceof ClassDescriptor) {
            for (DeclarationDescriptor descriptor2 : descriptors) {
              if (descriptor == descriptor2) {
                continue;
              }

              redeclarations.add(
                  Pair.create(
                      BindingContextUtils.classDescriptorToDeclaration(
                          trace.getBindingContext(), (ClassDescriptor) descriptor),
                      descriptor.getName()));
              if (descriptor2 instanceof PropertyDescriptor) {
                redeclarations.add(
                    Pair.create(
                        BindingContextUtils.descriptorToDeclaration(
                            trace.getBindingContext(), descriptor2),
                        descriptor2.getName()));
              }
            }
          }
        }
      }
    }
    for (Pair<PsiElement, Name> redeclaration : redeclarations) {
      trace.report(
          REDECLARATION.on(redeclaration.getFirst(), redeclaration.getSecond().asString()));
    }
  }
Пример #22
0
  public void checkRedeclarationsInPackages(
      @NotNull KotlinCodeAnalyzer resolveSession,
      @NotNull Multimap<FqName, JetElement> topLevelFqNames) {
    for (Map.Entry<FqName, Collection<JetElement>> entry : topLevelFqNames.asMap().entrySet()) {
      FqName fqName = entry.getKey();
      Collection<JetElement> declarationsOrPackageDirectives = entry.getValue();

      if (fqName.isRoot()) continue;

      Set<DeclarationDescriptor> descriptors =
          getTopLevelDescriptorsByFqName(resolveSession, fqName);

      if (descriptors.size() > 1) {
        for (JetElement declarationOrPackageDirective : declarationsOrPackageDirectives) {
          PsiElement reportAt =
              declarationOrPackageDirective instanceof JetNamedDeclaration
                  ? declarationOrPackageDirective
                  : ((JetPackageDirective) declarationOrPackageDirective).getNameIdentifier();
          trace.report(Errors.REDECLARATION.on(reportAt, fqName.shortName().asString()));
        }
      }
    }
  }
Пример #23
0
 public void updateNormalTokens(Collection<Token> tokens, InetAddress endpoint) {
   Multimap<InetAddress, Token> endpointTokens = HashMultimap.create();
   for (Token token : tokens) endpointTokens.put(endpoint, token);
   updateNormalTokens(endpointTokens);
 }
Пример #24
0
  /**
   * Retrieve all the info about the requested package types. This is used for the package types
   * that have one or more instances, each with different versions. The resulting array is sorted
   * according to the PkgInfo's sort order.
   *
   * <p>To force the LocalSdk parser to load <b>everything</b>, simply call this method with the
   * {@link PkgType#PKG_ALL} argument to load all the known package types.
   *
   * <p>Note: you can use this with {@link PkgType#PKG_TOOLS}, {@link PkgType#PKG_PLATFORM_TOOLS}
   * and {@link PkgType#PKG_DOC} but since there can only be one package of these types, it is more
   * efficient to use {@link #getPkgInfo(PkgType)} to query them.
   *
   * @param filters One or more of {@link PkgType#PKG_ADDON}, {@link PkgType#PKG_PLATFORM}, {@link
   *     PkgType#PKG_BUILD_TOOLS}, {@link PkgType#PKG_EXTRA}, {@link PkgType#PKG_SOURCE}, {@link
   *     PkgType#PKG_SYS_IMAGE}
   * @return A list (possibly empty) of matching installed packages. Never returns null.
   */
  @NonNull
  public LocalPkgInfo[] getPkgsInfos(@NonNull EnumSet<PkgType> filters) {
    List<LocalPkgInfo> list = Lists.newArrayList();

    for (PkgType filter : filters) {
      if (filter == PkgType.PKG_TOOLS
          || filter == PkgType.PKG_PLATFORM_TOOLS
          || filter == PkgType.PKG_DOC
          || filter == PkgType.PKG_NDK) {
        LocalPkgInfo info = getPkgInfo(filter);
        if (info != null) {
          list.add(info);
        }
      } else {
        synchronized (mLocalPackages) {
          Collection<LocalPkgInfo> existing = mLocalPackages.get(filter);
          assert existing != null; // Multimap returns an empty set if not found

          if (!existing.isEmpty()) {
            list.addAll(existing);
            continue;
          }

          File subDir = new File(mSdkRoot, filter.getFolderName());

          if (!mVisitedDirs.containsEntry(filter, new LocalDirInfo.MapComparator(subDir))) {
            switch (filter) {
              case PKG_BUILD_TOOLS:
                scanBuildTools(subDir, existing);
                break;

              case PKG_PLATFORM:
                scanPlatforms(subDir, existing);
                break;

              case PKG_SYS_IMAGE:
                scanSysImages(subDir, existing, false);
                break;

              case PKG_ADDON_SYS_IMAGE:
                scanSysImages(subDir, existing, true);
                break;

              case PKG_ADDON:
                scanAddons(subDir, existing);
                break;

              case PKG_SAMPLE:
                scanSamples(subDir, existing);
                break;

              case PKG_SOURCE:
                scanSources(subDir, existing);
                break;

              case PKG_EXTRA:
                scanExtras(subDir, existing);
                break;

              case PKG_TOOLS:
              case PKG_PLATFORM_TOOLS:
              case PKG_DOC:
              case PKG_NDK:
                break;
              default:
                throw new IllegalArgumentException("Unsupported pkg type " + filter.toString());
            }
            mVisitedDirs.put(filter, new LocalDirInfo(mFileOp, subDir));
            list.addAll(existing);
          }
        }
      }
    }

    Collections.sort(list);
    return list.toArray(new LocalPkgInfo[list.size()]);
  }
Пример #25
0
 protected void clear() {
   dcEndpoints.clear();
   dcRacks.clear();
   currentLocations.clear();
 }
Пример #26
0
 /** Removes current DC/rack assignment for ep */
 protected void removeEndpoint(InetAddress ep) {
   if (!currentLocations.containsKey(ep)) return;
   Pair<String, String> current = currentLocations.remove(ep);
   dcEndpoints.remove(current.left, ep);
   dcRacks.get(current.left).remove(current.right, ep);
 }