boolean unifyWithSubtype( NominalType other, List<String> typeParameters, Multimap<String, JSType> typeMultimap, SubtypeCache subSuperMap) { other = other.findMatchingAncestorWith(this); if (other == null) { return false; } if (!isGeneric()) { // Non-generic nominal types don't contribute to the unification. return true; } // Most of the time, both nominal types are already instantiated when // unifyWith is called. Rarely, when we call a polymorphic function from the // body of a method of a polymorphic class, then other.typeMap is // empty. For now, don't do anything fancy in that case. Preconditions.checkState(!typeMap.isEmpty()); if (other.typeMap.isEmpty()) { return true; } boolean hasUnified = true; for (String typeParam : this.rawType.getTypeParameters()) { JSType fromOtherMap = other.typeMap.get(typeParam); Preconditions.checkNotNull( fromOtherMap, "Type variable %s not found in map %s", typeParam, other.typeMap); hasUnified = hasUnified && this.typeMap .get(typeParam) .unifyWithSubtype(fromOtherMap, typeParameters, typeMultimap, subSuperMap); } return hasUnified; }
/** Returns an object of the same type as {@code o}, or null if it is not retained. */ private Object retainAll(Schema schema, MarkSet markSet, ProtoType type, Object o) { if (!markSet.contains(type)) { return null; // Prune this type. } else if (o instanceof Map) { ImmutableMap.Builder<ProtoMember, Object> builder = ImmutableMap.builder(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) o).entrySet()) { ProtoMember protoMember = (ProtoMember) entry.getKey(); if (!markSet.contains(protoMember)) continue; // Prune this field. Field field = schema.getField(protoMember); Object retainedValue = retainAll(schema, markSet, field.type(), entry.getValue()); if (retainedValue != null) { builder.put(protoMember, retainedValue); // This retained field is non-empty. } } ImmutableMap<ProtoMember, Object> map = builder.build(); return !map.isEmpty() ? map : null; } else if (o instanceof List) { ImmutableList.Builder<Object> builder = ImmutableList.builder(); for (Object value : ((List) o)) { Object retainedValue = retainAll(schema, markSet, type, value); if (retainedValue != null) { builder.add(retainedValue); // This retained value is non-empty. } } ImmutableList<Object> list = builder.build(); return !list.isEmpty() ? list : null; } else { return o; } }
@Override public int execute(ExecutionContext context) { File inputDirectory = inputDirectoryPath.toFile(); Preconditions.checkState( inputDirectory.exists() && inputDirectory.isDirectory(), "%s must be a directory.", inputDirectoryPath); try { ImmutableMap.Builder<File, ZipEntry> zipEntriesBuilder = ImmutableMap.builder(); addDirectoryToZipEntryList(inputDirectory, "", zipEntriesBuilder); ImmutableMap<File, ZipEntry> zipEntries = zipEntriesBuilder.build(); if (!zipEntries.isEmpty()) { try (CustomZipOutputStream outputStream = ZipOutputStreams.newOutputStream(outputZipPath.toFile())) { for (Map.Entry<File, ZipEntry> zipEntry : zipEntries.entrySet()) { outputStream.putNextEntry(zipEntry.getValue()); ByteStreams.copy(Files.newInputStreamSupplier(zipEntry.getKey()), outputStream); outputStream.closeEntry(); } } } } catch (IOException e) { e.printStackTrace(context.getStdErr()); return 1; } return 0; }
NominalType(ImmutableMap<String, JSType> typeMap, RawNominalType rawType) { Preconditions.checkState( typeMap.isEmpty() || typeMap.keySet().containsAll(rawType.getTypeParameters()) && rawType.getTypeParameters().containsAll(typeMap.keySet())); this.typeMap = typeMap; this.rawType = rawType; }
NominalType instantiateGenerics(Map<String, JSType> newTypeMap) { if (newTypeMap.isEmpty()) { return this; } if (!this.rawType.isGeneric()) { return this.rawType.getAsNominalType(); } ImmutableMap.Builder<String, JSType> builder = ImmutableMap.builder(); ImmutableMap<String, JSType> resultMap; if (!typeMap.isEmpty()) { // This branch is entered when a generic type appears "instantiated" // in some other type, and now we're actually instantiating it to concrete // types rather than to type variables, eg, here we instantiate Array's T to U, // and when we call f, we instantiate U to boolean. // /** // * @template U // * @param {!Array<U>} x // */ // function f(x) { return x[0]; } // f([true, false]); for (String oldKey : typeMap.keySet()) { builder.put(oldKey, typeMap.get(oldKey).substituteGenerics(newTypeMap)); } resultMap = builder.build(); } else { ImmutableList<String> typeParams = this.rawType.getTypeParameters(); for (String newKey : typeParams) { if (newTypeMap.containsKey(newKey)) { builder.put(newKey, newTypeMap.get(newKey)); } } resultMap = builder.build(); if (resultMap.isEmpty()) { return this; } // This works around a bug in FunctionType, because we can't know where // FunctionType#receiverType is coming from. // If the condition is true, receiverType comes from a method declaration, // and we should not create a new type here. if (resultMap.size() < typeParams.size()) { return this; } } return new NominalType(resultMap, this.rawType); }
Options retainAll(Schema schema, MarkSet markSet) { if (map.isEmpty()) return this; // Nothing to prune. Options result = new Options(optionType, optionElements); Object mapOrNull = retainAll(schema, markSet, optionType, map); result.map = mapOrNull != null ? (ImmutableMap<ProtoMember, Object>) mapOrNull : ImmutableMap.<ProtoMember, Object>of(); return result; }
@Override public Message get() { Map<String, Object> detail = Maps.newHashMap(); detail.put("Request http method", requestMethod); if (requestQueryString != null) { // including empty query string since that means request ended with ? detail.put("Request query string", requestQueryString); } if (requestParameters != null && !requestParameters.isEmpty()) { detail.put("Request parameters", requestParameters); } if (!requestHeaders.isEmpty()) { detail.put("Request headers", requestHeaders); } Map<String, Object> responseHeaderStrings = responseHeaderComponent.getMapOfStrings(); if (!responseHeaderStrings.isEmpty()) { detail.put("Response headers", responseHeaderStrings); } addSessionAttributeDetail(detail); return Message.from(requestUri, detail); }
private IndexMetaData( String index, long version, State state, Settings settings, ImmutableMap<String, MappingMetaData> mappings, ImmutableMap<String, AliasMetaData> aliases, ImmutableMap<String, Custom> customs) { Preconditions.checkArgument( settings.getAsInt(SETTING_NUMBER_OF_SHARDS, -1) != -1, "must specify numberOfShards for index [" + index + "]"); Preconditions.checkArgument( settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, -1) != -1, "must specify numberOfReplicas for index [" + index + "]"); this.index = index; this.version = version; this.state = state; this.settings = settings; this.mappings = mappings; this.customs = customs; this.totalNumberOfShards = numberOfShards() * (numberOfReplicas() + 1); this.aliases = aliases; ImmutableMap<String, String> includeMap = settings.getByPrefix("index.routing.allocation.include.").getAsMap(); if (includeMap.isEmpty()) { includeFilters = null; } else { includeFilters = DiscoveryNodeFilters.buildFromKeyValue(includeMap); } ImmutableMap<String, String> excludeMap = settings.getByPrefix("index.routing.allocation.exclude.").getAsMap(); if (excludeMap.isEmpty()) { excludeFilters = null; } else { excludeFilters = DiscoveryNodeFilters.buildFromKeyValue(excludeMap); } }
Property getProp(String pname) { if (this.rawType.isBuiltinWithName("Array") && NUMERIC_PATTERN.matcher(pname).matches()) { if (typeMap.isEmpty()) { return Property.make(getCommonTypes().UNKNOWN, null); } Preconditions.checkState(typeMap.size() == 1); JSType elmType = Iterables.getOnlyElement(typeMap.values()); return Property.make(elmType, null); } Property p = this.rawType.getProp(pname); // TODO(aravindpg): Also look for getters and setters specially (in RawNominalType::protoProps), // but avoid putting them in the hot path of getProp. return p == null ? null : p.substituteGenerics(typeMap); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (nodeName.length() > 0) { sb.append('[').append(nodeName).append(']'); } if (nodeId != null) { sb.append('[').append(nodeId).append(']'); } if (address != null) { sb.append('[').append(address).append(']'); } if (!attributes.isEmpty()) { sb.append(attributes); } return sb.toString(); }
private void addSessionAttributeDetail(Map<String, Object> detail) { if (!sessionAttributeInitialValueMap.isEmpty()) { if (sessionAttributeUpdatedValueMap == null) { // session attributes were captured at the beginning of the request, and no session // attributes were updated mid-request detail.put("Session attributes", sessionAttributeInitialValueMap); } else { // some session attributes were updated mid-request addMidRequestSessionAttributeDetail(detail); } } else if (sessionAttributeUpdatedValueMap != null) { // no session attributes were available at the beginning of the request, and session // attributes were updated mid-request detail.put( "Session attributes (updated during this request)", sessionAttributeUpdatedValueMap); } else { // both initial and updated value maps are null so there is nothing to add to the // detail map } }
public Aspect build() { if (!outputGroupBuilders.isEmpty()) { ImmutableMap.Builder<String, NestedSet<Artifact>> outputGroups = ImmutableMap.builder(); for (Map.Entry<String, NestedSetBuilder<Artifact>> entry : outputGroupBuilders.entrySet()) { outputGroups.put(entry.getKey(), entry.getValue().build()); } if (providers.containsKey(OutputGroupProvider.class)) { throw new IllegalStateException( "OutputGroupProvider was provided explicitly; do not use addOutputGroup"); } addProvider(OutputGroupProvider.class, new OutputGroupProvider(outputGroups.build())); } ImmutableMap<String, Object> skylarkProvidersMap = skylarkProviderBuilder.build(); if (!skylarkProvidersMap.isEmpty()) { providers.put(SkylarkProviders.class, new SkylarkProviders(skylarkProvidersMap)); } return new Aspect(name, ImmutableMap.copyOf(providers)); }
@Override protected GetFieldMappingsResponse shardOperation( final GetFieldMappingsIndexRequest request, ShardId shardId) throws ElasticsearchException { assert shardId != null; IndexService indexService = indicesService.indexServiceSafe(shardId.getIndex()); Collection<String> typeIntersection; if (request.types().length == 0) { typeIntersection = indexService.mapperService().types(); } else { typeIntersection = Collections2.filter( indexService.mapperService().types(), new Predicate<String>() { @Override public boolean apply(String type) { return Regex.simpleMatch(request.types(), type); } }); if (typeIntersection.isEmpty()) { throw new TypeMissingException(shardId.index(), request.types()); } } MapBuilder<String, ImmutableMap<String, FieldMappingMetaData>> typeMappings = new MapBuilder<>(); for (String type : typeIntersection) { DocumentMapper documentMapper = indexService.mapperService().documentMapper(type); ImmutableMap<String, FieldMappingMetaData> fieldMapping = findFieldMappingsByType(documentMapper, request); if (!fieldMapping.isEmpty()) { typeMappings.put(type, fieldMapping); } } return new GetFieldMappingsResponse( ImmutableMap.of(shardId.getIndex(), typeMappings.immutableMap())); }
@Override public IFlexibleBakedModel bake( IModelState state, VertexFormat format, Function<ResourceLocation, TextureAtlasSprite> bakedTextureGetter) { ImmutableList.Builder<BakedQuad> builder = ImmutableList.builder(); Optional<TRSRTransformation> transform = state.apply(Optional.<IModelPart>absent()); for (int i = 0; i < textures.size(); i++) { TextureAtlasSprite sprite = bakedTextureGetter.apply(textures.get(i)); builder.addAll(getQuadsForSprite(i, sprite, format, transform)); } TextureAtlasSprite particle = bakedTextureGetter.apply( textures.isEmpty() ? new ResourceLocation("missingno") : textures.get(0)); ImmutableMap<ItemCameraTransforms.TransformType, TRSRTransformation> transforms = IPerspectiveAwareModel.MapWrapper.getTransforms(state); IFlexibleBakedModel ret = new CustomBakedModel(builder.build(), particle, format, transforms); if (transforms.isEmpty()) { return ret; } return new IPerspectiveAwareModel.MapWrapper(ret, transforms); }
@Override public Optional<ImmutableWorkerInfo> findWorkerForTask( final WorkerTaskRunnerConfig config, final ImmutableMap<String, ImmutableWorkerInfo> zkWorkers, final Task task) { // don't run other datasources on affinity workers; we only want our configured datasources to // run on them ImmutableMap.Builder<String, ImmutableWorkerInfo> builder = new ImmutableMap.Builder<>(); for (String workerHost : zkWorkers.keySet()) { if (!affinityWorkerHosts.contains(workerHost)) { builder.put(workerHost, zkWorkers.get(workerHost)); } } ImmutableMap<String, ImmutableWorkerInfo> eligibleWorkers = builder.build(); List<String> workerHosts = affinityConfig.getAffinity().get(task.getDataSource()); if (workerHosts == null) { return super.findWorkerForTask(config, eligibleWorkers, task); } ImmutableMap.Builder<String, ImmutableWorkerInfo> affinityBuilder = new ImmutableMap.Builder<>(); for (String workerHost : workerHosts) { ImmutableWorkerInfo zkWorker = zkWorkers.get(workerHost); if (zkWorker != null) { affinityBuilder.put(workerHost, zkWorker); } } ImmutableMap<String, ImmutableWorkerInfo> affinityWorkers = affinityBuilder.build(); if (!affinityWorkers.isEmpty()) { Optional<ImmutableWorkerInfo> retVal = super.findWorkerForTask(config, affinityWorkers, task); if (retVal.isPresent()) { return retVal; } } return super.findWorkerForTask(config, eligibleWorkers, task); }
private void installNativeLibrariesForAbi(String abi, ImmutableMap<String, Path> libraries) throws Exception { if (libraries.isEmpty()) { return; } ImmutableSet<String> requiredHashes = libraries.keySet(); ImmutableSet<String> presentHashes = prepareNativeLibsDir(abi, requiredHashes); Map<String, Path> filesToInstallByHash = Maps.filterKeys(libraries, Predicates.not(Predicates.in(presentHashes))); String metadataContents = Joiner.on('\n') .join( FluentIterable.from(libraries.entrySet()) .transform( new Function<Map.Entry<String, Path>, String>() { @Override public String apply(Map.Entry<String, Path> input) { String hash = input.getKey(); String filename = input.getValue().getFileName().toString(); int index = filename.indexOf('.'); String libname = index == -1 ? filename : filename.substring(0, index); return String.format("%s native-%s.so", libname, hash); } })); installFiles( "native_library", ImmutableMap.copyOf(filesToInstallByHash), metadataContents, "native-%s.so", NATIVE_LIBS_DIR.resolve(abi)); }
@Override protected void masterOperation( final TypesExistsRequest request, final ClusterState state, final ActionListener<TypesExistsResponse> listener) throws ElasticSearchException { String[] concreteIndices = state.metaData().concreteIndices(request.indices(), request.ignoreIndices(), false); if (concreteIndices.length == 0) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String concreteIndex : concreteIndices) { if (!state.metaData().hasConcreteIndex(concreteIndex)) { listener.onResponse(new TypesExistsResponse(false)); return; } ImmutableMap<String, MappingMetaData> mappings = state.metaData().getIndices().get(concreteIndex).mappings(); if (mappings.isEmpty()) { listener.onResponse(new TypesExistsResponse(false)); return; } for (String type : request.types()) { if (!mappings.containsKey(type)) { listener.onResponse(new TypesExistsResponse(false)); return; } } } listener.onResponse(new TypesExistsResponse(true)); }
/** * Analyzes the specified targets using Skyframe as the driving framework. * * @return the configured targets that should be built along with a WalkableGraph of the analysis. */ public SkyframeAnalysisResult configureTargets( EventHandler eventHandler, List<ConfiguredTargetKey> values, List<AspectValueKey> aspectKeys, EventBus eventBus, boolean keepGoing) throws InterruptedException, ViewCreationFailedException { enableAnalysis(true); EvaluationResult<ActionLookupValue> result; try { result = skyframeExecutor.configureTargets(eventHandler, values, aspectKeys, keepGoing); } finally { enableAnalysis(false); } ImmutableMap<Action, ConflictException> badActions = skyframeExecutor.findArtifactConflicts(); Collection<AspectValue> goodAspects = Lists.newArrayListWithCapacity(values.size()); NestedSetBuilder<Package> packages = NestedSetBuilder.stableOrder(); for (AspectValueKey aspectKey : aspectKeys) { AspectValue value = (AspectValue) result.get(AspectValue.key(aspectKey)); if (value == null) { // Skip aspects that couldn't be applied to targets. continue; } goodAspects.add(value); packages.addTransitive(value.getTransitivePackages()); } // Filter out all CTs that have a bad action and convert to a list of configured targets. This // code ensures that the resulting list of configured targets has the same order as the incoming // list of values, i.e., that the order is deterministic. Collection<ConfiguredTarget> goodCts = Lists.newArrayListWithCapacity(values.size()); for (ConfiguredTargetKey value : values) { ConfiguredTargetValue ctValue = (ConfiguredTargetValue) result.get(ConfiguredTargetValue.key(value)); if (ctValue == null) { continue; } goodCts.add(ctValue.getConfiguredTarget()); packages.addTransitive(ctValue.getTransitivePackages()); } if (!result.hasError() && badActions.isEmpty()) { setDeserializedArtifactOwners(); return new SkyframeAnalysisResult( /*hasLoadingError=*/ false, /*hasAnalysisError=*/ false, ImmutableList.copyOf(goodCts), result.getWalkableGraph(), ImmutableList.copyOf(goodAspects), LoadingPhaseRunner.collectPackageRoots(packages.build().toCollection())); } // --nokeep_going so we fail with an exception for the first error. // TODO(bazel-team): We might want to report the other errors through the event bus but // for keeping this code in parity with legacy we just report the first error for now. if (!keepGoing) { for (Map.Entry<Action, ConflictException> bad : badActions.entrySet()) { ConflictException ex = bad.getValue(); try { ex.rethrowTyped(); } catch (MutableActionGraph.ActionConflictException ace) { ace.reportTo(eventHandler); String errorMsg = "Analysis of target '" + bad.getKey().getOwner().getLabel() + "' failed; build aborted"; throw new ViewCreationFailedException(errorMsg); } catch (ArtifactPrefixConflictException apce) { eventHandler.handle(Event.error(apce.getMessage())); } throw new ViewCreationFailedException(ex.getMessage()); } Map.Entry<SkyKey, ErrorInfo> error = result.errorMap().entrySet().iterator().next(); SkyKey topLevel = error.getKey(); ErrorInfo errorInfo = error.getValue(); assertSaneAnalysisError(errorInfo, topLevel); skyframeExecutor .getCyclesReporter() .reportCycles(errorInfo.getCycleInfo(), topLevel, eventHandler); Throwable cause = errorInfo.getException(); Preconditions.checkState( cause != null || !Iterables.isEmpty(errorInfo.getCycleInfo()), errorInfo); String errorMsg = null; if (topLevel.argument() instanceof ConfiguredTargetKey) { errorMsg = "Analysis of target '" + ConfiguredTargetValue.extractLabel(topLevel) + "' failed; build aborted"; } else if (topLevel.argument() instanceof AspectValueKey) { AspectValueKey aspectKey = (AspectValueKey) topLevel.argument(); errorMsg = "Analysis of aspect '" + aspectKey.getDescription() + "' failed; build aborted"; } else { assert false; } if (cause instanceof ActionConflictException) { ((ActionConflictException) cause).reportTo(eventHandler); } throw new ViewCreationFailedException(errorMsg); } boolean hasLoadingError = false; // --keep_going : We notify the error and return a ConfiguredTargetValue for (Map.Entry<SkyKey, ErrorInfo> errorEntry : result.errorMap().entrySet()) { // Only handle errors of configured targets, not errors of top-level aspects. // TODO(ulfjack): this is quadratic - if there are a lot of CTs, this could be rather slow. if (!values.contains(errorEntry.getKey().argument())) { continue; } SkyKey errorKey = errorEntry.getKey(); ConfiguredTargetKey label = (ConfiguredTargetKey) errorKey.argument(); Label topLevelLabel = label.getLabel(); ErrorInfo errorInfo = errorEntry.getValue(); assertSaneAnalysisError(errorInfo, errorKey); skyframeExecutor .getCyclesReporter() .reportCycles(errorInfo.getCycleInfo(), errorKey, eventHandler); Exception cause = errorInfo.getException(); Label analysisRootCause = null; if (cause instanceof ConfiguredValueCreationException) { ConfiguredValueCreationException ctCause = (ConfiguredValueCreationException) cause; for (Label rootCause : ctCause.getRootCauses()) { hasLoadingError = true; eventBus.post(new LoadingFailureEvent(topLevelLabel, rootCause)); } analysisRootCause = ctCause.getAnalysisRootCause(); } else if (!Iterables.isEmpty(errorInfo.getCycleInfo())) { analysisRootCause = maybeGetConfiguredTargetCycleCulprit(topLevelLabel, errorInfo.getCycleInfo()); } else if (cause instanceof ActionConflictException) { ((ActionConflictException) cause).reportTo(eventHandler); } eventHandler.handle( Event.warn( "errors encountered while analyzing target '" + topLevelLabel + "': it will not be built")); if (analysisRootCause != null) { eventBus.post( new AnalysisFailureEvent( LabelAndConfiguration.of(topLevelLabel, label.getConfiguration()), analysisRootCause)); } } Collection<Exception> reportedExceptions = Sets.newHashSet(); for (Map.Entry<Action, ConflictException> bad : badActions.entrySet()) { ConflictException ex = bad.getValue(); try { ex.rethrowTyped(); } catch (MutableActionGraph.ActionConflictException ace) { ace.reportTo(eventHandler); eventHandler.handle( Event.warn( "errors encountered while analyzing target '" + bad.getKey().getOwner().getLabel() + "': it will not be built")); } catch (ArtifactPrefixConflictException apce) { if (reportedExceptions.add(apce)) { eventHandler.handle(Event.error(apce.getMessage())); } } } if (!badActions.isEmpty()) { // In order to determine the set of configured targets transitively error free from action // conflict issues, we run a post-processing update() that uses the bad action map. EvaluationResult<PostConfiguredTargetValue> actionConflictResult = skyframeExecutor.postConfigureTargets(eventHandler, values, keepGoing, badActions); goodCts = Lists.newArrayListWithCapacity(values.size()); for (ConfiguredTargetKey value : values) { PostConfiguredTargetValue postCt = actionConflictResult.get(PostConfiguredTargetValue.key(value)); if (postCt != null) { goodCts.add(postCt.getCt()); } } } setDeserializedArtifactOwners(); return new SkyframeAnalysisResult( hasLoadingError, result.hasError() || !badActions.isEmpty(), ImmutableList.copyOf(goodCts), result.getWalkableGraph(), ImmutableList.copyOf(goodAspects), LoadingPhaseRunner.collectPackageRoots(packages.build().toCollection())); }
@Override public IModel retexture(ImmutableMap<String, String> textures) { if (textures.isEmpty()) return this; List<BlockPart> elements = Lists.newArrayList(); // We have to duplicate this so we can edit it below. for (BlockPart part : (List<BlockPart>) this.model.getElements()) { elements.add( new BlockPart( part.positionFrom, part.positionTo, Maps.newHashMap(part.mapFaces), part.partRotation, part.shade)); } ModelBlock neweModel = new ModelBlock( this.model.getParentLocation(), elements, Maps.newHashMap(this.model.textures), this.model.isAmbientOcclusion(), this.model.isGui3d(), // New Textures man VERY IMPORTANT model.func_181682_g()); neweModel.name = this.model.name; neweModel.parent = this.model.parent; Set<String> removed = Sets.newHashSet(); for (Entry<String, String> e : textures.entrySet()) { if ("".equals(e.getValue())) { removed.add(e.getKey()); neweModel.textures.remove(e.getKey()); } else neweModel.textures.put(e.getKey(), e.getValue()); } // Map the model's texture references as if it was the parent of a model with the retexture // map as its textures. Map<String, String> remapped = Maps.newHashMap(); for (Entry<String, String> e : (Set<Entry<String, String>>) neweModel.textures.entrySet()) { if (e.getValue().startsWith("#")) { String key = e.getValue().substring(1); if (neweModel.textures.containsKey(key)) remapped.put(e.getKey(), (String) neweModel.textures.get(key)); } } neweModel.textures.putAll(remapped); // Remove any faces that use a null texture, this is for performance reasons, also allows some // cool layering stuff. for (BlockPart part : (List<BlockPart>) neweModel.getElements()) { Iterator<Entry<EnumFacing, BlockPartFace>> itr = part.mapFaces.entrySet().iterator(); while (itr.hasNext()) { Entry<EnumFacing, BlockPartFace> entry = itr.next(); if (removed.contains(entry.getValue().texture)) itr.remove(); } } return new VanillaModelWrapper(location, neweModel); }
/** * Generate {@link Lex} and {@link Yacc} rules generating C/C++ sources from the given lex/yacc * sources. * * @return {@link CxxHeaderSourceSpec} containing the generated headers/sources */ public static CxxHeaderSourceSpec createLexYaccBuildRules( BuildRuleParams params, BuildRuleResolver resolver, CxxPlatform cxxPlatform, ImmutableList<String> lexFlags, ImmutableMap<String, SourcePath> lexSrcs, ImmutableList<String> yaccFlags, ImmutableMap<String, SourcePath> yaccSrcs) { if (!lexSrcs.isEmpty() && !cxxPlatform.getLex().isPresent()) { throw new HumanReadableException( "Platform %s must support lex to compile srcs %s", cxxPlatform, lexSrcs); } if (!yaccSrcs.isEmpty() && !cxxPlatform.getYacc().isPresent()) { throw new HumanReadableException( "Platform %s must support yacc to compile srcs %s", cxxPlatform, yaccSrcs); } SourcePathResolver pathResolver = new SourcePathResolver(resolver); ImmutableMap.Builder<String, CxxSource> lexYaccCxxSourcesBuilder = ImmutableMap.builder(); ImmutableMap.Builder<Path, SourcePath> lexYaccHeadersBuilder = ImmutableMap.builder(); // Loop over all lex sources, generating build rule for each one and adding the sources // and headers it generates to our bookkeeping maps. UnflavoredBuildTarget unflavoredBuildTarget = params.getBuildTarget().getUnflavoredBuildTarget(); for (ImmutableMap.Entry<String, SourcePath> ent : lexSrcs.entrySet()) { final String name = ent.getKey(); final SourcePath source = ent.getValue(); BuildTarget target = createLexBuildTarget(unflavoredBuildTarget, name); Path outputSource = getLexSourceOutputPath(unflavoredBuildTarget, name); Path outputHeader = getLexHeaderOutputPath(unflavoredBuildTarget, name); // Create the build rule to run lex on this source and add it to the resolver. Lex lex = new Lex( params.copyWithChanges( target, Suppliers.ofInstance( ImmutableSortedSet.copyOf( pathResolver.filterBuildRuleInputs(ImmutableList.of(source)))), Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of())), pathResolver, cxxPlatform.getLex().get(), ImmutableList.<String>builder() .addAll(cxxPlatform.getLexFlags()) .addAll(lexFlags) .build(), outputSource, outputHeader, source); resolver.addToIndex(lex); // Record the output source and header as {@link BuildRuleSourcePath} objects. lexYaccCxxSourcesBuilder.put( name + ".cc", CxxSource.of( CxxSource.Type.CXX, new BuildTargetSourcePath(lex.getBuildTarget(), outputSource), ImmutableList.<String>of())); lexYaccHeadersBuilder.put( params.getBuildTarget().getBasePath().resolve(name + ".h"), new BuildTargetSourcePath(lex.getBuildTarget(), outputHeader)); } // Loop over all yaccc sources, generating build rule for each one and adding the sources // and headers it generates to our bookkeeping maps. for (ImmutableMap.Entry<String, SourcePath> ent : yaccSrcs.entrySet()) { final String name = ent.getKey(); final SourcePath source = ent.getValue(); BuildTarget target = createYaccBuildTarget(unflavoredBuildTarget, name); Path outputPrefix = getYaccOutputPrefix(unflavoredBuildTarget, Files.getNameWithoutExtension(name)); // Create the build rule to run yacc on this source and add it to the resolver. Yacc yacc = new Yacc( params.copyWithChanges( target, Suppliers.ofInstance( ImmutableSortedSet.copyOf( pathResolver.filterBuildRuleInputs(ImmutableList.of(source)))), Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of())), pathResolver, cxxPlatform.getYacc().get(), ImmutableList.<String>builder() .addAll(cxxPlatform.getYaccFlags()) .addAll(yaccFlags) .build(), outputPrefix, source); resolver.addToIndex(yacc); // Record the output source and header as {@link BuildRuleSourcePath} objects. lexYaccCxxSourcesBuilder.put( name + ".cc", CxxSource.of( CxxSource.Type.CXX, new BuildTargetSourcePath( yacc.getBuildTarget(), Yacc.getSourceOutputPath(outputPrefix)), ImmutableList.<String>of())); lexYaccHeadersBuilder.put( params.getBuildTarget().getBasePath().resolve(name + ".h"), new BuildTargetSourcePath(yacc.getBuildTarget(), Yacc.getHeaderOutputPath(outputPrefix))); } return CxxHeaderSourceSpec.of(lexYaccHeadersBuilder.build(), lexYaccCxxSourcesBuilder.build()); }
public void toXContent( XContentBuilder builder, Params params, ToXContent custom, Mapper... additionalMappers) throws IOException { builder.startObject(name); if (nested.isNested()) { builder.field("type", NESTED_CONTENT_TYPE); if (nested.isIncludeInParent()) { builder.field("include_in_parent", true); } if (nested.isIncludeInRoot()) { builder.field("include_in_root", true); } } else if (mappers .isEmpty()) { // only write the object content type if there are no properties, otherwise, // it is automatically detected builder.field("type", CONTENT_TYPE); } // grr, ugly! on root, dynamic defaults to TRUE, on children, it defaults to null to // inherit the root behavior if (this instanceof RootObjectMapper) { if (dynamic != Dynamic.TRUE) { builder.field("dynamic", dynamic.name().toLowerCase()); } } else { if (dynamic != Defaults.DYNAMIC) { builder.field("dynamic", dynamic.name().toLowerCase()); } } if (enabled != Defaults.ENABLED) { builder.field("enabled", enabled); } if (pathType != Defaults.PATH_TYPE) { builder.field("path", pathType.name().toLowerCase()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } if (custom != null) { custom.toXContent(builder, params); } doXContent(builder, params); // sort the mappers so we get consistent serialization format TreeMap<String, Mapper> sortedMappers = new TreeMap<String, Mapper>(mappers); // check internal mappers first (this is only relevant for root object) for (Mapper mapper : sortedMappers.values()) { if (mapper instanceof InternalMapper) { mapper.toXContent(builder, params); } } if (additionalMappers != null && additionalMappers.length > 0) { TreeMap<String, Mapper> additionalSortedMappers = new TreeMap<String, Mapper>(); for (Mapper mapper : additionalMappers) { additionalSortedMappers.put(mapper.name(), mapper); } for (Mapper mapper : additionalSortedMappers.values()) { mapper.toXContent(builder, params); } } if (!mappers.isEmpty()) { builder.startObject("properties"); for (Mapper mapper : sortedMappers.values()) { if (!(mapper instanceof InternalMapper)) { mapper.toXContent(builder, params); } } builder.endObject(); } builder.endObject(); }
public LinkCommandLine build() { if (linkTargetType.isStaticLibraryLink()) { Preconditions.checkArgument( linkstamps.isEmpty(), "linkstamps may only be present on dynamic library or executable links"); Preconditions.checkArgument( buildInfoHeaderArtifacts.isEmpty(), "build info headers may only be present on dynamic library or executable links"); } ImmutableList<String> actualLinkstampCompileOptions; if (linkstampCompileOptions.isEmpty()) { actualLinkstampCompileOptions = DEFAULT_LINKSTAMP_OPTIONS; } else { actualLinkstampCompileOptions = ImmutableList.copyOf( Iterables.concat(DEFAULT_LINKSTAMP_OPTIONS, linkstampCompileOptions)); } // The ruleContext can be null for some tests. if (ruleContext != null) { if (featureConfiguration == null) { if (toolchain != null) { featureConfiguration = CcCommon.configureFeatures( ruleContext, toolchain, CcLibraryHelper.SourceCategory.CC); } else { featureConfiguration = CcCommon.configureFeatures(ruleContext); } } } if (variables == null) { variables = Variables.EMPTY; } String actionName = linkTargetType.getActionName(); return new LinkCommandLine( actionName, configuration, owner, output, interfaceOutput, buildInfoHeaderArtifacts, linkerInputs, runtimeInputs, linkTargetType, linkStaticness, linkopts, features, linkstamps, actualLinkstampCompileOptions, CppHelper.getFdoBuildStamp(ruleContext), runtimeSolibDir, nativeDeps, useTestOnlyFlags, needWholeArchive, paramFile, interfaceSoBuilder, noWholeArchiveFlags, variables, featureConfiguration); }
/** * Computes, for each C++ source file in {@link #getLinkstamps}, the command necessary to compile * that file such that the output is correctly fed into the link command. * * <p>As these options (as well as all others) are taken into account when computing the action * key, they do not directly contain volatile build information to avoid unnecessary relinking. * Instead this information is passed as an additional header generated by {@link * com.google.devtools.build.lib.rules.cpp.WriteBuildInfoHeaderAction}. * * @param outputPrefix prefix to add before the linkstamp outputs' exec paths * @return a list of shell-escaped compiler commmands, one for each entry in {@link * #getLinkstamps} */ public List<String> getLinkstampCompileCommands(String outputPrefix) { if (linkstamps.isEmpty()) { return ImmutableList.of(); } String compilerCommand = cppConfiguration.getCppExecutable().getPathString(); List<String> commands = Lists.newArrayListWithCapacity(linkstamps.size()); for (Map.Entry<Artifact, Artifact> linkstamp : linkstamps.entrySet()) { List<String> optionList = new ArrayList<>(); // Defines related to the build info are read from generated headers. for (Artifact header : buildInfoHeaderArtifacts) { optionList.add("-include"); optionList.add(header.getExecPathString()); } String labelReplacement = Matcher.quoteReplacement( isSharedNativeLibrary() ? output.getExecPathString() : Label.print(owner.getLabel())); String outputPathReplacement = Matcher.quoteReplacement(output.getExecPathString()); for (String option : linkstampCompileOptions) { optionList.add( option .replaceAll(Pattern.quote("${LABEL}"), labelReplacement) .replaceAll(Pattern.quote("${OUTPUT_PATH}"), outputPathReplacement)); } optionList.add("-DGPLATFORM=\"" + cppConfiguration + "\""); // Needed to find headers included from linkstamps. optionList.add("-I."); // Add sysroot. PathFragment sysroot = cppConfiguration.getSysroot(); if (sysroot != null) { optionList.add("--sysroot=" + sysroot.getPathString()); } // Add toolchain compiler options. optionList.addAll(cppConfiguration.getCompilerOptions(features)); optionList.addAll(cppConfiguration.getCOptions()); optionList.addAll(cppConfiguration.getUnfilteredCompilerOptions(features)); if (CppFileTypes.CPP_SOURCE.matches(linkstamp.getKey().getExecPath())) { optionList.addAll(cppConfiguration.getCxxOptions(features)); } // For dynamic libraries, produce position independent code. if (linkTargetType == LinkTargetType.DYNAMIC_LIBRARY && cppConfiguration.toolchainNeedsPic()) { optionList.add("-fPIC"); } // Stamp FDO builds with FDO subtype string if (fdoBuildStamp != null) { optionList.add("-D" + CppConfiguration.FDO_STAMP_MACRO + "=\"" + fdoBuildStamp + "\""); } // Add the compilation target. optionList.add("-c"); optionList.add(linkstamp.getKey().getExecPathString()); // Assemble the final command, exempting outputPrefix from shell escaping. commands.add( compilerCommand + " " + ShellEscaper.escapeJoinAll(optionList) + " -o " + outputPrefix + ShellEscaper.escapeString(linkstamp.getValue().getExecPathString())); } return commands; }
/** * Analyzes the specified targets using Skyframe as the driving framework. * * @return the configured targets that should be built along with a WalkableGraph of the analysis. */ public SkyframeAnalysisResult configureTargets( List<ConfiguredTargetKey> values, List<AspectKey> aspectKeys, EventBus eventBus, boolean keepGoing) throws InterruptedException, ViewCreationFailedException { enableAnalysis(true); EvaluationResult<ActionLookupValue> result; try { result = skyframeExecutor.configureTargets(values, aspectKeys, keepGoing); } finally { enableAnalysis(false); } ImmutableMap<Action, ConflictException> badActions = skyframeExecutor.findArtifactConflicts(); Collection<AspectValue> goodAspects = Lists.newArrayListWithCapacity(values.size()); for (AspectKey aspectKey : aspectKeys) { AspectValue value = (AspectValue) result.get(AspectValue.key(aspectKey)); if (value == null) { // Skip aspects that couldn't be applied to targets. continue; } goodAspects.add(value); } // Filter out all CTs that have a bad action and convert to a list of configured targets. This // code ensures that the resulting list of configured targets has the same order as the incoming // list of values, i.e., that the order is deterministic. Collection<ConfiguredTarget> goodCts = Lists.newArrayListWithCapacity(values.size()); for (ConfiguredTargetKey value : values) { ConfiguredTargetValue ctValue = (ConfiguredTargetValue) result.get(ConfiguredTargetValue.key(value)); if (ctValue == null) { continue; } goodCts.add(ctValue.getConfiguredTarget()); } if (!result.hasError() && badActions.isEmpty()) { setDeserializedArtifactOwners(); return new SkyframeAnalysisResult( ImmutableList.copyOf(goodCts), result.getWalkableGraph(), ImmutableList.copyOf(goodAspects)); } // --nokeep_going so we fail with an exception for the first error. // TODO(bazel-team): We might want to report the other errors through the event bus but // for keeping this code in parity with legacy we just report the first error for now. if (!keepGoing) { for (Map.Entry<Action, ConflictException> bad : badActions.entrySet()) { ConflictException ex = bad.getValue(); try { ex.rethrowTyped(); } catch (MutableActionGraph.ActionConflictException ace) { ace.reportTo(skyframeExecutor.getReporter()); String errorMsg = "Analysis of target '" + bad.getKey().getOwner().getLabel() + "' failed; build aborted"; throw new ViewCreationFailedException(errorMsg); } catch (ArtifactPrefixConflictException apce) { skyframeExecutor.getReporter().handle(Event.error(apce.getMessage())); } throw new ViewCreationFailedException(ex.getMessage()); } Map.Entry<SkyKey, ErrorInfo> error = result.errorMap().entrySet().iterator().next(); SkyKey topLevel = error.getKey(); ErrorInfo errorInfo = error.getValue(); assertSaneAnalysisError(errorInfo, topLevel); skyframeExecutor .getCyclesReporter() .reportCycles(errorInfo.getCycleInfo(), topLevel, skyframeExecutor.getReporter()); Throwable cause = errorInfo.getException(); Preconditions.checkState( cause != null || !Iterables.isEmpty(errorInfo.getCycleInfo()), errorInfo); String errorMsg = "Analysis of target '" + ConfiguredTargetValue.extractLabel(topLevel) + "' failed; build aborted"; if (cause instanceof ActionConflictException) { ((ActionConflictException) cause).reportTo(skyframeExecutor.getReporter()); } throw new ViewCreationFailedException(errorMsg); } // --keep_going : We notify the error and return a ConfiguredTargetValue for (Map.Entry<SkyKey, ErrorInfo> errorEntry : result.errorMap().entrySet()) { if (values.contains(errorEntry.getKey().argument())) { SkyKey errorKey = errorEntry.getKey(); ConfiguredTargetKey label = (ConfiguredTargetKey) errorKey.argument(); ErrorInfo errorInfo = errorEntry.getValue(); assertSaneAnalysisError(errorInfo, errorKey); skyframeExecutor .getCyclesReporter() .reportCycles(errorInfo.getCycleInfo(), errorKey, skyframeExecutor.getReporter()); // We try to get the root cause key first from ErrorInfo rootCauses. If we don't have one // we try to use the cycle culprit if the error is a cycle. Otherwise we use the top-level // error key. Label root; if (!Iterables.isEmpty(errorEntry.getValue().getRootCauses())) { SkyKey culprit = Preconditions.checkNotNull( Iterables.getFirst(errorEntry.getValue().getRootCauses(), null)); root = ((ConfiguredTargetKey) culprit.argument()).getLabel(); } else { root = maybeGetConfiguredTargetCycleCulprit(errorInfo.getCycleInfo()); } Exception cause = errorInfo.getException(); if (cause instanceof ActionConflictException) { ((ActionConflictException) cause).reportTo(skyframeExecutor.getReporter()); } skyframeExecutor .getReporter() .handle( Event.warn( "errors encountered while analyzing target '" + label.getLabel() + "': it will not be built")); eventBus.post( new AnalysisFailureEvent( LabelAndConfiguration.of(label.getLabel(), label.getConfiguration()), root)); } } Collection<Exception> reportedExceptions = Sets.newHashSet(); for (Map.Entry<Action, ConflictException> bad : badActions.entrySet()) { ConflictException ex = bad.getValue(); try { ex.rethrowTyped(); } catch (MutableActionGraph.ActionConflictException ace) { ace.reportTo(skyframeExecutor.getReporter()); skyframeExecutor .getReporter() .handle( Event.warn( "errors encountered while analyzing target '" + bad.getKey().getOwner().getLabel() + "': it will not be built")); } catch (ArtifactPrefixConflictException apce) { if (reportedExceptions.add(apce)) { skyframeExecutor.getReporter().handle(Event.error(apce.getMessage())); } } } if (!badActions.isEmpty()) { // In order to determine the set of configured targets transitively error free from action // conflict issues, we run a post-processing update() that uses the bad action map. EvaluationResult<PostConfiguredTargetValue> actionConflictResult = skyframeExecutor.postConfigureTargets(values, keepGoing, badActions); goodCts = Lists.newArrayListWithCapacity(values.size()); for (ConfiguredTargetKey value : values) { PostConfiguredTargetValue postCt = actionConflictResult.get(PostConfiguredTargetValue.key(value)); if (postCt != null) { goodCts.add(postCt.getCt()); } } } setDeserializedArtifactOwners(); return new SkyframeAnalysisResult( ImmutableList.copyOf(goodCts), result.getWalkableGraph(), ImmutableList.copyOf(goodAspects)); }
@Override public <A extends Args> BuildRule createBuildRule( TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) { SourcePathResolver pathResolver = new SourcePathResolver(resolver); ImmutableMap<String, SourcePath> nativeLibraries = JavaLibraryRules.getNativeLibraries(targetGraph, params.getDeps(), cxxPlatform); BuildRuleParams binaryParams = params; // If we're packaging native libraries, we'll build the binary JAR in a separate rule and // package it into the final fat JAR, so adjust it's params to use a flavored target. if (!nativeLibraries.isEmpty()) { binaryParams = params.copyWithChanges( BuildTarget.builder(params.getBuildTarget()) .addFlavors(FAT_JAR_INNER_JAR_FLAVOR) .build(), params.getDeclaredDeps(), params.getExtraDeps()); } // Construct the build rule to build the binary JAR. ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries = Classpaths.getClasspathEntries(binaryParams.getDeps()); BuildRule rule = new JavaBinary( binaryParams.appendExtraDeps(transitiveClasspathEntries.keys()), pathResolver, args.mainClass.orNull(), args.manifestFile.orNull(), args.mergeManifests.or(true), args.metaInfDirectory.orNull(), args.blacklist.or(ImmutableSortedSet.<String>of()), new DefaultDirectoryTraverser(), transitiveClasspathEntries, javaBinOverride); // If we're packaging native libraries, construct the rule to build the fat JAR, which packages // up the original binary JAR and any required native libraries. if (!nativeLibraries.isEmpty()) { BuildRule innerJarRule = rule; resolver.addToIndex(innerJarRule); SourcePath innerJar = new BuildTargetSourcePath(innerJarRule.getBuildTarget()); rule = new JarFattener( params.appendExtraDeps( Suppliers.<Iterable<BuildRule>>ofInstance( pathResolver.filterBuildRuleInputs( ImmutableList.<SourcePath>builder() .add(innerJar) .addAll(nativeLibraries.values()) .build()))), pathResolver, javacOptions, innerJar, nativeLibraries, javaBinOverride); } return rule; }
public boolean isUninstantiatedGenericType() { return this.rawType.isGeneric() && typeMap.isEmpty(); }
public JSType getInstanceAsJSType() { return (this.rawType.isGeneric() && !typeMap.isEmpty()) ? JSType.fromObjectType(ObjectType.fromNominalType(this)) : this.rawType.getInstanceAsJSType(); }