1# Copyright 2024 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Generates provider factories.""" 15 16load("@bazel_skylib//lib:structs.bzl", "structs") 17load("@rules_testing//lib:truth.bzl", "subjects") 18 19visibility("private") 20 21def generate_factory(type, name, attrs): 22 """Generates a factory for a custom struct. 23 24 There are three reasons we need to do so: 25 1. It's very difficult to read providers printed by these types. 26 eg. If you have a 10 layer deep diamond dependency graph, and try to 27 print the top value, the bottom value will be printed 2^10 times. 28 2. Collections of subjects are not well supported by rules_testing 29 eg. `FeatureInfo(flag_sets = [FlagSetInfo(...)])` 30 (You can do it, but the inner values are just regular bazel structs and 31 you can't do fluent assertions on them). 32 3. Recursive types are not supported at all 33 eg. `FeatureInfo(implies = depset([FeatureInfo(...)]))` 34 35 To solve this, we create a factory that: 36 * Validates that the types of the children are correct. 37 * Inlines providers to their labels when unambiguous. 38 39 For example, given: 40 41 ``` 42 foo = FeatureInfo(name = "foo", label = Label("//:foo")) 43 bar = FeatureInfo(..., implies = depset([foo])) 44 ``` 45 46 It would convert itself a subject for the following struct: 47 `FeatureInfo(..., implies = depset([Label("//:foo")]))` 48 49 Args: 50 type: (type) The type to create a factory for (eg. FooInfo) 51 name: (str) The name of the type (eg. "FooInfo") 52 attrs: (dict[str, Factory]) The attributes associated with this type. 53 54 Returns: 55 A struct `FooFactory` suitable for use with 56 * `analysis_test(provider_subject_factories=[FooFactory])` 57 * `generate_factory(..., attrs=dict(foo = FooFactory))` 58 * `ProviderSequence(FooFactory)` 59 * `DepsetSequence(FooFactory)` 60 """ 61 attrs["label"] = subjects.label 62 63 want_keys = sorted(attrs.keys()) 64 65 def validate(*, value, meta): 66 if value == None: 67 meta.add_failure("Wanted a %s but got" % name, value) 68 got_keys = sorted(structs.to_dict(value).keys()) 69 subjects.collection(got_keys, meta = meta.derive(details = [ 70 "Value was not a %s - it has a different set of fields" % name, 71 ])).contains_exactly(want_keys).in_order() 72 73 def type_factory(value, *, meta): 74 validate(value = value, meta = meta) 75 76 transformed_value = {} 77 transformed_factories = {} 78 for field, factory in attrs.items(): 79 field_value = getattr(value, field) 80 81 # If it's a type generated by generate_factory, inline it. 82 if hasattr(factory, "factory"): 83 factory.validate(value = field_value, meta = meta.derive(field)) 84 transformed_value[field] = field_value.label 85 transformed_factories[field] = subjects.label 86 else: 87 transformed_value[field] = field_value 88 transformed_factories[field] = factory 89 90 return subjects.struct( 91 struct(**transformed_value), 92 meta = meta, 93 attrs = transformed_factories, 94 ) 95 96 return struct( 97 type = type, 98 name = name, 99 factory = type_factory, 100 validate = validate, 101 ) 102 103def _provider_collection(element_factory, fn): 104 def factory(value, *, meta): 105 value = fn(value) 106 107 # Validate that it really is the correct type 108 for i in range(len(value)): 109 element_factory.validate( 110 value = value[i], 111 meta = meta.derive("offset({})".format(i)), 112 ) 113 114 # Inline the providers to just labels. 115 return subjects.collection([v.label for v in value], meta = meta) 116 117 return factory 118 119# This acts like a class, so we name it like one. 120# buildifier: disable=name-conventions 121ProviderSequence = lambda element_factory: _provider_collection( 122 element_factory, 123 fn = lambda x: list(x), 124) 125 126# buildifier: disable=name-conventions 127ProviderDepset = lambda element_factory: _provider_collection( 128 element_factory, 129 fn = lambda x: x.to_list(), 130) 131