diff --git a/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java b/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java index 48ede75f8e2..28f4f2e8eed 100644 --- a/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java +++ b/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddBinaryTypes.java @@ -21,12 +21,12 @@ import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.knowledge.HttpBinding; import software.amazon.smithy.model.knowledge.HttpBindingIndex; import software.amazon.smithy.model.knowledge.TopDownIndex; import software.amazon.smithy.model.node.ArrayNode; import software.amazon.smithy.model.node.Node; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.MediaTypeTrait; import software.amazon.smithy.openapi.fromsmithy.Context; import software.amazon.smithy.openapi.fromsmithy.OpenApiMapper; @@ -63,7 +63,7 @@ public OpenApi after(Context context, OpenApi openApi) { } private Stream supportedMediaTypes(Context context) { - ShapeIndex shapeIndex = context.getModel().getShapeIndex(); + Model model = context.getModel(); HttpBindingIndex httpBindingIndex = context.getModel().getKnowledge(HttpBindingIndex.class); TopDownIndex topDownIndex = context.getModel().getKnowledge(TopDownIndex.class); @@ -71,16 +71,16 @@ private Stream supportedMediaTypes(Context context) { return topDownIndex.getContainedOperations(context.getService()).stream() .flatMap(operation -> Stream.concat( OptionalUtils.stream( - binaryMediaType(shapeIndex, httpBindingIndex.getRequestBindings(operation))), + binaryMediaType(model, httpBindingIndex.getRequestBindings(operation))), OptionalUtils.stream( - binaryMediaType(shapeIndex, httpBindingIndex.getResponseBindings(operation))))); + binaryMediaType(model, httpBindingIndex.getResponseBindings(operation))))); } - private Optional binaryMediaType(ShapeIndex shapes, Map httpBindings) { + private Optional binaryMediaType(Model model, Map httpBindings) { return httpBindings.values().stream() .filter(binding -> binding.getLocation().equals(HttpBinding.Location.PAYLOAD)) .map(HttpBinding::getMember) - .flatMap(member -> OptionalUtils.stream(member.getMemberTrait(shapes, MediaTypeTrait.class))) + .flatMap(member -> OptionalUtils.stream(member.getMemberTrait(model, MediaTypeTrait.class))) .map(MediaTypeTrait::getValue) .findFirst(); } diff --git a/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java b/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java index dc29556c3ca..9770fcda39c 100644 --- a/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java +++ b/aws/smithy-aws-apigateway-openapi/src/main/java/software/amazon/smithy/aws/apigateway/openapi/AddRequestValidators.java @@ -66,7 +66,7 @@ public OperationObject updateOperation(Context context, OperationShape shape, Op @Override public OpenApi after(Context context, OpenApi openapi) { // Find each known request validator on operation shapes. - Set validators = context.getModel().getShapeIndex().shapes(OperationShape.class) + Set validators = context.getModel().shapes(OperationShape.class) .flatMap(shape -> OptionalUtils.stream(shape.getTrait(RequestValidatorTrait.class))) .map(RequestValidatorTrait::getValue) .filter(KNOWN_VALIDATORS::containsKey) diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java index a08b222124c..43f9a4c7066 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnIndex.java @@ -47,14 +47,14 @@ public final class ArnIndex implements KnowledgeIndex { public ArnIndex(Model model) { // Pre-compute the ARN services. - arnServices = unmodifiableMap(model.getShapeIndex().shapes(ServiceShape.class) + arnServices = unmodifiableMap(model.shapes(ServiceShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ServiceTrait.class)) .map(pair -> Pair.of(pair.getLeft().getId(), resolveServiceArn(pair))) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight))); // Pre-compute all of the ArnTemplates in a service shape. TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - List services = model.getShapeIndex().shapes(ServiceShape.class) + List services = model.shapes(ServiceShape.class) .filter(shape -> shape.hasTrait(ServiceTrait.class)) .collect(Collectors.toList()); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java index 37c8e0a9906..75284b12374 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/ArnTemplateValidator.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; @@ -46,16 +45,16 @@ public final class ArnTemplateValidator extends AbstractValidator { @Override public List validate(Model model) { ArnIndex arnIndex = model.getKnowledge(ArnIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> Trait.flatMapStream(service, ServiceTrait.class)) - .flatMap(pair -> validateService(model.getShapeIndex(), arnIndex, pair.getLeft())) + .flatMap(pair -> validateService(model, arnIndex, pair.getLeft())) .collect(toList()); } - private Stream validateService(ShapeIndex index, ArnIndex arnIndex, ServiceShape service) { + private Stream validateService(Model model, ArnIndex arnIndex, ServiceShape service) { // Make sure each ARN template contains relevant identifiers. return arnIndex.getServiceResourceArns(service.getId()).entrySet().stream() - .flatMap(entry -> OptionalUtils.stream(index.getShape(entry.getKey()) + .flatMap(entry -> OptionalUtils.stream(model.getShape(entry.getKey()) .flatMap(Shape::asResourceShape) .map(resource -> Pair.of(resource, entry.getValue())))) .flatMap(pair -> validateResourceArn(pair.getLeft(), pair.getRight())); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/PlaneIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/PlaneIndex.java index 9363468e6c1..b8fcc3ad7c0 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/PlaneIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/PlaneIndex.java @@ -50,7 +50,7 @@ private enum Plane { CONTROL, DATA } public PlaneIndex(Model model) { pathFinder = PathFinder.create(model); - model.getShapeIndex().shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { Plane plane = extractPlane(service); if (plane != null) { servicePlanes.put(service.getId(), plane); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java index 764d8445c56..e5a6514aa18 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/SdkServiceIdValidator.java @@ -70,7 +70,7 @@ public final class SdkServiceIdValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> Trait.flatMapStream(service, ServiceTrait.class)) .flatMap(pair -> OptionalUtils.stream(validateService(pair.getLeft(), pair.getRight()))) .collect(toList()); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizerIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizerIndex.java index 88e4e31a089..9da50f91d4a 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizerIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizerIndex.java @@ -48,7 +48,7 @@ public class AuthorizerIndex implements KnowledgeIndex { public AuthorizerIndex(Model model) { PathFinder finder = PathFinder.create(model); - model.getShapeIndex().shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { service.getTrait(AuthorizersTrait.class).ifPresent(trait -> authorizerTraits.put(service.getId(), trait)); Map serviceMap = new HashMap<>(); authorizers.put(service.getId(), serviceMap); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizersTraitValidator.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizersTraitValidator.java index 663e03376d1..98a23f4342d 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizersTraitValidator.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/AuthorizersTraitValidator.java @@ -36,7 +36,7 @@ public class AuthorizersTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> OptionalUtils.stream(validateService(service))) .collect(Collectors.toList()); } diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitIndex.java index f54024aaa90..d8cb867fd5a 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitIndex.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.utils.MapUtils; @@ -37,10 +36,10 @@ public class IntegrationTraitIndex implements KnowledgeIndex { private Map> traits = new HashMap<>(); public IntegrationTraitIndex(Model model) { - model.getShapeIndex().shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { Map serviceMap = new HashMap<>(); traits.put(service.getId(), serviceMap); - walk(model.getShapeIndex(), service.getId(), service, null); + walk(model, service.getId(), service, null); }); } @@ -78,19 +77,19 @@ public Optional getIntegrationTrait(ToShapeId service, ToSh return getIntegrationTrait(service, shape).filter(type::isInstance).map(type::cast); } - private void walk(ShapeIndex index, ShapeId service, EntityShape current, Trait trait) { + private void walk(Model model, ShapeId service, EntityShape current, Trait trait) { Trait updatedTrait = extractTrait(current, trait); Map serviceMapping = traits.get(service); serviceMapping.put(current.getId(), updatedTrait); for (ShapeId resource : current.getResources()) { - index.getShape(resource) + model.getShape(resource) .flatMap(Shape::asResourceShape) - .ifPresent(resourceShape -> walk(index, service, resourceShape, updatedTrait)); + .ifPresent(resourceShape -> walk(model, service, resourceShape, updatedTrait)); } for (ShapeId operation : current.getAllOperations()) { - index.getShape(operation).ifPresent(op -> serviceMapping.put(operation, extractTrait(op, updatedTrait))); + model.getShape(operation).ifPresent(op -> serviceMapping.put(operation, extractTrait(op, updatedTrait))); } } diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java index 53e0403c44b..ef43b45701c 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformer.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -61,7 +60,7 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo } private Set getServicesToUpdate(Model model, Set removedOperations, Set removedErrors) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> Trait.flatMapStream(service, ClientEndpointDiscoveryTrait.class)) .filter(pair -> removedOperations.contains(pair.getRight().getOperation()) || removedErrors.contains(pair.getRight().getError())) @@ -78,7 +77,7 @@ private Set getOperationsToUpdate( Set updatedServices ) { ClientEndpointDiscoveryIndex discoveryIndex = model.getKnowledge(ClientEndpointDiscoveryIndex.class); - Set stillBoundOperations = model.getShapeIndex().shapes(ServiceShape.class) + Set stillBoundOperations = model.shapes(ServiceShape.class) // Get all endpoint discovery services .filter(service -> service.hasTrait(ClientEndpointDiscoveryTrait.class)) .map(Shape::getId) @@ -88,7 +87,7 @@ private Set getOperationsToUpdate( .flatMap(service -> discoveryIndex.getEndpointDiscoveryOperations(service).stream()) .collect(Collectors.toSet()); - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) // Get all endpoint discovery operations .flatMap(operation -> Trait.flatMapStream(operation, ClientDiscoveredEndpointTrait.class)) // Only get the ones where discovery is optional, as it is safe to remove in that case @@ -101,22 +100,21 @@ private Set getOperationsToUpdate( } private Set getMembersToUpdate(Model model, Set updatedOperations) { - ShapeIndex shapeIndex = model.getShapeIndex(); - Set stillBoundMembers = shapeIndex.shapes(OperationShape.class) + Set stillBoundMembers = model.shapes(OperationShape.class) // Get all endpoint discovery operations .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) // Filter out the ones which are having their endpoint discovery traits removed .filter(operation -> !updatedOperations.contains(operation.getId())) // Get the input shapes of those operations .filter(operation -> operation.getInput().isPresent()) - .map(operation -> shapeIndex.getShape(operation.getInput().get()).flatMap(Shape::asStructureShape)) + .map(operation -> model.getShape(operation.getInput().get()).flatMap(Shape::asStructureShape)) .filter(Optional::isPresent) // Get the input members .flatMap(input -> input.get().getAllMembers().values().stream()) .map(Shape::getId) .collect(Collectors.toSet()); - return shapeIndex.shapes(MemberShape.class) + return model.shapes(MemberShape.class) // Get all members which have the endpoint discovery id trait .filter(member -> member.hasTrait(ClientEndpointDiscoveryIdTrait.class)) // Get those which are on structures that aren't still bound to endpoint discovery operations diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java index fc0c1277326..c110b54fb0b 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIndex.java @@ -32,7 +32,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.Trait; @@ -42,20 +41,19 @@ public final class ClientEndpointDiscoveryIndex implements KnowledgeIndex { private final Map> endpointDiscoveryInfo = new HashMap<>(); public ClientEndpointDiscoveryIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); OperationIndex opIndex = model.getKnowledge(OperationIndex.class); - index.shapes(ServiceShape.class) + model.shapes(ServiceShape.class) .flatMap(service -> Trait.flatMapStream(service, ClientEndpointDiscoveryTrait.class)) .forEach(servicePair -> { ServiceShape service = servicePair.getLeft(); ShapeId endpointOperationId = servicePair.getRight().getOperation(); ShapeId endpointErrorId = servicePair.getRight().getError(); - Optional endpointOperation = index.getShape(endpointOperationId) + Optional endpointOperation = model.getShape(endpointOperationId) .flatMap(Shape::asOperationShape); - Optional endpointError = index.getShape(endpointErrorId) + Optional endpointError = model.getShape(endpointErrorId) .flatMap(Shape::asStructureShape); if (endpointOperation.isPresent() && endpointError.isPresent()) { diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java index f57ae8e38c4..3c2951856c2 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryValidator.java @@ -30,7 +30,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -41,26 +40,25 @@ public class ClientEndpointDiscoveryValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex shapeIndex = model.getShapeIndex(); ClientEndpointDiscoveryIndex discoveryIndex = model.getKnowledge(ClientEndpointDiscoveryIndex.class); OperationIndex opIndex = model.getKnowledge(OperationIndex.class); - Map endpointDiscoveryServices = shapeIndex + Map endpointDiscoveryServices = model .shapes(ServiceShape.class) .flatMap(service -> Trait.flatMapStream(service, ClientEndpointDiscoveryTrait.class)) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight)); List validationEvents = endpointDiscoveryServices.values().stream() .map(ClientEndpointDiscoveryTrait::getOperation) - .map(operation -> shapeIndex.getShape(operation).flatMap(Shape::asOperationShape)) + .map(operation -> model.getShape(operation).flatMap(Shape::asOperationShape)) .filter(Optional::isPresent) .map(Optional::get) .flatMap(endpointOperation -> validateEndpointOperation( - shapeIndex, opIndex, endpointOperation).stream()) + model, opIndex, endpointOperation).stream()) .collect(Collectors.toList()); validationEvents.addAll(validateServices(discoveryIndex, endpointDiscoveryServices)); - validationEvents.addAll(validateOperations(shapeIndex, discoveryIndex, endpointDiscoveryServices)); + validationEvents.addAll(validateOperations(model, discoveryIndex, endpointDiscoveryServices)); return validationEvents; } @@ -89,11 +87,11 @@ private List validateServices( } private List validateOperations( - ShapeIndex shapeIndex, + Model model, ClientEndpointDiscoveryIndex discoveryIndex, Map endpointDiscoveryServices ) { - return shapeIndex.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .filter(operation -> operation.hasTrait(ClientDiscoveredEndpointTrait.class)) .map(operation -> { List infos = endpointDiscoveryServices.keySet().stream() @@ -132,7 +130,7 @@ private List validateOperation(OperationShape operation, List validateEndpointOperation( - ShapeIndex shapeIndex, OperationIndex opIndex, OperationShape operation + Model model, OperationIndex opIndex, OperationShape operation ) { List events = new ArrayList<>(); opIndex.getInput(operation).ifPresent(input -> { @@ -147,17 +145,17 @@ private List validateEndpointOperation( } input.getMember("Operation") - .flatMap(member -> shapeIndex.getShape(member.getTarget())) + .flatMap(member -> model.getShape(member.getTarget())) .filter(shape -> !shape.isStringShape()) .ifPresent(shape -> events.add(error( shape, "The Operation member of an endpoint discovery operation must be a string"))); input.getMember("Identifiers") - .map(member -> Pair.of(member, shapeIndex.getShape(member.getTarget()))) + .map(member -> Pair.of(member, model.getShape(member.getTarget()))) .ifPresent(pair -> { Optional map = pair.getRight().flatMap(Shape::asMapShape); if (map.isPresent()) { - Optional value = shapeIndex.getShape(map.get().getValue().getTarget()); + Optional value = model.getShape(map.get().getValue().getTarget()); if (value.isPresent() && value.get().isStringShape()) { return; } @@ -182,7 +180,7 @@ private List validateEndpointOperation( } Optional.ofNullable(outputMembers.get("Endpoints")) - .map(member -> Pair.of(member, shapeIndex.getShape(member.getTarget()))) + .map(member -> Pair.of(member, model.getShape(member.getTarget()))) .ifPresent(pair -> { Optional listShape = pair.getRight().flatMap(Shape::asListShape); if (!listShape.isPresent()) { @@ -191,7 +189,7 @@ private List validateEndpointOperation( return; } - Optional listMember = shapeIndex.getShape(listShape.get().getMember().getTarget()) + Optional listMember = model.getShape(listShape.get().getMember().getTarget()) .flatMap(Shape::asStructureShape); if (!listMember.isPresent()) { events.add(error(listShape.get(), "The member of the Endpoints list in an " @@ -200,7 +198,7 @@ private List validateEndpointOperation( } Optional addressMember = listMember.get().getMember("Address"); - Optional address = addressMember.flatMap(member -> shapeIndex.getShape(member.getTarget())); + Optional address = addressMember.flatMap(member -> model.getShape(member.getTarget())); if (address.isPresent() && !address.get().isStringShape()) { events.add(error(addressMember.get(), "The `Address` member of the `Endpoint` shape must " + "be a string type.")); @@ -208,7 +206,7 @@ private List validateEndpointOperation( Optional cachePeriodMember = listMember.get().getMember("CachePeriodInMinutes"); Optional cachePeriod = cachePeriodMember - .flatMap(member -> shapeIndex.getShape(member.getTarget())); + .flatMap(member -> model.getShape(member.getTarget())); if (cachePeriod.isPresent() && !cachePeriod.get().isLongShape()) { events.add(error(cachePeriodMember.get(), "The `CachePeriodInMinutes` member of the " + "`Endpoint` shape must be a long type.")); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysIndex.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysIndex.java index a52cb1b4d38..be6a41c1356 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysIndex.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysIndex.java @@ -28,7 +28,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.utils.MapUtils; @@ -48,9 +47,7 @@ public final class ConditionKeysIndex implements KnowledgeIndex { private final Map>> resourceConditionKeys = new HashMap<>(); public ConditionKeysIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); - - index.shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { service.getTrait(ServiceTrait.class).ifPresent(trait -> { // Copy over the explicitly defined condition keys into the service map. // This will be mutated when adding inferred resource condition keys. @@ -65,16 +62,16 @@ public ConditionKeysIndex(Model model) { // Compute the keys of child resources. service.getResources().stream() - .flatMap(id -> OptionalUtils.stream(index.getShape(id))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id))) .forEach(resource -> { - compute(index, service.getId(), arnRoot, resource, null); + compute(model, service.getId(), arnRoot, resource, null); }); // Compute the keys of operations of the service. service.getOperations().stream() - .flatMap(id -> OptionalUtils.stream(index.getShape(id))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id))) .forEach(operation -> { - compute(index, service.getId(), arnRoot, operation, null); + compute(model, service.getId(), arnRoot, operation, null); }); }); }); @@ -151,17 +148,17 @@ public Map getDefinedConditionKeys( } private void compute( - ShapeIndex index, + Model model, ShapeId service, String arnRoot, Shape subject, ResourceShape parent ) { - compute(index, service, arnRoot, subject, parent, SetUtils.of()); + compute(model, service, arnRoot, subject, parent, SetUtils.of()); } private void compute( - ShapeIndex index, + Model model, ShapeId service, String arnRoot, Shape subject, @@ -176,25 +173,25 @@ private void compute( subject.asResourceShape().ifPresent(resource -> { // Add any inferred resource identifiers to the resource and to the service-wide definitions. Map childIdentifiers = !resource.hasTrait(DisableConditionKeyInferenceTrait.class) - ? inferChildResourceIdentifiers(index, service, arnRoot, resource, parent) + ? inferChildResourceIdentifiers(model, service, arnRoot, resource, parent) : MapUtils.of(); // Compute the keys of each child operation, passing no keys. - resource.getAllOperations().stream().flatMap(id -> OptionalUtils.stream(index.getShape(id))) - .forEach(child -> compute(index, service, arnRoot, child, resource)); + resource.getAllOperations().stream().flatMap(id -> OptionalUtils.stream(model.getShape(id))) + .forEach(child -> compute(model, service, arnRoot, child, resource)); // Child resources always inherit the identifiers of the parent. definitions.addAll(childIdentifiers.values()); // Compute the keys of each child resource. - resource.getResources().stream().flatMap(id -> OptionalUtils.stream(index.getShape(id))).forEach(child -> { - compute(index, service, arnRoot, child, resource, definitions); + resource.getResources().stream().flatMap(id -> OptionalUtils.stream(model.getShape(id))).forEach(child -> { + compute(model, service, arnRoot, child, resource, definitions); }); }); } private Map inferChildResourceIdentifiers( - ShapeIndex index, + Model model, ShapeId service, String arnRoot, ResourceShape resource, @@ -209,7 +206,7 @@ private Map inferChildResourceIdentifiers( childIds.removeAll(parentIds); for (String childId : childIds) { - index.getShape(resource.getIdentifiers().get(childId)).ifPresent(shape -> { + model.getShape(resource.getIdentifiers().get(childId)).ifPresent(shape -> { // Only infer identifiers introduced by a child. Children should // use their parent identifiers and not duplicate them. ConditionKeyDefinition.Builder builder = ConditionKeyDefinition.builder(); diff --git a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysValidator.java b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysValidator.java index 97c75a2fbfe..be272171b11 100644 --- a/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysValidator.java +++ b/aws/smithy-aws-traits/src/main/java/software/amazon/smithy/aws/traits/iam/ConditionKeysValidator.java @@ -43,7 +43,7 @@ public List validate(Model model) { ConditionKeysIndex conditionIndex = model.getKnowledge(ConditionKeysIndex.class); TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .filter(service -> service.hasTrait(ServiceTrait.class)) .flatMap(service -> { List results = new ArrayList<>(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java index 8c357f78c68..f513f65bbef 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnIndexTest.java @@ -43,15 +43,15 @@ public static void beforeClass() { public void loadsFromModel() { ArnIndex arnIndex = new ArnIndex(model); ShapeId id = ShapeId.from("ns.foo#SomeService"); - Shape someResource = model.getShapeIndex().getShape(ShapeId.from("ns.foo#SomeResource")).get(); + Shape someResource = model.getShape(ShapeId.from("ns.foo#SomeResource")).get(); ArnTrait template1 = ArnTrait.builder() .template("someresource/{someId}") .build(); - Shape childResource = model.getShapeIndex().getShape(ShapeId.from("ns.foo#ChildResource")).get(); + Shape childResource = model.getShape(ShapeId.from("ns.foo#ChildResource")).get(); ArnTrait template2 = ArnTrait.builder() .template("someresource/{someId}/{childId}") .build(); - Shape rootArnResource = model.getShapeIndex().getShape(ShapeId.from("ns.foo#RootArnResource")).get(); + Shape rootArnResource = model.getShape(ShapeId.from("ns.foo#RootArnResource")).get(); ArnTrait template3 = ArnTrait.builder() .template("rootArnResource") .noAccount(true) diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java index a1cde73bfca..6ec887db586 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ArnReferenceTraitTest.java @@ -79,8 +79,7 @@ public void loadsFromModel() { .addImport(getClass().getResource("test-model.json")) .assemble() .unwrap(); - Shape service = result.getShapeIndex() - .getShape(ShapeId.from("ns.foo#AbsoluteResourceArn")).get(); + Shape service = result.expectShape(ShapeId.from("ns.foo#AbsoluteResourceArn")); ArnReferenceTrait trait = service.getTrait(ArnReferenceTrait.class).get(); assertThat(trait.getType(), equalTo(Optional.of("AWS::SomeService::AbsoluteResource"))); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java index a8f007c7adb..97a72ab2e1a 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/DataTraitTest.java @@ -34,12 +34,12 @@ private Model getModel() { @Test public void loadsWithString() { Model model = getModel(); - assertTrue(model.getShapeIndex().getShape(ShapeId.from("ns.foo#A")) + assertTrue(model.getShape(ShapeId.from("ns.foo#A")) .flatMap(shape -> shape.getTrait(DataTrait.class)) .filter(trait -> trait.getValue().equals("account")) .isPresent()); - assertTrue(model.getShapeIndex().getShape(ShapeId.from("ns.foo#B")) + assertTrue(model.getShape(ShapeId.from("ns.foo#B")) .flatMap(shape -> shape.getTrait(DataTrait.class)) .filter(trait -> trait.getValue().equals("tagging")) .isPresent()); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java index 818f7c7d8fc..0e5ebf96288 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/ServiceTraitTest.java @@ -86,8 +86,8 @@ public void loadsFromModel() { .addImport(getClass().getResource("test-model.json")) .assemble() .unwrap(); - ServiceShape service = result.getShapeIndex() - .getShape(ShapeId.from("ns.foo#SomeService")).get() + ServiceShape service = result + .expectShape(ShapeId.from("ns.foo#SomeService")) .asServiceShape().get(); ServiceTrait trait = service.getTrait(ServiceTrait.class).get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/UnsignedPayloadTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/UnsignedPayloadTraitTest.java index ce35863c3f5..7e61bb38092 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/UnsignedPayloadTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/UnsignedPayloadTraitTest.java @@ -31,12 +31,12 @@ public void loadsFromModel() { .assemble() .unwrap(); - assertTrue(result.getShapeIndex() + assertTrue(result .getShape(ShapeId.from("ns.foo#Unsigned1")) .flatMap(shape -> shape.getTrait(UnsignedPayloadTrait.class)) .isPresent()); - assertTrue(result.getShapeIndex() + assertTrue(result .getShape(ShapeId.from("ns.foo#Unsigned2")) .flatMap(shape -> shape.getTrait(UnsignedPayloadTrait.class)) .filter(trait -> trait.getValues().equals(ListUtils.of("aws.v4"))) diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitTest.java index f45e7639d70..c99235aaabc 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/apigateway/IntegrationTraitTest.java @@ -50,8 +50,7 @@ public void loadsTraitFromModel() { .assemble() .unwrap(); - MockIntegrationTrait trait = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Operation")) - .get() + MockIntegrationTrait trait = model.expectShape(ShapeId.from("ns.foo#Operation")) .getTrait(MockIntegrationTrait.class) .get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java index e4087b1d31b..20cac4b3b07 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/CleanClientDiscoveryTraitTransformerTest.java @@ -41,22 +41,22 @@ public void removesTraitsWhenOperationRemoved() { return !shape.getId().toString().equals("ns.foo#DescribeEndpoints"); }); - ServiceShape service = result.getShapeIndex() + ServiceShape service = result .getShape(ShapeId.from("ns.foo#FooService")) .flatMap(Shape::asServiceShape) .get(); - OperationShape getOperation = result.getShapeIndex() + OperationShape getOperation = result .getShape(ShapeId.from("ns.foo#GetObject")) .flatMap(Shape::asOperationShape) .get(); - OperationShape putOperation = result.getShapeIndex() + OperationShape putOperation = result .getShape(ShapeId.from("ns.foo#PutObject")) .flatMap(Shape::asOperationShape) .get(); - MemberShape putId = result.getShapeIndex() + MemberShape putId = result .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) .flatMap(Shape::asMemberShape) .get(); @@ -80,22 +80,22 @@ public void removesTraitsWhenErrorRemoved() { return !shape.getId().toString().equals("ns.foo#InvalidEndpointError"); }); - ServiceShape service = result.getShapeIndex() + ServiceShape service = result .getShape(ShapeId.from("ns.foo#FooService")) .flatMap(Shape::asServiceShape) .get(); - OperationShape getOperation = result.getShapeIndex() + OperationShape getOperation = result .getShape(ShapeId.from("ns.foo#GetObject")) .flatMap(Shape::asOperationShape) .get(); - OperationShape putOperation = result.getShapeIndex() + OperationShape putOperation = result .getShape(ShapeId.from("ns.foo#PutObject")) .flatMap(Shape::asOperationShape) .get(); - MemberShape putId = result.getShapeIndex() + MemberShape putId = result .getShape(ShapeId.from("ns.foo#PutObjectInput$Id")) .flatMap(Shape::asMemberShape) .get(); @@ -119,12 +119,12 @@ public void doesntRemoveOptionalOperationTraitIfStillBoundToDiscoveryService() { return !shape.getId().toString().equals("ns.foo#DescribeEndpointsFoo"); }); - OperationShape getOperation = result.getShapeIndex() + OperationShape getOperation = result .getShape(ShapeId.from("ns.foo#GetObjectFoo")) .flatMap(Shape::asOperationShape) .get(); - OperationShape putOperation = result.getShapeIndex() + OperationShape putOperation = result .getShape(ShapeId.from("ns.foo#PutObject")) .flatMap(Shape::asOperationShape) .get(); @@ -145,7 +145,7 @@ public void keepsDiscoveryIdTraitIfStillBound() { return !shape.getId().toString().equals("ns.foo#DescribeEndpointsFoo"); }); - MemberShape id = result.getShapeIndex() + MemberShape id = result .getShape(ShapeId.from("ns.foo#GetObjectInput$Id")) .flatMap(Shape::asMemberShape) .get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java index 757a205e631..50e8ab52e3c 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientDiscoveredEndpointTraitTest.java @@ -31,8 +31,8 @@ public void loadsFromModel() { .addImport(getClass().getResource("test-model.json")) .assemble() .unwrap(); - OperationShape operation = result.getShapeIndex() - .getShape(ShapeId.from("ns.foo#GetObject")).get() + OperationShape operation = result + .expectShape(ShapeId.from("ns.foo#GetObject")) .asOperationShape().get(); ClientDiscoveredEndpointTrait trait = operation.getTrait(ClientDiscoveredEndpointTrait.class).get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java index e512fca503c..2309da7e405 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryIdTraitTest.java @@ -40,10 +40,10 @@ public void loadsFromModel() { .addImport(getClass().getResource("test-model.json")) .assemble() .unwrap(); - OperationShape operation = result.getShapeIndex() - .getShape(ShapeId.from("ns.foo#GetObject")).get() + OperationShape operation = result + .expectShape(ShapeId.from("ns.foo#GetObject")) .asOperationShape().get(); - MemberShape member = result.getShapeIndex() + MemberShape member = result .getShape(operation.getInput().get()).get() .asStructureShape().get() .getMember("Id").get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java index 1dee0a4b68f..73eea3155a8 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/clientendpointdiscovery/ClientEndpointDiscoveryTraitTest.java @@ -16,7 +16,6 @@ package software.amazon.smithy.aws.traits.clientendpointdiscovery; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; @@ -32,8 +31,8 @@ public void loadsFromModel() { .addImport(getClass().getResource("test-model.json")) .assemble() .unwrap(); - ServiceShape service = result.getShapeIndex() - .getShape(ShapeId.from("ns.foo#FooService")).get() + ServiceShape service = result + .expectShape(ShapeId.from("ns.foo#FooService")) .asServiceShape().get(); ClientEndpointDiscoveryTrait trait = service.getTrait(ClientEndpointDiscoveryTrait.class).get(); diff --git a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/iam/RequiredActionsTraitTest.java b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/iam/RequiredActionsTraitTest.java index f92ced6f771..cf4949f3725 100644 --- a/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/iam/RequiredActionsTraitTest.java +++ b/aws/smithy-aws-traits/src/test/java/software/amazon/smithy/aws/traits/iam/RequiredActionsTraitTest.java @@ -33,7 +33,7 @@ public void loadsFromModel() { .assemble() .unwrap(); - Shape myOperation = result.getShapeIndex().getShape(ShapeId.from("smithy.example#MyOperation")).get(); + Shape myOperation = result.getShape(ShapeId.from("smithy.example#MyOperation")).get(); assertTrue(myOperation.hasTrait(RequiredActionsTrait.class)); assertThat(myOperation.getTrait(RequiredActionsTrait.class).get().getValues(), containsInAnyOrder( diff --git a/smithy-build/src/main/java/software/amazon/smithy/build/PluginContext.java b/smithy-build/src/main/java/software/amazon/smithy/build/PluginContext.java index 0c6dcbbd547..df911dd5620 100644 --- a/smithy-build/src/main/java/software/amazon/smithy/build/PluginContext.java +++ b/smithy-build/src/main/java/software/amazon/smithy/build/PluginContext.java @@ -49,7 +49,7 @@ public final class PluginContext implements ToSmithyBuilder { private final FileManifest fileManifest; private final ClassLoader pluginClassLoader; private final Set sources; - private ShapeIndex nonTraitsIndex; + private Model nonTraitsModel; private PluginContext(Builder builder) { model = SmithyBuilder.requiredState("model", builder.model); @@ -148,28 +148,32 @@ public Optional getPluginClassLoader() { return Optional.ofNullable(pluginClassLoader); } + @Deprecated + public synchronized ShapeIndex getNonTraitShapes() { + return getModelWithoutTraitShapes().getShapeIndex(); + } + /** - * Gets all shapes from a model as a {@code ShapeIndex} where shapes that - * define traits or shapes that are only used as part of a trait - * definition have been removed. + * Creates a new Model where shapes that define traits or shapes + * that are only used as part of a trait definition have been removed. * *

This is typically functionality used by code generators when * generating data structures from a model. It's useful because it only * provides shapes that are used to describe data structures rather than * shapes used to describe metadata about the data structures. * - *

Note: this method just calls {@link ModelTransformer#getNonTraitShapes}. + *

Note: this method just calls {@link ModelTransformer#getModelWithoutTraitShapes}. * It's added to {@code PluginContext} to make it more easily available * to code generators. * - * @return Returns a ShapeIndex containing matching shapes. + * @return Returns a Model containing matching shapes. */ - public synchronized ShapeIndex getNonTraitShapes() { - if (nonTraitsIndex == null) { - nonTraitsIndex = ModelTransformer.create().getNonTraitShapes(model); + public synchronized Model getModelWithoutTraitShapes() { + if (nonTraitsModel == null) { + nonTraitsModel = ModelTransformer.create().getModelWithoutTraitShapes(model); } - return nonTraitsIndex; + return nonTraitsModel; } /** @@ -197,8 +201,7 @@ public Set getSources() { * @return Returns true if this shape is considered a source shape. */ public boolean isSourceShape(ToShapeId shape) { - return originalModel == null - || isSource(originalModel.getShapeIndex().getShape(shape.toShapeId()).orElse(null)); + return originalModel == null || isSource(originalModel.getShape(shape.toShapeId()).orElse(null)); } /** diff --git a/smithy-build/src/main/java/software/amazon/smithy/build/plugins/BuildInfoPlugin.java b/smithy-build/src/main/java/software/amazon/smithy/build/plugins/BuildInfoPlugin.java index c708795c8e6..e86ebc88bba 100644 --- a/smithy-build/src/main/java/software/amazon/smithy/build/plugins/BuildInfoPlugin.java +++ b/smithy-build/src/main/java/software/amazon/smithy/build/plugins/BuildInfoPlugin.java @@ -88,7 +88,7 @@ private static Node serializeBuildInfo(PluginContext context) { } private static Node findTraitNames(Model model) { - return model.getShapeIndex().shapes() + return model.shapes() .flatMap(shape -> shape.getAllTraits().keySet().stream()) .map(ShapeId::toString) .distinct() @@ -98,7 +98,7 @@ private static Node findTraitNames(Model model) { } private static Node findShapeIds(Model model, Class clazz) { - return model.getShapeIndex().shapes(clazz) + return model.shapes(clazz) .map(Shape::getId) .map(Object::toString) .sorted() diff --git a/smithy-build/src/main/java/software/amazon/smithy/build/transforms/RemoveUnusedShapes.java b/smithy-build/src/main/java/software/amazon/smithy/build/transforms/RemoveUnusedShapes.java index 4c06f7f7c15..c8b9d4f69a7 100644 --- a/smithy-build/src/main/java/software/amazon/smithy/build/transforms/RemoveUnusedShapes.java +++ b/smithy-build/src/main/java/software/amazon/smithy/build/transforms/RemoveUnusedShapes.java @@ -58,10 +58,10 @@ public BiFunction createTransformer(List int currentShapeCount; do { - currentShapeCount = model.getShapeIndex().toSet().size(); + currentShapeCount = model.toSet().size(); model = transformer.removeUnreferencedShapes(model, keepShapesByTag); model = transformer.removeUnreferencedTraitDefinitions(model, keepTraitDefsByTag); - } while (currentShapeCount != model.getShapeIndex().toSet().size()); + } while (currentShapeCount != model.toSet().size()); return model; }; diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/PluginContextTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/PluginContextTest.java index 610b00818fa..aa26b499e4e 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/PluginContextTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/PluginContextTest.java @@ -10,7 +10,6 @@ import software.amazon.smithy.build.model.ProjectionConfig; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.Node; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.transform.ModelTransformer; import software.amazon.smithy.utils.ListUtils; @@ -48,20 +47,20 @@ public void hasSources() { } @Test - public void createsNonTraitShapeIndex() { + public void createsNonTraitModel() { Model model = Model.assembler() .addImport(getClass().getResource("simple-model.json")) .assemble() .unwrap(); - ShapeIndex scrubbed = ModelTransformer.create().getNonTraitShapes(model); + Model scrubbed = ModelTransformer.create().getModelWithoutTraitShapes(model); PluginContext context = PluginContext.builder() .fileManifest(new MockManifest()) .model(model) .sources(ListUtils.of(Paths.get("/foo/baz"))) .build(); - assertThat(context.getNonTraitShapes(), equalTo(scrubbed)); - assertThat(context.getNonTraitShapes(), equalTo(scrubbed)); // trigger loading from cache + assertThat(context.getModelWithoutTraitShapes(), equalTo(scrubbed)); + assertThat(context.getModelWithoutTraitShapes(), equalTo(scrubbed)); // trigger loading from cache } @Test diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/SmithyBuildTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/SmithyBuildTest.java index c662021fc8c..5a7a8bcca16 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/SmithyBuildTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/SmithyBuildTest.java @@ -96,13 +96,13 @@ public void appliesAllProjections() throws Exception { Model resultA = results.getProjectionResult("a").get().getModel(); Model resultB = results.getProjectionResult("b").get().getModel(); - assertThat(resultA.getShapeIndex().getShape(ShapeId.from("ns.foo#String1")), not(Optional.empty())); - assertThat(resultA.getShapeIndex().getShape(ShapeId.from("ns.foo#String2")), is(Optional.empty())); - assertThat(resultA.getShapeIndex().getShape(ShapeId.from("ns.foo#String3")), not(Optional.empty())); + assertThat(resultA.getShape(ShapeId.from("ns.foo#String1")), not(Optional.empty())); + assertThat(resultA.getShape(ShapeId.from("ns.foo#String2")), is(Optional.empty())); + assertThat(resultA.getShape(ShapeId.from("ns.foo#String3")), not(Optional.empty())); - assertThat(resultB.getShapeIndex().getShape(ShapeId.from("ns.foo#String1")), not(Optional.empty())); - assertThat(resultB.getShapeIndex().getShape(ShapeId.from("ns.foo#String2")), not(Optional.empty())); - assertThat(resultB.getShapeIndex().getShape(ShapeId.from("ns.foo#String3")), not(Optional.empty())); + assertThat(resultB.getShape(ShapeId.from("ns.foo#String1")), not(Optional.empty())); + assertThat(resultB.getShape(ShapeId.from("ns.foo#String2")), not(Optional.empty())); + assertThat(resultB.getShape(ShapeId.from("ns.foo#String3")), not(Optional.empty())); } @Test @@ -205,23 +205,23 @@ public void loadsImports() throws Exception { Model resultB = results.getProjectionResult("b").get().getModel(); Model resultC = results.getProjectionResult("c").get().getModel(); - assertTrue(resultA.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertTrue(resultA.getShape(ShapeId.from("com.foo#String")).get() .getTrait(SensitiveTrait.class).isPresent()); - assertFalse(resultA.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertFalse(resultA.getShape(ShapeId.from("com.foo#String")).get() .getTrait(DocumentationTrait.class).isPresent()); - assertTrue(resultB.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertTrue(resultB.getShape(ShapeId.from("com.foo#String")).get() .getTrait(SensitiveTrait.class).isPresent()); - assertTrue(resultB.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertTrue(resultB.getShape(ShapeId.from("com.foo#String")).get() .getTrait(DocumentationTrait.class).isPresent()); - assertThat(resultB.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertThat(resultB.getShape(ShapeId.from("com.foo#String")).get() .getTrait(DocumentationTrait.class).get().getValue(), equalTo("b.json")); - assertTrue(resultC.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertTrue(resultC.getShape(ShapeId.from("com.foo#String")).get() .getTrait(SensitiveTrait.class).isPresent()); - assertTrue(resultC.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertTrue(resultC.getShape(ShapeId.from("com.foo#String")).get() .getTrait(DocumentationTrait.class).isPresent()); - assertThat(resultC.getShapeIndex().getShape(ShapeId.from("com.foo#String")).get() + assertThat(resultC.getShape(ShapeId.from("com.foo#String")).get() .getTrait(DocumentationTrait.class).get().getValue(), equalTo("c.json")); } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeShapesByTagTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeShapesByTagTest.java index c758b03004f..0625158e1eb 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeShapesByTagTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeShapesByTagTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.TagsTrait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -40,17 +39,14 @@ public void removesTraitsNotInList() { .id("ns.foo#bar") .addTrait(TagsTrait.builder().addValue("qux").build()) .build(); - ShapeIndex index = ShapeIndex.builder() - .addShapes(stringA, stringB) - .build(); Model model = Model.builder() - .shapeIndex(index) + .addShapes(stringA, stringB) .build(); Model result = new ExcludeShapesByTag() .createTransformer(Collections.singletonList("foo")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(stringA.getId()), is(Optional.empty())); - assertThat(result.getShapeIndex().getShape(stringB.getId()), not(Optional.empty())); + assertThat(result.getShape(stringA.getId()), is(Optional.empty())); + assertThat(result.getShape(stringB.getId()), not(Optional.empty())); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeTraitsTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeTraitsTest.java index 63c9c1f5512..40823c39450 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeTraitsTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/ExcludeTraitsTest.java @@ -48,9 +48,9 @@ public void removesTraitsInList() { .createTransformer(Collections.singletonList("documentation")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(DocumentationTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(DocumentationTrait.class), is(Optional.empty())); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(SensitiveTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(SensitiveTrait.class), not(Optional.empty())); assertFalse(result.getTraitDefinition("smithy.api#documentation").isPresent()); } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeAuthTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeAuthTest.java index e41fb1b6873..ef7a6247629 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeAuthTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeAuthTest.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.AuthTrait; import software.amazon.smithy.model.traits.Protocol; import software.amazon.smithy.model.traits.ProtocolsTrait; @@ -51,20 +50,17 @@ public void filtersUnsupportedAuthSchemes() { .version("1") .addTrait(ProtocolsTrait.builder().addProtocol(Protocol.builder().name("foo").build()).build()) .build(); - ShapeIndex index = ShapeIndex.builder() - .addShapes(service1, service2, service3) - .build(); Model model = Model.builder() - .shapeIndex(index) + .addShapes(service1, service2, service3) .build(); Model result = new IncludeAuth() .createTransformer(Collections.singletonList("foo")) .apply(ModelTransformer.create(), model); - Shape updateService1 = result.getShapeIndex().getShape(service1.getId()).get(); + Shape updateService1 = result.getShape(service1.getId()).get(); assertThat(updateService1.getTrait(AuthTrait.class).get().getValues(), contains("foo")); assertThat(updateService1.getTrait(ProtocolsTrait.class).get().getAllAuthSchemes(), contains("foo")); - assertThat(result.getShapeIndex().getShape(service2.getId()).get(), equalTo(service2)); - assertThat(result.getShapeIndex().getShape(service3.getId()).get(), equalTo(service3)); + assertThat(result.getShape(service2.getId()).get(), equalTo(service2)); + assertThat(result.getShape(service3.getId()).get(), equalTo(service3)); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeNamespacesTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeNamespacesTest.java index cdf892a2c21..22c5dace61c 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeNamespacesTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeNamespacesTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.transform.ModelTransformer; @@ -35,15 +34,14 @@ public void removesShapesNotInNamespaces() { StringShape string2 = StringShape.builder().id("ns.foo#qux").build(); StringShape string3 = StringShape.builder().id("ns.bar#yuck").build(); StringShape string4 = StringShape.builder().id("ns.qux#yuck").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(string1, string2, string3, string4).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(string1, string2, string3, string4).build(); Model result = new IncludeNamespaces() .createTransformer(Arrays.asList("ns.foo", "ns.bar")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(string1.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(string2.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(string3.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(string4.getId()), is(Optional.empty())); + assertThat(result.getShape(string1.getId()), not(Optional.empty())); + assertThat(result.getShape(string2.getId()), not(Optional.empty())); + assertThat(result.getShape(string3.getId()), not(Optional.empty())); + assertThat(result.getShape(string4.getId()), is(Optional.empty())); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeProtocolsTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeProtocolsTest.java index 718f9da8485..f519efab9ee 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeProtocolsTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeProtocolsTest.java @@ -20,7 +20,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.Protocol; import software.amazon.smithy.model.traits.ProtocolsTrait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -37,12 +36,11 @@ public void filtersUnsupportedProtocols() { .addProtocol(Protocol.builder().name("qux").build()).build()) .id("ns.foo#baz") .build(); - ShapeIndex index = ShapeIndex.builder().addShape(service).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShape(service).build(); Model result = new IncludeProtocols() .createTransformer(Collections.singletonList("qux")) .apply(ModelTransformer.create(), model); - ServiceShape shape = result.getShapeIndex().getShape(service.getId()).get().asServiceShape().get(); + ServiceShape shape = result.getShape(service.getId()).get().asServiceShape().get(); Assertions.assertEquals(shape.getTrait(ProtocolsTrait.class).get().getProtocolNames(), ListUtils.of("qux")); } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeServicesTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeServicesTest.java index ccaba9eba48..1aa1e4dbea9 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeServicesTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeServicesTest.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ServiceShape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.transform.ModelTransformer; @@ -35,14 +34,13 @@ public void removesTraitsNotInList() { ServiceShape serviceA = ServiceShape.builder().id("ns.foo#baz").version("1").build(); ServiceShape serviceB = ServiceShape.builder().id("ns.foo#bar").version("1").build(); StringShape string = StringShape.builder().id("ns.foo#yuck").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(serviceA, serviceB, string).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(serviceA, serviceB, string).build(); Model result = new IncludeServices() .createTransformer(Collections.singletonList("ns.foo#baz")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(serviceA.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(string.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(serviceB.getId()), is(Optional.empty())); + assertThat(result.getShape(serviceA.getId()), not(Optional.empty())); + assertThat(result.getShape(string.getId()), not(Optional.empty())); + assertThat(result.getShape(serviceB.getId()), is(Optional.empty())); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeShapesByTagTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeShapesByTagTest.java index a8c9934554e..fb3b602e648 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeShapesByTagTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeShapesByTagTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.TagsTrait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -40,17 +39,14 @@ public void removesTraitsNotInList() { .id("ns.foo#bar") .addTrait(TagsTrait.builder().addValue("qux").build()) .build(); - ShapeIndex index = ShapeIndex.builder() - .addShapes(stringA, stringB) - .build(); Model model = Model.builder() - .shapeIndex(index) + .addShapes(stringA, stringB) .build(); Model result = new IncludeShapesByTag() .createTransformer(Collections.singletonList("foo")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(stringA.getId()), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(stringB.getId()), is(Optional.empty())); + assertThat(result.getShape(stringA.getId()), not(Optional.empty())); + assertThat(result.getShape(stringB.getId()), is(Optional.empty())); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTagsTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTagsTest.java index ba1bc8adc84..64202a7fc6b 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTagsTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTagsTest.java @@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.TagsTrait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -41,14 +40,13 @@ public void removesTagsFromShapesNotInList() { .addTrait(TagsTrait.builder().addValue("foo").build()) .build(); Shape shape3 = StringShape.builder().id("ns.foo#shape3").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(shape1, shape2, shape3).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(shape1, shape2, shape3).build(); Model result = new IncludeTags() .createTransformer(Collections.singletonList("foo")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(shape1.getId()).get().getTags(), contains("foo")); - assertThat(result.getShapeIndex().getShape(shape2.getId()).get(), equalTo(shape2)); - assertThat(result.getShapeIndex().getShape(shape3.getId()).get(), equalTo(shape3)); + assertThat(result.expectShape(shape1.getId()).getTags(), contains("foo")); + assertThat(result.expectShape(shape2.getId()), equalTo(shape2)); + assertThat(result.expectShape(shape3.getId()), equalTo(shape3)); } } diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTraitsTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTraitsTest.java index bee566a505b..c58764e6ef8 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTraitsTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/IncludeTraitsTest.java @@ -50,9 +50,9 @@ public void removesTraitsNotInList() { .createTransformer(ListUtils.of("documentation")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(DocumentationTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(DocumentationTrait.class), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(SensitiveTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(SensitiveTrait.class), is(Optional.empty())); assertTrue(result.getTraitDefinition("smithy.api#documentation").isPresent()); @@ -74,9 +74,9 @@ public void includesBuiltinTraits() { .createTransformer(Collections.singletonList("smithy.api")) .apply(ModelTransformer.create(), model); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(DocumentationTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(DocumentationTrait.class), not(Optional.empty())); - assertThat(result.getShapeIndex().getShape(ShapeId.from("ns.foo#baz")).get().getTrait(SensitiveTrait.class), + assertThat(result.expectShape(ShapeId.from("ns.foo#baz")).getTrait(SensitiveTrait.class), not(Optional.empty())); assertTrue(result.getTraitDefinition("smithy.api#documentation").isPresent()); assertTrue(result.getTraitDefinition("smithy.api#sensitive").isPresent()); diff --git a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/RemoveUnusedShapesTest.java b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/RemoveUnusedShapesTest.java index 73cb7cc2ba0..01c442de52d 100644 --- a/smithy-build/src/test/java/software/amazon/smithy/build/transforms/RemoveUnusedShapesTest.java +++ b/smithy-build/src/test/java/software/amazon/smithy/build/transforms/RemoveUnusedShapesTest.java @@ -43,7 +43,7 @@ public void treeShakerWithExports() throws Exception { Model result = new RemoveUnusedShapes() .createTransformer(Collections.singletonList("export")) .apply(ModelTransformer.create(), model); - List ids = result.getShapeIndex().shapes() + List ids = result.shapes() .filter(FunctionalUtils.not(Prelude::isPreludeShape)) .map(Shape::getId) .map(Object::toString) @@ -63,8 +63,8 @@ public void shouldRetainUsedTraitsAndShapesUsedBySaidTraits() throws Exception { .apply(ModelTransformer.create(), model); assertTrue(result.getTraitDefinition("ns.foo#bar").isPresent()); - assertTrue(result.getShapeIndex().getShape(ShapeId.from("ns.foo#bar")).isPresent()); - assertTrue(result.getShapeIndex().getShape(ShapeId.from("ns.foo#BarTraitShapeMember")).isPresent()); + assertTrue(result.getShape(ShapeId.from("ns.foo#bar")).isPresent()); + assertTrue(result.getShape(ShapeId.from("ns.foo#BarTraitShapeMember")).isPresent()); assertFalse(result.getTraitDefinition("ns.foo#QuuxTraitShapeMember").isPresent()); } @@ -79,6 +79,6 @@ public void shouldPruneUnusedTraitsAndShapesUsedBySaidTraits() throws Exception .apply(ModelTransformer.create(), model); assertFalse(result.getTraitDefinition("ns.foo#quux").isPresent()); - assertFalse(result.getShapeIndex().getShape(ShapeId.from("ns.foo#QuuxTraitShape")).isPresent()); + assertFalse(result.getShape(ShapeId.from("ns.foo#QuuxTraitShape")).isPresent()); } } diff --git a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/Validator.java b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/Validator.java index c62a2383c40..acd92857b30 100644 --- a/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/Validator.java +++ b/smithy-cli/src/main/java/software/amazon/smithy/cli/commands/Validator.java @@ -61,7 +61,7 @@ static void validate(ValidatedResult result, boolean quiet) { System.out.println(String.join("", Collections.nCopies(line.length(), "-"))); System.out.println(line); result.getResult().ifPresent(model -> System.out.println(String.format( - "Validated %d shapes in model", model.getShapeIndex().shapes().count()))); + "Validated %d shapes in model", model.shapes().count()))); } if (errors + dangers > 0) { diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java index 290534e0dd0..6b6b0244340 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/Differences.java @@ -67,8 +67,7 @@ public Model getNewModel() { * @return Returns a stream of each added shape. */ public Stream addedShapes() { - return newModel.getShapeIndex().shapes() - .filter(shape -> !oldModel.getShapeIndex().getShape(shape.getId()).isPresent()); + return newModel.shapes().filter(shape -> !oldModel.getShape(shape.getId()).isPresent()); } /** @@ -102,8 +101,7 @@ public Stream> addedMetadata() { * @return Returns a stream of each removed shape. */ public Stream removedShapes() { - return oldModel.getShapeIndex().shapes() - .filter(shape -> !newModel.getShapeIndex().getShape(shape.getId()).isPresent()); + return oldModel.shapes().filter(shape -> !newModel.getShape(shape.getId()).isPresent()); } /** @@ -164,8 +162,8 @@ public Stream changedMetadata() { } private static void detectShapeChanges(Model oldModel, Model newModel, Differences differences) { - for (Shape oldShape : oldModel.getShapeIndex().toSet()) { - newModel.getShapeIndex().getShape(oldShape.getId()).ifPresent(newShape -> { + for (Shape oldShape : oldModel.toSet()) { + newModel.getShape(oldShape.getId()).ifPresent(newShape -> { if (!oldShape.equals(newShape)) { differences.changedShapes.add(new ChangedShape<>(oldShape, newShape)); } diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationInputOutput.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationInputOutput.java index 6795741c3f8..4185e83ee44 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationInputOutput.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/AddedOperationInputOutput.java @@ -64,7 +64,7 @@ private List checkOperation(Model newModel, ChangedShape validateChange(String rel, Model model, Shape operation, ShapeId target) { String eventId = "AddedOperation" + rel; - return model.getShapeIndex().getShape(target).flatMap(Shape::asStructureShape).map(struct -> { + return model.getShape(target).flatMap(Shape::asStructureShape).map(struct -> { if (struct.getAllMembers().values().stream().noneMatch(MemberShape::isRequired)) { // This is a backward compatible change. return ValidationEvent.builder() diff --git a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java index 992f827788e..554ad881b7d 100644 --- a/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java +++ b/smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/ChangedMemberTarget.java @@ -57,7 +57,7 @@ private ValidationEvent createChangeEvent(Differences differences, ChangedShape< } private Shape getShapeTarget(Model model, ShapeId id) { - return model.getShapeIndex().getShape(id).orElse(null); + return model.getShape(id).orElse(null); } private boolean areShapesCompatible(Shape oldShape, Shape newShape) { diff --git a/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java b/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java index 55ac3cc5abf..ffa558d8a5c 100644 --- a/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java +++ b/smithy-diff/src/test/java/software/amazon/smithy/diff/DifferencesTest.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.SensitiveTrait; @@ -62,7 +61,7 @@ public void detectsChangedMetadata() { public void detectsAddedShapes() { Shape shape = StringShape.builder().id("foo.bar#Baz").build(); Model previous = Model.builder().build(); - Model current = Model.builder().shapeIndex(ShapeIndex.builder().addShapes(shape).build()).build(); + Model current = Model.builder().addShapes(shape).build(); Differences differences = Differences.detect(previous, current); assertThat(differences.addedShapes().count(), equalTo(1L)); @@ -72,7 +71,7 @@ public void detectsAddedShapes() { @Test public void detectsRemovedShapes() { Shape shape = StringShape.builder().id("foo.bar#Baz").build(); - Model previous = Model.builder().shapeIndex(ShapeIndex.builder().addShapes(shape).build()).build(); + Model previous = Model.builder().addShapes(shape).build(); Model current = Model.builder().build(); Differences differences = Differences.detect(previous, current); diff --git a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java index 137ae69c1d9..6a6bb4ee4ab 100644 --- a/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java +++ b/smithy-jsonschema/src/main/java/software/amazon/smithy/jsonschema/JsonSchemaConverter.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.Set; import java.util.function.Predicate; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.loader.Prelude; import software.amazon.smithy.model.neighbor.Walker; import software.amazon.smithy.model.node.Node; @@ -170,14 +171,19 @@ public JsonSchemaConverter addMapper(JsonSchemaMapper jsonSchemaMapper) { return this; } + @Deprecated + public SchemaDocument convert(ShapeIndex shapeIndex) { + return doConversion(shapeIndex, null); + } + /** * Perform the conversion of the entire shape Index. * - * @param shapeIndex Shape index to convert. + * @param model Model to convert. * @return Returns the created SchemaDocument. */ - public SchemaDocument convert(ShapeIndex shapeIndex) { - return doConversion(shapeIndex, null); + public SchemaDocument convert(Model model) { + return convert(model.getShapeIndex()); } /** @@ -194,6 +200,20 @@ public SchemaDocument convert(ShapeIndex shapeIndex, Shape shape) { return doConversion(shapeIndex, shape); } + /** + * Perform the conversion of a single shape. + * + *

The root shape of the created document is set to the given shape, + * and only shapes connected to the given shape are added as a definition. + * + * @param model Model to convert. + * @param shape Shape to convert. + * @return Returns the created SchemaDocument. + */ + public SchemaDocument convert(Model model, Shape shape) { + return convert(model.getShapeIndex(), shape); + } + private SchemaDocument doConversion(ShapeIndex shapeIndex, Shape rootShape) { // TODO: break this API to make this work more reliably. // diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java index c536b7ac63b..8e7e64d6b04 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/AbbreviationNameValidator.java @@ -60,7 +60,7 @@ public Provider() { @Override public List validate(Model model) { - return model.getShapeIndex().shapes() + return model.shapes() .flatMap(this::validateShapeName) .collect(Collectors.toList()); } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java index c67084c16cd..ab33d7f7e44 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/CamelCaseValidator.java @@ -68,7 +68,7 @@ public List validate(Model model) { List events = new ArrayList<>(); // Normal shapes are expected to be upper camel. - model.getShapeIndex().shapes() + model.shapes() .filter(FunctionalUtils.not(Shape::isMemberShape)) .filter(shape -> !shape.hasTrait(TraitDefinition.class)) .filter(shape -> !getPattern(UPPER).matcher(shape.getId().getName()).find()) @@ -77,7 +77,7 @@ public List validate(Model model) { .forEach(events::add); // Trait shapes are expected to be lower camel. - model.getShapeIndex().shapes() + model.shapes() .filter(shape -> shape.hasTrait(TraitDefinition.class)) .filter(shape -> !getPattern(LOWER).matcher(shape.getId().getName()).find()) .map(shape -> danger(shape, format("%s trait definition, `%s`, is not lower camel case", @@ -85,7 +85,7 @@ public List validate(Model model) { .forEach(events::add); Pattern isValidMemberName = getPattern(memberNames); - model.getShapeIndex().shapes(MemberShape.class) + model.shapes(MemberShape.class) .filter(shape -> !isValidMemberName.matcher(shape.getMemberName()).find()) .map(shape -> danger(shape, format("Member shape member name, `%s`, is not %s camel case", shape.getMemberName(), memberNames))) diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedAuthSchemesValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedAuthSchemesValidator.java index aa0ae2ae3da..e423c1e2d19 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedAuthSchemesValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedAuthSchemesValidator.java @@ -63,7 +63,7 @@ public Provider() { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> Trait.flatMapStream(shape, AuthTrait.class)) .flatMap(pair -> validateAuthSchemes(pair.getLeft(), pair.getRight())) .collect(Collectors.toList()); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedProtocolsValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedProtocolsValidator.java index fbfdf432e82..27c2972fb05 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedProtocolsValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/DeprecatedProtocolsValidator.java @@ -63,7 +63,7 @@ public Provider() { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ProtocolsTrait.class)) .flatMap(pair -> validateProtocols(pair.getLeft(), pair.getRight())) .collect(Collectors.toList()); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitEachSelectorValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitEachSelectorValidator.java index 59ad8271f44..8ef50abb5d4 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitEachSelectorValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitEachSelectorValidator.java @@ -55,7 +55,7 @@ private static Selector parse(StringNode expression) { @Override public List validate(Model model) { - return selector.select(model.getShapeIndex()).stream() + return selector.select(model).stream() .map(shape -> danger(shape, "Selector capture matched selector: " + selector)) .collect(Collectors.toList()); } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitNoneSelectorValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitNoneSelectorValidator.java index 5e90aacc544..cfc0b092c87 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitNoneSelectorValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/EmitNoneSelectorValidator.java @@ -61,7 +61,7 @@ private static Selector parse(StringNode expression) { @Override public List validate(Model model) { // Filter out prelude types. - Set shapes = selector.select(model.getShapeIndex()).stream() + Set shapes = selector.select(model).stream() .filter(shape -> !Prelude.isPreludeShape(shape.getId())) .collect(Collectors.toSet()); diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java index 7bc521c29ae..4e3470e08fb 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/InputOutputStructureReuseValidator.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.Severity; import software.amazon.smithy.model.validation.ValidationEvent; @@ -51,45 +50,44 @@ public Provider() { @Override public List validate(Model model) { List events = new ArrayList<>(); - ShapeIndex index = model.getShapeIndex(); - Map> inputs = createStructureToOperation(index, OperationShape::getInput); - Map> outputs = createStructureToOperation(index, OperationShape::getOutput); + Map> inputs = createStructureToOperation(model, OperationShape::getInput); + Map> outputs = createStructureToOperation(model, OperationShape::getOutput); // Look for structures used as both input and output. Set both = new HashSet<>(inputs.keySet()); both.retainAll(outputs.keySet()); both.stream().map(id -> emitWhenBothInputAndOutput( - index, id, inputs.get(id), outputs.get(id))).forEach(events::add); + model, id, inputs.get(id), outputs.get(id))).forEach(events::add); // Look for shared usage across multiple operations. - events.addAll(emitShared(index, inputs, "input")); - events.addAll(emitShared(index, outputs, "output")); + events.addAll(emitShared(model, inputs, "input")); + events.addAll(emitShared(model, outputs, "output")); return events; } private List emitShared( - ShapeIndex index, + Model model, Map> mapping, String descriptor ) { return mapping.entrySet().stream() .filter(entry -> entry.getValue().size() > 1) - .map(entry -> emitWhenShared(index, entry.getKey(), entry.getValue(), descriptor)) + .map(entry -> emitWhenShared(model, entry.getKey(), entry.getValue(), descriptor)) .collect(Collectors.toList()); } /** * Creates a map of structure ShapeId to a list of operations that reference it as input/output. * - * @param index The shape index used to get all operations. + * @param model The model used to get all operations. * @param f The mapping function used to retrieve input out output structures. * @return Returns the mapping. */ private static Map> createStructureToOperation( - ShapeIndex index, + Model model, Function> f ) { - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Pair.flatMapStream(shape, f)) .collect(Collectors.groupingBy( Pair::getRight, @@ -99,12 +97,12 @@ private static Map> createStructureToOperation( } private ValidationEvent emitWhenBothInputAndOutput( - ShapeIndex index, + Model model, ShapeId structure, Set inputs, Set outputs ) { - return emit(index, structure, String.format( + return emit(model, structure, String.format( "Using the same structure for both input and output can lead to backward-compatibility problems " + "in the future if the members or traits used in input needs to diverge from those used in " + "output. It is always better to use structures that are exclusively used as input or " @@ -115,12 +113,12 @@ private ValidationEvent emitWhenBothInputAndOutput( } private ValidationEvent emitWhenShared( - ShapeIndex index, + Model model, ShapeId structure, Set operations, String descriptor ) { - return emit(index, structure, String.format( + return emit(model, structure, String.format( "Referencing the same %1$s structure from multiple operations can lead to backward-compatibility " + "problems in the future if the %1$ss ever need to diverge. By using the same structure, you " + "are unnecessarily tying the interfaces of these operations together. This structure is" @@ -128,13 +126,13 @@ private ValidationEvent emitWhenShared( descriptor, tickedList(operations))); } - private ValidationEvent emit(ShapeIndex index, ShapeId shape, String message) { + private ValidationEvent emit(Model model, ShapeId shape, String message) { ValidationEvent.Builder builder = ValidationEvent.builder() .eventId(getName()) .severity(Severity.DANGER) .message(message) .shapeId(shape); - index.getShape(shape).ifPresent(builder::shape); + model.getShape(shape).ifPresent(builder::shape); return builder.build(); } } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java index 9c78144321c..db2a49869c6 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/MissingPaginatedTraitValidator.java @@ -32,7 +32,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.PaginatedTrait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -124,14 +123,14 @@ private static Optional findMember(Collection haystack, Collecti @Override public List validate(Model model) { OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .filter(shape -> !shape.getTrait(PaginatedTrait.class).isPresent()) - .flatMap(shape -> validateShape(model.getShapeIndex(), operationIndex, shape)) + .flatMap(shape -> validateShape(model, operationIndex, shape)) .collect(Collectors.toList()); } private Stream validateShape( - ShapeIndex index, + Model model, OperationIndex operationIndex, OperationShape operation ) { @@ -162,7 +161,7 @@ private Stream validateShape( .map(member -> Stream.of(danger(operation, format( "This operation contains an output member, `%s`, that requires that the " + "operation is marked with the `paginated` trait. %s", member, DISCLAIMER)))) - .orElseGet(() -> suggestPagination(verb, operation, output, index)); + .orElseGet(() -> suggestPagination(verb, operation, output, model)); } return Stream.empty(); @@ -172,7 +171,7 @@ private Stream suggestPagination( String verb, OperationShape operation, StructureShape output, - ShapeIndex index + Model model ) { if (!verbsSuggestPagination.contains(verb)) { return Stream.empty(); @@ -181,7 +180,7 @@ private Stream suggestPagination( // We matched a verb, but only suggest pagination if there's a top-level output member that's a list. boolean hasListMember = output.getAllMembers().values().stream() .map(MemberShape::getTarget) - .flatMap(id -> OptionalUtils.stream(index.getShape(id))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id))) .anyMatch(Shape::isListShape); if (!hasListMember) { diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java index 460b0f9f6cb..47ff1336b0a 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/ReservedWordsValidator.java @@ -32,7 +32,6 @@ import software.amazon.smithy.model.selector.SelectorSyntaxException; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.Severity; import software.amazon.smithy.model.validation.ValidationEvent; @@ -82,8 +81,7 @@ public Provider() { @Override public List validate(Model model) { - ShapeIndex shapeIndex = model.getShapeIndex(); - return reservations.stream().flatMap(reservation -> reservation.validate(shapeIndex)) + return reservations.stream().flatMap(reservation -> reservation.validate(model)) .collect(Collectors.toList()); } @@ -135,8 +133,8 @@ private Selector parse(StringNode expression) { } } - private Stream validate(ShapeIndex shapeIndex) { - return selector.select(shapeIndex).stream().flatMap(shape -> OptionalUtils.stream(validateShape(shape))); + private Stream validate(Model model) { + return selector.select(model).stream().flatMap(shape -> OptionalUtils.stream(validateShape(shape))); } private Optional validateShape(Shape shape) { diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java index 019cb40986c..511bd33659e 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/ShouldHaveUsedTimestampValidator.java @@ -28,7 +28,6 @@ import software.amazon.smithy.model.shapes.LongShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.ShortShape; @@ -103,52 +102,51 @@ public Provider() { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); ShapeVisitor> visitor = Shape.>visitor() .when(StringShape.class, s -> validateSimpleShape(s, patterns)) .when(ShortShape.class, s -> validateSimpleShape(s, patterns)) .when(IntegerShape.class, s -> validateSimpleShape(s, patterns)) .when(LongShape.class, s -> validateSimpleShape(s, patterns)) .when(FloatShape.class, s -> validateSimpleShape(s, patterns)) - .when(StructureShape.class, shape -> validateStructure(shape, index, patterns)) - .when(UnionShape.class, shape -> validateUnion(shape, index, patterns)) + .when(StructureShape.class, shape -> validateStructure(shape, model, patterns)) + .when(UnionShape.class, shape -> validateUnion(shape, model, patterns)) .orElse(ListUtils.of()); - return index.shapes().flatMap(shape -> shape.accept(visitor).stream()).collect(Collectors.toList()); + return model.shapes().flatMap(shape -> shape.accept(visitor).stream()).collect(Collectors.toList()); } private List validateStructure( StructureShape structure, - ShapeIndex shapeIndex, + Model model, List patterns ) { return structure .getAllMembers() .entrySet() .stream() - .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), shapeIndex, patterns)) + .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model, patterns)) .collect(Collectors.toList()); } private List validateUnion( UnionShape union, - ShapeIndex shapeIndex, + Model model, List patterns ) { return union .getAllMembers() .entrySet() .stream() - .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), shapeIndex, patterns)) + .flatMap(entry -> validateTargetShape(entry.getKey(), entry.getValue(), model, patterns)) .collect(Collectors.toList()); } private Stream validateTargetShape( String name, MemberShape target, - ShapeIndex shapeIndex, + Model model, List patterns ) { - return OptionalUtils.stream(shapeIndex.getShape(target.getTarget()) + return OptionalUtils.stream(model.getShape(target.getTarget()) .flatMap(shape -> validateName(name, shape.getType(), target, patterns))); } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java index c4e838f379a..2a45861ca16 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/StandardOperationVerbValidator.java @@ -87,7 +87,7 @@ private static Map> extractAlternatives(ObjectNode node) { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> OptionalUtils.stream(validateShape(shape, verbs, prefixes, alts))) .collect(Collectors.toList()); } diff --git a/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java b/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java index 287745d4770..a226388d8d7 100644 --- a/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java +++ b/smithy-linters/src/main/java/software/amazon/smithy/linters/StutteredShapeNameValidator.java @@ -22,7 +22,6 @@ import java.util.stream.Collectors; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -44,25 +43,24 @@ public Provider() { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); ShapeVisitor> visitor = Shape.>visitor() - .when(UnionShape.class, shape -> validateNames(index, shape, shape.getMemberNames())) - .when(StructureShape.class, shape -> validateNames(index, shape, shape.getMemberNames())) + .when(UnionShape.class, shape -> validateNames(model, shape, shape.getMemberNames())) + .when(StructureShape.class, shape -> validateNames(model, shape, shape.getMemberNames())) .orElseGet(Collections::emptyList); - return index.shapes().flatMap(shape -> shape.accept(visitor).stream()).collect(Collectors.toList()); + return model.shapes().flatMap(shape -> shape.accept(visitor).stream()).collect(Collectors.toList()); } - private List validateNames(ShapeIndex index, Shape shape, Collection memberNames) { + private List validateNames(Model model, Shape shape, Collection memberNames) { String shapeName = shape.getId().getName(); String lowerCaseShapeName = shapeName.toLowerCase(Locale.US); return memberNames.stream() .filter(memberName -> memberName.toLowerCase(Locale.US).startsWith(lowerCaseShapeName)) - .map(memberName -> stutteredMemberName(index, shape, shapeName, memberName)) + .map(memberName -> stutteredMemberName(model, shape, shapeName, memberName)) .collect(Collectors.toList()); } - private ValidationEvent stutteredMemberName(ShapeIndex index, Shape shape, String shapeName, String memberName) { - Shape member = index.getShape(shape.getId().withMember(memberName)).orElseThrow( + private ValidationEvent stutteredMemberName(Model model, Shape shape, String shapeName, String memberName) { + Shape member = model.getShape(shape.getId().withMember(memberName)).orElseThrow( () -> new RuntimeException("Invalid member name for shape: " + shape + ", " + memberName)); return warning(member, String.format( "The `%s` %s shape stutters its name in the member `%s`; %2$s member names should not be " diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/Model.java b/smithy-model/src/main/java/software/amazon/smithy/model/Model.java index ea726bf13b4..1918b089ae1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/Model.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/Model.java @@ -21,11 +21,16 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import java.util.stream.Stream; import software.amazon.smithy.model.knowledge.KnowledgeIndex; import software.amazon.smithy.model.loader.ModelAssembler; +import software.amazon.smithy.model.node.ExpectationNotMetException; import software.amazon.smithy.model.node.Node; +import software.amazon.smithy.model.shapes.MemberShape; +import software.amazon.smithy.model.shapes.NumberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -110,11 +115,7 @@ public static ModelAssembler assembler(ClassLoader classLoader) { .validatorFactory(ValidatorFactory.createServiceFactory(classLoader)); } - /** - * Gets the {@link ShapeIndex} of the {@code Model}. - * - * @return Returns the index of shapes. - */ + @Deprecated public ShapeIndex getShapeIndex() { return shapeIndex; } @@ -184,6 +185,63 @@ public Collection getTraitShapes() { return getTraitDefinitions().keySet(); } + /** + * Attempts to retrieve a {@link Shape} by {@link ShapeId}. + * + * @param id Shape to retrieve by ID. + * @return Returns the optional shape. + */ + public Optional getShape(ShapeId id) { + return shapeIndex.getShape(id); + } + + /** + * Attempts to retrieve a {@link Shape} by {@link ShapeId} and + * throws if not found. + * + * @param id Shape to retrieve by ID. + * @return Returns the shape. + * @throws ExpectationNotMetException if the shape is not found. + */ + public Shape expectShape(ShapeId id) { + return getShape(id).orElseThrow(() -> new ExpectationNotMetException( + "Shape not found in model: " + id, SourceLocation.NONE)); + } + + /** + * Gets a stream of {@link Shape}s in the index. + * + * @return Returns a stream of shapes. + */ + public Stream shapes() { + return shapeIndex.shapes(); + } + + /** + * Gets a stream of shapes in the index of a specific type {@code T}. + * + *

The provided shapeType class must exactly match the class of a + * shape in the shape index in order to be returned from this method; + * that is, the provided class must be a concrete subclass of + * {@link Shape} and not an abstract class like {@link NumberShape}. + * + * @param shapeType Shape type {@code T} to retrieve. + * @param Shape type to stream from the index. + * @return A stream of shapes of {@code T} matching {@code shapeType}. + */ + public Stream shapes(Class shapeType) { + return shapeIndex.shapes(shapeType); + } + + /** + * Converts the model to an immutable Set of shapes. + * + * @return Returns an unmodifiable set of Shapes in the index. + */ + public Set toSet() { + return shapeIndex.toSet(); + } + @Override public boolean equals(Object other) { if (!(other instanceof Model)) { @@ -202,7 +260,7 @@ && getMetadata().equals(otherModel.getMetadata()) public int hashCode() { int result = hash; if (result == 0) { - result = Objects.hash(getSmithyVersion(), getMetadata(), getShapeIndex()); + result = Objects.hash(getSmithyVersion(), getMetadata(), shapeIndex); hash = result; } return result; @@ -260,6 +318,7 @@ public static final class Builder implements SmithyBuilder { private Map metadata = new HashMap<>(); private String smithyVersion = MODEL_VERSION; private ShapeIndex shapeIndex; + private ShapeIndex.Builder shapeIndexBuilder; private Builder() {} @@ -284,13 +343,101 @@ public Builder clearMetadata() { return this; } + @Deprecated public Builder shapeIndex(ShapeIndex shapeIndex) { this.shapeIndex = Objects.requireNonNull(shapeIndex); + shapeIndexBuilder = null; + return this; + } + + /** + * Add a shape to the builder. + * + *

{@link MemberShape} shapes are not added to the model directly. + * They must be added by adding their containing shapes (e.g., to add a + * list member, you must add the list shape that contains it). Any member + * shape provided to any of the methods used to add shapes to the + * shape index are ignored. + * + * @param shape Shape to add. + * @return Returns the builder. + */ + public Builder addShape(Shape shape) { + getShapeIndexBuilder().addShape(shape); + return this; + } + + private ShapeIndex.Builder getShapeIndexBuilder() { + if (shapeIndexBuilder == null) { + if (shapeIndex != null) { + shapeIndexBuilder = shapeIndex.toBuilder(); + shapeIndex = null; + } else { + shapeIndexBuilder = ShapeIndex.builder(); + } + } + + return shapeIndexBuilder; + } + + /** + * Adds the shapes of another model to the builder. + * + * @param model Model to add shapes from. + * @return Returns the builder. + */ + public Builder addShapes(Model model) { + getShapeIndexBuilder().addShapes(model.shapeIndex); + return this; + } + + /** + * Adds a collection of shapes to the builder. + * + * @param shapes Collection of Shapes to add. + * @param Type of shape being added. + * @return Returns the builder. + */ + public Builder addShapes(Collection shapes) { + for (Shape shape : shapes) { + addShape(shape); + } + return this; + } + + /** + * Adds a variadic list of shapes. + * + * @param shapes Shapes to add. + * @return Returns the builder. + */ + public Builder addShapes(Shape... shapes) { + for (Shape shape : shapes) { + addShape(shape); + } + return this; + } + + /** + * Removes a shape from the builder by ID. + * + *

Members of shapes are automatically removed when their + * containing shape is removed. + * + * @param shapeId Shape to remove. + * @return Returns the builder. + */ + public Builder removeShape(ShapeId shapeId) { + getShapeIndexBuilder().removeShape(shapeId); return this; } @Override public Model build() { + if (shapeIndexBuilder != null) { + shapeIndex = shapeIndexBuilder.build(); + } + return new Model(this); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/AuthIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/AuthIndex.java index 5f0e8470f59..fed721dbf7b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/AuthIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/AuthIndex.java @@ -18,7 +18,6 @@ import java.util.ArrayList; import java.util.List; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.AuthTrait; import software.amazon.smithy.model.traits.Protocol; @@ -31,13 +30,13 @@ * for specific protocols. */ public final class AuthIndex implements KnowledgeIndex { - private final ShapeIndex index; + private final Model model; /** * @param model Model to compute the index from. */ public AuthIndex(Model model) { - this.index = model.getShapeIndex(); + this.model = model; } /** @@ -49,7 +48,7 @@ public AuthIndex(Model model) { * @return Returns the list of auth schemes or an empty list if not found. */ public List getDefaultServiceSchemes(ToShapeId service) { - return index.getShape(service.toShapeId()) + return model.getShape(service.toShapeId()) .flatMap(serviceShape -> OptionalUtils.or(serviceShape.getTrait(AuthTrait.class) .map(AuthTrait::getValues), () -> serviceShape.getTrait(ProtocolsTrait.class) @@ -75,7 +74,7 @@ public List getDefaultServiceSchemes(ToShapeId service) { * @return Returns the computed authentication schemes. */ public List getOperationSchemes(ToShapeId service, ToShapeId operation) { - return index.getShape(operation.toShapeId()) + return model.getShape(operation.toShapeId()) // Get the auth trait from the operation or the service. .map(shape -> shape.getTrait(AuthTrait.class) .map(AuthTrait::getValues) @@ -98,7 +97,7 @@ public List getOperationSchemes(ToShapeId service, ToShapeId operation) */ public List getOperationSchemes(ToShapeId service, ToShapeId operation, String protocolName) { // Get the authentication schemes of the protocol. - List protocolSchemes = index.getShape(service.toShapeId()) + List protocolSchemes = model.getShape(service.toShapeId()) .flatMap(serviceShape -> serviceShape.getTrait(ProtocolsTrait.class)) .flatMap(protocolsTrait -> protocolsTrait.getProtocol(protocolName)) .map(Protocol::getAuth) diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java index b91ddb7f156..44faadfa259 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/BottomUpIndex.java @@ -40,7 +40,7 @@ public final class BottomUpIndex implements KnowledgeIndex { public BottomUpIndex(Model model) { PathFinder pathFinder = PathFinder.create(model); - model.getShapeIndex().shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { Map> serviceBindings = new HashMap<>(); parentBindings.put(service.getId(), serviceBindings); for (PathFinder.Path path : pathFinder.search(service, SELECTOR)) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java index 96c33eb24d7..df77da48373 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/EventStreamIndex.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.EventStreamTrait; @@ -44,28 +43,27 @@ public final class EventStreamIndex implements KnowledgeIndex { private final Map outputInfo = new HashMap<>(); public EventStreamIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); - model.getShapeIndex().shapes(OperationShape.class).forEach(operation -> { + model.shapes(OperationShape.class).forEach(operation -> { operationIndex.getInput(operation).ifPresent(input -> { - computeEvents(index, operation, input, inputInfo); + computeEvents(model, operation, input, inputInfo); }); operationIndex.getOutput(operation).ifPresent(output -> { - computeEvents(index, operation, output, outputInfo); + computeEvents(model, operation, output, outputInfo); }); }); } private void computeEvents( - ShapeIndex index, + Model model, OperationShape operation, StructureShape shape, Map infoMap ) { for (MemberShape member : shape.getAllMembers().values()) { if (member.hasTrait(EventStreamTrait.class)) { - createEventStreamInfo(index, operation, shape, member).ifPresent(info -> { + createEventStreamInfo(model, operation, shape, member).ifPresent(info -> { infoMap.put(operation.getId(), info); }); } @@ -103,14 +101,14 @@ public Optional getOutputInfo(ToShapeId operationShape) { } private Optional createEventStreamInfo( - ShapeIndex index, + Model model, OperationShape operation, StructureShape structure, MemberShape member ) { EventStreamTrait trait = member.getTrait(EventStreamTrait.class).get(); - Shape eventStreamTarget = index.getShape(member.getTarget()).orElse(null); + Shape eventStreamTarget = model.getShape(member.getTarget()).orElse(null); if (eventStreamTarget == null) { LOGGER.severe(String.format( "Skipping event stream info for %s because the %s member target %s does not exist", @@ -122,7 +120,7 @@ private Optional createEventStreamInfo( Map events = new HashMap<>(); if (eventStreamTarget.asUnionShape().isPresent()) { for (MemberShape unionMember : eventStreamTarget.asUnionShape().get().getAllMembers().values()) { - index.getShape(unionMember.getTarget()).flatMap(Shape::asStructureShape).ifPresent(struct -> { + model.getShape(unionMember.getTarget()).flatMap(Shape::asStructureShape).ifPresent(struct -> { events.put(unionMember.getMemberName(), struct); }); } @@ -141,7 +139,7 @@ private Optional createEventStreamInfo( for (MemberShape structureMember : structure.getAllMembers().values()) { if (!structureMember.getMemberName().equals(member.getMemberName())) { - index.getShape(structureMember.getTarget()).ifPresent(shapeTarget -> { + model.getShape(structureMember.getTarget()).ifPresent(shapeTarget -> { initialMembers.put(structureMember.getMemberName(), structureMember); initialTargets.put(structureMember.getMemberName(), shapeTarget); }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java index 10ec2c388ec..06a8c3dab0e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/HttpBindingIndex.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.ErrorTrait; @@ -57,14 +56,14 @@ *

This index does not perform validation of the underlying model. */ public final class HttpBindingIndex implements KnowledgeIndex { - private final ShapeIndex index; + private final Model model; private final Map> requestBindings = new HashMap<>(); private final Map> responseBindings = new HashMap<>(); public HttpBindingIndex(Model model) { - index = model.getShapeIndex(); + this.model = model; OperationIndex opIndex = model.getKnowledge(OperationIndex.class); - index.shapes(OperationShape.class).forEach(shape -> { + model.shapes(OperationShape.class).forEach(shape -> { if (shape.getTrait(HttpTrait.class).isPresent()) { requestBindings.put(shape.getId(), computeRequestBindings(opIndex, shape)); responseBindings.put(shape.getId(), computeResponseBindings(opIndex, shape)); @@ -75,7 +74,7 @@ public HttpBindingIndex(Model model) { }); // Add error structure bindings. - index.shapes(StructureShape.class) + model.shapes(StructureShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ErrorTrait.class)) .forEach(pair -> responseBindings.put( pair.getLeft().getId(), @@ -112,7 +111,7 @@ public static boolean hasHttpResponseBindings(Shape shape) { private HttpTrait getHttpTrait(ToShapeId operation) { ShapeId id = operation.toShapeId(); - return index.getShape(id) + return model.getShape(id) .orElseThrow(() -> new IllegalArgumentException(id + " is not a valid shape")) .asOperationShape() .orElseThrow(() -> new IllegalArgumentException(id + " is not an operation shape")) @@ -130,7 +129,7 @@ private HttpTrait getHttpTrait(ToShapeId operation) { */ public int getResponseCode(ToShapeId shapeOrId) { ShapeId id = shapeOrId.toShapeId(); - Shape shape = index.getShape(id).orElseThrow(() -> new IllegalArgumentException("Shape not found " + id)); + Shape shape = model.getShape(id).orElseThrow(() -> new IllegalArgumentException("Shape not found " + id)); if (shape.isOperationShape()) { return getHttpTrait(id).getCode(); @@ -235,9 +234,9 @@ public TimestampFormatTrait.Format determineTimestampFormat( HttpBinding.Location location, TimestampFormatTrait.Format defaultFormat ) { - return index.getShape(member.toShapeId()) + return model.getShape(member.toShapeId()) // Use the timestampFormat trait on the member or target if present. - .flatMap(shape -> shape.getMemberTrait(index, TimestampFormatTrait.class)) + .flatMap(shape -> shape.getMemberTrait(model, TimestampFormatTrait.class)) .map(TimestampFormatTrait::getFormat) .orElseGet(() -> { // Determine the format based on the location. @@ -321,7 +320,7 @@ private String determineContentType(Collection bindings, String doc } if (binding.getLocation() == HttpBinding.Location.PAYLOAD) { - Shape target = index.getShape(binding.getMember().getTarget()).orElse(null); + Shape target = model.getShape(binding.getMember().getTarget()).orElse(null); if (target == null) { break; diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java index ea678d45762..2a024566508 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/IdentifierBindingIndex.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.RequiredTrait; @@ -53,9 +52,8 @@ public enum BindingType { } public IdentifierBindingIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); - index.shapes(ResourceShape.class).forEach(resource -> processResource(resource, operationIndex, index)); + model.shapes(ResourceShape.class).forEach(resource -> processResource(resource, operationIndex, model)); } /** @@ -91,12 +89,12 @@ public Map getOperationBindings(ToShapeId resource, ToShapeId op .orElseGet(Collections::emptyMap); } - private void processResource(ResourceShape resource, OperationIndex operationIndex, ShapeIndex index) { + private void processResource(ResourceShape resource, OperationIndex operationIndex, Model model) { bindings.put(resource.getId(), new HashMap<>()); bindingTypes.put(resource.getId(), new HashMap<>()); resource.getAllOperations().forEach(operationId -> { // Ignore broken models in this index. - Map computedBindings = index.getShape(operationId).flatMap(Shape::asOperationShape) + Map computedBindings = model.getShape(operationId).flatMap(Shape::asOperationShape) .flatMap(operationIndex::getInput) .map(inputShape -> computeBindings(resource, inputShape)) .orElseGet(HashMap::new); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/KnowledgeIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/KnowledgeIndex.java index 1ba6c7ef660..95b91f5867d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/KnowledgeIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/KnowledgeIndex.java @@ -18,7 +18,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; /** @@ -29,7 +28,7 @@ * A KnowledgeIndex is often a mapping of {@link ShapeId} to some kind of * interesting computed information. For example, in order to resolve the * input/output/error structures referenced by an {@link OperationShape}, - * you need a {@link ShapeIndex}, to ensure that the reference from the + * you need a {@link Model}, to ensure that the reference from the * operation to the structure is resolvable in the shape index, that the * shape it references is a structure, and then to cast the shape to a * {@link StructureShape}. Because this process is error prone, verbose, diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java index 738569c0315..6229fbeb134 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/NeighborProviderIndex.java @@ -26,8 +26,8 @@ public final class NeighborProviderIndex implements KnowledgeIndex { private volatile NeighborProvider reversed; public NeighborProviderIndex(Model model) { - provider = NeighborProvider.precomputed(model.getShapeIndex()); - reversed = NeighborProvider.reverse(model.getShapeIndex(), provider); + provider = NeighborProvider.precomputed(model); + reversed = NeighborProvider.reverse(model, provider); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java index d4b8cc8c125..59aeafef11d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/OperationIndex.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.utils.ListUtils; @@ -42,18 +41,17 @@ public final class OperationIndex implements KnowledgeIndex { private final Map> errors = new HashMap<>(); public OperationIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); - index.shapes(OperationShape.class).forEach(operation -> { + model.shapes(OperationShape.class).forEach(operation -> { operation.getInput() - .flatMap(id -> getStructure(index, id)) + .flatMap(id -> getStructure(model, id)) .ifPresent(shape -> inputs.put(operation.getId(), shape)); operation.getOutput() - .flatMap(id -> getStructure(index, id)) + .flatMap(id -> getStructure(model, id)) .ifPresent(shape -> outputs.put(operation.getId(), shape)); errors.put(operation.getId(), operation.getErrors() .stream() - .map(e -> getStructure(index, e)) + .map(e -> getStructure(model, e)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList())); @@ -72,7 +70,7 @@ public List getErrors(ToShapeId operation) { return errors.getOrDefault(operation.toShapeId(), ListUtils.of()); } - private Optional getStructure(ShapeIndex index, ToShapeId id) { - return index.getShape(id.toShapeId()).flatMap(Shape::asStructureShape); + private Optional getStructure(Model model, ToShapeId id) { + return model.getShape(id.toShapeId()).flatMap(Shape::asStructureShape); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java index ec93959598a..5953c65fbf1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/PaginatedIndex.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.PaginatedTrait; @@ -49,11 +48,10 @@ public final class PaginatedIndex implements KnowledgeIndex { private final Map> paginationInfo = new HashMap<>(); public PaginatedIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); OperationIndex opIndex = model.getKnowledge(OperationIndex.class); - index.shapes(ServiceShape.class).forEach(service -> { + model.shapes(ServiceShape.class).forEach(service -> { PaginatedTrait serviceTrait = service.getTrait(PaginatedTrait.class).orElse(null); Map mappings = topDownIndex.getContainedOperations(service).stream() .flatMap(operation -> Trait.flatMapStream(operation, PaginatedTrait.class)) diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TopDownIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TopDownIndex.java index 0515fea8f09..cdead382056 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TopDownIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/knowledge/TopDownIndex.java @@ -31,7 +31,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.utils.SetUtils; @@ -44,7 +43,6 @@ public final class TopDownIndex implements KnowledgeIndex { private final Map> operations = new HashMap<>(); public TopDownIndex(Model model) { - ShapeIndex index = model.getShapeIndex(); NeighborProvider provider = model.getKnowledge(NeighborProviderIndex.class).getProvider(); Walker walker = new Walker(provider); @@ -64,9 +62,9 @@ public TopDownIndex(Model model) { } }; - index.shapes(ResourceShape.class).forEach(resource -> findContained( + model.shapes(ResourceShape.class).forEach(resource -> findContained( resource.getId(), walker.walkShapes(resource, filter))); - index.shapes(ServiceShape.class).forEach(resource -> findContained( + model.shapes(ServiceShape.class).forEach(resource -> findContained( resource.getId(), walker.walkShapes(resource, filter))); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderVisitor.java index 528a0509a9e..36cc6f06dfd 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/LoaderVisitor.java @@ -37,7 +37,6 @@ import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeIdSyntaxException; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.traits.DynamicTrait; import software.amazon.smithy.model.traits.Trait; @@ -590,7 +589,6 @@ public ValidatedResult onEnd() { validateState(SourceLocation.NONE); calledOnEnd = true; Model.Builder modelBuilder = Model.builder().smithyVersion(smithyVersion).metadata(metadata); - ShapeIndex.Builder shapeIndexBuilder = ShapeIndex.builder(); finalizeShapeTargets(); finalizePendingTraits(); @@ -611,7 +609,7 @@ public ValidatedResult onEnd() { // Build members and add them to their containing shape builders. for (AbstractShapeBuilder shape : pendingShapes.values()) { if (shape.getClass() == MemberShape.Builder.class) { - MemberShape member = (MemberShape) buildShape(shapeIndexBuilder, shape); + MemberShape member = (MemberShape) buildShape(modelBuilder, shape); if (member != null) { AbstractShapeBuilder container = pendingShapes.get(shape.getId().withoutMember()); if (container == null) { @@ -631,13 +629,12 @@ public ValidatedResult onEnd() { // Now that members were built, build all non-members. for (AbstractShapeBuilder shape : pendingShapes.values()) { if (shape.getClass() != MemberShape.Builder.class) { - buildShape(shapeIndexBuilder, shape); + buildShape(modelBuilder, shape); } } // Add any remaining built shapes. - shapeIndexBuilder.addShapes(builtShapes.values()); - modelBuilder.shapeIndex(shapeIndexBuilder.build()); + modelBuilder.addShapes(builtShapes.values()); return new ValidatedResult<>(modelBuilder.build(), events); } @@ -715,10 +712,10 @@ private void emitErrorsForEachInvalidTraitTarget(ShapeId target, List doAssemble() { private static void mergeModelIntoVisitor(Model model, LoaderVisitor visitor) { visitor.onVersion(SourceLocation.NONE, model.getSmithyVersion()); model.getMetadata().forEach(visitor::onMetadata); - model.getShapeIndex().shapes().forEach(visitor::onShape); + model.shapes().forEach(visitor::onShape); } private ValidatedResult validate(Model model, List modelResultEvents) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java index 1187482c3da..75889a37c1b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/Prelude.java @@ -230,23 +230,28 @@ public static boolean isPublicPreludeShape(ToShapeId id) { return PUBLIC_PRELUDE_SHAPE_IDS.contains(toId) || PRELUDE_TRAITS.contains(toId); } + @Deprecated + public static Optional resolveShapeId(ShapeIndex index, String fromNamespace, String target) { + // First check shapes in the same namespace. + return OptionalUtils.or(index.getShape(ShapeId.fromOptionalNamespace(fromNamespace, target)), + // Then check shapes in the prelude that are public. + () -> index.getShape(ShapeId.fromParts(NAMESPACE, target)) + .filter(Prelude::isPublicPreludeShape)); + } + /** * Returns the resolved shape of a shape target by first checking if a * shape in the namespace relative to the target matches the given name, * and then by checking if a public prelude shape matches the given name. * - * @param index Shape index to resolve against. + * @param model Model to resolve against. * @param fromNamespace Namespace the target was defined in. * @param target The shape target (e.g., "foo", "smithy.api#String", etc.). * @return Returns the optionally resolved shape. * @throws ShapeIdSyntaxException if the target or namespace is invalid. */ - public static Optional resolveShapeId(ShapeIndex index, String fromNamespace, String target) { - // First check shapes in the same namespace. - return OptionalUtils.or(index.getShape(ShapeId.fromOptionalNamespace(fromNamespace, target)), - // Then check shapes in the prelude that are public. - () -> index.getShape(ShapeId.fromParts(NAMESPACE, target)) - .filter(Prelude::isPublicPreludeShape)); + public static Optional resolveShapeId(Model model, String fromNamespace, String target) { + return resolveShapeId(model.getShapeIndex(), fromNamespace, target); } // Used by the ModelAssembler to load the prelude into another visitor. diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java index c09260971ff..afa9f446b47 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/loader/ValidatorDefinition.java @@ -57,7 +57,7 @@ List map(Model model, List events) { // If there's a selector, create a list of candidate shape IDs that can be emitted. if (selector != null) { NeighborProvider provider = model.getKnowledge(NeighborProviderIndex.class).getProvider(); - candidates = selector.select(provider, model.getShapeIndex()).stream() + candidates = selector.select(provider, model).stream() .map(Shape::getId) .collect(Collectors.toSet()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java index 707dddc2c48..d10c3377d63 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborProvider.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -37,43 +38,64 @@ public interface NeighborProvider { */ List getNeighbors(Shape shape); - /** - * Creates a default NeighborProvider for the given shape index. - * - * @param index Index to create a neighbor provider for. - * @return Returns the created neighbor provider. - */ + @Deprecated static NeighborProvider of(ShapeIndex index) { return new NeighborVisitor(index); } /** - * Creates a NeighborProvider that precomputes the neighbors of an index. + * Creates a default NeighborProvider for the given model. * - * @param index Index to create a neighbor provider for. + * @param model Model to create a neighbor provider for. * @return Returns the created neighbor provider. */ + static NeighborProvider of(Model model) { + return new NeighborVisitor(model); + } + + @Deprecated static NeighborProvider precomputed(ShapeIndex index) { return precomputed(index, of(index)); } /** - * Creates a NeighborProvider that precomputes the neighbors of an index. + * Creates a NeighborProvider that precomputes the neighbors of a model. * - * @param index Index to create a neighbor provider for. - * @param provider Provider to use when precomputing. + * @param model Model to create a neighbor provider for. * @return Returns the created neighbor provider. */ + static NeighborProvider precomputed(Model model) { + return precomputed(model.getShapeIndex()); + } + + @Deprecated static NeighborProvider precomputed(ShapeIndex index, NeighborProvider provider) { Map> relationships = new HashMap<>(); index.shapes().forEach(shape -> relationships.put(shape.getId(), provider.getNeighbors(shape))); return shape -> relationships.getOrDefault(shape.getId(), ListUtils.of()); } + /** + * Creates a NeighborProvider that precomputes the neighbors of a model. + * + * @param model Model to create a neighbor provider for. + * @param provider Provider to use when precomputing. + * @return Returns the created neighbor provider. + */ + static NeighborProvider precomputed(Model model, NeighborProvider provider) { + return precomputed(model.getShapeIndex(), provider); + } + + @Deprecated static NeighborProvider bottomUp(ShapeIndex index) { return reverse(index, of(index)); } + static NeighborProvider bottomUp(Model model) { + return reverse(model.getShapeIndex(), of(model.getShapeIndex())); + } + + @Deprecated static NeighborProvider reverse(ShapeIndex index, NeighborProvider topDown) { Map> targetedFrom = index.shapes() .map(topDown::getNeighbors) @@ -83,4 +105,8 @@ static NeighborProvider reverse(ShapeIndex index, NeighborProvider topDown) { return shape -> targetedFrom.getOrDefault(shape.getId(), ListUtils.of()); } + + static NeighborProvider reverse(Model model, NeighborProvider topDown) { + return reverse(model.getShapeIndex(), topDown); + } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java index 197c8dad281..633b735f986 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/NeighborVisitor.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; @@ -47,10 +48,15 @@ final class NeighborVisitor extends ShapeVisitor.Default> implements NeighborProvider { private final ShapeIndex shapeIndex; + @Deprecated NeighborVisitor(ShapeIndex shapeIndex) { this.shapeIndex = shapeIndex; } + NeighborVisitor(Model model) { + this(model.getShapeIndex()); + } + @Override public List getNeighbors(Shape shape) { return shape.accept(this); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java index 809d86b595d..caa02fdefdb 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedShapes.java @@ -57,18 +57,18 @@ public Set compute(Model model) { Walker shapeWalker = new Walker(model.getKnowledge(NeighborProviderIndex.class).getProvider()); // Find all shapes connected to any service shape. - Set connected = model.getShapeIndex().shapes(ServiceShape.class) + Set connected = model.shapes(ServiceShape.class) .flatMap(service -> shapeWalker.walkShapes(service).stream()) .collect(Collectors.toSet()); // Don't remove shapes that are traits or connected to traits. - model.getShapeIndex().shapes() + model.shapes() .filter(shape -> shape.hasTrait(TraitDefinition.class)) .flatMap(shape -> shapeWalker.walkShapes(shape).stream()) .forEach(connected::add); // Any shape that wasn't identified as connected to a service is considered unreferenced. - return model.getShapeIndex().shapes() + return model.shapes() .filter(FunctionalUtils.not(Shape::isMemberShape)) .filter(FunctionalUtils.not(connected::contains)) // Retain prelude shapes diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java index 655cee824af..1ec80f43289 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitions.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.loader.Prelude; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.utils.FunctionalUtils; import software.amazon.smithy.utils.OptionalUtils; @@ -49,7 +48,6 @@ public UnreferencedTraitDefinitions(Predicate keepFilter) { public Set compute(Model model) { Walker walker = new Walker(model.getKnowledge(NeighborProviderIndex.class).getProvider()); - ShapeIndex index = model.getShapeIndex(); // Begin with a mutable set of all trait definitions contained in the model Set unused = model.getTraitShapes().stream() @@ -59,13 +57,13 @@ public Set compute(Model model) { // Find all traits used directly or indirectly by a service shape and remove // their definitions from the unused set. - index.shapes(ServiceShape.class) + model.shapes(ServiceShape.class) .flatMap(service -> walker.walkShapes(service).stream()) .distinct() .map(Shape::getAllTraits) .flatMap(traits -> traits.keySet().stream()) .distinct() - .flatMap(traitId -> OptionalUtils.stream(index.getShape(traitId))) + .flatMap(traitId -> OptionalUtils.stream(model.getShape(traitId))) .filter(keepFilter) .forEach(unused::remove); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Walker.java b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Walker.java index aaa174cda83..be524b75c62 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Walker.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/neighbor/Walker.java @@ -23,6 +23,8 @@ import java.util.Stack; import java.util.function.Predicate; import java.util.stream.Collectors; +import software.amazon.smithy.model.Model; +import software.amazon.smithy.model.knowledge.NeighborProviderIndex; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -44,14 +46,19 @@ public final class Walker { private final NeighborProvider provider; - public Walker(ShapeIndex shapeIndex) { - this(NeighborProvider.of(shapeIndex)); + public Walker(Model model) { + this(model.getKnowledge(NeighborProviderIndex.class).getProvider()); } public Walker(NeighborProvider provider) { this.provider = provider; } + @Deprecated + public Walker(ShapeIndex shapeIndex) { + this(NeighborProvider.of(shapeIndex)); + } + /** * Walks connected shapes in the shape index, returning them in a set. * diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java index 8cec88952fc..18e0795b6db 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/PathFinder.java @@ -83,13 +83,7 @@ public static PathFinder create(Model model) { return new PathFinder(model.getShapeIndex(), model.getKnowledge(NeighborProviderIndex.class).getProvider()); } - /** - * Creates a {@code PathFinder} that uses the given {@code ShapeIndex} - * and computes the neighbors. - * - * @param index Shape index to search using a {@code PathFinder}. - * @return Returns the crated {@code PathFinder}. - */ + @Deprecated public static PathFinder create(ShapeIndex index) { return new PathFinder(index, NeighborProvider.of(index)); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java b/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java index 8f44ce33bcd..05563100618 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/selector/Selector.java @@ -16,6 +16,7 @@ package software.amazon.smithy.model.selector; import java.util.Set; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.neighbor.NeighborProvider; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -37,26 +38,36 @@ public interface Selector { */ Set select(NeighborProvider neighborProvider, Set shapes); + @Deprecated + default Set select(NeighborProvider neighborProvider, ShapeIndex index) { + return select(neighborProvider, index.toSet()); + } + /** * Matches a selector against a shape index using a custom * neighbor visitor. * * @param neighborProvider Provides neighbors for shapes - * @param index Index to query. + * @param model Model to query. * @return Returns the matching shapes. */ - default Set select(NeighborProvider neighborProvider, ShapeIndex index) { - return select(neighborProvider, index.toSet()); + default Set select(NeighborProvider neighborProvider, Model model) { + return select(neighborProvider, model.toSet()); + } + + @Deprecated + default Set select(ShapeIndex index) { + return select(NeighborProvider.of(index), index); } /** - * Matches a selector against a shape index. + * Matches a selector against a model. * - * @param index Index to query. + * @param model Model to query. * @return Returns the matching shapes. */ - default Set select(ShapeIndex index) { - return select(NeighborProvider.of(index), index); + default Set select(Model model) { + return select(NeighborProvider.of(model), model); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java index f006560735a..4d01804e70a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/MemberShape.java @@ -16,6 +16,7 @@ package software.amazon.smithy.model.shapes; import java.util.Optional; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.utils.OptionalUtils; import software.amazon.smithy.utils.SmithyBuilder; @@ -101,17 +102,29 @@ public boolean equals(Object other) { } @Override + @Deprecated public Optional getMemberTrait(ShapeIndex index, Class trait) { return OptionalUtils.or(getTrait(trait), () -> index.getShape(getTarget()).flatMap(targetedShape -> targetedShape.getTrait(trait))); } @Override + @Deprecated public Optional findMemberTrait(ShapeIndex index, String traitName) { return OptionalUtils.or(findTrait(traitName), () -> index.getShape(getTarget()).flatMap(targetedShape -> targetedShape.findTrait(traitName))); } + @Override + public Optional getMemberTrait(Model model, Class trait) { + return getMemberTrait(model.getShapeIndex(), trait); + } + + @Override + public Optional findMemberTrait(Model model, String traitName) { + return findMemberTrait(model.getShapeIndex(), traitName); + } + /** * Builder used to create a {@link MemberShape}. */ diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java index 83f9c71389d..02aec2b75c5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ModelSerializer.java @@ -100,7 +100,7 @@ private ObjectNode createNamespaceNode(List shapes) { * @return Returns the grouped namespaces. */ private TreeMap> createNamespaces(Model model) { - Map> shapes = model.getShapeIndex().shapes() + Map> shapes = model.shapes() .filter(shapeFilter) .collect(Collectors.groupingBy(s -> s.getId().getNamespace())); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java index 06b1febdd2e..37b09235ffa 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/Shape.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.Optional; import software.amazon.smithy.model.FromSourceLocation; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.traits.TagsTrait; import software.amazon.smithy.model.traits.Trait; @@ -37,7 +38,7 @@ * *

Shape does implement {@link Comparable}, but comparisons are based * solely on the ShapeId of the shape. This assumes that shapes are being - * compared in the context of a ShapeIndex that forbids shape ID conflcits. + * compared in the context of a Model that forbids shape ID conflicts. */ public abstract class Shape implements FromSourceLocation, Tagged, ToShapeId, Comparable { private final ShapeId id; @@ -215,6 +216,11 @@ public final Map getAllTraits() { return traits; } + @Deprecated + public Optional getMemberTrait(ShapeIndex index, Class trait) { + return getTrait(trait); + } + /** * Gets a trait from the member shape or from the shape targeted by the * member. @@ -222,16 +228,21 @@ public final Map getAllTraits() { *

If the shape is not a member, then the method functions the same as * {@link #getTrait(Class)}. * - * @param index Shape index used to find member targets. + * @param model Model used to find member targets. * @param trait Trait type to get. * @param Trait type to get. * @return Returns the optionally found trait on the shape or member. * @see MemberShape#getTrait(Class) */ - public Optional getMemberTrait(ShapeIndex index, Class trait) { + public Optional getMemberTrait(Model model, Class trait) { return getTrait(trait); } + @Deprecated + public Optional findMemberTrait(ShapeIndex index, String traitName) { + return findTrait(traitName); + } + /** * Gets a trait from the member shape or from the shape targeted by the * member. @@ -239,12 +250,12 @@ public Optional getMemberTrait(ShapeIndex index, Class t *

If the shape is not a member, then the method functions the same as * {@link #findTrait(String)}. * - * @param index Shape index used to find member targets. + * @param model Model used to find member targets. * @param traitName Trait name to get. * @return Returns the optionally found trait on the shape or member. * @see MemberShape#findTrait(String) */ - public Optional findMemberTrait(ShapeIndex index, String traitName) { + public Optional findMemberTrait(Model model, String traitName) { return findTrait(traitName); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeIndex.java b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeIndex.java index 36d2a093d85..6ceb24ddea5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeIndex.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/shapes/ShapeIndex.java @@ -44,6 +44,7 @@ * invalid state when it is accessed. As such, a {@code ShapeIndex} should be * thoroughly validated before it is utilized. */ +@Deprecated public final class ShapeIndex implements ToSmithyBuilder { /** A map of shape ID to shapes that backs the shape map. */ diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java index b04491b4e66..767cea2c545 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/traits/EffectiveTraitQuery.java @@ -15,6 +15,7 @@ package software.amazon.smithy.model.traits; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -95,15 +96,20 @@ public EffectiveTraitQuery build() { return new EffectiveTraitQuery(this); } + @Deprecated + public Builder shapeIndex(ShapeIndex shapeIndex) { + this.shapeIndex = shapeIndex; + return this; + } + /** - * Sets the required shape index to query. + * Sets the required model to query. * - * @param shapeIndex Shape index to query. + * @param model Model to query. * @return Returns the query object builder. */ - public Builder shapeIndex(ShapeIndex shapeIndex) { - this.shapeIndex = shapeIndex; - return this; + public Builder model(Model model) { + return shapeIndex(model.getShapeIndex()); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java index 273ba0b2e42..ac30c6c6703 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/FilterShapes.java @@ -20,7 +20,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.loader.Prelude; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.utils.FunctionalUtils; /** @@ -44,14 +43,14 @@ final class FilterShapes { } Model transform(ModelTransformer transformer, Model model) { - return transformer.removeShapes(model, model.getShapeIndex().shapes() - .filter(shape -> canFilterShape(model.getShapeIndex(), shape)) + return transformer.removeShapes(model, model.shapes() + .filter(shape -> canFilterShape(model, shape)) .filter(FunctionalUtils.not(predicate)) .collect(Collectors.toSet())); } - private static boolean canFilterShape(ShapeIndex index, Shape shape) { - return !shape.isMemberShape() || index.getShape(shape.asMemberShape().get().getContainer()) + private static boolean canFilterShape(Model model, Shape shape) { + return !shape.isMemberShape() || model.getShape(shape.asMemberShape().get().getContainer()) .filter(container -> container.isStructureShape() || container.isUnionShape()) .isPresent(); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java index 2ce4a06a9a6..c4522357079 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MapShapes.java @@ -39,7 +39,7 @@ final class MapShapes { } Model transform(ModelTransformer transformer, Model model) { - return transformer.replaceShapes(model, model.getShapeIndex().shapes() + return transformer.replaceShapes(model, model.shapes() .flatMap(shape -> { Shape mapped = Objects.requireNonNull(mapper.apply(shape), "Shape mapper must not return null"); if (mapped.equals(shape)) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java index 4525bf395b6..1ac4cb296cc 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/MarkAndSweep.java @@ -27,7 +27,6 @@ import software.amazon.smithy.model.neighbor.Relationship; import software.amazon.smithy.model.neighbor.RelationshipType; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; /** * Performs a garbage collection style cleanup of a model by removing @@ -53,8 +52,7 @@ final class MarkAndSweep { } Set markAndSweep(Model model) { - ShapeIndex index = model.getShapeIndex(); - NeighborProvider reverseNeighbors = NeighborProvider.bottomUp(model.getShapeIndex()); + NeighborProvider reverseNeighbors = NeighborProvider.bottomUp(model); MarkerContext context = new MarkerContext(reverseNeighbors, model, sweepFilter); int currentSize; @@ -62,7 +60,7 @@ Set markAndSweep(Model model) { currentSize = context.getMarkedForRemoval().size(); marker.accept(context); // Find shapes that are only referenced by a shape that has been marked for removal. - index.shapes().filter(shape -> !shape.isMemberShape()).forEach(shape -> { + model.shapes().filter(shape -> !shape.isMemberShape()).forEach(shape -> { if (!context.getMarkedForRemoval().contains(shape)) { Set targetedFrom = context.getTargetedFrom(shape); if (!targetedFrom.isEmpty()) { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java index c81b8b49ac9..445637e7fa0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ModelTransformer.java @@ -338,15 +338,9 @@ public Model scrubTraitDefinitions(Model model) { return new ScrubTraitDefinitions().transform(this, model); } - /** - * Gets all shapes from a model as a {@code ShapeIndex} where shapes that - * define traits or shapes that are only used as part of a trait - * definition have been removed. - * - * @param model Model that contains shapes. - * @return Returns a ShapeIndex containing matching shapes. - */ + @Deprecated public ShapeIndex getNonTraitShapes(Model model) { + // TODO: remove once ShapeIndex is removed. ShapeIndex currentIndex = model.getShapeIndex(); ShapeIndex.Builder indexBuilder = ShapeIndex.builder(); @@ -356,7 +350,7 @@ public ShapeIndex getNonTraitShapes(Model model) { // a ShapeIndex is created by getting all shape IDs from the modified // model, grabbing shapes from the original model, and building a new // ShapeIndex. - scrubTraitDefinitions(model).getShapeIndex().shapes() + scrubTraitDefinitions(model).shapes() .map(Shape::getId) .map(currentIndex::getShape) .map(Optional::get) @@ -364,4 +358,16 @@ public ShapeIndex getNonTraitShapes(Model model) { return indexBuilder.build(); } + + /** + * Gets all shapes from a model where shapes that define traits or shapes + * that are only used as part of a trait definition have been removed. + * + * @param model Model that contains shapes. + * @return Returns a model that contains matching shapes. + */ + public Model getModelWithoutTraitShapes(Model model) { + ShapeIndex updatedIndex = getNonTraitShapes(model); + return model.toBuilder().shapeIndex(updatedIndex).build(); + } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveShapes.java index 6d1e0f847a8..01c38cccf09 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/RemoveShapes.java @@ -21,7 +21,6 @@ import java.util.Set; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; /** * Removes shapes from a model while ensuring that relationships to/from @@ -45,8 +44,7 @@ final class RemoveShapes { } Model transform(ModelTransformer transformer, Model model) { - ShapeIndex index = model.getShapeIndex(); - ShapeIndex.Builder builder = index.toBuilder(); + Model.Builder builder = model.toBuilder(); // Iteratively add each shape that needs to be removed from the index using multiple rounds. Set removed = new HashSet<>(toRemove); @@ -57,7 +55,7 @@ Model transform(ModelTransformer transformer, Model model) { removed.addAll(removedShape.members()); } - Model result = model.toBuilder().shapeIndex(builder.build()).build(); + Model result = builder.build(); for (ModelTransformerPlugin plugin : plugins) { result = plugin.onRemove(transformer, removed, result); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java index f9093744a80..2347b3e2229 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ReplaceShapes.java @@ -33,7 +33,6 @@ import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -51,9 +50,9 @@ *

  • When a member is modified, ensures that its containing shape * references the new member.
  • *
  • When an aggregate shape is modified, ensures that all members are - * updated in the ShapeIndex.
  • + * updated in the model. *
  • When a member is removed from a structure or union, - * ensures that the member is removed from the model shape index.
  • + * ensures that the member is removed from the model. * * *

    Only shapes that are not currently in a model or shapes that are @@ -64,9 +63,9 @@ * by the container shape, the member updates takes precedent over any * updated made to the old member referenced by the container (e.g., if you * update a structure and change one of the members of the structure without - * also updating the member in the shape index *and* you update a member in - * the shape index, the member in the shape index will overwrite the member - * referenced by the structure). + * also updating the member in the model *and* you update a member in + * the model, the member in the model will overwrite the member referenced + * by the structure). * *

    This transformer only supports replacing shapes if the previous shape * and new shape are of the same type. Any replacements encountered that @@ -86,30 +85,28 @@ Model transform(ModelTransformer transformer, Model model) { } assertNoShapeChangedType(model, shouldReplace); - ShapeIndex.Builder builder = createReplacedShapeIndexBuilder(model, shouldReplace); + Model.Builder builder = createReplacedModelBuilder(model, shouldReplace); // If a member shape changes, then ensure that the containing shape // is also updated to reference the updated member. Note that the updated container // shapes will be a modified version of shapes present in the shouldReplace Set - // over shapes in the provided index. - getUpdatedContainers(model.getShapeIndex(), shouldReplace).forEach(builder::addShape); + // over shapes in the provided model. + getUpdatedContainers(model, shouldReplace).forEach(builder::addShape); // Builds the model, then returns a model that removes any shapes that // need to be removed after mapping over the shapes. - return transformer.removeShapes( - model.toBuilder().shapeIndex(builder.build()).build(), - getShapesToRemove(model, shouldReplace)); + return transformer.removeShapes(builder.build(), getShapesToRemove(model, shouldReplace)); } private List determineShapesToReplace(Model model) { return replacements.stream() - // Only replace shapes if they don't exist in the index or if they are - // different than the current shape in the index. + // Only replace shapes if they don't exist in the model or if they are + // different than the current shape in the model. // // This prevents infinite recursion when this transformer and the // RemoveShapes transformer recursively call each other. It also // prevents unnecessary allocations. - .filter(shape -> !model.getShapeIndex().getShape(shape.getId()) + .filter(shape -> !model.getShape(shape.getId()) .filter(original -> original.equals(shape)) .isPresent()) // Sort the replacements to ensure that members come after container shapes. @@ -127,7 +124,7 @@ private List determineShapesToReplace(Model model) { private void assertNoShapeChangedType(Model model, List shouldReplace) { // Throws if any mappings attempted to change a shape's type. shouldReplace.stream() - .flatMap(previous -> Pair.flatMapStream(previous, p -> model.getShapeIndex().getShape(p.getId()))) + .flatMap(previous -> Pair.flatMapStream(previous, p -> model.getShape(p.getId()))) .filter(pair -> pair.getLeft().getType() != pair.getRight().getType()) .forEach(pair -> { throw new RuntimeException(String.format( @@ -136,11 +133,11 @@ private void assertNoShapeChangedType(Model model, List shouldReplace) { }); } - private ShapeIndex.Builder createReplacedShapeIndexBuilder(Model model, List shouldReplace) { - // Add member shapes to a ShapeIndex.Builder. This builder is mutated - // by the visitor, which will ensure that newly added members show up - // in the index. - ShapeIndex.Builder builder = model.getShapeIndex().toBuilder(); + private Model.Builder createReplacedModelBuilder(Model model, List shouldReplace) { + // Add member shapes to the builder. This builder is mutated + // by the visitor, which will ensure that newly added members + // show up in the model. + Model.Builder builder = model.toBuilder(); shouldReplace.forEach(shape -> { builder.addShape(shape); builder.addShapes(shape.members()); @@ -151,9 +148,9 @@ private ShapeIndex.Builder createReplacedShapeIndexBuilder(Model model, List getShapesToRemove(Model model, List shouldReplace) { // Ensure that when members are removed from a container shape // (e.g., a structure with fewer members), the removed members are - // removed from the index. + // removed from the model. return shouldReplace.stream() - .flatMap(shape -> Pair.flatMapStream(shape, s -> model.getShapeIndex().getShape(s.getId()))) + .flatMap(shape -> Pair.flatMapStream(shape, s -> model.getShape(s.getId()))) .flatMap(pair -> { RemoveShapesVisitor removeShapesVisitor = new RemoveShapesVisitor(pair.getRight()); return pair.getLeft().accept(removeShapesVisitor).stream(); @@ -161,12 +158,12 @@ private Set getShapesToRemove(Model model, List shouldReplace) { .collect(Collectors.toSet()); } - private Set getUpdatedContainers(ShapeIndex index, List shouldReplace) { + private Set getUpdatedContainers(Model model, List shouldReplace) { // Account for multiple members being updated on the same container. Map> containerToMemberMapping = shouldReplace.stream() .flatMap(shape -> OptionalUtils.stream(shape.asMemberShape())) .flatMap(member -> Pair.flatMapStream( - member, m -> findContainerShape(m.getContainer(), index, shouldReplace))) + member, m -> findContainerShape(m.getContainer(), model, shouldReplace))) .collect(Collectors.groupingBy(Pair::getRight, mapping(Pair::getLeft, toList()))); // TODO: This could be made more efficient by building containers only once. @@ -184,18 +181,18 @@ private Set getUpdatedContainers(ShapeIndex index, List shouldRepl .collect(Collectors.toSet()); } - private Optional findContainerShape(ShapeId shapeId, ShapeIndex index, List shouldReplace) { - // Shapes in the replacement set take precedence over shapes in the previous index. + private Optional findContainerShape(ShapeId shapeId, Model model, List shouldReplace) { + // Shapes in the replacement set take precedence over shapes in the previous model. // This accounts for newly added shapes and not overwriting changes also made to the // container shape. Optional result = shouldReplace.stream().filter(shape -> shape.getId().equals(shapeId)).findFirst(); - return result.isPresent() ? result : index.getShape(shapeId); + return result.isPresent() ? result : model.getShape(shapeId); } /** * Gets the member shapes of structures and unions that were * removed as a result of mapping. These removed members need to also be - * removed from the ShapeIndex. + * removed from the Model. */ private static final class RemoveShapesVisitor extends ShapeVisitor.Default> { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java index c243cf50639..5978710232a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/ScrubTraitDefinitions.java @@ -44,9 +44,8 @@ final class ScrubTraitDefinitions { Model transform(ModelTransformer transformer, Model model) { // Find all trait definition shapes and private shapes in the prelude. Set toMark = Stream.concat( - model.getShapeIndex().shapes().filter(shape -> shape.hasTrait(TraitDefinition.class)), - model.getShapeIndex().shapes().filter(shape -> Prelude.isPreludeShape(shape) - && shape.hasTrait(PrivateTrait.class)) + model.shapes().filter(shape -> shape.hasTrait(TraitDefinition.class)), + model.shapes().filter(shape -> Prelude.isPreludeShape(shape) && shape.hasTrait(PrivateTrait.class)) ).collect(Collectors.toSet()); MarkAndSweep markAndSweep = new MarkAndSweep( diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java index bc6a6c7aa2e..127d2620ebd 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanBindings.java @@ -50,7 +50,7 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo } private Set getServicesToUpdate(Model model, Set resources, Set operations) { - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .filter(service -> containsAny(service.getResources(), resources) || containsAny(service.getOperations(), operations)) .map(service -> { @@ -63,7 +63,7 @@ private Set getServicesToUpdate(Model model, Set resources, Set< } private Set getResourcesToUpdate(Model model, Set resources, Set operations) { - return model.getShapeIndex().shapes(ResourceShape.class) + return model.shapes(ResourceShape.class) .filter(resource -> containsAny(resource.getAllOperations(), operations) || containsAny(resource.getResources(), resources)) .map(resource -> { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java index 5355e9fa1fd..a89b61b9f00 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanOperationStructures.java @@ -39,7 +39,7 @@ public Model onRemove(ModelTransformer transformer, Collection removed, M } private Collection getModifiedOperations(Model model, Collection removed) { - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(operation -> { OperationShape result = transformErrors(removed, operation); result = transformInput(removed, result); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanResourceReferences.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanResourceReferences.java index 8561a6bc579..c2f907488bc 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanResourceReferences.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanResourceReferences.java @@ -43,7 +43,7 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo } private Set getAffectedStructures(Model model, Shape resource) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(s -> Trait.flatMapStream(s, ReferencesTrait.class)) .flatMap(pair -> { // Subject is the structure shape that might be modified. diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java index d24e20da033..b71752243d9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/CleanStructureAndUnionMembers.java @@ -31,7 +31,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.model.transform.ModelTransformer; @@ -59,21 +58,21 @@ public Model onRemove(ModelTransformer transformer, Collection removed, M } private Model removeMembersFromContainers(ModelTransformer transformer, Collection removed, Model model) { - List replacements = new ArrayList<>(getStructureReplacements(model.getShapeIndex(), removed)); - replacements.addAll(getUnionReplacements(model.getShapeIndex(), removed)); + List replacements = new ArrayList<>(getStructureReplacements(model, removed)); + replacements.addAll(getUnionReplacements(model, removed)); return transformer.replaceShapes(model, replacements); } - private Collection getStructureReplacements(ShapeIndex index, Collection removed) { - return createUpdatedShapes(index, removed, Shape::asStructureShape, entry -> { + private Collection getStructureReplacements(Model model, Collection removed) { + return createUpdatedShapes(model, removed, Shape::asStructureShape, entry -> { StructureShape.Builder builder = entry.getKey().toBuilder(); entry.getValue().forEach(member -> builder.removeMember(member.getMemberName())); return builder.build(); }); } - private Collection getUnionReplacements(ShapeIndex index, Collection removed) { - return createUpdatedShapes(index, removed, Shape::asUnionShape, entry -> { + private Collection getUnionReplacements(Model model, Collection removed) { + return createUpdatedShapes(model, removed, Shape::asUnionShape, entry -> { UnionShape.Builder builder = entry.getKey().toBuilder(); entry.getValue().forEach(member -> builder.removeMember(member.getMemberName())); return builder.build(); @@ -92,7 +91,7 @@ private Collection getUnionReplacements(ShapeIndex index, Collection getUnionReplacements(ShapeIndex index, Collection Collection createUpdatedShapes( - ShapeIndex index, + Model model, Collection removed, Function> containerShapeMapper, Function>, S> entryMapperAndFactory ) { return removed.stream() .flatMap(shape -> OptionalUtils.stream(shape.asMemberShape())) - .flatMap(member -> OptionalUtils.stream(index.getShape(member.getContainer()) + .flatMap(member -> OptionalUtils.stream(model.getShape(member.getContainer()) .flatMap(containerShapeMapper) .map(container -> Pair.of(container, member)))) .collect(groupingBy(Pair::getLeft, mapping(Pair::getRight, Collectors.toList()))) @@ -129,14 +128,13 @@ private Collection createUpdatedShapes( * their target was removed. */ private Collection findMembersThatNeedRemoval(Model model, Collection removed) { - ShapeIndex index = model.getShapeIndex(); Set removedIds = removed.stream().map(Shape::getId).collect(Collectors.toSet()); Collection removeMembers = new HashSet<>(); - index.shapes(StructureShape.class) + model.shapes(StructureShape.class) .flatMap(shape -> shape.getAllMembers().values().stream()) .filter(value -> removedIds.contains(value.getTarget())) .forEach(removeMembers::add); - index.shapes(UnionShape.class) + model.shapes(UnionShape.class) .flatMap(shape -> shape.getAllMembers().values().stream()) .filter(value -> removedIds.contains(value.getTarget())) .forEach(removeMembers::add); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java index f4b398ae3e4..43e14d0d8ee 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/transform/plugins/RemoveTraits.java @@ -52,7 +52,7 @@ public Model onRemove(ModelTransformer transformer, Collection shapes, Mo } private List determineShapesToUpdate(Model model, Set removedTraits) { - List shapes = model.getShapeIndex().shapes() + List shapes = model.shapes() .filter(shape -> !removedTraits.contains(shape.getId())) .filter(shape -> isShapeInNeedOfUpdate(shape, removedTraits)) .map(shape -> removeTraitsFromShape(shape, removedTraits)) diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java index 0c01268fb46..06024d2eb1a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/NodeValidationVisitor.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.node.NodeType; import software.amazon.smithy.model.node.StringNode; @@ -394,16 +395,21 @@ public static final class Builder implements SmithyBuilderrequired shape index to use when traversing + * Sets the required model to use when traversing * walking shapes during validation. * - * @param index Shape index that contains shapes to validate. + * @param model Model that contains shapes to validate. * @return Returns the builder. */ - public Builder index(ShapeIndex index) { - this.index = Objects.requireNonNull(index); - return this; + public Builder model(Model model) { + return index(model.getShapeIndex()); } /** diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java index eb4820b7116..e029dc86551 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/node/NodeValidatorPlugin.java @@ -16,6 +16,7 @@ package software.amazon.smithy.model.validation.node; import java.util.List; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeIndex; @@ -26,13 +27,18 @@ * provided for a trait in the model are valid for the shape of the trait). */ public interface NodeValidatorPlugin { + @Deprecated + List apply(Shape shape, Node value, ShapeIndex index); + /** * Applies the plugin to the given shape, node value, and shape index. * * @param shape Shape being checked. * @param value Value being evaluated. - * @param index Shape index used to traverse the model. + * @param model Model to traverse. * @return Returns any validation messages that were encountered. */ - List apply(Shape shape, Node value, ShapeIndex index); + default List apply(Shape shape, Node value, Model model) { + return apply(shape, value, model.getShapeIndex()); + } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthProtocolsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthProtocolsValidator.java index a9232985d2f..abf8c11d947 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthProtocolsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthProtocolsValidator.java @@ -41,7 +41,7 @@ public final class AuthProtocolsValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> validateOperationAgainstProtocols(topDownIndex, service)) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthValidator.java index fd00716daad..818518721b5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/AuthValidator.java @@ -50,7 +50,7 @@ public final class AuthValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(service -> validateService(topDownIndex, service).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java index 45e8c118905..9de041e00b2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EnumTraitValidator.java @@ -39,7 +39,7 @@ public class EnumTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StringShape.class) + return model.shapes(StringShape.class) .flatMap(shape -> Trait.flatMapStream(shape, EnumTrait.class)) .flatMap(pair -> validateEnumTrait(pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java index 00bf3d19623..a594391a41b 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventPayloadTraitValidator.java @@ -39,7 +39,7 @@ public class EventPayloadTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(this::validateEvent) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventStreamValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventStreamValidator.java index 0cb2de54ead..b240c8df884 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventStreamValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/EventStreamValidator.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.EventStreamTrait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -49,17 +48,16 @@ public class EventStreamValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); List events = new ArrayList<>(); List eventStreamStructures = new ArrayList<>(); - model.getShapeIndex().shapes(OperationShape.class).forEach(operation -> { + model.shapes(OperationShape.class).forEach(operation -> { operationIndex.getInput(operation).ifPresent(input -> { for (MemberShape member : input.getAllMembers().values()) { if (member.hasTrait(EventStreamTrait.class)) { eventStreamStructures.add(input); - events.addAll(check(index, operation, member, "input")); + events.addAll(check(model, operation, member, "input")); } } }); @@ -67,7 +65,7 @@ public List validate(Model model) { for (MemberShape member : output.getAllMembers().values()) { if (member.hasTrait(EventStreamTrait.class)) { eventStreamStructures.add(output); - events.addAll(check(index, operation, member, "output")); + events.addAll(check(model, operation, member, "output")); } } }); @@ -79,12 +77,12 @@ public List validate(Model model) { } private List check( - ShapeIndex index, + Model model, OperationShape operation, MemberShape member, String inputOrOutputName ) { - Shape target = index.getShape(member.getTarget()).orElse(null); + Shape target = model.getShape(member.getTarget()).orElse(null); if (target == null) { return Collections.emptyList(); } @@ -94,7 +92,7 @@ private List check( // Find members that don't reference a structure and combine // these member names into a comma separated list. String invalidMembers = target.asUnionShape().get().getAllMembers().values().stream() - .map(em -> Pair.of(em.getMemberName(), index.getShape(em.getTarget()).orElse(null))) + .map(em -> Pair.of(em.getMemberName(), model.getShape(em.getTarget()).orElse(null))) .filter(pair -> pair.getRight() != null && !(pair.getRight() instanceof StructureShape)) .map(Pair::getLeft) .sorted() diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java index a6b4e2e2c84..e9a039bb9ee 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExamplesTraitValidator.java @@ -22,7 +22,6 @@ import software.amazon.smithy.model.node.ObjectNode; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.ExamplesTrait; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -36,22 +35,21 @@ public final class ExamplesTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ExamplesTrait.class)) - .flatMap(pair -> validateExamples(index, pair.getLeft(), pair.getRight()).stream()) + .flatMap(pair -> validateExamples(model, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); } - private List validateExamples(ShapeIndex index, OperationShape shape, ExamplesTrait trait) { + private List validateExamples(Model model, OperationShape shape, ExamplesTrait trait) { List events = new ArrayList<>(); List examples = trait.getExamples(); for (ExamplesTrait.Example example : examples) { if (shape.getInput().isPresent()) { - index.getShape(shape.getInput().get()).ifPresent(input -> { + model.getShape(shape.getInput().get()).ifPresent(input -> { NodeValidationVisitor validator = createVisitor( - "input", example.getInput(), index, shape, example); + "input", example.getInput(), model, shape, example); events.addAll(input.accept(validator)); }); } else if (!example.getInput().isEmpty()) { @@ -59,9 +57,9 @@ private List validateExamples(ShapeIndex index, OperationShape + "input structure members: `%s`", example.getTitle()))); } if (shape.getOutput().isPresent()) { - index.getShape(shape.getOutput().get()).ifPresent(output -> { + model.getShape(shape.getOutput().get()).ifPresent(output -> { NodeValidationVisitor validator = createVisitor( - "output", example.getOutput(), index, shape, example); + "output", example.getOutput(), model, shape, example); events.addAll(output.accept(validator)); }); } else if (!example.getOutput().isEmpty()) { @@ -77,12 +75,12 @@ private List validateExamples(ShapeIndex index, OperationShape private NodeValidationVisitor createVisitor( String name, ObjectNode value, - ShapeIndex index, + Model model, Shape shape, ExamplesTrait.Example example ) { return NodeValidationVisitor.builder() - .index(index) + .model(model) .eventShapeId(shape.getId()) .value(value) .startingContext("Example " + name + " of `" + example.getTitle() + "`") diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java index 2370e9f0d80..d9ad93bf424 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ExclusiveStructureMemberTraitValidator.java @@ -38,7 +38,7 @@ public class ExclusiveStructureMemberTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(shape -> validateExclusiveTraits(model, shape).stream()) .collect(toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java index 7b57ae81e7b..fe13eec98d7 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HostLabelTraitValidator.java @@ -27,7 +27,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.EndpointTrait; import software.amazon.smithy.model.traits.HostLabelTrait; @@ -62,14 +61,14 @@ public class HostLabelTraitValidator extends AbstractValidator { @Override public List validate(Model model) { // Validate all operation shapes with the `endpoint` trait. - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, EndpointTrait.class)) - .flatMap(pair -> validateStructure(model.getShapeIndex(), pair.getLeft(), pair.getRight()).stream()) + .flatMap(pair -> validateStructure(model, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); } private List validateStructure( - ShapeIndex index, + Model model, OperationShape operation, EndpointTrait endpoint ) { @@ -88,7 +87,7 @@ private List validateStructure( // Only validate the bindings if the input is a structure. Typing // validation of the input is handled elsewhere. operation.getInput() - .flatMap(index::getShape) + .flatMap(model::getShape) .flatMap(Shape::asStructureShape) .ifPresent(input -> events.addAll(validateBindings(operation, endpoint, input))); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java index f15ae06fd9b..4caee70e2c1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpBindingsMissingValidator.java @@ -35,7 +35,7 @@ public final class HttpBindingsMissingValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> validateService(topDownIndex, shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java index 4fd7eaa56fc..1a959bc5e6c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpHeaderTraitValidator.java @@ -57,11 +57,11 @@ public final class HttpHeaderTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - List events = model.getShapeIndex().shapes(StructureShape.class) + List events = model.shapes(StructureShape.class) .flatMap(shape -> validateStructure(shape).stream()) .collect(Collectors.toList()); - events.addAll(model.getShapeIndex().shapes(MemberShape.class) + events.addAll(model.shapes(MemberShape.class) .flatMap(member -> Trait.flatMapStream(member, HttpHeaderTrait.class)) .filter(pair -> BLACKLIST.contains(pair.getRight().getValue().toLowerCase(Locale.US))) .map(pair -> danger(pair.getLeft(), String.format( diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java index 8b861c47b8f..63055f7d186 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpLabelTraitValidator.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.HttpLabelTrait; import software.amazon.smithy.model.traits.HttpTrait; @@ -56,13 +55,13 @@ public final class HttpLabelTraitValidator extends AbstractValidator { @Override public List validate(Model model) { // Validate all operation shapes with the `http` trait. - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, HttpTrait.class)) - .flatMap(pair -> validateStructure(model.getShapeIndex(), pair.getLeft(), pair.getRight()).stream()) + .flatMap(pair -> validateStructure(model, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); } - private List validateStructure(ShapeIndex index, OperationShape operation, HttpTrait http) { + private List validateStructure(Model model, OperationShape operation, HttpTrait http) { // If the operation has labels then it must also have input. if (!operation.getInput().isPresent() && !http.getUri().getLabels().isEmpty()) { return ListUtils.of(error(operation, http, String.format( @@ -73,13 +72,13 @@ private List validateStructure(ShapeIndex index, OperationShape // Only continue validating if the input is a structure. Typing // validation of the input is handled elsewhere. - return operation.getInput().flatMap(index::getShape).flatMap(Shape::asStructureShape) - .map(input -> validateBindings(index, operation, http, input)) + return operation.getInput().flatMap(model::getShape).flatMap(Shape::asStructureShape) + .map(input -> validateBindings(model, operation, http, input)) .orElse(ListUtils.of()); } private List validateBindings( - ShapeIndex index, + Model model, OperationShape operation, HttpTrait http, StructureShape input @@ -111,7 +110,7 @@ private List validateBindings( + "corresponding `http` URI label could be found when used as the input of " + "the `%s` operation.", member.getMemberName(), operation.getId()))); } else if (http.getUri().getLabel(member.getMemberName()).get().isGreedyLabel()) { - index.getShape(member.getTarget()).ifPresent(target -> { + model.getShape(member.getTarget()).ifPresent(target -> { // Greedy labels must be strings. if (!target.isStringShape()) { events.add(error(member, trait, format( diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java index f4d20176317..f822b53f97e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpMethodSemanticsValidator.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.knowledge.HttpBinding; import software.amazon.smithy.model.knowledge.HttpBindingIndex; import software.amazon.smithy.model.shapes.OperationShape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.HttpTrait; import software.amazon.smithy.model.traits.IdempotentTrait; import software.amazon.smithy.model.traits.ReadonlyTrait; @@ -64,9 +63,8 @@ public final class HttpMethodSemanticsValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); HttpBindingIndex bindingIndex = model.getKnowledge(HttpBindingIndex.class); - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, HttpTrait.class)) .flatMap(pair -> validateOperation(bindingIndex, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java index c8b296f3f23..f0b43073dc0 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPayloadValidator.java @@ -49,11 +49,11 @@ public List validate(Model model) { OperationIndex opIndex = model.getKnowledge(OperationIndex.class); HttpBindingIndex bindings = model.getKnowledge(HttpBindingIndex.class); List events = new ArrayList<>(); - events.addAll(model.getShapeIndex().shapes(OperationShape.class) + events.addAll(model.shapes(OperationShape.class) .filter(shape -> shape.getTrait(HttpTrait.class).isPresent()) .flatMap(shape -> validateOperation(bindings, opIndex, shape).stream()) .collect(toList())); - events.addAll(model.getShapeIndex().shapes(StructureShape.class) + events.addAll(model.shapes(StructureShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ErrorTrait.class)) .flatMap(pair -> validateError(pair.getLeft(), bindings).stream()) .collect(toList())); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java index 9bc1c6f068f..4776c184a51 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpPrefixHeadersTraitValidator.java @@ -37,7 +37,7 @@ public final class HttpPrefixHeadersTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(shape -> validateStructure(shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java index fa9195cfc3c..597a2756b19 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpQueryTraitValidator.java @@ -35,7 +35,7 @@ public final class HttpQueryTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(shape -> validateStructure(shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java index 47984edc5b9..8081c894832 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpResponseCodeSemanticsValidator.java @@ -22,7 +22,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ErrorTrait; import software.amazon.smithy.model.traits.HttpErrorTrait; @@ -40,13 +39,13 @@ public final class HttpResponseCodeSemanticsValidator extends AbstractValidator @Override public List validate(Model model) { List events = new ArrayList<>(); - events.addAll(validateOperations(model.getShapeIndex())); - events.addAll(validateErrors(model.getShapeIndex())); + events.addAll(validateOperations(model)); + events.addAll(validateErrors(model)); return events; } - private List validateOperations(ShapeIndex index) { - return index.shapes(OperationShape.class) + private List validateOperations(Model model) { + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, HttpTrait.class)) .filter(pair -> pair.getRight().getCode() < 200 || pair.getRight().getCode() >= 300) .map(pair -> invalidOperation(pair.getLeft(), pair.getRight())) @@ -57,8 +56,8 @@ private ValidationEvent invalidOperation(Shape shape, HttpTrait trait) { return danger(shape, trait, "Expected an `http` code in the 2xx range, but found " + trait.getCode()); } - private List validateErrors(ShapeIndex index) { - return index.shapes(StructureShape.class) + private List validateErrors(Model model) { + return model.shapes(StructureShape.class) .flatMap(shape -> Trait.flatMapStream(shape, ErrorTrait.class)) .flatMap(pair -> OptionalUtils.stream(validateError(pair.getLeft(), pair.getRight()))) .collect(Collectors.toList()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java index e9886356d2a..37f113adc5e 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/HttpUriConflictValidator.java @@ -38,7 +38,7 @@ public final class HttpUriConflictValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> validateService(topDownIndex, shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java index 3f933faec09..9f41a40841f 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PaginatedTraitValidator.java @@ -30,7 +30,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.PaginatedTrait; @@ -66,18 +65,17 @@ public final class PaginatedTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex shapeIndex = model.getShapeIndex(); OperationIndex opIndex = model.getKnowledge(OperationIndex.class); TopDownIndex topDown = model.getKnowledge(TopDownIndex.class); - return shapeIndex.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, PaginatedTrait.class)) - .flatMap(pair -> validateOperation(shapeIndex, topDown, opIndex, pair.left, pair.right).stream()) + .flatMap(pair -> validateOperation(model, topDown, opIndex, pair.left, pair.right).stream()) .collect(Collectors.toList()); } private List validateOperation( - ShapeIndex index, + Model model, TopDownIndex topDownIndex, OperationIndex opIndex, OperationShape operation, @@ -88,26 +86,26 @@ private List validateOperation( if (!opIndex.getInput(operation).isPresent()) { events.add(error(operation, trait, "paginated operations require an input")); } else { - events.addAll(validateMember(opIndex, index, null, operation, trait, new InputTokenValidator())); - events.addAll(validateMember(opIndex, index, null, operation, trait, new PageSizeValidator())); + events.addAll(validateMember(opIndex, model, null, operation, trait, new InputTokenValidator())); + events.addAll(validateMember(opIndex, model, null, operation, trait, new PageSizeValidator())); } if (!opIndex.getOutput(operation).isPresent()) { events.add(error(operation, trait, "paginated operations require an output")); } else { - events.addAll(validateMember(opIndex, index, null, operation, trait, new OutputTokenValidator())); - events.addAll(validateMember(opIndex, index, null, operation, trait, new ItemValidator())); + events.addAll(validateMember(opIndex, model, null, operation, trait, new OutputTokenValidator())); + events.addAll(validateMember(opIndex, model, null, operation, trait, new ItemValidator())); } if (events.isEmpty()) { - index.shapes(ServiceShape.class).forEach(svc -> { + model.shapes(ServiceShape.class).forEach(svc -> { if (topDownIndex.getContainedOperations(svc).contains(operation)) { // Create a merged trait if one is present on the service. PaginatedTrait merged = svc.getTrait(PaginatedTrait.class).map(trait::merge).orElse(trait); - events.addAll(validateMember(opIndex, index, svc, operation, merged, new InputTokenValidator())); - events.addAll(validateMember(opIndex, index, svc, operation, merged, new PageSizeValidator())); - events.addAll(validateMember(opIndex, index, svc, operation, merged, new OutputTokenValidator())); - events.addAll(validateMember(opIndex, index, svc, operation, merged, new ItemValidator())); + events.addAll(validateMember(opIndex, model, svc, operation, merged, new InputTokenValidator())); + events.addAll(validateMember(opIndex, model, svc, operation, merged, new PageSizeValidator())); + events.addAll(validateMember(opIndex, model, svc, operation, merged, new OutputTokenValidator())); + events.addAll(validateMember(opIndex, model, svc, operation, merged, new ItemValidator())); } }); } @@ -117,7 +115,7 @@ private List validateOperation( private List validateMember( OperationIndex opIndex, - ShapeIndex index, + Model model, ServiceShape service, OperationShape operation, PaginatedTrait trait, @@ -139,7 +137,7 @@ private List validateMember( ))); } - MemberShape member = validator.getMember(index, opIndex, operation, trait).orElse(null); + MemberShape member = validator.getMember(model, opIndex, operation, trait).orElse(null); if (member == null) { return Collections.singletonList(error(operation, trait, String.format( "%spaginated trait `%s` targets a member `%s` that does not exist", @@ -153,7 +151,7 @@ private List validateMember( prefix, validator.propertyName(), member.getMemberName()))); } - Shape target = index.getShape(member.getTarget()).orElse(null); + Shape target = model.getShape(member.getTarget()).orElse(null); if (target != null && !validator.validTargets().contains(target.getType())) { events.add(error(operation, trait, String.format( "%spaginated trait `%s` member `%s` targets a %s shape, but must target one of " @@ -185,7 +183,7 @@ private abstract static class PropertyValidator { abstract Optional getMemberPath(OperationIndex opIndex, OperationShape operation, PaginatedTrait trait); abstract Optional getMember( - ShapeIndex index, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait + Model model, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait ); boolean pathsAllowed() { @@ -201,7 +199,7 @@ boolean pathsAllowed() { } Optional getMember( - ShapeIndex index, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait + Model model, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait ) { // Split up the path expression into a list of member names List memberNames = getMemberPath(opIndex, operation, trait) @@ -223,7 +221,7 @@ Optional getMember( if (!memberShape.isPresent()) { return Optional.empty(); } - memberShape = index.getShape(memberShape.get().getTarget()) + memberShape = model.getShape(memberShape.get().getTarget()) .flatMap(Shape::asStructureShape) .flatMap(target -> target.getMember(memberName)); } @@ -254,7 +252,7 @@ Optional getMemberPath(OperationIndex opIndex, OperationShape operation, } Optional getMember( - ShapeIndex index, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait + Model model, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait ) { return getMemberPath(opIndex, operation, trait) .flatMap(memberName -> opIndex.getInput(operation).flatMap(input -> input.getMember(memberName))); @@ -305,7 +303,7 @@ Optional getMemberPath(OperationIndex opIndex, OperationShape operation, } Optional getMember( - ShapeIndex index, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait + Model model, OperationIndex opIndex, OperationShape operation, PaginatedTrait trait ) { return getMemberPath(opIndex, operation, trait) .flatMap(memberName -> opIndex.getInput(operation).flatMap(input -> input.getMember(memberName))); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java index 45de427d749..5b859accad1 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/PrivateAccessValidator.java @@ -39,13 +39,13 @@ public final class PrivateAccessValidator extends AbstractValidator { @Override public List validate(Model model) { - Set privateShapes = model.getShapeIndex().shapes() + Set privateShapes = model.shapes() .filter(shape -> shape.getTrait(PrivateTrait.class).isPresent()) .map(Shape::getId) .collect(Collectors.toSet()); NeighborProvider provider = model.getKnowledge(NeighborProviderIndex.class).getProvider(); - return model.getShapeIndex().shapes() + return model.shapes() .filter(shape -> !(shape instanceof SimpleShape)) .flatMap(shape -> validateNeighbors(shape, provider.getNeighbors(shape), privateShapes)) .collect(Collectors.toList()); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java index 626f4ddf30a..9b5741ac007 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/RangeTraitValidator.java @@ -25,7 +25,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.RangeTrait; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -39,21 +38,20 @@ public class RangeTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return index.shapes() + return model.shapes() .flatMap(shape -> Trait.flatMapStream(shape, RangeTrait.class)) - .flatMap(pair -> validateRangeTrait(index, pair.getLeft(), pair.getRight()).stream()) + .flatMap(pair -> validateRangeTrait(model, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); } - private List validateRangeTrait(ShapeIndex index, Shape shape, RangeTrait trait) { + private List validateRangeTrait(Model model, Shape shape, RangeTrait trait) { List events = new ArrayList<>(); trait.getMin() - .flatMap(min -> validateRangeProperty(index, shape, trait, min, "min")) + .flatMap(min -> validateRangeProperty(model, shape, trait, min, "min")) .ifPresent(events::add); trait.getMax() - .flatMap(max -> validateRangeProperty(index, shape, trait, max, "max")) + .flatMap(max -> validateRangeProperty(model, shape, trait, max, "max")) .ifPresent(events::add); // Makes sure that `min` is less than `max` @@ -68,7 +66,7 @@ private List validateRangeTrait(ShapeIndex index, Shape shape, } private Optional validateRangeProperty( - ShapeIndex index, + Model model, Shape shape, RangeTrait trait, BigDecimal property, @@ -77,7 +75,7 @@ private Optional validateRangeProperty( if (!property.remainder(BigDecimal.ONE).equals(BigDecimal.ZERO)) { if (shape.isMemberShape()) { MemberShape member = shape.asMemberShape().get(); - Optional target = index.getShape(member.getTarget()); + Optional target = model.getShape(member.getTarget()); if (target.isPresent() && !isDecimalShape(target.get())) { return Optional.of(error(shape, trait, format( "Member `%s` is marked with the `range` trait, but its `%s` property " diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java index 20d3c3fa989..442fe6a5169 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ReferencesTraitValidator.java @@ -33,7 +33,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.ReferencesTrait; @@ -50,14 +49,13 @@ public final class ReferencesTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes() + return model.shapes() .flatMap(shape -> Trait.flatMapStream(shape, ReferencesTrait.class)) - .flatMap(pair -> validateShape( - model.getShapeIndex(), pair.getLeft(), pair.getRight()).stream()) + .flatMap(pair -> validateShape(model, pair.getLeft(), pair.getRight()).stream()) .collect(Collectors.toList()); } - private List validateShape(ShapeIndex index, Shape shape, ReferencesTrait trait) { + private List validateShape(Model model, Shape shape, ReferencesTrait trait) { List events = new ArrayList<>(); for (ReferencesTrait.Reference reference : trait.getReferences()) { if (shape.isStringShape() && !reference.getIds().isEmpty()) { @@ -66,7 +64,7 @@ private List validateShape(ShapeIndex index, Shape shape, Refer } ShapeId shapeId = reference.getResource(); - Optional targetedShape = index.getShape(shapeId); + Optional targetedShape = model.getShape(shapeId); if (targetedShape.isPresent()) { if (!targetedShape.get().isResourceShape()) { events.add(error(shape, trait, format( @@ -74,7 +72,7 @@ private List validateShape(ShapeIndex index, Shape shape, Refer targetedShape.get().getType(), reference))); } else { ResourceShape resource = targetedShape.get().asResourceShape().get(); - events.addAll(validateSingleReference(index, reference, shape, trait, resource)); + events.addAll(validateSingleReference(model, reference, shape, trait, resource)); } } } @@ -83,14 +81,14 @@ private List validateShape(ShapeIndex index, Shape shape, Refer } private List validateSingleReference( - ShapeIndex index, + Model model, ReferencesTrait.Reference reference, Shape shape, ReferencesTrait trait, ResourceShape target ) { return shape.accept(Shape.>visitor() - .when(StructureShape.class, s -> validateStructureRef(index, reference, s, trait, target)) + .when(StructureShape.class, s -> validateStructureRef(model, reference, s, trait, target)) .when(StringShape.class, s -> validateStringShapeRef(reference, s, trait, target)) .orElse(ListUtils.of())); } @@ -116,7 +114,7 @@ private List validateStringShapeRef( private enum ErrorReason { BAD_TARGET, NOT_FOUND, NOT_REQUIRED } private List validateStructureRef( - ShapeIndex index, + Model model, ReferencesTrait.Reference reference, StructureShape shape, ReferencesTrait trait, @@ -138,7 +136,7 @@ private List validateStructureRef( errors.put(memberName, ErrorReason.NOT_FOUND); } else { MemberShape structMember = shape.getMember(memberName).get(); - if (!index.getShape(structMember.getTarget()).filter(Shape::isStringShape).isPresent()) { + if (!model.getShape(structMember.getTarget()).filter(Shape::isStringShape).isPresent()) { errors.put(memberName, ErrorReason.BAD_TARGET); } else if (!structMember.isRequired()) { errors.put(memberName, ErrorReason.NOT_REQUIRED); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java index b18cf1049ca..dc1a3ff5ad2 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceCycleValidator.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; import software.amazon.smithy.utils.OptionalUtils; @@ -36,22 +35,21 @@ public final class ResourceCycleValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex shapeIndex = model.getShapeIndex(); - return shapeIndex.shapes(ResourceShape.class) - .flatMap(shape -> OptionalUtils.stream(detectCycles(shapeIndex, shape, new LinkedHashSet<>()))) + return model.shapes(ResourceShape.class) + .flatMap(shape -> OptionalUtils.stream(detectCycles(model, shape, new LinkedHashSet<>()))) .collect(Collectors.toList()); } - private Optional detectCycles(ShapeIndex index, ResourceShape resource, Set visited) { + private Optional detectCycles(Model model, ResourceShape resource, Set visited) { if (visited.contains(resource.getId())) { return Optional.of(cycle(resource, visited)); } visited.add(resource.getId()); for (ShapeId child : resource.getResources()) { - ResourceShape childResource = index.getShape(child).flatMap(Shape::asResourceShape).orElse(null); + ResourceShape childResource = model.getShape(child).flatMap(Shape::asResourceShape).orElse(null); if (childResource != null) { - Optional error = detectCycles(index, childResource, visited); + Optional error = detectCycles(model, childResource, visited); if (error.isPresent()) { return error; } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java index 15d562eff24..996d6074efb 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierBindingValidator.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; import software.amazon.smithy.model.validation.ValidationUtils; @@ -49,27 +48,26 @@ public final class ResourceIdentifierBindingValidator extends AbstractValidator @Override public List validate(Model model) { IdentifierBindingIndex bindingIndex = model.getKnowledge(IdentifierBindingIndex.class); - ShapeIndex index = model.getShapeIndex(); return Stream.of( - index.shapes(ResourceShape.class) - .flatMap(resource -> validateResource(index, resource, bindingIndex)), - index.shapes(ResourceShape.class) - .flatMap(resource -> validateCollectionBindings(index, resource, bindingIndex)), - index.shapes(ResourceShape.class) - .flatMap(resource -> validateInstanceBindings(index, resource, bindingIndex)) + model.shapes(ResourceShape.class) + .flatMap(resource -> validateResource(model, resource, bindingIndex)), + model.shapes(ResourceShape.class) + .flatMap(resource -> validateCollectionBindings(model, resource, bindingIndex)), + model.shapes(ResourceShape.class) + .flatMap(resource -> validateInstanceBindings(model, resource, bindingIndex)) ).flatMap(Function.identity()).collect(Collectors.toList()); } private Stream validateResource( - ShapeIndex index, + Model model, ResourceShape parent, IdentifierBindingIndex bindingIndex ) { return parent.getResources().stream() - .flatMap(childId -> OptionalUtils.stream(index.getShape(childId).flatMap(Shape::asResourceShape))) + .flatMap(childId -> OptionalUtils.stream(model.getShape(childId).flatMap(Shape::asResourceShape))) .flatMap(child -> child.getAllOperations().stream() - .flatMap(id -> OptionalUtils.stream(index.getShape(id).flatMap(Shape::asOperationShape))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) .map(operation -> Pair.of(child, operation))) .flatMap(pair -> OptionalUtils.stream( validateOperation(parent, pair.getLeft(), pair.getRight(), bindingIndex))); @@ -98,7 +96,7 @@ private Optional validateOperation( } private Stream validateCollectionBindings( - ShapeIndex index, + Model model, ResourceShape resource, IdentifierBindingIndex identifierIndex ) { @@ -107,7 +105,7 @@ private Stream validateCollectionBindings( .filter(operation -> identifierIndex.getOperationBindingType(resource, operation) == IdentifierBindingIndex.BindingType.COLLECTION) // Get their operation shapes. - .flatMap(id -> OptionalUtils.stream(index.getShape(id).flatMap(Shape::asOperationShape))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) // Find collection operations which improperly bind all the resource identifiers. .filter(operation -> hasAllIdentifiersBound(resource, operation, identifierIndex)) .map(operation -> error(operation, format( @@ -118,7 +116,7 @@ private Stream validateCollectionBindings( } private Stream validateInstanceBindings( - ShapeIndex index, + Model model, ResourceShape resource, IdentifierBindingIndex bindingIndex ) { @@ -127,7 +125,7 @@ private Stream validateInstanceBindings( .filter(operation -> bindingIndex.getOperationBindingType(resource, operation) == IdentifierBindingIndex.BindingType.INSTANCE) // Get their operation shapes. - .flatMap(id -> OptionalUtils.stream(index.getShape(id).flatMap(Shape::asOperationShape))) + .flatMap(id -> OptionalUtils.stream(model.getShape(id).flatMap(Shape::asOperationShape))) // Find instance operations which do not bind all of the resource identifiers. .filter(operation -> !hasAllIdentifiersBound(resource, operation, bindingIndex)) .map(operation -> { diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java index c1d029b0af3..ca3a18dacf5 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceIdentifierValidator.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; import software.amazon.smithy.utils.OptionalUtils; @@ -36,14 +35,14 @@ public final class ResourceIdentifierValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(ResourceShape.class) - .flatMap(resource -> validateAgainstChildren(resource, model.getShapeIndex())) + return model.shapes(ResourceShape.class) + .flatMap(resource -> validateAgainstChildren(resource, model)) .collect(Collectors.toList()); } - private Stream validateAgainstChildren(ResourceShape resource, ShapeIndex index) { + private Stream validateAgainstChildren(ResourceShape resource, Model model) { return resource.getResources().stream() - .flatMap(shape -> OptionalUtils.stream(index.getShape(shape).flatMap(Shape::asResourceShape))) + .flatMap(shape -> OptionalUtils.stream(model.getShape(shape).flatMap(Shape::asResourceShape))) .flatMap(child -> Stream.concat( OptionalUtils.stream(checkForMissing(child, resource)), OptionalUtils.stream(checkForMismatches(child, resource)))); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java index 6eca622c165..3c1fc4872db 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ResourceLifecycleValidator.java @@ -25,7 +25,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.IdempotentTrait; import software.amazon.smithy.model.traits.ReadonlyTrait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -38,39 +37,38 @@ public final class ResourceLifecycleValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return model.getShapeIndex().shapes(ResourceShape.class) - .flatMap(shape -> validateResource(index, shape).stream()) + return model.shapes(ResourceShape.class) + .flatMap(shape -> validateResource(model, shape).stream()) .collect(Collectors.toList()); } - private List validateResource(ShapeIndex index, ResourceShape resource) { + private List validateResource(Model model, ResourceShape resource) { List events = new ArrayList<>(); // Note: Whether or not these use a valid bindings is validated in ResourceIdentifierBindingValidator. - resource.getPut().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getPut().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "put", false).ifPresent(events::add); validateIdempotent(resource, operation, "put", "").ifPresent(events::add); }); - resource.getCreate().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getCreate().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "create", false).ifPresent(events::add); }); - resource.getRead().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getRead().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "read", true).ifPresent(events::add); }); - resource.getUpdate().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getUpdate().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "update", false).ifPresent(events::add); }); - resource.getDelete().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getDelete().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "delete", false).ifPresent(events::add); validateIdempotent(resource, operation, "delete", "").ifPresent(events::add); }); - resource.getList().flatMap(index::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { + resource.getList().flatMap(model::getShape).flatMap(Shape::asOperationShape).ifPresent(operation -> { validateReadonly(resource, operation, "list", true).ifPresent(events::add); }); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java index 3f433244bb1..bf54bd8af74 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ServiceValidator.java @@ -36,7 +36,7 @@ public class ServiceValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> validateService(topDownIndex, shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java index c02f6a3c9cb..e2f9034ea9c 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeIdConflictValidator.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; @@ -34,8 +33,7 @@ public class ShapeIdConflictValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - Map> conflicts = index.shapes() + Map> conflicts = model.shapes() .collect(Collectors.groupingBy(shape -> shape.getId().toString().toLowerCase(Locale.US))) .entrySet().stream() .filter(entry -> entry.getValue().size() > 1) diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java index c62d9995fc0..b8060a5b524 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/ShapeRecursionValidator.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; @@ -48,27 +47,26 @@ public class ShapeRecursionValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return index.shapes() - .map(shape -> validateShape(index, shape)) + return model.shapes() + .map(shape -> validateShape(model, shape)) .filter(Objects::nonNull) .collect(Collectors.toList()); } - private ValidationEvent validateShape(ShapeIndex index, Shape shape) { - return new RecursiveNeighborVisitor(index, shape).visit(shape); + private ValidationEvent validateShape(Model model, Shape shape) { + return new RecursiveNeighborVisitor(model, shape).visit(shape); } private final class RecursiveNeighborVisitor extends ShapeVisitor.Default { - private final ShapeIndex index; + private final Model model; private final Shape root; private final Set visited = new HashSet<>(); private final Deque context = new ArrayDeque<>(); - RecursiveNeighborVisitor(ShapeIndex index, Shape root) { + RecursiveNeighborVisitor(Model model, Shape root) { this.root = root; - this.index = index; + this.model = model; } ValidationEvent visit(Shape shape) { @@ -109,7 +107,7 @@ public ValidationEvent mapShape(MapShape shape) { private ValidationEvent validateMember(Shape container, MemberShape member) { ValidationEvent event = null; - Shape target = index.getShape(member.getTarget()).orElse(null); + Shape target = model.getShape(member.getTarget()).orElse(null); if (target != null) { // Add to the visited set and the context deque before visiting, diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleOperationBindingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleOperationBindingValidator.java index b7673565492..502b0585f1a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleOperationBindingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleOperationBindingValidator.java @@ -39,7 +39,7 @@ public class SingleOperationBindingValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> validateService(topDownIndex, shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java index 0e73e4a8910..51d6aa92b00 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/SingleResourceBindingValidator.java @@ -38,7 +38,7 @@ public class SingleResourceBindingValidator extends AbstractValidator { @Override public List validate(Model model) { TopDownIndex topDownIndex = model.getKnowledge(TopDownIndex.class); - return model.getShapeIndex().shapes(ServiceShape.class) + return model.shapes(ServiceShape.class) .flatMap(shape -> validateService(topDownIndex, shape).stream()) .collect(Collectors.toList()); } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TargetValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TargetValidator.java index ff7da0c4399..416791c8bdb 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TargetValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TargetValidator.java @@ -31,7 +31,6 @@ import software.amazon.smithy.model.neighbor.RelationshipType; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.traits.TraitDefinition; import software.amazon.smithy.model.validation.AbstractValidator; @@ -50,25 +49,24 @@ public class TargetValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); NeighborProvider neighborProvider = model.getKnowledge(NeighborProviderIndex.class).getProvider(); - return index.shapes() - .flatMap(shape -> validateShape(index, shape, neighborProvider.getNeighbors(shape))) + return model.shapes() + .flatMap(shape -> validateShape(model, shape, neighborProvider.getNeighbors(shape))) .collect(Collectors.toList()); } - private Stream validateShape(ShapeIndex index, Shape shape, List relationships) { + private Stream validateShape(Model model, Shape shape, List relationships) { return relationships.stream().flatMap(relationship -> { if (relationship.getNeighborShape().isPresent()) { return OptionalUtils.stream( - validateTarget(index, shape, relationship.getNeighborShape().get(), relationship)); + validateTarget(model, shape, relationship.getNeighborShape().get(), relationship)); } else { return Stream.of(unresolvedTarget(shape, relationship)); } }); } - private Optional validateTarget(ShapeIndex index, Shape shape, Shape target, Relationship rel) { + private Optional validateTarget(Model model, Shape shape, Shape target, Relationship rel) { RelationshipType relType = rel.getRelationshipType(); if (relType.getDirection() == RelationshipDirection.DIRECTED && target.hasTrait(TraitDefinition.class)) { @@ -86,7 +84,7 @@ private Optional validateTarget(ShapeIndex index, Shape shape, "Members cannot target %s shapes, but found %s", target.getType(), target))); } case MAP_KEY: - return target.asMemberShape().flatMap(m -> validateMapKey(shape, m.getTarget(), index)); + return target.asMemberShape().flatMap(m -> validateMapKey(shape, m.getTarget(), model)); case RESOURCE: if (target.getType() != ShapeType.RESOURCE) { return Optional.of(badType(shape, target, relType, ShapeType.RESOURCE)); @@ -135,8 +133,8 @@ private Optional validateTarget(ShapeIndex index, Shape shape, } } - private Optional validateMapKey(Shape shape, ShapeId target, ShapeIndex index) { - return index.getShape(target) + private Optional validateMapKey(Shape shape, ShapeId target, Model model) { + return model.getShape(target) .filter(FunctionalUtils.not(Shape::isStringShape)) .map(resolved -> error(shape, format( "Map key member targets %s, but is expected to target a string", resolved))); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java index d0508132734..90b26e0f52d 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitConflictValidator.java @@ -35,7 +35,7 @@ public final class TraitConflictValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes() + return model.shapes() .flatMap(shape -> { // Map of trait shape IDs to trait value. Map traits = shape.getAllTraits(); diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java index bb64aced423..f15cd47907a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitTargetValidator.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.neighbor.NeighborProvider; import software.amazon.smithy.model.selector.Selector; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.traits.TraitDefinition; import software.amazon.smithy.model.validation.AbstractValidator; @@ -41,11 +40,10 @@ public final class TraitTargetValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex shapeIndex = model.getShapeIndex(); NeighborProvider neighborProvider = model.getKnowledge(NeighborProviderIndex.class).getProvider(); - return shapeIndex.shapes() + return model.shapes() .flatMap(shape -> getSelectors(shape, model)) - .filter(check -> !matchesSelector(check, shapeIndex, neighborProvider)) + .filter(check -> !matchesSelector(check, model, neighborProvider)) .map(check -> error(check.shape, String.format( "Trait `%s` cannot be applied to `%s`. This trait may only be applied to shapes " + "that match the following selector: %s", @@ -77,9 +75,9 @@ private Selector resolveSelector(Trait trait, Model model) { private boolean matchesSelector( SelectorCheck check, - ShapeIndex index, + Model model, NeighborProvider neighborProvider ) { - return check.selector.select(neighborProvider, index).contains(check.shape); + return check.selector.select(neighborProvider, model).contains(check.shape); } } diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java index 2546a076810..f9b91c354c9 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/TraitValueValidator.java @@ -21,7 +21,6 @@ import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.NodeValidationVisitor; import software.amazon.smithy.model.validation.ValidationEvent; @@ -38,27 +37,26 @@ public final class TraitValueValidator implements Validator { @Override public List validate(Model model) { - return model.getShapeIndex() - .shapes() + return model.shapes() // Get pairs of .flatMap(shape -> shape.getAllTraits().values().stream().map(t -> Pair.of(shape, t))) - .flatMap(pair -> validateTrait(model.getShapeIndex(), pair.left, pair.right).stream()) + .flatMap(pair -> validateTrait(model, pair.left, pair.right).stream()) .collect(Collectors.toList()); } - private List validateTrait(ShapeIndex index, Shape targetShape, Trait trait) { + private List validateTrait(Model model, Shape targetShape, Trait trait) { ShapeId shape = trait.toShapeId(); - if (!index.getShape(shape).isPresent()) { + if (!model.getShape(shape).isPresent()) { // Punt; invalid ID targets are validated in TraitDefinitionShapeValidator. return ListUtils.of(); } - Shape schema = index.getShape(shape).get(); + Shape schema = model.getShape(shape).get(); Node coerced = Trait.coerceTraitValue(trait.toNode(), schema.getType()); NodeValidationVisitor cases = NodeValidationVisitor.builder() - .index(index) + .model(model) .value(coerced) .eventShapeId(targetShape.getId()) .eventId(NAME) diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableFeatureValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableFeatureValidator.java index c033a913e79..c62aebd26ce 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableFeatureValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/UnstableFeatureValidator.java @@ -35,7 +35,7 @@ public final class UnstableFeatureValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(DocumentShape.class) + return model.shapes(DocumentShape.class) .filter(FunctionalUtils.not(Prelude::isPreludeShape)) .map(shape -> warning(shape, "The document shape type is currently unstable and subject to " + "change. It is not generally supported across tooling and should " diff --git a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java index 0a1eb9d62b5..2c6b138264a 100644 --- a/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java +++ b/smithy-model/src/main/java/software/amazon/smithy/model/validation/validators/XmlNamespaceTraitValidator.java @@ -40,7 +40,7 @@ public class XmlNamespaceTraitValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(StructureShape.class) + return model.shapes(StructureShape.class) .flatMap(shape -> Trait.flatMapStream(shape, XmlNamespaceTrait.class)) .flatMap(pair -> OptionalUtils.stream(validateTrait(pair.getLeft(), pair.getRight()))) .collect(Collectors.toList()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java index 677a3e50a4b..95e695518af 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/ModelTest.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.node.Node; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.TraitDefinition; @@ -32,16 +31,12 @@ public class ModelTest { @Test public void buildsModel() { - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() + .putMetadataProperty("name.name", Node.objectNode()) .addShape(StringShape.builder() .id("smithy.example#String") .addTrait(TraitDefinition.builder().build()) .build()) - .build(); - - Model model = Model.builder() - .putMetadataProperty("name.name", Node.objectNode()) - .shapeIndex(index) .smithyVersion(Model.MODEL_VERSION) .build(); @@ -54,12 +49,9 @@ public void buildsModel() { public void modelEquality() { Model modelA = Model.builder() .putMetadataProperty("foo", Node.from("baz")) - .shapeIndex(ShapeIndex.builder() - .addShape(StringShape.builder().id("ns.foo#baz").build()) - .build()) + .addShape(StringShape.builder().id("ns.foo#baz").build()) .build(); Model modelB = Model.builder() - .shapeIndex(ShapeIndex.builder().build()) .putMetadataProperty("foo", Node.from("baz")) .build(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/AuthIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/AuthIndexTest.java index 0a800977142..6283da1a22a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/AuthIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/AuthIndexTest.java @@ -22,7 +22,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ServiceShape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.AuthTrait; import software.amazon.smithy.model.traits.Protocol; import software.amazon.smithy.model.traits.ProtocolsTrait; @@ -39,8 +38,7 @@ public void supportedServiceSchemesDefaultsToAllProtocols() { .addProtocol(Protocol.builder().name("xml").addAuth("qux").addAuth("foo").build()) .build()) .build(); - ShapeIndex index = ShapeIndex.builder().addShapes(service).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShape(service).build(); AuthIndex authIndex = model.getKnowledge(AuthIndex.class); assertThat(authIndex.getDefaultServiceSchemes(service), equalTo(ListUtils.of("foo", "baz", "qux"))); @@ -69,8 +67,7 @@ public void getSchemesOfOperationBoundToServiceAndProtocol() { .addProtocol(Protocol.builder().name("xml").addAuth("qux").build()) .build()) .build(); - ShapeIndex index = ShapeIndex.builder().addShapes(service, operation1, operation2, operation3).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(service, operation1, operation2, operation3).build(); AuthIndex authIndex = model.getKnowledge(AuthIndex.class); // Use the schemes defined on the shape itself or the schemes of the service. @@ -98,8 +95,7 @@ public void includesNoneEvenIfNotListedInSchemes() { .addProtocol(Protocol.builder().name("json").addAuth("foo").build()) .build()) .build(); - ShapeIndex index = ShapeIndex.builder().addShapes(service, operation1).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(service, operation1).build(); AuthIndex authIndex = model.getKnowledge(AuthIndex.class); assertThat(authIndex.getOperationSchemes(service, operation1), equalTo(ListUtils.of("none"))); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java index 8264cb561be..ac49dbbbbc2 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/HttpBindingIndexTest.java @@ -270,7 +270,7 @@ public void resolvesMediaTypeContentType() { private static MemberShape expectMember(Model model, String id) { ShapeId shapeId = ShapeId.from(id); - return model.getShapeIndex().getShape(shapeId).get().asMemberShape().get(); + return model.expectShape(shapeId).asMemberShape().get(); } @Test diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java index 5265080cd54..1ca1adeb3e6 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/OperationIndexTest.java @@ -57,10 +57,10 @@ public void indexesEmptyOperations() { @Test public void indexesOperations() { OperationIndex opIndex = model.getKnowledge(OperationIndex.class); - Shape input = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Input")).get(); - Shape output = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Output")).get(); - Shape error1 = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Error1")).get(); - Shape error2 = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Error2")).get(); + Shape input = model.getShape(ShapeId.from("ns.foo#Input")).get(); + Shape output = model.getShape(ShapeId.from("ns.foo#Output")).get(); + Shape error1 = model.getShape(ShapeId.from("ns.foo#Error1")).get(); + Shape error2 = model.getShape(ShapeId.from("ns.foo#Error2")).get(); assertThat(opIndex.getInput(ShapeId.from("ns.foo#B")), is(Optional.of(input))); assertThat(opIndex.getOutput(ShapeId.from("ns.foo#B")), is(Optional.of(output))); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java index fbc45ee4eae..d5e8e2d5604 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/knowledge/TopDownIndexTest.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; public class TopDownIndexTest { @Test @@ -37,8 +36,7 @@ public void findDirectChildren() { .addResource("ns.foo#Resource") .build(); ResourceShape resource = ResourceShape.builder().id("ns.foo#Resource").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(service, resource).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(service, resource).build(); TopDownIndex childIndex = model.getKnowledge(TopDownIndex.class); assertThat(childIndex.getContainedOperations(service), empty()); @@ -63,8 +61,7 @@ public void findsAllChildren() { ResourceShape resourceB = ResourceShape.builder().id("ns.foo#B").addOperation("ns.foo#Operation").build(); OperationShape operation = OperationShape.builder().id("ns.foo#Operation").build(); OperationShape list = OperationShape.builder().id("ns.foo#List").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(service, resourceA, resourceB, operation, list).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(service, resourceA, resourceB, operation, list).build(); TopDownIndex childIndex = model.getKnowledge(TopDownIndex.class); assertThat(childIndex.getContainedResources(service.getId()), containsInAnyOrder(resourceA, resourceB)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/LoaderVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/LoaderVisitorTest.java index 6b37de29c88..27233a5ee13 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/LoaderVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/LoaderVisitorTest.java @@ -194,7 +194,7 @@ public void createsDynamicTraitWhenTraitFactoryReturnsEmpty() { visitor.onTrait(id, "foo.baz#Bar", Node.from(true)); Model model = visitor.onEnd().unwrap(); - assertThat(model.getShapeIndex().getShape(id).get().findTrait("foo.baz#Bar").get(), + assertThat(model.expectShape(id).findTrait("foo.baz#Bar").get(), instanceOf(DynamicTrait.class)); } @@ -219,7 +219,7 @@ public void coercesNullTraitValues() { .assemble() .unwrap(); - Shape shape = model.getShapeIndex().getShape(ShapeId.from("ns.foo#Foo")).get(); + Shape shape = model.expectShape(ShapeId.from("ns.foo#Foo")); assertTrue(shape.getTrait(DeprecatedTrait.class).isPresent()); assertTrue(shape.getTrait(TagsTrait.class).isPresent()); assertTrue(shape.getTrait(ReferencesTrait.class).isPresent()); @@ -235,7 +235,7 @@ public void coercesBooleanToStructureTraitValues() { + "structure foo {}\n") .assemble() .unwrap(); - Shape shape = model.getShapeIndex().getShape(ShapeId.from("smithy.example#MyString")).get(); + Shape shape = model.expectShape(ShapeId.from("smithy.example#MyString")); assertTrue(shape.hasTrait("smithy.example#foo")); } @@ -254,7 +254,7 @@ private static Model createCoercionModel(String traitType) { @Test public void coercesListTraitValues() { Model model = createCoercionModel("list foo { member: String }"); - Shape shape = model.getShapeIndex().getShape(ShapeId.from("smithy.example#MyString")).get(); + Shape shape = model.expectShape(ShapeId.from("smithy.example#MyString")); assertTrue(shape.hasTrait("smithy.example#foo")); } @@ -262,7 +262,7 @@ public void coercesListTraitValues() { @Test public void coercesBooleanTraitValuesToStructures() { Model model = createCoercionModel("structure foo {}"); - Shape shape = model.getShapeIndex().getShape(ShapeId.from("smithy.example#MyString")).get(); + Shape shape = model.expectShape(ShapeId.from("smithy.example#MyString")); assertTrue(shape.hasTrait("smithy.example#foo")); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java index 76bdca96c07..18de514bf34 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ModelAssemblerTest.java @@ -96,7 +96,7 @@ public void addsExplicitShapes() { .assemble(); assertThat(result.getValidationEvents(), empty()); - assertThat(result.unwrap().getShapeIndex().getShape(ShapeId.from("ns.foo#Bar")), is(Optional.of(shape))); + assertThat(result.unwrap().getShape(ShapeId.from("ns.foo#Bar")), is(Optional.of(shape))); } @Test @@ -110,7 +110,7 @@ public void addsExplicitDocumentNode() { ValidatedResult result = new ModelAssembler().addDocumentNode(node).assemble(); assertThat(result.getValidationEvents(), empty()); - assertTrue(result.unwrap().getShapeIndex().getShape(ShapeId.from("ns.foo#String")).isPresent()); + assertTrue(result.unwrap().getShape(ShapeId.from("ns.foo#String")).isPresent()); } @Test @@ -121,7 +121,7 @@ public void addsExplicitUnparsedDocumentNode() { .assemble(); assertThat(result.getValidationEvents(), empty()); - assertTrue(result.unwrap().getShapeIndex().getShape(ShapeId.from("ns.foo#String")).isPresent()); + assertTrue(result.unwrap().getShape(ShapeId.from("ns.foo#String")).isPresent()); } @Test @@ -159,7 +159,7 @@ public void detectsInvalidShapeTypes() { assertThat(result.getValidationEvents(), hasSize(1)); assertThat(result.getValidationEvents().get(0).getMessage(), containsString("Invalid shape `type`: foobaz")); assertThat(result.getValidationEvents().get(0).getSeverity(), is(Severity.ERROR)); - assertTrue(result.getResult().get().getShapeIndex() + assertTrue(result.getResult().get() .getShape(ShapeId.from("example.namespace#String")).isPresent()); } @@ -176,48 +176,48 @@ public void importsSymlinksDirectoryWithAllShapes() throws Exception { .assemble(); assertThat(result.getValidationEvents(), empty()); Model model = result.unwrap(); - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).isPresent()); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get().getType(), + assertTrue(model.getShape(ShapeId.from("example.namespace#String")).isPresent()); + assertThat(model.getShape(ShapeId.from("example.namespace#String")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String2")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String3")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Integer")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), is(ShapeType.INTEGER)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Long")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), is(ShapeType.LONG)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Float")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), is(ShapeType.FLOAT)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), is(ShapeType.BIG_DECIMAL)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), is(ShapeType.BIG_INTEGER)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Blob")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), is(ShapeType.BLOB)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), is(ShapeType.BOOLEAN)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), is(ShapeType.TIMESTAMP)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#List")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#List")).get().getType(), is(ShapeType.LIST)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Map")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), is(ShapeType.MAP)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Structure")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), is(ShapeType.STRUCTURE)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), is(ShapeType.UNION)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Resource")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), is(ShapeType.RESOURCE)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Operation")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), is(ShapeType.OPERATION)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Service")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), is(ShapeType.SERVICE)); ShapeId stringId = ShapeId.from("example.namespace#String"); - Optional sensitiveTrait = model.getShapeIndex() + Optional sensitiveTrait = model .getShape(stringId).get() .getTrait(SensitiveTrait.class); assertTrue(sensitiveTrait.isPresent()); @@ -233,7 +233,7 @@ public void importsSymlinksDirectoryWithAllShapes() throws Exception { containsInAnyOrder("a", "b", "c")); // The String shape should have a documentation trait applied. - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")) + assertTrue(model.getShape(ShapeId.from("example.namespace#String")) .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) .isPresent()); } @@ -248,7 +248,7 @@ public void importsSymlinkFileWithAllShapes() throws Exception { assertThat(result.getValidationEvents(), empty()); Model model = result.unwrap(); // The String shape should have a documentation trait applied. - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")) + assertTrue(model.getShape(ShapeId.from("example.namespace#String")) .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) .isPresent()); } @@ -270,48 +270,48 @@ public void importsFilesWithAllShapes() throws Exception { assertThat(result.getValidationEvents(), empty()); Model model = result.unwrap(); - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).isPresent()); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get().getType(), + assertTrue(model.getShape(ShapeId.from("example.namespace#String")).isPresent()); + assertThat(model.getShape(ShapeId.from("example.namespace#String")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String2")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String2")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String3")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String3")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#String")).get().getType(), is(ShapeType.STRING)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Integer")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Integer")).get().getType(), is(ShapeType.INTEGER)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Long")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Long")).get().getType(), is(ShapeType.LONG)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Float")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Float")).get().getType(), is(ShapeType.FLOAT)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#BigDecimal")).get().getType(), is(ShapeType.BIG_DECIMAL)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#BigInteger")).get().getType(), is(ShapeType.BIG_INTEGER)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Blob")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Blob")).get().getType(), is(ShapeType.BLOB)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Boolean")).get().getType(), is(ShapeType.BOOLEAN)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Timestamp")).get().getType(), is(ShapeType.TIMESTAMP)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#List")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#List")).get().getType(), is(ShapeType.LIST)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Map")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Map")).get().getType(), is(ShapeType.MAP)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Structure")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Structure")).get().getType(), is(ShapeType.STRUCTURE)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#TaggedUnion")).get().getType(), is(ShapeType.UNION)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Resource")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Resource")).get().getType(), is(ShapeType.RESOURCE)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Operation")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Operation")).get().getType(), is(ShapeType.OPERATION)); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#Service")).get().getType(), + assertThat(model.getShape(ShapeId.from("example.namespace#Service")).get().getType(), is(ShapeType.SERVICE)); ShapeId stringId = ShapeId.from("example.namespace#String"); - Optional sensitiveTrait = model.getShapeIndex() + Optional sensitiveTrait = model .getShape(stringId).get() .getTrait(SensitiveTrait.class); assertTrue(sensitiveTrait.isPresent()); @@ -327,7 +327,7 @@ public void importsFilesWithAllShapes() throws Exception { containsInAnyOrder("a", "b", "c")); // The String shape should have a documentation trait applied. - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")) + assertTrue(model.getShape(ShapeId.from("example.namespace#String")) .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) .isPresent()); } @@ -340,9 +340,9 @@ public void reportsSourceLocationOfShapesImportedFromFiles() throws Exception { .assemble() .unwrap(); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get().getSourceLocation(), + assertThat(model.getShape(ShapeId.from("example.namespace#String")).get().getSourceLocation(), is(new SourceLocation(getClass().getResource("main.json").toString(), 13, 23))); - assertThat(model.getShapeIndex().getShape(ShapeId.from("example.namespace#TaggedUnion$foo")).get().getSourceLocation(), + assertThat(model.getShape(ShapeId.from("example.namespace#TaggedUnion$foo")).get().getSourceLocation(), is(new SourceLocation(getClass().getResource("main.json").toString(), 76, 28))); } @@ -355,9 +355,9 @@ public void supportsMultiNamespaceDocuments() { assertThat(result.getValidationEvents(), empty()); // Each namespace had a separate name. - assertThat(result.unwrap().getShapeIndex().shapes().count(), equalTo(4L)); + assertThat(result.unwrap().shapes().count(), equalTo(4L)); // Each shape had a documentation trait in each namespace. - assertThat(result.unwrap().getShapeIndex().shapes() + assertThat(result.unwrap().shapes() .filter(shape -> shape.findTrait("ns.shared#customTrait").isPresent()) .count(), equalTo(3L)); } @@ -398,10 +398,10 @@ public void mergesDirectories() throws Exception { } private void assertImportPathsWereLoaded(Model model) { - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")) + assertTrue(model.getShape(ShapeId.from("example.namespace#String")) .flatMap(shape -> shape.getTrait(DocumentationTrait.class)) .isPresent()); - assertTrue(model.getShapeIndex().getShape(ShapeId.from("example.namespace#String")) + assertTrue(model.getShape(ShapeId.from("example.namespace#String")) .flatMap(shape -> shape.getTrait(MediaTypeTrait.class)) .isPresent()); } @@ -415,7 +415,7 @@ public void canAddEntireModelsToAssembler() { .assemble() .unwrap(); - assertEquals("hi", model2.getShapeIndex().getShape(ShapeId.from("example.namespace#String")).get() + assertEquals("hi", model2.expectShape(ShapeId.from("example.namespace#String")) .getTrait(DocumentationTrait.class).get().getValue()); } @@ -473,8 +473,8 @@ public void canLoadModelsFromJar() { for (String id : ListUtils.of("foo.baz#A", "foo.baz#B", "foo.baz#C")) { ShapeId shapeId = ShapeId.from(id); - assertTrue(model.getShapeIndex().getShape(shapeId).isPresent()); - assertThat(model.getShapeIndex().getShape(shapeId).get().getSourceLocation().getFilename(), + assertTrue(model.getShape(shapeId).isPresent()); + assertThat(model.getShape(shapeId).get().getSourceLocation().getFilename(), startsWith("jar:file:")); } } @@ -486,6 +486,6 @@ public void gracefullyParsesPartialDocuments() { assertTrue(result.isBroken()); assertTrue(result.getResult().isPresent()); - assertTrue(result.getResult().get().getShapeIndex().getShape(ShapeId.from("foo.baz#MyString")).isPresent()); + assertTrue(result.getResult().get().getShape(ShapeId.from("foo.baz#MyString")).isPresent()); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/NodeModelLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/NodeModelLoaderTest.java index fb1ea096d83..72a55dd3848 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/NodeModelLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/NodeModelLoaderTest.java @@ -70,13 +70,14 @@ public void fallsBackToPublicPreludeShapes() { .assemble() .unwrap(); - MemberShape baz = model.getShapeIndex() - .getShape(ShapeId.from("smithy.example#Foo$baz")).get() + MemberShape baz = model + .expectShape(ShapeId.from("smithy.example#Foo$baz")) .asMemberShape().get(); - MemberShape bar = model.getShapeIndex() - .getShape(ShapeId.from("smithy.example#Foo$bar")).get() + MemberShape bar = model + .expectShape(ShapeId.from("smithy.example#Foo$bar")) .asMemberShape().get(); - ResourceShape resource = model.getShapeIndex().getShape(ShapeId.from("smithy.example#MyResource")).get() + ResourceShape resource = model + .expectShape(ShapeId.from("smithy.example#MyResource")) .asResourceShape().get(); assertThat(baz.getTarget().toString(), equalTo("smithy.api#String")); @@ -97,6 +98,6 @@ public void loadsTraitDefinitions() { assertTrue(model.getTraitDefinition("example.namespace#documentation").isPresent()); assertTrue(model.getTraitDefinition("example.namespace#numeric").isPresent()); assertThat(model.getTraitShapes(), - hasItem(model.getShapeIndex().getShape(ShapeId.from("example.namespace#numeric")).get())); + hasItem(model.expectShape(ShapeId.from("example.namespace#numeric")))); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java index 57cb0a0b772..c37ddb3947c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/PreludeTest.java @@ -28,7 +28,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.PrivateTrait; import software.amazon.smithy.model.transform.ModelTransformer; @@ -56,7 +55,7 @@ public void checkIfPrivateShapesAreReferenced() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.scrubTraitDefinitions(model); - Set unreferencedPrivateShapes = result.getShapeIndex().shapes() + Set unreferencedPrivateShapes = result.shapes() .filter(shape -> shape.hasTrait(PrivateTrait.class)) .map(Shape::getId) .collect(Collectors.toSet()); @@ -67,19 +66,19 @@ public void checkIfPrivateShapesAreReferenced() { @Test public void resolvesToTargetInNamespace() { Shape stringShape = StringShape.builder().id("foo.baz#Bar").build(); - ShapeIndex index = ShapeIndex.builder().addShape(stringShape).build(); + Model model = Model.builder().addShape(stringShape).build(); - assertThat(Prelude.resolveShapeId(index, "foo.baz", "Bar"), equalTo(Optional.of(stringShape))); - assertThat(Prelude.resolveShapeId(index, "foo.baz", "Bam"), equalTo(Optional.empty())); + assertThat(Prelude.resolveShapeId(model, "foo.baz", "Bar"), equalTo(Optional.of(stringShape))); + assertThat(Prelude.resolveShapeId(model, "foo.baz", "Bam"), equalTo(Optional.empty())); } @Test public void resolvesToTargetInPrelude() { Shape customStringShape = StringShape.builder().id("foo.baz#String").build(); Shape preludeStringShape = StringShape.builder().id("smithy.api#String").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(customStringShape, preludeStringShape).build(); + Model model = Model.builder().addShapes(customStringShape, preludeStringShape).build(); - assertThat(Prelude.resolveShapeId(index, "foo.baz", "String"), equalTo(Optional.of(customStringShape))); - assertThat(Prelude.resolveShapeId(index, "other.ns", "String"), equalTo(Optional.of(preludeStringShape))); + assertThat(Prelude.resolveShapeId(model, "foo.baz", "String"), equalTo(Optional.of(customStringShape))); + assertThat(Prelude.resolveShapeId(model, "other.ns", "String"), equalTo(Optional.of(preludeStringShape))); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/SmithyModelLoaderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/SmithyModelLoaderTest.java index 0fcf7aae368..2f798c4d1f9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/SmithyModelLoaderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/SmithyModelLoaderTest.java @@ -22,9 +22,7 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; -import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.MemberShape; -import software.amazon.smithy.model.shapes.ModelSerializer; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ShapeId; @@ -36,7 +34,7 @@ public void loadsAppropriateSourceLocations() { .assemble() .unwrap(); - model.getShapeIndex().shapes().forEach(shape -> { + model.shapes().forEach(shape -> { if (!Prelude.isPreludeShape(shape.getId())) { assertThat(shape.getSourceLocation(), not(equalTo(SourceLocation.NONE))); } @@ -57,13 +55,11 @@ public void fallsBackToPublicPreludeShapes() { .assemble() .unwrap(); - MemberShape baz = model.getShapeIndex() - .getShape(ShapeId.from("smithy.example#Foo$baz")).get() + MemberShape baz = model.expectShape(ShapeId.from("smithy.example#Foo$baz")) .asMemberShape().get(); - MemberShape bar = model.getShapeIndex() - .getShape(ShapeId.from("smithy.example#Foo$bar")).get() + MemberShape bar = model.expectShape(ShapeId.from("smithy.example#Foo$bar")) .asMemberShape().get(); - ResourceShape resource = model.getShapeIndex().getShape(ShapeId.from("smithy.example#MyResource")).get() + ResourceShape resource = model.expectShape(ShapeId.from("smithy.example#MyResource")) .asResourceShape().get(); assertThat(baz.getTarget().toString(), equalTo("smithy.api#String")); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java index c78bee35b17..2d28ccde705 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/loader/ValidatorDefinitionTest.java @@ -33,7 +33,7 @@ public List loadBuiltinValidators() { public Optional createValidator(String name, ObjectNode configuration) { return name.equals("hello") ? Optional.of( - model -> model.getShapeIndex().shapes() + model -> model.shapes() .map(shape -> ValidationEvent.builder() .eventId(name) .shape(shape) diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java index ae76ad5218c..fdab225fd50 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/BottomUpNeighborVisitorTest.java @@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.empty; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.BlobShape; import software.amazon.smithy.model.shapes.ListShape; @@ -30,7 +31,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -71,10 +71,10 @@ public void dataShape() { .addMember(structureMemberShape) .build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(shape, listShape, mapShape, structureShape) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(shape), containsInAnyOrder( Relationship.create(listMemberShape, RelationshipType.MEMBER_TARGET, shape), @@ -109,7 +109,7 @@ public void memberShape() { .id("ns.foo#union$aMember") .build(); Shape unionShape = UnionShape.builder().addMember(tuMemberShape).id("ns.foo#union").build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(shape) .addShape(listMemberShape) .addShape(listShape) @@ -121,7 +121,7 @@ public void memberShape() { .addShape(tuMemberShape) .addShape(unionShape) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(listMemberShape), containsInAnyOrder( Relationship.create(listShape, RelationshipType.LIST_MEMBER, listMemberShape))); @@ -152,8 +152,8 @@ public void structureShape() { .output(input.getId()) .addError(error.getId()) .build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShapes(fooOperation, barOperation, input, output, error).build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + Model model = Model.builder().addShapes(fooOperation, barOperation, input, output, error).build(); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(input), containsInAnyOrder( Relationship.create(fooOperation, RelationshipType.INPUT, input), @@ -176,10 +176,10 @@ public void serviceShape() { .build(); OperationShape operationShape = OperationShape.builder().id("ns.foo#Operation").build(); ResourceShape resourceShape = ResourceShape.builder().id("ns.foo#Resource").build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(service, resourceShape, operationShape) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(service), containsInAnyOrder( Relationship.create(resourceShape, RelationshipType.BOUND, service), @@ -206,11 +206,11 @@ public void resourceShape() { .build(); ResourceShape child1 = ResourceShape.builder().id("ns.foo#Child1").addResource("ns.foo#Child2").build(); ResourceShape child2 = ResourceShape.builder().id("ns.foo#Child2").build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(parent, resource, child1, child2) .addShape(otherService) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(child2), containsInAnyOrder( Relationship.create(child1, RelationshipType.RESOURCE, child2))); @@ -272,12 +272,12 @@ public void operationShape() { OperationShape putOperation = OperationShape.builder() .id("ns.foo#Put") .build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(parent) .addShapes(resource, createOperation, getOperation, updateOperation, deleteOperation, listOperation) .addShapes(otherService, namedOperation, collectionOperation, putOperation) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(namedOperation), containsInAnyOrder( Relationship.create(resource, RelationshipType.OPERATION, namedOperation), @@ -317,10 +317,10 @@ public void returnsEmptyOnUnreferencedShape() { StringShape target = StringShape.builder() .id("ns.foo#String") .build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(target) .build(); - NeighborProvider neighborVisitor = NeighborProvider.bottomUp(shapeIndex); + NeighborProvider neighborVisitor = NeighborProvider.bottomUp(model); assertThat(neighborVisitor.getNeighbors(target), empty()); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java index ba40ed44237..97d57914f58 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/NeighborVisitorTest.java @@ -22,6 +22,7 @@ import java.util.List; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.BlobShape; import software.amazon.smithy.model.shapes.BooleanShape; @@ -33,7 +34,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.TimestampShape; @@ -46,8 +46,8 @@ public class NeighborVisitorTest { @Test public void blobShape() { Shape shape = BlobShape.builder().id("ns.foo#name").build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(shape).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(shape).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = shape.accept(neighborVisitor); assertThat(relationships, empty()); @@ -56,8 +56,8 @@ public void blobShape() { @Test public void booleanShape() { Shape shape = BooleanShape.builder().id("ns.foo#name").build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(shape).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(shape).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = shape.accept(neighborVisitor); assertThat(relationships, empty()); @@ -66,8 +66,8 @@ public void booleanShape() { @Test public void stringShape() { Shape shape = StringShape.builder().id("ns.foo#name").build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(shape).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(shape).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = shape.accept(neighborVisitor); assertThat(relationships, empty()); @@ -76,8 +76,8 @@ public void stringShape() { @Test public void timestampShape() { Shape shape = TimestampShape.builder().id("ns.foo#name").build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(shape).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(shape).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = shape.accept(neighborVisitor); assertThat(relationships, empty()); @@ -90,8 +90,8 @@ public void listShape() { .id("ns.foo#name") .member(string.getId()) .build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(list).addShape(string).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(list).addShape(string).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); MemberShape memberTarget = list.getMember(); List relationships = list.accept(neighborVisitor); @@ -115,8 +115,8 @@ public void mapShape() { .build(); MemberShape keyTarget = map.getKey(); MemberShape valueTarget = map.getValue(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShape(map).addShape(key).addShape(value).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShape(map).addShape(key).addShape(value).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = map.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -141,14 +141,14 @@ public void structureShape() { .build(); MemberShape member1Target = struct.getMember("m1").get(); MemberShape member2Target = struct.getMember("m2").get(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(struct) .addShape(memberShape1) .addShape(memberShape2) .addShape(member1Target) .addShape(member2Target) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = struct.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -173,14 +173,14 @@ public void unionShape() { .build(); MemberShape v1Target = union.getMember("tag1").get(); MemberShape v2Target = union.getMember("tag2").get(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(union) .addShape(variant1Shape) .addShape(variant2Shape) .addShape(v1Target) .addShape(v2Target) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = union.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -198,10 +198,10 @@ public void serviceShape() { .build(); OperationShape operationShape = OperationShape.builder().id("ns.foo#Operation").build(); ResourceShape resourceShape = ResourceShape.builder().id("ns.foo#Resource").build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(service, resourceShape, operationShape) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = service.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -257,12 +257,12 @@ public void resourceShape() { .build(); ResourceShape child1 = ResourceShape.builder().id("ns.foo#Child1").addResource("ns.foo#Child2").build(); ResourceShape child2 = ResourceShape.builder().id("ns.foo#Child2").build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(parent, resource, identifier, child1, child2) .addShapes(createOperation, getOperation, updateOperation, deleteOperation, listOperation) .addShapes(namedOperation, collectionOperation, putOperation) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = resource.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -318,8 +318,8 @@ public void operationShape() { .output(output.getId()) .addError(error.getId()) .build(); - ShapeIndex shapeIndex = ShapeIndex.builder().addShapes(method, input, output, error).build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + Model model = Model.builder().addShapes(method, input, output, error).build(); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = method.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -341,12 +341,12 @@ public void memberShape() { .id("ns.foo#List") .member(target) .build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(target) .addShape(string) .addShape(list) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = target.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( @@ -360,10 +360,10 @@ public void returnsEmptyOnMissingShape() { .id("ns.foo#List$member") .target("ns.foo#String") .build(); - ShapeIndex shapeIndex = ShapeIndex.builder() + Model model = Model.builder() .addShape(target) .build(); - NeighborVisitor neighborVisitor = new NeighborVisitor(shapeIndex); + NeighborVisitor neighborVisitor = new NeighborVisitor(model); List relationships = target.accept(neighborVisitor); assertThat(relationships, containsInAnyOrder( diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java index 4d13a432fe4..20ee5796954 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/UnreferencedTraitDefinitionsTest.java @@ -32,6 +32,6 @@ public void shouldReportDefinitionsForTraitsThatAreNotUsed() { UnreferencedTraitDefinitions unreferencedTraitDefinitions = new UnreferencedTraitDefinitions(); assertThat(unreferencedTraitDefinitions.compute(model), - contains(model.getShapeIndex().getShape(ShapeId.from("ns.foo#quux")).get())); + contains(model.expectShape(ShapeId.from("ns.foo#quux")))); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java index 23c2a90bdfb..78270241952 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/neighbor/WalkerTest.java @@ -20,11 +20,11 @@ import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; public class WalkerTest { @@ -56,7 +56,7 @@ public void getASetOfConnectedShapes() { .id("ns.foo#List") .member(listMember) .build(); - Walker walker = new Walker(ShapeIndex.builder() + Walker walker = new Walker(Model.builder() .addShape(list) .addShape(listMember) .addShape(map) @@ -96,7 +96,7 @@ public void supportsCycles() { .id("ns.foo#List") .member(listMember) .build(); - Walker walker = new Walker(ShapeIndex.builder() + Walker walker = new Walker(Model.builder() .addShape(list) .addShape(listMember) .addShape(map) diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/AndSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/AndSelectorTest.java index e374764f08e..e51b49a314c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/AndSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/AndSelectorTest.java @@ -22,10 +22,10 @@ import java.util.Arrays; import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.SensitiveTrait; @@ -38,8 +38,8 @@ public void matchesAllPredicates() { new AttributeSelector(new TraitAttributeKey("sensitive")))); Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").addTrait(new SensitiveTrait(SourceLocation.NONE)).build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b).build(); + Set result = selector.select(model); assertThat(result, contains(b)); } @@ -51,8 +51,8 @@ public void shortCircuits() { new AttributeSelector(new TraitAttributeKey("sensitive")))); Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").addTrait(new SensitiveTrait(SourceLocation.NONE)).build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b).build(); + Set result = selector.select(model); assertThat(result, empty()); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/EachSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/EachSelectorTest.java index 8f9b0b5bb4c..9639de4a45b 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/EachSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/EachSelectorTest.java @@ -21,10 +21,10 @@ import java.util.Arrays; import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.FloatShape; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StringShape; @@ -37,8 +37,8 @@ public void projectsOutValues() { Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").build(); Shape c = FloatShape.builder().id("foo.baz#Qux").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b, c).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b, c).build(); + Set result = selector.select(model); assertThat(result, containsInAnyOrder(a, b)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java index 76758330ebc..cf5a50ebc1a 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/NeighborSelectorTest.java @@ -27,28 +27,26 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; public class NeighborSelectorTest { - private static ShapeIndex index; + private static Model model; @BeforeAll public static void before() { - index = Model.assembler() + model = Model.assembler() .addImport(NeighborSelectorTest.class.getResource("neighbor-test.smithy")) .assemble() - .unwrap() - .getShapeIndex(); + .unwrap(); } @AfterAll public static void after() { - index = null; + model = null; } private Set selectIds(String expression) { return Selector.parse(expression) - .select(index) + .select(model) .stream() .map(Shape::getId) .map(ShapeId::toString) diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/OfSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/OfSelectorTest.java index 94eca586f71..931aa7802de 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/OfSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/OfSelectorTest.java @@ -24,12 +24,12 @@ import java.util.Collections; import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; @@ -38,32 +38,32 @@ public class OfSelectorTest { @Test public void matchesMembersThatAreContainedWithinSelector() { - ShapeIndex index = createIndex(); + Model model = createModel(); // Containing shape must have the sensitive trait. Selector selector = new OfSelector(Collections.singletonList( new AttributeSelector(new TraitAttributeKey("sensitive")))); - Set result = selector.select(index); + Set result = selector.select(model); assertThat(result, hasSize(1)); assertThat(result.iterator().next().getId().toString(), equalTo("foo.baz#B$member")); } @Test public void matchesMembersThatAreContainedWithinSelectorUsingOr() { - ShapeIndex index = createIndex(); + Model model = createModel(); // Match either a structure shape container or a list container. Selector selector = new OfSelector(Arrays.asList( new ShapeTypeSelector(ShapeType.STRUCTURE), new ShapeTypeSelector(ShapeType.LIST))); - Set result = selector.select(index); + Set result = selector.select(model); assertThat(result, containsInAnyOrder( - index.getShape(ShapeId.from("foo.baz#B$member")).get(), - index.getShape(ShapeId.from("foo.baz#C$member")).get(), - index.getShape(ShapeId.from("foo.baz#D$member")).get())); + model.expectShape(ShapeId.from("foo.baz#B$member")), + model.expectShape(ShapeId.from("foo.baz#C$member")), + model.expectShape(ShapeId.from("foo.baz#D$member")))); } - private ShapeIndex createIndex() { + private Model createModel() { Shape a = StringShape.builder().id("foo.baz#A").build(); MemberShape bMember = MemberShape.builder() .id("foo.baz#B$member") @@ -89,6 +89,6 @@ private ShapeIndex createIndex() { .member(dMember) .build(); - return ShapeIndex.builder().addShapes(a, b, bMember, c, cMember, d, dMember).build(); + return Model.builder().addShapes(a, b, bMember, c, cMember, d, dMember).build(); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java index 47741f19f6b..677ada41247 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/PathFinderTest.java @@ -31,7 +31,6 @@ import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.SensitiveTrait; @@ -49,17 +48,17 @@ public void findsPathsFromAtoB() { .addMember(structMemberFoo) .addMember(structMemberBaz) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) .build(); - List result1 = formatPaths(PathFinder.create(index).search(struct, "string")); + List result1 = formatPaths(PathFinder.create(model).search(struct, "string")); assertThat(result1, containsInAnyOrder( "[id|a.b#Struct] -[member]-> [id|a.b#Struct$baz] > [id|a.b#String]", "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]" )); - List result2 = formatPaths(PathFinder.create(index).search(structMemberFoo, "string")); + List result2 = formatPaths(PathFinder.create(model).search(structMemberFoo, "string")); assertThat(result2, contains( "[id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#String]")); } @@ -81,10 +80,10 @@ public void doesNotFailOnRecursion() { .addMember(structMemberFoo) .addMember(structMemberBaz) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(struct, structMemberFoo, structMemberBaz, list, listMember, string, structMemberBaz) .build(); - List result = formatPaths(PathFinder.create(index).search(struct, "[trait|sensitive]")); + List result = formatPaths(PathFinder.create(model).search(struct, "[trait|sensitive]")); assertThat(result, containsInAnyOrder( "[id|a.b#Struct] -[member]-> [id|a.b#Struct$foo] > [id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#Struct]", @@ -95,16 +94,16 @@ public void doesNotFailOnRecursion() { @Test public void emptyResultsWhenNothingMatchesSelector() { StringShape string = StringShape.builder().id("a.b#String").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(string).build(); - List result = formatPaths(PathFinder.create(index).search(string, "[trait|required]")); + Model model = Model.builder().addShapes(string).build(); + List result = formatPaths(PathFinder.create(model).search(string, "[trait|required]")); assertThat(result, empty()); } @Test public void doesNotFailOnMissingShape() { - ShapeIndex index = ShapeIndex.builder().build(); - List result = formatPaths(PathFinder.create(index).search(ShapeId.from("foo.baz#Bar"), "string")); + Model model = Model.builder().build(); + List result = formatPaths(PathFinder.create(model).search(ShapeId.from("foo.baz#Bar"), "string")); assertThat(result, empty()); } @@ -113,8 +112,8 @@ public void doesNotFailOnMissingShape() { public void doesNotAddItselfToResultAsFirstMatch() { MemberShape listMember = MemberShape.builder().id("a.b#List$member").target("a.b#List").build(); ListShape list = ListShape.builder().id("a.b#List").member(listMember).build(); - ShapeIndex index = ShapeIndex.builder().addShapes(list, listMember).build(); - List result = formatPaths(PathFinder.create(index).search(list, "list")); + Model model = Model.builder().addShapes(list, listMember).build(); + List result = formatPaths(PathFinder.create(model).search(list, "list")); assertThat(result, contains( "[id|a.b#List] -[member]-> [id|a.b#List$member] > [id|a.b#List]")); @@ -124,8 +123,8 @@ public void doesNotAddItselfToResultAsFirstMatch() { public void providesStartAndEndShapes() { MemberShape listMember = MemberShape.builder().id("a.b#List$member").target("a.b#List").build(); ListShape list = ListShape.builder().id("a.b#List").member(listMember).build(); - ShapeIndex index = ShapeIndex.builder().addShapes(list, listMember).build(); - List result = PathFinder.create(index).search(list, "list"); + Model model = Model.builder().addShapes(list, listMember).build(); + List result = PathFinder.create(model).search(list, "list"); assertThat(result, hasSize(1)); assertThat(result.get(0).getStartShape(), equalTo(list)); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java index b8db5e58336..0242c61bb0c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/SelectorTest.java @@ -23,15 +23,12 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; -import software.amazon.smithy.model.SourceLocation; -import software.amazon.smithy.model.node.BooleanNode; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.DynamicTrait; import software.amazon.smithy.model.traits.RequiredTrait; import software.amazon.smithy.model.traits.Trait; @@ -40,12 +37,11 @@ public class SelectorTest { @Test public void selectsCollections() { - ShapeIndex index = Model.assembler().addImport(getClass().getResource("model.json")) + Model model = Model.assembler().addImport(getClass().getResource("model.json")) .disablePrelude() .assemble() - .unwrap() - .getShapeIndex(); - Set result = Selector.parse("collection").select(index); + .unwrap(); + Set result = Selector.parse("collection").select(model); assertThat(result, containsInAnyOrder( SetShape.builder() @@ -60,12 +56,11 @@ public void selectsCollections() { @Test public void selectsCustomTraits() { - ShapeIndex index = Model.assembler() + Model model = Model.assembler() .addImport(getClass().getResource("model-custom-trait.json")) .assemble() - .unwrap() - .getShapeIndex(); - Set result = Selector.parse("*[trait|'com.example#beta']").select(index); + .unwrap(); + Set result = Selector.parse("*[trait|'com.example#beta']").select(model); Trait betaTrait = new DynamicTrait(ShapeId.from("com.example#beta"), Node.objectNode()); Trait requiredTrait = new RequiredTrait(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java index 00fb5cac1fe..1821fdd9525 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeCategorySelectorTest.java @@ -20,10 +20,10 @@ import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.NumberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; public class ShapeTypeCategorySelectorTest { @@ -32,8 +32,8 @@ public void matchesByClass() { Selector selector = new ShapeTypeCategorySelector(NumberShape.class); Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b).build(); + Set result = selector.select(model); assertThat(result, contains(a)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java index 0be54a94fcf..e04181e5738 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/ShapeTypeSelectorTest.java @@ -20,9 +20,9 @@ import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StringShape; @@ -32,8 +32,8 @@ public void matchesByType() { Selector selector = new ShapeTypeSelector(ShapeType.STRING); Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b).build(); + Set result = selector.select(model); assertThat(result, contains(b)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/selector/TestSelectorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/selector/TestSelectorTest.java index c45fd0cd88d..b8e3d0f3703 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/selector/TestSelectorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/selector/TestSelectorTest.java @@ -21,10 +21,10 @@ import java.util.Arrays; import java.util.Set; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.FloatShape; import software.amazon.smithy.model.shapes.IntegerShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeType; import software.amazon.smithy.model.shapes.StringShape; @@ -37,8 +37,8 @@ public void matchesUsingOr() { Shape a = IntegerShape.builder().id("foo.baz#Bar").build(); Shape b = StringShape.builder().id("foo.baz#Bam").build(); Shape c = FloatShape.builder().id("foo.baz#Qux").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(a, b, c).build(); - Set result = selector.select(index); + Model model = Model.builder().addShapes(a, b, c).build(); + Set result = selector.select(model); assertThat(result, containsInAnyOrder(a, b)); } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java index f8edfec7a9d..4ba2f8e811d 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/MemberShapeTest.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.model.traits.ExternalDocumentationTrait; @@ -93,19 +94,19 @@ public void getsMemberTraits() { .target(target) .addTrait(new DocumentationTrait("override")) .build(); - ShapeIndex index = ShapeIndex.builder().addShapes(member, target).build(); + Model model = Model.builder().addShapes(member, target).build(); assertThat( - member.getMemberTrait(index, DocumentationTrait.class).get().getValue(), + member.getMemberTrait(model, DocumentationTrait.class).get().getValue(), equalTo("override")); assertThat( - member.getMemberTrait(index, ExternalDocumentationTrait.class).get().getValue(), + member.getMemberTrait(model, ExternalDocumentationTrait.class).get().getValue(), equalTo("http://example.com")); assertThat( - member.findMemberTrait(index, "documentation"), + member.findMemberTrait(model, "documentation"), equalTo(member.findTrait("documentation"))); assertThat( - member.findMemberTrait(index, "externalDocumentation"), + member.findMemberTrait(model, "externalDocumentation"), equalTo(target.findTrait("externalDocumentation"))); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java index ec769f57e15..d4b80c563b9 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ModelSerializerTest.java @@ -61,7 +61,6 @@ public void filtersMetadata() { Model model = Model.builder() .putMetadataProperty("foo", Node.from("baz")) .putMetadataProperty("bar", Node.from("qux")) - .shapeIndex(ShapeIndex.builder().build()) .build(); ObjectNode result = serializer.serialize(model); @@ -77,10 +76,8 @@ public void filtersShapes() { .shapeFilter(shape -> shape.getId().getName().equals("foo")) .build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder() - .addShape(StringShape.builder().id("ns.foo#foo").build()) - .addShape(StringShape.builder().id("ns.foo#baz").build()) - .build()) + .addShape(StringShape.builder().id("ns.foo#foo").build()) + .addShape(StringShape.builder().id("ns.foo#baz").build()) .build(); ObjectNode result = serializer.serialize(model); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java index b4087a0c8d3..8d47561874f 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/shapes/ShapeTest.java @@ -29,6 +29,7 @@ import java.util.Collection; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.node.Node; import software.amazon.smithy.model.traits.DocumentationTrait; @@ -119,15 +120,15 @@ public void hasTraits() { .addTrait(otherTrait) .addTrait(documentationTrait) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(shape) .build(); assertTrue(shape.getTrait(MyTrait.class).isPresent()); - assertTrue(shape.getMemberTrait(index, MyTrait.class).isPresent()); + assertTrue(shape.getMemberTrait(model, MyTrait.class).isPresent()); assertTrue(shape.findTrait("foo.baz#foo").isPresent()); - assertTrue(shape.findMemberTrait(index, "foo.baz#foo").isPresent()); + assertTrue(shape.findMemberTrait(model, "foo.baz#foo").isPresent()); assertTrue(shape.hasTrait("foo.baz#foo")); assertTrue(shape.getTrait(OtherTrait.class).isPresent()); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java index 739c4cccd60..b05e22b9255 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/traits/EffectiveTraitQueryTest.java @@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; public class EffectiveTraitQueryTest { @@ -16,11 +16,11 @@ public void detectsTraitOnShape() { Shape stringShape = StringShape.builder().id("foo.bar#Baz") .addTrait(new SensitiveTrait()) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(stringShape) .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .shapeIndex(index) + .model(model) .traitClass(SensitiveTrait.class) .build(); @@ -33,11 +33,11 @@ public void detectsTraitOnMemberTarget() { .addTrait(new SensitiveTrait()) .build(); ListShape list = ListShape.builder().id("foo.bar#List").member(stringShape.getId()).build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(stringShape, list) .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .shapeIndex(index) + .model(model) .traitClass(SensitiveTrait.class) .build(); @@ -56,11 +56,11 @@ public void ignoresTraitOnMemberContainerByDefault() { .member(member) .addTrait(new SensitiveTrait()) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(stringShape, member, list) .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .shapeIndex(index) + .model(model) .traitClass(SensitiveTrait.class) .build(); @@ -79,11 +79,11 @@ public void detectsTraitOnMemberContainer() { .member(member) .addTrait(new SensitiveTrait()) .build(); - ShapeIndex index = ShapeIndex.builder() + Model model = Model.builder() .addShapes(stringShape, member, list) .build(); EffectiveTraitQuery query = EffectiveTraitQuery.builder() - .shapeIndex(index) + .model(model) .traitClass(SensitiveTrait.class) .inheritFromContainer(true) .build(); diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java index 2c78cbfa08b..0386975a7ec 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterMetadataTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.node.Node; -import software.amazon.smithy.model.shapes.ShapeIndex; public class FilterMetadataTest { @Test @@ -30,7 +29,6 @@ public void filtersMetadata() { .putMetadataProperty("foo", Node.from("string")) .putMetadataProperty("baz", Node.from(1)) .putMetadataProperty("lorem", Node.from(true)) - .shapeIndex(ShapeIndex.builder().build()) .build(); ModelTransformer transformer = ModelTransformer.create(); // Remove boolean and number metadata key-value pairs. diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java index a4de0fbb1ba..7fb7af604a2 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterShapesTest.java @@ -29,7 +29,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.DynamicTrait; @@ -47,13 +46,12 @@ public void removesShapesThatMatchPredicate() { .build(); ShapeId bId = ShapeId.from("ns.foo#B"); StringShape b = StringShape.builder().id(bId).build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShapes(a, b).build()).build(); + Model model = Model.builder().addShapes(a, b).build(); Model result = ModelTransformer.create() .filterShapes(model, shape -> !shape.getTrait(SensitiveTrait.class).isPresent()); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.is(1L)); - assertThat(index.getShape(bId), Matchers.not(Optional.empty())); + assertThat(result.shapes().count(), Matchers.is(1L)); + assertThat(result.getShape(bId), Matchers.not(Optional.empty())); } @Test @@ -68,15 +66,13 @@ public void doesNotFilterListOrMapMembers() { MemberShape mapValue = MemberShape.builder().id("ns.foo#Map$value").target(stringShapeId).build(); MapShape map = MapShape.builder().id("ns.foo#Map").key(mapKey).value(mapValue).build(); - ShapeIndex inIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(string, list, listMember, map, mapKey, mapValue) .build(); - Model model = Model.builder().shapeIndex(inIndex).build(); Model result = ModelTransformer.create().filterShapes(model, shape -> !shape.isMemberShape()); - ShapeIndex outIndex = result.getShapeIndex(); // No members should be removed because they are not eligible. - assertThat(outIndex.shapes().count(), Matchers.is(6L)); + assertThat(result.shapes().count(), Matchers.is(6L)); } @Test @@ -93,29 +89,27 @@ public void updatesStructureContainerWhenMemberIsRemoved() { .addMember(member2) .addMember(member3) .build(); - ShapeIndex inIndex = ShapeIndex.builder() + Model model = Model.builder() .addShapes(string, structure, member1, member2, member3) .build(); - Model model = Model.builder().shapeIndex(inIndex).build(); // Remove "member2" from the structure. Model result = ModelTransformer.create().filterShapes(model, shape -> { return !shape.getId().toString().equals("ns.foo#Structure$member2"); }); - ShapeIndex outIndex = result.getShapeIndex(); // Ensure that the member shapes were removed from the index. - assertThat(outIndex.getShape(member1.getId()), Matchers.equalTo(Optional.of(member1))); - assertThat(outIndex.getShape(member3.getId()), Matchers.equalTo(Optional.of(member3))); - assertThat(outIndex.getShape(member2.getId()), Matchers.is(Optional.empty())); - assertThat(outIndex.getShape(structure.getId()), Matchers.not(Optional.empty())); + assertThat(result.getShape(member1.getId()), Matchers.equalTo(Optional.of(member1))); + assertThat(result.getShape(member3.getId()), Matchers.equalTo(Optional.of(member3))); + assertThat(result.getShape(member2.getId()), Matchers.is(Optional.empty())); + assertThat(result.getShape(structure.getId()), Matchers.not(Optional.empty())); // Make sure the structure was updated so that it no longer has the removed member shape. - assertThat(outIndex.getShape(structure.getId()).get().asStructureShape().get().getMember("member1"), + assertThat(result.getShape(structure.getId()).get().asStructureShape().get().getMember("member1"), Matchers.not(Optional.empty())); - assertThat(outIndex.getShape(structure.getId()).get().asStructureShape().get().getMember("member3"), + assertThat(result.getShape(structure.getId()).get().asStructureShape().get().getMember("member3"), Matchers.not(Optional.empty())); - assertThat(outIndex.getShape(structure.getId()).get().asStructureShape().get().getMember("member2"), + assertThat(result.getShape(structure.getId()).get().asStructureShape().get().getMember("member2"), Matchers.is(Optional.empty())); } @@ -144,22 +138,21 @@ public void removesTraitsWhenDefinitionIsRemoved() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(shape1, shape2, bazTrait, barTrait).build()) + .addShapes(shape1, shape2, bazTrait, barTrait) .build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterShapes(model, shape -> !shape.getId().toString().equals("ns.foo#baz")); Map definitions = result.getTraitDefinitions(); - ShapeIndex index = result.getShapeIndex(); assertThat(definitions.size(), Matchers.is(1)); assertThat(definitions, Matchers.hasKey(barTrait)); assertThat(definitions, Matchers.hasValue(barTrait.getTrait(TraitDefinition.class).get())); - assertThat(index.getShape(shapeId1).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(shapeId1).get().findTrait("ns.foo#baz"), Matchers.is(Optional.empty())); - assertThat(index.getShape(shapeId2).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(shapeId2).get().findTrait("ns.foo#baz"), Matchers.is(Optional.empty())); - assertThat(index.getShape(shapeId2).get().findTrait("ns.foo#bar"), Matchers.not(Optional.empty())); + assertThat(result.getShape(shapeId1).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(shapeId1).get().findTrait("ns.foo#baz"), Matchers.is(Optional.empty())); + assertThat(result.getShape(shapeId2).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(shapeId2).get().findTrait("ns.foo#baz"), Matchers.is(Optional.empty())); + assertThat(result.getShape(shapeId2).get().findTrait("ns.foo#bar"), Matchers.not(Optional.empty())); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java index eac75fa2b48..6ef589613bc 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/FilterTraitsTest.java @@ -23,7 +23,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.model.traits.DocumentationTrait; @@ -45,17 +44,16 @@ public void removesTraits() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .addTrait(DeprecatedTrait.builder().build()) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShapes(a, b).build()).build(); + Model model = Model.builder().addShapes(a, b).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterTraits( model, (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive"))); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.is(2L)); - assertThat(index.getShape(aId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); - assertThat(index.getShape(aId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(bId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); - assertThat(index.getShape(bId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); + assertThat(result.shapes().count(), Matchers.is(2L)); + assertThat(result.getShape(aId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); + assertThat(result.getShape(aId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(bId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); + assertThat(result.getShape(bId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); } @Test @@ -67,28 +65,26 @@ public void removesTraitsWithComposedPredicate() { .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) .addTrait(DeprecatedTrait.builder().build()) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(a).build()).build(); + Model model = Model.builder().addShape(a).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterTraits( model, (shape, trait) -> !trait.toShapeId().equals(ShapeId.from("smithy.api#sensitive")) && !trait.toShapeId().equals(ShapeId.from("smithy.api#documentation"))); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.is(1L)); - assertThat(index.getShape(aId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); - assertThat(index.getShape(aId).get().getTrait(DocumentationTrait.class), Matchers.is(Optional.empty())); - assertThat(index.getShape(aId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); + assertThat(result.shapes().count(), Matchers.is(1L)); + assertThat(result.getShape(aId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); + assertThat(result.getShape(aId).get().getTrait(DocumentationTrait.class), Matchers.is(Optional.empty())); + assertThat(result.getShape(aId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); } @Test public void leavesShapesAlone() { ShapeId aId = ShapeId.from("ns.foo#A"); StringShape a = StringShape.builder().id(aId).build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(a).build()).build(); + Model model = Model.builder().addShape(a).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.filterTraits(model, (shape, trait) -> true); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.is(1L)); + assertThat(result.shapes().count(), Matchers.is(1L)); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java index ba601873443..340b4857594 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/IntegTest.java @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; public class IntegTest { @@ -42,26 +41,24 @@ public static void before() { public void removesResources() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapesIf(model, shape -> shape.getId().toString().equals("ns.foo#MyResource")); - ShapeIndex index = result.getShapeIndex(); assertValidModel(result); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); // The operations bound to the resource remain, now orphaned. - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.not(Optional.empty())); } @Test public void removesServices() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapesIf(model, shape -> shape.getId().toString().equals("ns.foo#MyService")); - ShapeIndex index = result.getShapeIndex(); assertValidModel(result); // Operations and resources bound to the service remain. - assertThat(index.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyOperation")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyOperation")), Matchers.not(Optional.empty())); } @Test @@ -69,15 +66,14 @@ public void removesUnreferencedShapes() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapesIf(model, shape -> shape.getId().toString().equals("ns.foo#MyResource")); result = transformer.removeUnreferencedShapes(result); - ShapeIndex index = result.getShapeIndex(); assertValidModel(result); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), Matchers.is(Optional.empty())); } @Test @@ -85,15 +81,14 @@ public void removesUnreferencedShapesWithFilter() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapesIf(model, shape -> shape.getId().toString().equals("ns.foo#MyResource")); result = transformer.removeUnreferencedShapes(result, shape -> !shape.getTags().contains("foo")); - ShapeIndex index = result.getShapeIndex(); assertValidModel(result); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResource")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceIdentifier")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResource")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#CreateMyResourceOutput")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInput")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#MyResourceOperationInputString")), Matchers.not(Optional.empty())); } private void assertValidModel(Model model) { diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java index eb01ce8b89d..b91ba80a9f7 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapShapesTest.java @@ -26,7 +26,6 @@ import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.model.traits.SensitiveTrait; @@ -40,13 +39,12 @@ public void replacesMappedShapes() { .id(shapeId) .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapShapes(model, s -> Shape.shapeToBuilder(s).removeTrait("sensitive").build()); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(shapeId).get().getId(), Matchers.equalTo(shapeId)); - assertThat(index.getShape(shapeId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); + assertThat(result.expectShape(shapeId).getId(), Matchers.equalTo(shapeId)); + assertThat(result.expectShape(shapeId).getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); } @Test @@ -54,7 +52,7 @@ public void throwsWhenMapperChangesShapeId() { Assertions.assertThrows(RuntimeException.class, () -> { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder().id(shapeId).build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapShapes(model, (s -> Shape.shapeToBuilder(s).id("ns.foo#change").build())); }); @@ -68,14 +66,13 @@ public void mapsUsingAllMappers() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapShapes(model, Arrays.asList( s -> Shape.shapeToBuilder(s).removeTrait("sensitive").build(), s -> Shape.shapeToBuilder(s).removeTrait("documentation").build())); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(shapeId).get().getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); - assertThat(index.getShape(shapeId).get().getTrait(DocumentationTrait.class), Matchers.is(Optional.empty())); + assertThat(result.expectShape(shapeId).getTrait(SensitiveTrait.class), Matchers.is(Optional.empty())); + assertThat(result.expectShape(shapeId).getTrait(DocumentationTrait.class), Matchers.is(Optional.empty())); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java index 43a1cb9de15..a6f744782f4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/MapTraitsTest.java @@ -24,7 +24,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.SourceLocation; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.traits.DeprecatedTrait; import software.amazon.smithy.model.traits.DocumentationTrait; @@ -39,7 +38,7 @@ public void doesNotReplaceUnchangedShapes() { .id(shapeId) .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapTraits(model, (s, t) -> t); } @@ -52,7 +51,7 @@ public void appliesAllMappersToShapes() { .addTrait(DeprecatedTrait.builder().message("foo").build()) .addTrait(new DocumentationTrait("docs", SourceLocation.NONE)) .build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.mapTraits(model, Arrays.asList( (s, t) -> { @@ -70,12 +69,11 @@ public void appliesAllMappersToShapes() { } } )); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(shapeId).get().getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(shapeId).get().getTrait(DeprecatedTrait.class).get().getMessage().get(), + assertThat(result.expectShape(shapeId).getTrait(DeprecatedTrait.class), Matchers.not(Optional.empty())); + assertThat(result.expectShape(shapeId).getTrait(DeprecatedTrait.class).get().getMessage().get(), Matchers.equalTo("baz")); - assertThat(index.getShape(shapeId).get().getTrait(DocumentationTrait.class).get().getValue(), + assertThat(result.expectShape(shapeId).getTrait(DocumentationTrait.class).get().getValue(), Matchers.equalTo("changed")); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java index f5435653ebd..1fd805f7cd6 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ModelTransformerTest.java @@ -25,7 +25,6 @@ import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.EnumTrait; import software.amazon.smithy.model.traits.ReadonlyTrait; @@ -36,15 +35,14 @@ public void discoversOnRemoveClassesWithSpi() { ModelTransformer transformer = ModelTransformer.create(); Model model = createTestModel(); Model result = transformer.removeShapesIf(model, Shape::isStructureShape); - ShapeIndex index = result.getShapeIndex(); ShapeId operation = ShapeId.from("ns.foo#MyOperation"); - assertThat(index.getShape(operation), Matchers.not(Optional.empty())); - assertThat(index.getShape(operation).get().asOperationShape().flatMap(OperationShape::getInput), + assertThat(result.expectShape(operation), Matchers.not(Optional.empty())); + assertThat(result.expectShape(operation).asOperationShape().flatMap(OperationShape::getInput), Matchers.is(Optional.empty())); - assertThat(index.getShape(operation).get().asOperationShape().flatMap(OperationShape::getOutput), + assertThat(result.expectShape(operation).asOperationShape().flatMap(OperationShape::getOutput), Matchers.is(Optional.empty())); - assertThat(index.getShape(operation).get().asOperationShape().map(OperationShape::getErrors), + assertThat(result.expectShape(operation).asOperationShape().map(OperationShape::getErrors), Matchers.equalTo(Optional.of(Collections.emptyList()))); } @@ -52,12 +50,12 @@ public void discoversOnRemoveClassesWithSpi() { public void removesTraitShapesButNotTraitUsage() { ModelTransformer transformer = ModelTransformer.create(); Model model = createTestModel(); - ShapeIndex index = transformer.getNonTraitShapes(model); + Model nonTraitShapes = transformer.getModelWithoutTraitShapes(model); ShapeId operation = ShapeId.from("ns.foo#MyOperation"); - assertThat(index.getShape(operation), Matchers.not(Optional.empty())); - assertThat(index.getShape(operation).get().getTrait(ReadonlyTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(EnumTrait.ID), Matchers.equalTo(Optional.empty())); + assertThat(nonTraitShapes.getShape(operation), Matchers.not(Optional.empty())); + assertThat(nonTraitShapes.getShape(operation).get().getTrait(ReadonlyTrait.class), Matchers.not(Optional.empty())); + assertThat(nonTraitShapes.getShape(EnumTrait.ID), Matchers.equalTo(Optional.empty())); } private Model createTestModel() { diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java index a3329d61baf..791e0e12c08 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/RemoveShapesTest.java @@ -32,7 +32,6 @@ import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -43,18 +42,17 @@ public class RemoveShapesTest { private static final ShapeId STRING_TARGET = ShapeId.from("ns.foo#String"); private void assertContainerMembersAreRemoved(Shape container, List members) { - ShapeIndex.Builder builder = ShapeIndex.builder() + Model.Builder builder = Model.builder() .addShape(container) .addShape(StringShape.builder().id(STRING_TARGET).build()); members.forEach(builder::addShape); - Model model = Model.builder().shapeIndex(builder.build()).build(); + Model model = builder.build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapes(model, Collections.singleton(container)); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.equalTo(1L)); - assertThat(index.getShape(STRING_TARGET), Matchers.not(Optional.empty())); - assertThat(index.getShape(container.getId()), Matchers.is(Optional.empty())); + assertThat(result.shapes().count(), Matchers.equalTo(1L)); + assertThat(result.getShape(STRING_TARGET), Matchers.not(Optional.empty())); + assertThat(result.getShape(container.getId()), Matchers.is(Optional.empty())); } @Test @@ -132,16 +130,14 @@ public void removesOperationsFromResourcesWhenOperationRemoved() { OperationShape b = OperationShape.builder().id("ns.foo#B").build(); OperationShape c = OperationShape.builder().id("ns.foo#C").build(); - ShapeIndex index = ShapeIndex.builder().addShapes(container, a, b, c).build(); - Model model = Model.builder().shapeIndex(index).build(); + Model model = Model.builder().addShapes(container, a, b, c).build(); ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.removeShapes(model, Arrays.asList(a, b)); - ShapeIndex resultShapeIndex = result.getShapeIndex(); - assertThat(resultShapeIndex.shapes().count(), Matchers.equalTo(2L)); - assertThat(resultShapeIndex.getShape(container.getId()), Matchers.not(Optional.empty())); - assertThat(resultShapeIndex.getShape(c.getId()), Matchers.not(Optional.empty())); - assertThat(resultShapeIndex.getShape(container.getId()).get().asResourceShape().get().getOperations(), - Matchers.contains(c.getId())); + assertThat(result.shapes().count(), Matchers.equalTo(2L)); + assertThat(result.getShape(container.getId()), Matchers.not(Optional.empty())); + assertThat(result.getShape(c.getId()), Matchers.not(Optional.empty())); + assertThat(result.expectShape(container.getId()).asResourceShape().get().getOperations(), + Matchers.contains(c.getId())); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java index 079f565a6bd..aace51dae4c 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ReplaceShapesTest.java @@ -31,7 +31,6 @@ import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StringShape; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -46,7 +45,7 @@ public void cannotChangeShapeTypes() { Assertions.assertThrows(RuntimeException.class, () -> { ShapeId shapeId = ShapeId.from("ns.foo#id1"); StringShape shape = StringShape.builder().id(shapeId).build(); - Model model = Model.builder().shapeIndex(ShapeIndex.builder().addShape(shape).build()).build(); + Model model = Model.builder().addShape(shape).build(); ModelTransformer transformer = ModelTransformer.create(); transformer.mapShapes(model, s -> IntegerShape.builder().id(shapeId).build()); }); @@ -61,7 +60,7 @@ public void updatesListMemberWhenContainerUpdated() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, member, container).build()) + .addShapes(target, member, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMember = MemberShape.builder() @@ -71,12 +70,11 @@ public void updatesListMemberWhenContainerUpdated() { .build(); ListShape newList = ListShape.builder().id(containerId).member(newMember).build(); Model result = transformer.replaceShapes(model, Arrays.asList(newList)); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.equalTo(3L)); - assertThat(index.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(containerId).get(), Matchers.is(newList)); - assertThat(index.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); + assertThat(result.shapes().count(), Matchers.equalTo(3L)); + assertThat(result.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(containerId).get(), Matchers.is(newList)); + assertThat(result.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); } @Test @@ -91,7 +89,7 @@ public void updatesMapMembersWhenContainerUpdated() { MemberShape valueMember = MemberShape.builder().id(valueId).target(stringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, keyMember, valueMember, container).build()) + .addShapes(target, keyMember, valueMember, container) .build(); ModelTransformer transformer = ModelTransformer.create(); @@ -107,14 +105,13 @@ public void updatesMapMembersWhenContainerUpdated() { .build(); MapShape newMap = MapShape.builder().id(containerId).key(newKey).value(newValue).build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMap)); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.shapes().count(), Matchers.equalTo(4L)); - assertThat(index.getShape(keyId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(valueId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(containerId).get(), Matchers.is(newMap)); - assertThat(index.getShape(containerId).get().asMapShape().get().getKey(), Matchers.is(newKey)); - assertThat(index.getShape(containerId).get().asMapShape().get().getValue(), Matchers.is(newValue)); + assertThat(result.shapes().count(), Matchers.equalTo(4L)); + assertThat(result.getShape(keyId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(valueId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(containerId).get(), Matchers.is(newMap)); + assertThat(result.getShape(containerId).get().asMapShape().get().getKey(), Matchers.is(newKey)); + assertThat(result.getShape(containerId).get().asMapShape().get().getValue(), Matchers.is(newValue)); } @Test @@ -127,8 +124,7 @@ public void updatesTaggedUnionMembersWhenContainerUpdated() { MemberShape member3 = MemberShape.builder().id("ns.foo#Shape$member3").target("ns.foo#String").build(); UnionShape shape = UnionShape.builder() .id("ns.foo#Shape").addMember(member1).addMember(member2).addMember(member3).build(); - ShapeIndex inIndex = ShapeIndex.builder().addShapes(string, shape, member1, member2, member3).build(); - Model model = Model.builder().shapeIndex(inIndex).build(); + Model model = Model.builder().addShapes(string, shape, member1, member2, member3).build(); // Add a trait to a replaced member3. MemberShape newMember3 = MemberShape.builder() @@ -142,12 +138,11 @@ public void updatesTaggedUnionMembersWhenContainerUpdated() { .id("ns.foo#Shape").addMember(member1).addMember(newMember3).build(); Model result = ModelTransformer.create().replaceShapes(model, Collections.singleton(other)); - ShapeIndex outIndex = result.getShapeIndex(); - assertThat(outIndex.getShape(member1.getId()), Matchers.equalTo(Optional.of(member1))); - assertThat(outIndex.getShape(member2.getId()), Matchers.is(Optional.empty())); - assertThat(outIndex.getShape(member3.getId()), Matchers.equalTo(Optional.of(newMember3))); - assertThat(outIndex.getShape(shape.getId()), Matchers.not(Optional.empty())); + assertThat(result.getShape(member1.getId()), Matchers.equalTo(Optional.of(member1))); + assertThat(result.getShape(member2.getId()), Matchers.is(Optional.empty())); + assertThat(result.getShape(member3.getId()), Matchers.equalTo(Optional.of(newMember3))); + assertThat(result.getShape(shape.getId()), Matchers.not(Optional.empty())); } @Test @@ -159,7 +154,7 @@ public void updatesListShapeWhenMemberModified() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, member, container).build()) + .addShapes(target, member, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMember = MemberShape.builder() @@ -168,10 +163,9 @@ public void updatesListShapeWhenMemberModified() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMember)); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); + assertThat(result.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); } @Test @@ -185,7 +179,7 @@ public void updatesMapShapeWhenKeyOrValueIsUpdated() { MemberShape valueMember = MemberShape.builder().id(valueMemberId).target(stringId).build(); MapShape container = MapShape.builder().id(containerId).key(keyMember).value(valueMember).build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, keyMember, valueMember, container).build()) + .addShapes(target, keyMember, valueMember, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newKeyMember = MemberShape.builder() @@ -201,15 +195,14 @@ public void updatesMapShapeWhenKeyOrValueIsUpdated() { .build(); Model resultWithNewValue = transformer.replaceShapes(model, Arrays.asList(newValueMember)); - - assertThat(resultWithNewKey.getShapeIndex().getShape(keyMemberId).get().getTrait(SensitiveTrait.class), + assertThat(resultWithNewKey.getShape(keyMemberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(resultWithNewKey.getShapeIndex().getShape(containerId).get().asMapShape().get().getKey(), + assertThat(resultWithNewKey.getShape(containerId).get().asMapShape().get().getKey(), Matchers.is(newKeyMember)); - assertThat(resultWithNewValue.getShapeIndex().getShape(valueMemberId).get().getTrait(SensitiveTrait.class), + assertThat(resultWithNewValue.getShape(valueMemberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); - assertThat(resultWithNewValue.getShapeIndex().getShape(containerId).get().asMapShape().get().getValue(), + assertThat(resultWithNewValue.getShape(containerId).get().asMapShape().get().getValue(), Matchers.is(newValueMember)); } @@ -232,7 +225,7 @@ public void updatesStructureWhenMemberChanges() { .addMember(memberB) .build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, memberA, memberB, container).build()) + .addShapes(target, memberA, memberB, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberB = MemberShape.builder() @@ -241,15 +234,14 @@ public void updatesStructureWhenMemberChanges() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMemberB)); - ShapeIndex index = result.getShapeIndex(); // Make sure the member has the trait that was applied. - assertThat(index.getShape(memberBId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(memberBId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); // Make sure it's still optional. - assertTrue(index.getShape(containerId).get().asStructureShape().get().getMember("b").get().isOptional()); + assertTrue(result.getShape(containerId).get().asStructureShape().get().getMember("b").get().isOptional()); // Ensure that the structure that contains the shape was updated. - assertThat(index.getShape(containerId).get().asStructureShape().get().getMember("b").get(), - Matchers.is(newMemberB)); + assertThat(result.getShape(containerId).get().asStructureShape().get().getMember("b").get(), + Matchers.is(newMemberB)); } @Test @@ -267,23 +259,22 @@ public void canReplaceMultipleMembersOfSameShape() { .addMember(memberB) .build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, memberA, memberB, container).build()) + .addShapes(target, memberA, memberB, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberA = memberA.toBuilder().addTrait(new RequiredTrait(SourceLocation.NONE)).build(); MemberShape newMemberB = memberB.toBuilder().addTrait(new RequiredTrait(SourceLocation.NONE)).build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMemberA, newMemberB)); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(memberAId).get().getTrait(RequiredTrait.class), Matchers.not(Optional.empty())); - assertThat(index.getShape(memberBId).get().getTrait(RequiredTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(memberAId).get().getTrait(RequiredTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(memberBId).get().getTrait(RequiredTrait.class), Matchers.not(Optional.empty())); // Make sure the members got updated inside of the container. - assertTrue(index.getShape(containerId).get() + assertTrue(result.getShape(containerId).get() .asStructureShape().get() .getMember("a").get() .hasTrait(RequiredTrait.class)); - assertTrue(index.getShape(containerId).get() + assertTrue(result.getShape(containerId).get() .asStructureShape().get() .getMember("b").get() .hasTrait(RequiredTrait.class)); @@ -304,7 +295,7 @@ public void updatesTaggedUnionShapeWhenMemberChanges() { .addMember(memberB) .build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, memberA, memberB, container).build()) + .addShapes(target, memberA, memberB, container) .build(); ModelTransformer transformer = ModelTransformer.create(); MemberShape newMemberB = MemberShape.builder() @@ -313,13 +304,12 @@ public void updatesTaggedUnionShapeWhenMemberChanges() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMemberB)); - ShapeIndex index = result.getShapeIndex(); // Make sure the member has the trait that was applied. - assertThat(index.getShape(memberBId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(memberBId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); // Ensure that the union that contains the shape was updated. - assertThat(index.getShape(containerId).get().asUnionShape().get().getMember("b").get(), - Matchers.is(newMemberB)); + assertThat(result.getShape(containerId).get().asUnionShape().get().getMember("b").get(), + Matchers.is(newMemberB)); } @Test @@ -331,7 +321,7 @@ public void doesNotOverwriteOtherContainerUpdatesWhenAlsoUpdatingMembers() { MemberShape member = MemberShape.builder().id(memberId).target(stringId).build(); ListShape container = ListShape.builder().id(containerId).member(member).build(); Model model = Model.builder() - .shapeIndex(ShapeIndex.builder().addShapes(target, member, container).build()) + .addShapes(target, member, container) .build(); ModelTransformer transformer = ModelTransformer.create(); ListShape newContainer = container.toBuilder() @@ -347,14 +337,13 @@ public void doesNotOverwriteOtherContainerUpdatesWhenAlsoUpdatingMembers() { .addTrait(new SensitiveTrait(SourceLocation.NONE)) .build(); Model result = transformer.replaceShapes(model, Arrays.asList(newMember, newContainer)); - ShapeIndex index = result.getShapeIndex(); // Make sure the member has the trait that was applied. - assertThat(index.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); + assertThat(result.getShape(memberId).get().getTrait(SensitiveTrait.class), Matchers.not(Optional.empty())); // Ensure that the list shape changes were not overwritten. - assertThat(index.getShape(containerId).get().asListShape().get().getTrait(LengthTrait.class), + assertThat(result.getShape(containerId).get().asListShape().get().getTrait(LengthTrait.class), Matchers.not(Optional.empty())); // Ensure that the list shape has the new member. - assertThat(index.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); + assertThat(result.getShape(containerId).get().asListShape().get().getMember(), Matchers.is(newMember)); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java index 08d01b96864..87ea6c722b4 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/transform/ScrubTraitDefinitionsTest.java @@ -22,7 +22,6 @@ import org.junit.jupiter.api.Test; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; public class ScrubTraitDefinitionsTest { @@ -35,32 +34,31 @@ public void removesTracesOfTraitDefinitions() { ModelTransformer transformer = ModelTransformer.create(); Model result = transformer.scrubTraitDefinitions(model); - ShapeIndex index = result.getShapeIndex(); - assertThat(index.getShape(ShapeId.from("ns.foo#FooStructure")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#BarString")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#BarStringList")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#ComplexRemoved")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#FooStructure")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#BarString")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#BarStringList")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#ComplexRemoved")), Matchers.is(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#IpsumString")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#IpsumList")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("ns.foo#KeepStructure")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#IpsumString")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#IpsumList")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("ns.foo#KeepStructure")), Matchers.not(Optional.empty())); // Make sure public prelude shapes weren't removed. - assertThat(index.getShape(ShapeId.from("smithy.api#String")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Blob")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Boolean")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Byte")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Short")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Integer")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Long")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Float")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Double")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#BigInteger")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#BigDecimal")), Matchers.not(Optional.empty())); - assertThat(index.getShape(ShapeId.from("smithy.api#Timestamp")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#String")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Blob")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Boolean")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Byte")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Short")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Integer")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Long")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Float")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Double")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#BigInteger")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#BigDecimal")), Matchers.not(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#Timestamp")), Matchers.not(Optional.empty())); // Make sure public prelude trait definition shapes were removed. - assertThat(index.getShape(ShapeId.from("smithy.api#length")), Matchers.is(Optional.empty())); + assertThat(result.getShape(ShapeId.from("smithy.api#length")), Matchers.is(Optional.empty())); } } diff --git a/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java b/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java index 5a7e65d22a0..b057b865631 100644 --- a/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java +++ b/smithy-model/src/test/java/software/amazon/smithy/model/validation/NodeValidationVisitorTest.java @@ -58,11 +58,9 @@ public void nodeValidationVisitorTest(String target, String value, String[] erro Node nodeValue = FACTORY.createNode("N/A", value); NodeValidationVisitor cases = NodeValidationVisitor.builder() .value(nodeValue) - .index(MODEL.getShapeIndex()) + .model(MODEL) .build(); - List events = MODEL.getShapeIndex().getShape(targetId) - .orElseThrow(() -> new IllegalArgumentException("No shape found for " + targetId)) - .accept(cases); + List events = MODEL.expectShape(targetId).accept(cases); if (errors != null) { List messages = events.stream().map(ValidationEvent::getMessage).collect(Collectors.toList()); diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java index 55209ce0984..595d2530789 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/ResolvedTopicIndex.java @@ -28,7 +28,6 @@ import software.amazon.smithy.model.knowledge.OperationIndex; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.ToShapeId; import software.amazon.smithy.model.traits.Trait; @@ -60,11 +59,10 @@ public final class ResolvedTopicIndex implements KnowledgeIndex { public ResolvedTopicIndex(Model model) { // Find all the MQTT topic bindings in the model. - ShapeIndex index = model.getShapeIndex(); EventStreamIndex eventStreamIndex = model.getKnowledge(EventStreamIndex.class); OperationIndex operationIndex = model.getKnowledge(OperationIndex.class); - index.shapes(OperationShape.class).forEach(operation -> { + model.shapes(OperationShape.class).forEach(operation -> { if (operation.hasTrait(PublishTrait.class)) { PublishTrait trait = operation.getTrait(PublishTrait.class).get(); createPublishBindings(operationIndex, operation, trait); diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttPublishInputValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttPublishInputValidator.java index 1d7d2fab6bf..df1d2662461 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttPublishInputValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttPublishInputValidator.java @@ -21,7 +21,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.EventStreamTrait; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; @@ -34,15 +33,14 @@ public class MqttPublishInputValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .filter(shape -> shape.hasTrait(PublishTrait.class)) - .flatMap(shape -> validateOperation(index, shape)) + .flatMap(shape -> validateOperation(model, shape)) .collect(Collectors.toList()); } - private Stream validateOperation(ShapeIndex index, OperationShape operation) { - return OptionalUtils.stream(operation.getInput().flatMap(index::getShape).flatMap(Shape::asStructureShape)) + private Stream validateOperation(Model model, OperationShape operation) { + return OptionalUtils.stream(operation.getInput().flatMap(model::getShape).flatMap(Shape::asStructureShape)) .flatMap(input -> input.getAllMembers().values().stream() .filter(member -> member.hasTrait(EventStreamTrait.class)) .map(member -> error(member, String.format( diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeInputValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeInputValidator.java index d88eddb7112..987c30c8acc 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeInputValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeInputValidator.java @@ -21,7 +21,6 @@ import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.validation.AbstractValidator; import software.amazon.smithy.model.validation.ValidationEvent; import software.amazon.smithy.mqtt.traits.SubscribeTrait; @@ -38,15 +37,14 @@ public final class MqttSubscribeInputValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .filter(shape -> shape.hasTrait(SubscribeTrait.class)) - .flatMap(shape -> validateOperation(index, shape)) + .flatMap(shape -> validateOperation(model, shape)) .collect(Collectors.toList()); } - private Stream validateOperation(ShapeIndex index, OperationShape operation) { - return OptionalUtils.stream(operation.getInput().flatMap(index::getShape).flatMap(Shape::asStructureShape)) + private Stream validateOperation(Model model, OperationShape operation) { + return OptionalUtils.stream(operation.getInput().flatMap(model::getShape).flatMap(Shape::asStructureShape)) .flatMap(input -> input.getAllMembers().values().stream() .filter(member -> !member.hasTrait(TopicLabelTrait.class)) .map(member -> error(member, String.format( diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeOutputValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeOutputValidator.java index ce38bbe4764..ea15d8e739a 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeOutputValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttSubscribeOutputValidator.java @@ -25,7 +25,6 @@ import software.amazon.smithy.model.knowledge.EventStreamInfo; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; @@ -48,16 +47,15 @@ public final class MqttSubscribeOutputValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); EventStreamIndex eventStreamIndex = model.getKnowledge(EventStreamIndex.class); - return index.shapes(OperationShape.class) + return model.shapes(OperationShape.class) .flatMap(shape -> Trait.flatMapStream(shape, SubscribeTrait.class)) - .flatMap(pair -> validateOperation(index, pair.getLeft(), eventStreamIndex).stream()) + .flatMap(pair -> validateOperation(model, pair.getLeft(), eventStreamIndex).stream()) .collect(Collectors.toList()); } private List validateOperation( - ShapeIndex index, + Model model, OperationShape shape, EventStreamIndex eventStreamIndex ) { @@ -78,7 +76,7 @@ private List validateOperation( // Find events in the output's event stream that have members marked // with the eventHeader trait. - getOutputEvents(info, index) + getOutputEvents(info, model) .flatMap(target -> target.getAllMembers().values().stream() .filter(member -> member.hasTrait(EventHeaderTrait.class))) .map(member -> danger(shape, "This member is used as part of an MQTT event stream event, and MQTT " @@ -88,7 +86,7 @@ private List validateOperation( return events; } - private Stream getOutputEvents(EventStreamInfo info, ShapeIndex index) { + private Stream getOutputEvents(EventStreamInfo info, Model model) { return info.getEventStreamTarget().accept(new ShapeVisitor.Default>() { @Override public Stream getDefault(Shape shape) { @@ -98,7 +96,7 @@ public Stream getDefault(Shape shape) { @Override public Stream unionShape(UnionShape shape) { return shape.getAllMembers().entrySet().stream() - .flatMap(member -> OptionalUtils.stream(index.getShape(member.getValue().getTarget()) + .flatMap(member -> OptionalUtils.stream(model.getShape(member.getValue().getTarget()) .flatMap(Shape::asStructureShape))); } diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java index 8f69513e06c..9923b86148d 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttTopicLabelValidator.java @@ -25,7 +25,6 @@ import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.Shape; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.traits.Trait; import software.amazon.smithy.model.validation.AbstractValidator; @@ -49,11 +48,10 @@ public class MqttTopicLabelValidator extends AbstractValidator { @Override public List validate(Model model) { - ShapeIndex index = model.getShapeIndex(); - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .map(MqttTopicLabelValidator::createTopics) .filter(Objects::nonNull) - .flatMap(topics -> validateMqtt(index, topics).stream()) + .flatMap(topics -> validateMqtt(model, topics).stream()) .collect(Collectors.toList()); } @@ -71,10 +69,10 @@ private static TopicCollection createTopics(OperationShape shape) { } } - private List validateMqtt(ShapeIndex index, TopicCollection topics) { + private List validateMqtt(Model model, TopicCollection topics) { Set labels = topics.getLabels(); StructureShape input = topics.operation.getInput() - .flatMap(index::getShape) + .flatMap(model::getShape) .flatMap(Shape::asStructureShape) .orElse(null); diff --git a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttUnsupportedErrorsValidator.java b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttUnsupportedErrorsValidator.java index 50c70c65f4d..bc9e2f62a98 100644 --- a/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttUnsupportedErrorsValidator.java +++ b/smithy-mqtt-traits/src/main/java/software/amazon/smithy/mqtt/traits/validators/MqttUnsupportedErrorsValidator.java @@ -38,7 +38,7 @@ public final class MqttUnsupportedErrorsValidator extends AbstractValidator { @Override public List validate(Model model) { - return model.getShapeIndex().shapes(OperationShape.class) + return model.shapes(OperationShape.class) .filter(shape -> !shape.getErrors().isEmpty()) .flatMap(shape -> OptionalUtils.stream(validateOperation(shape))) .collect(Collectors.toList()); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java index 215b85f75d4..8cb3477ba62 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java @@ -45,7 +45,6 @@ import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; -import software.amazon.smithy.model.shapes.ShapeIndex; import software.amazon.smithy.model.traits.DocumentationTrait; import software.amazon.smithy.model.traits.ExternalDocumentationTrait; import software.amazon.smithy.model.traits.Protocol; @@ -237,7 +236,7 @@ private ConversionEnvironment createConversionEnvironment(Model model, ShapeId s .withMember(JsonSchemaConstants.DEFINITION_POINTER, OpenApiConstants.SCHEMA_COMPONENTS_POINTER); // Find the service shape. - ServiceShape service = model.getShapeIndex().getShape(serviceShapeId) + ServiceShape service = model.getShape(serviceShapeId) .orElseThrow(() -> new IllegalArgumentException(String.format( "Shape `%s` not found in shape index", serviceShapeId))) .asServiceShape() @@ -275,7 +274,7 @@ private ConversionEnvironment createConversionEnvironment(Model model, ShapeId s // Set a protocol name if one wasn't set but instead derived. protocolName = protocolName != null ? protocolName : resolvedProtocol.getName(); ComponentsObject.Builder components = ComponentsObject.builder(); - SchemaDocument schemas = addSchemas(components, model.getShapeIndex(), service); + SchemaDocument schemas = addSchemas(components, model, service); // Load security scheme converters. List securitySchemeConverters = loadSecuritySchemes(service, extensions); @@ -444,10 +443,10 @@ private InfoObject createInfo(ServiceShape service) { // Copies the JSON schema schemas over into the OpenAPI object. private SchemaDocument addSchemas( ComponentsObject.Builder components, - ShapeIndex index, + Model model, ServiceShape service ) { - SchemaDocument document = getJsonSchemaConverter().convert(index, service); + SchemaDocument document = getJsonSchemaConverter().convert(model, service); for (Map.Entry entry : document.getDefinitions().entrySet()) { String key = entry.getKey().replace(OpenApiConstants.SCHEMA_COMPONENTS_POINTER + "/", ""); components.putSchema(key, entry.getValue()); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java index fd5c564cf63..0957c274a41 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/CheckForPrefixHeaders.java @@ -48,7 +48,7 @@ public byte getOrder() { @Override public void before(Context context, OpenApi.Builder builder) { HttpBindingIndex httpBindings = context.getModel().getKnowledge(HttpBindingIndex.class); - context.getModel().getShapeIndex().shapes(OperationShape.class).forEach(operation -> { + context.getModel().shapes(OperationShape.class).forEach(operation -> { check(context, httpBindings.getRequestBindings(operation, HttpBinding.Location.PREFIX_HEADERS)); checkForResponseHeaders(context, httpBindings, operation); operation.getErrors().forEach(error -> checkForResponseHeaders(context, httpBindings, error)); diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java index 742af95baf4..e99d88a8410 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/mappers/UnsupportedTraits.java @@ -44,7 +44,7 @@ public byte getOrder() { @Override public void before(Context context, OpenApi.Builder builder) { - List>> violations = context.getModel().getShapeIndex().shapes() + List>> violations = context.getModel().shapes() .map(shape -> Pair.of(shape.getId(), TRAITS.stream() .filter(trait -> shape.findTrait(trait).isPresent()) .collect(Collectors.toList()))) diff --git a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java index d3360df730b..264b5171c1c 100644 --- a/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java +++ b/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/protocols/AbstractRestProtocol.java @@ -127,7 +127,7 @@ private List createPathParameters(Context context, OperationSha ParameterObject.Builder paramBuilder = ModelUtils.createParameterMember( context, member).in("path"); // Timestamps sent in the URI are serialized as a date-time string by default. - boolean needsInlineSchema = context.getModel().getShapeIndex().getShape(member.getTarget()) + boolean needsInlineSchema = context.getModel().getShape(member.getTarget()) .filter(Shape::isTimestampShape) .isPresent() && !ModelUtils.getMemberTrait(context, member, TimestampFormatTrait.class).isPresent(); @@ -149,8 +149,7 @@ private List createQueryParameters(Context context, OperationSh ParameterObject.Builder param = ModelUtils.createParameterMember(context, binding.getMember()) .in("query") .name(binding.getLocationName()); - Shape target = context.getModel().getShapeIndex() - .getShape(binding.getMember().getTarget()).get(); + Shape target = context.getModel().expectShape(binding.getMember().getTarget()); // List and set shapes in the query string are repeated, so we need to "explode" them. if (target instanceof CollectionShape) { @@ -184,7 +183,7 @@ private Map createHeaderParameters( // Response headers don't use "in" or "name". param.in(null).name(null); } - Shape target = context.getModel().getShapeIndex().getShape(binding.getMember().getTarget()).get(); + Shape target = context.getModel().expectShape(binding.getMember().getTarget()); Schema refSchema = context.createRef(binding.getMember()); param.schema(target.accept(new HeaderSchemaVisitor(context, refSchema, binding.getMember()))); return Pair.of(binding.getLocationName(), param.build()); @@ -352,7 +351,7 @@ public Schema setShape(SetShape shape) { } private Schema collection(CollectionShape collection) { - Shape memberTarget = context.getModel().getShapeIndex().getShape(collection.getMember().getTarget()).get(); + Shape memberTarget = context.getModel().getShape(collection.getMember().getTarget()).get(); String memberPointer = context.getPointer(collection.getMember()); Schema currentMemberSchema = context.getSchema(memberPointer); Schema newMemberSchema = memberTarget.accept( @@ -411,7 +410,7 @@ public Schema setShape(SetShape shape) { } private Schema collection(CollectionShape collection) { - Shape memberTarget = context.getModel().getShapeIndex().getShape(collection.getMember().getTarget()).get(); + Shape memberTarget = context.getModel().expectShape(collection.getMember().getTarget()); String memberPointer = context.getPointer(collection.getMember()); Schema currentMemberSchema = context.getSchema(memberPointer); Schema newMemberSchema = memberTarget.accept(