Skip to content

Commit

Permalink
Warn when default used with union member target
Browse files Browse the repository at this point in the history
This NOTE warning makes it clear to modelers that default values on the
target shape of a union member are ignored.
  • Loading branch information
mtdowling authored and Michael Dowling committed Sep 21, 2022
1 parent 53aa9d7 commit e2c9e28
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
import java.util.ArrayList;
import java.util.List;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.shapes.MemberShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.UnionShape;
import software.amazon.smithy.model.traits.DefaultTrait;
import software.amazon.smithy.model.validation.AbstractValidator;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.utils.SmithyInternalApi;
Expand All @@ -31,6 +35,17 @@ public List<ValidationEvent> validate(Model model) {
for (UnionShape union : model.getUnionShapes()) {
if (union.members().isEmpty()) {
events.add(error(union, "Tagged unions must have one or more members"));
} else {
for (MemberShape member : union.getAllMembers().values()) {
Shape target = model.expectShape(member.getTarget());
if (target.hasTrait(DefaultTrait.class)) {
events.add(note(member, String.format(
"This union member targets `%s`, a shape with a default value of `%s`. Note that "
+ "default values are only applicable to structures and ignored in tagged unions. It "
+ "is a best practice for union members to target shapes with no default value.",
target.getId(), Node.printJson(target.expectTrait(DefaultTrait.class).toNode()))));
}
}
}
}
return events;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[NOTE] smithy.example#Example$foo: This union member targets `smithy.api#PrimitiveInteger`, a shape with a default value of `0`. Note that default values are only applicable to structures and ignored in tagged unions. It is a best practice for union members to target shapes with no default value. | Union
[NOTE] smithy.example#Example$bar: This union member targets `smithy.api#PrimitiveBoolean`, a shape with a default value of `false`. Note that default values are only applicable to structures and ignored in tagged unions. It is a best practice for union members to target shapes with no default value. | Union
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
$version: "2.0"

namespace smithy.example

union Example {
foo: PrimitiveInteger, // warn
foo2: Integer, // dont' warn
bar: PrimitiveBoolean, // warn
baz: String // don't warn
}

0 comments on commit e2c9e28

Please sign in to comment.