@Override
  public List<Target> getLabelListAttr(
      QueryExpression caller, Target target, String attrName, String errorMsgPrefix)
      throws QueryException {
    Preconditions.checkArgument(target instanceof Rule);

    List<Target> result = new ArrayList<>();
    Rule rule = (Rule) target;

    AggregatingAttributeMapper attrMap = AggregatingAttributeMapper.of(rule);
    Type<?> attrType = attrMap.getAttributeType(attrName);
    if (attrType == null) {
      // Return an empty list if the attribute isn't defined for this rule.
      return ImmutableList.of();
    }

    for (Label label : attrMap.getReachableLabels(attrName, false)) {
      try {
        result.add(queryEnvironment.getTarget(label));
      } catch (TargetNotFoundException e) {
        queryEnvironment.reportBuildFileError(caller, errorMsgPrefix + e.getMessage());
      }
    }

    return result;
  }
 // CAUTION: keep in sync with ConfiguredTargetFactory#convertVisibility()
 private void convertVisibility(
     ImmutableSet.Builder<QueryVisibility<Target>> packageSpecifications, Target target)
     throws QueryException {
   RuleVisibility ruleVisibility = target.getVisibility();
   if (ruleVisibility instanceof ConstantRuleVisibility) {
     if (((ConstantRuleVisibility) ruleVisibility).isPubliclyVisible()) {
       packageSpecifications.add(QueryVisibility.<Target>everything());
     }
     return;
   } else if (ruleVisibility instanceof PackageGroupsRuleVisibility) {
     PackageGroupsRuleVisibility packageGroupsVisibility =
         (PackageGroupsRuleVisibility) ruleVisibility;
     for (Label groupLabel : packageGroupsVisibility.getPackageGroups()) {
       try {
         convertGroupVisibility(
             (PackageGroup) queryEnvironment.getTarget(groupLabel), packageSpecifications);
       } catch (TargetNotFoundException e) {
         throw new QueryException(e.getMessage());
       }
     }
     for (PackageSpecification spec : packageGroupsVisibility.getDirectPackages()) {
       packageSpecifications.add(new BlazeQueryVisibility(spec));
     }
     return;
   } else {
     throw new IllegalStateException("unknown visibility: " + ruleVisibility.getClass());
   }
 }