Skip to content

Commit

Permalink
Add checks to annotation getters. (#5052)
Browse files Browse the repository at this point in the history
* Add annotation error messages.

Signed-off-by: fruffy <[email protected]>

* Check for KVAnnotation instead of deferring to annotationKind().

Signed-off-by: fruffy <[email protected]>

* Use try-catch instead of BUG_CHECK.

Signed-off-by: fruffy <[email protected]>

---------

Signed-off-by: fruffy <[email protected]>
  • Loading branch information
fruffy authored Dec 12, 2024
1 parent 650af7e commit b0f775c
Showing 1 changed file with 50 additions and 9 deletions.
59 changes: 50 additions & 9 deletions ir/base.def
Original file line number Diff line number Diff line change
Expand Up @@ -332,17 +332,58 @@ class Annotation {
Vector<Expression>,
IndexedVector<NamedExpression>> body;

inline auto &getUnparsed() { return std::get<UnparsedAnnotation>(body); }
inline const auto &getUnparsed() const { return std::get<UnparsedAnnotation>(body); }
inline auto &getExpr() { return std::get<ExpressionAnnotation>(body); }
inline const auto &getExpr() const { return std::get<ExpressionAnnotation>(body); }
inline auto &getUnparsed() {
try {
return std::get<UnparsedAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation has been parsed already.");
}
}
inline const auto &getUnparsed() const {
try {
return std::get<UnparsedAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation has been parsed already.");
}
}
inline auto &getExpr() {
try {
return std::get<ExpressionAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation does not contain an expression list.");
}
}
inline const auto &getExpr() const {
try {
return std::get<ExpressionAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation does not contain an expression list.");
}
}
inline Expression getExpr(size_t idx) const {
const auto &expr = getExpr();
BUG_CHECK(idx < expr.size(), "invalid annotation expression index");
return expr[idx];
try {
const auto &expr = getExpr();
return expr[idx];
} catch (const std::out_of_range &) {
BUG("invalid annotation expression index");
} catch (const std::bad_variant_access &) {
BUG("Annotation does not contain an expression list.");
}
}
inline auto &getKV() {
try {
return std::get<KVAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation does not contain a key-value list.");
}
}
inline const auto &getKV() const {
try {
return std::get<KVAnnotation>(body);
} catch (const std::bad_variant_access &) {
BUG("Annotation does not contain a key-value list.");
}
}
inline auto &getKV() { return std::get<KVAnnotation>(body); }
inline const auto &getKV() const { return std::get<KVAnnotation>(body); }

/// If this is true this is a structured annotation, and there are some
/// constraints on its contents.
Expand Down

0 comments on commit b0f775c

Please sign in to comment.