You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/07/07 01:09:32 UTC
(groovy) branch master updated: GROOVY-12135: groovy-contracts: Add a ThrowsIf annotation
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new 7b3c77f788 GROOVY-12135: groovy-contracts: Add a ThrowsIf annotation
7b3c77f788 is described below
commit 7b3c77f78818579d4ff193f6abfdb6a2462a81c6
Author: Paul King <pa...@asert.com.au>
AuthorDate: Tue Jul 7 08:05:35 2026 +1000
GROOVY-12135: groovy-contracts: Add a ThrowsIf annotation
---
.../src/main/java/groovy/contracts/ThrowsIf.java | 201 ++++++++
.../java/groovy/contracts/ThrowsIfConditions.java | 45 ++
.../apache/groovy/contracts/ThrowsIfSupport.java | 94 ++++
.../apache/groovy/contracts/ThrowsIfViolation.java | 105 +++++
.../contracts/ast/ThrowsIfASTTransformation.java | 287 +++++++++++
.../src/spec/doc/contracts-userguide.adoc | 127 +++++
.../src/spec/test/ContractsTest.groovy | 75 +++
.../contracts/tests/other/ThrowsIfTests.groovy | 522 +++++++++++++++++++++
8 files changed, 1456 insertions(+)
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIf.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIf.java
new file mode 100644
index 0000000000..8ea56d299a
--- /dev/null
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIf.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.contracts;
+
+import org.apache.groovy.lang.annotation.Incubating;
+import org.codehaus.groovy.transform.GroovyASTTransformationClass;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Represents a method's <b>exceptional contract</b>: the method throws the given
+ * exception when the given condition holds on entry.
+ * <pre>
+ * {@code @ThrowsIf}(value = { b == 0 }, exception = ArithmeticException)
+ * int divide(int a, int b) { a.intdiv(b) }
+ * </pre>
+ * <p>
+ * This is the exceptional counterpart of {@link Requires}: a precondition says
+ * <em>the caller must not do this</em> (violating it is the caller's bug), whereas
+ * a {@code @ThrowsIf} arm says <em>this input is handled, by throwing</em> — it is
+ * <b>defined behaviour</b>, part of the contract, that callers may rely on (and
+ * catch). The condition is a closure over the method's parameters, using the same
+ * conventions as {@link Requires}.
+ * <p>
+ * <b>Weaving.</b> With the default {@code woven = true} the guard-throw is
+ * <em>generated</em> at method entry — the general form of the pattern
+ * {@code groovy.transform.NullCheck} provides for the null-check special case —
+ * so the annotation is the implementation, not a comment about one:
+ * <pre>
+ * if (b == 0) throw new ArithmeticException(...) // inserted; message derived from the condition
+ * </pre>
+ * On a constructor whose first statement is an explicit {@code super(...)} or
+ * {@code this(...)} call, the guard is inserted immediately <em>after</em> that
+ * call, which must stay first — a language constraint.
+ * <p>
+ * With {@code woven = false} nothing is generated: the throw already exists.
+ * <em>Where</em> it exists is the {@code direct} member — pure information for
+ * readers and tools, with no effect on bytecode. {@code direct = true} (the
+ * default): a hand-written {@code throw} statement lives in this body — checkable
+ * documentation of a guard that is already there. {@code direct = false}: the
+ * exception arises from code this method <em>executes</em> — a call, possibly
+ * transitively (a third-party library), or a runtime operation — so there is no
+ * throw statement in this body to find (and weaving a wrong specification about
+ * invoked code would silently change behaviour, which is why such arms are
+ * spelled {@code woven = false}). For woven code {@code direct} is implicitly
+ * true and the member is ignored — most users never set it; a tool that cannot
+ * find the promised throw in the body is the usual prompt to add
+ * {@code direct = false}. The attributes are per-arm because real methods mix
+ * modes:
+ * <pre>
+ * {@code @ThrowsIf}(value = { x == null }, exception = NullPointerException) // woven for x
+ * {@code @ThrowsIf}(value = { y == null }, exception = NullPointerException, woven = false) // body guards y
+ * Object process(Object x, Object y) { ... }
+ * </pre>
+ * <p>
+ * <b>Semantics.</b> Read as an <b>iff</b> by default: the method throws a matching
+ * exception <em>exactly when</em> some arm's condition holds — each arm is a
+ * <em>must-throw</em> (condition on entry ⇒ the method throws, not returns),
+ * and the arm-set as a whole claims <em>only-when</em> (a matching throw ⇒
+ * some arm's condition held). {@code exhaustive = false} disclaims the only-when
+ * half for the whole arm-set (a one-directional, JML {@code signals}-style arm):
+ * the condition is <em>sufficient</em> for the throw but the set does not claim to
+ * list every reason — useful when the full condition is inexpressible (for
+ * example, {@code Integer.parseInt}: {@code s == null} is a true sufficient
+ * condition, while "malformed or out of range" is not reasonably a parameter
+ * closure). Note what neither mode claims: exhaustiveness is (at most) over the
+ * <em>conditions for the exception types mentioned</em>, never over exception
+ * types themselves — declaring an {@code ArithmeticException} arm says nothing
+ * about whether the method can throw anything else. And no claim, however
+ * exhaustive, reasons about VM resource conditions: an {@code OutOfMemoryError}
+ * or {@code StackOverflowError} is outside contract semantics — the checked
+ * wrapper passes any {@link VirtualMachineError} through unjudged, whatever the
+ * arm types.
+ * <p>
+ * <b>Checking.</b> Weaving <em>implements</em> the contract; {@code checked = true}
+ * additionally <em>verifies</em> it at runtime, in the same assertion style as
+ * {@link Ensures}: on a normal return, no non-woven arm's condition may have held
+ * (must-throw), and an escaping exception matching some arm's type must be
+ * justified by a matching arm's condition having held on entry (only-when —
+ * checked only for {@code exhaustive} arm-sets). A broken implementation raises
+ * {@link org.apache.groovy.contracts.ThrowsIfViolation} — never the declared
+ * exception, which is defined behaviour delivered at entry; a justified throw
+ * always propagates untouched. {@code checked} is <em>set-level</em>: if any arm
+ * is {@code checked}, the whole arm-set is checked — every non-woven arm is
+ * must-throw checked, and every arm serves as an only-when justifier (a sibling
+ * cannot silently opt out). A pleasant corollary:
+ * {@code woven = false, direct = false} plus {@code checked = true}
+ * runtime-validates a claim about invoked third-party code — a wrong
+ * specification is exposed, not silently believed.
+ * <p>
+ * The annotation is runtime-retained and repeatable, so the exceptional contract
+ * is structured metadata available to documentation generators, static analysers,
+ * verification tools, and AI coding agents — none of which can reliably consume
+ * javadoc prose or discover guarded throw sites by body traversal. Only the
+ * must-throw guard of a woven arm and the {@code checked} wrapper affect
+ * generated code; {@code exception}, {@code exhaustive} and {@code direct} are
+ * otherwise consumed by tools.
+ *
+ * @since 6.0.0
+ * @see Requires
+ * @see ThrowsIfConditions
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
+@Incubating
+@Repeatable(ThrowsIfConditions.class)
+@GroovyASTTransformationClass("org.apache.groovy.contracts.ast.ThrowsIfASTTransformation")
+public @interface ThrowsIf {
+ /**
+ * Returns the closure class that evaluates the throw condition, a boolean
+ * expression over the method's parameters.
+ *
+ * @return the generated closure class backing the condition
+ */
+ Class value();
+
+ /**
+ * The exception type thrown when the condition holds. A woven arm generates
+ * {@code new <exception>(String)}, so the type should provide a
+ * {@code (String)} constructor (all the standard JDK exceptions do).
+ *
+ * @return the exception type
+ */
+ Class<? extends Throwable> exception() default Throwable.class;
+
+ /**
+ * {@code true} (default): generate the guard-throw at method entry.
+ * {@code false}: the throw already exists (see {@code direct} for where) —
+ * nothing is generated.
+ *
+ * @return whether the guard is generated
+ */
+ boolean woven() default true;
+
+ /**
+ * Information for readers and tools, with no effect on bytecode; ignored
+ * (implicitly {@code true}) for woven arms. {@code true} (default): a
+ * hand-written {@code throw} statement lives in this body. {@code false}:
+ * the exception arises from code this method executes — a call, possibly
+ * transitively, or a runtime operation — so there is no throw statement in
+ * this body to find. Most users never set this; a verification or analysis
+ * tool unable to find the promised throw in the body is the usual prompt.
+ *
+ * @return whether the body itself contains the throw
+ */
+ boolean direct() default true;
+
+ /**
+ * No effect on generated code by itself. Under {@code checked = true} it
+ * gates the escaping-throw check: {@code true} (default) claims the listed
+ * conditions are the <em>only</em> reasons a matching exception is thrown,
+ * so an escaping match with no condition held is a
+ * {@link org.apache.groovy.contracts.ThrowsIfViolation}; {@code false}
+ * says the method may throw the same exception for other, unlisted reasons
+ * — escaping throws are never judged (and verification tools likewise skip
+ * the only-when direction). One {@code false} arm disclaims the check for
+ * the whole arm-set. In specification terms: {@code true} is an iff,
+ * {@code false} a one-directional (JML {@code signals}-style) sufficient
+ * condition — the honest choice when the full condition is unstatable
+ * ({@code Integer.parseInt}: {@code s == null} is a true sufficient half;
+ * "malformed or out of range" is not a parameter closure).
+ *
+ * @return whether the arm-set claims to list every reason a matching
+ * exception is thrown
+ */
+ boolean exhaustive() default true;
+
+ /**
+ * {@code true}: verify the contract at runtime in the assertion style of
+ * {@link Ensures} — a normal return with a non-woven arm's condition held, or
+ * an unjustified escaping throw of a matching type ({@code exhaustive}
+ * arm-sets only), raises a
+ * {@link org.apache.groovy.contracts.ThrowsIfViolation}. {@code false}
+ * (default): no runtime checking beyond any {@code WOVEN} guard.
+ *
+ * @return whether the contract is runtime-checked
+ */
+ boolean checked() default false;
+}
diff --git a/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIfConditions.java b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIfConditions.java
new file mode 100644
index 0000000000..247496fc4d
--- /dev/null
+++ b/subprojects/groovy-contracts/src/main/java/groovy/contracts/ThrowsIfConditions.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package groovy.contracts;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Container annotation for multiple {@link ThrowsIf} arms on the same target.
+ * Synthesized by the compiler from stacked {@code @ThrowsIf} annotations via
+ * {@link java.lang.annotation.Repeatable}; not normally written by hand.
+ *
+ * @since 6.0.0
+ * @see ThrowsIf
+ */
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
+public @interface ThrowsIfConditions {
+ /**
+ * Returns the repeated exceptional-contract arms declared on the target element.
+ *
+ * @return the contained {@link ThrowsIf} annotations
+ */
+ ThrowsIf[] value();
+}
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfSupport.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfSupport.java
new file mode 100644
index 0000000000..0fbc3c7389
--- /dev/null
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfSupport.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.contracts;
+
+/**
+ * Runtime support for {@code checked} {@code @ThrowsIf} arm-sets (invoked from
+ * generated code; not intended to be called by user code). The checks report a
+ * broken contract <em>implementation</em> as a {@link ThrowsIfViolation} — never
+ * as the arm's declared exception, which is defined behaviour delivered at method
+ * entry.
+ *
+ * @since 6.0.0
+ * @see ThrowsIfViolation
+ */
+public final class ThrowsIfSupport {
+
+ private ThrowsIfSupport() {
+ }
+
+ /**
+ * The <em>only-when</em> check, run when the method body throws: a throwable
+ * matching some arm's exception type must be justified by some matching arm's
+ * condition having held on entry. A justified (or unmatched, or
+ * non-{@code exhaustive}) throwable is returned for rethrow — defined
+ * behaviour propagates untouched.
+ * <p>
+ * {@link VirtualMachineError}s ({@code OutOfMemoryError}, {@code StackOverflowError},
+ * ...) are never judged, whatever the arm types: a VM resource condition is outside
+ * contract semantics — no {@code @ThrowsIf} claim, however {@code exhaustive}, reasons
+ * about it — so it always propagates untouched.
+ *
+ * @param thrown the throwable escaping the method body
+ * @param held per-arm: whether the arm's condition held on entry
+ * @param types per-arm: the arm's declared exception type
+ * @param conditions per-arm: the arm's condition text (for the violation message)
+ * @param exhaustive whether the whole arm-set claims exhaustiveness (an iff);
+ * one-directional arm-sets are never only-when checked
+ * @return {@code thrown}, for rethrow, when it is in-contract
+ * @throws ThrowsIfViolation when {@code thrown} matches an arm's type but no
+ * matching arm's condition held
+ */
+ public static Throwable onlyWhen(final Throwable thrown, final boolean[] held, final Class<?>[] types,
+ final String[] conditions, final boolean exhaustive) {
+ if (!exhaustive || thrown instanceof AssertionViolation || thrown instanceof VirtualMachineError) {
+ return thrown;
+ }
+ boolean typeMatched = false;
+ for (int i = 0; i < types.length; i++) {
+ if (types[i].isInstance(thrown)) {
+ if (held[i]) return thrown; // justified: defined behaviour, propagate
+ typeMatched = true;
+ }
+ }
+ if (typeMatched) {
+ throw new ThrowsIfViolation("@ThrowsIf violated: threw " + thrown.getClass().getSimpleName()
+ + " although no matching condition holds (conditions: " + String.join("; ", conditions) + ")");
+ }
+ return thrown; // an exception type no arm mentions — outside the declared contract
+ }
+
+ /**
+ * The <em>must-throw</em> check, run when the method body completes normally:
+ * no unwoven arm's condition may have held on entry (a woven arm's guard makes
+ * this unreachable for that arm by construction).
+ *
+ * @param held per-unwoven-arm: whether the arm's condition held on entry
+ * @param conditions per-unwoven-arm: the arm's condition text (for the violation message)
+ * @throws ThrowsIfViolation when some condition held and the method nevertheless returned
+ */
+ public static void mustThrow(final boolean[] held, final String[] conditions) {
+ for (int i = 0; i < held.length; i++) {
+ if (held[i]) {
+ throw new ThrowsIfViolation("@ThrowsIf violated: returned normally although the condition holds: "
+ + conditions[i]);
+ }
+ }
+ }
+}
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfViolation.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfViolation.java
new file mode 100644
index 0000000000..b307576ff0
--- /dev/null
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ThrowsIfViolation.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.contracts;
+
+/**
+ * Thrown whenever a {@code @ThrowsIf} exceptional-contract violation is detected
+ * by a {@code checked} arm-set: the method returned normally although a
+ * must-throw condition held, or threw a matching exception although no arm's
+ * condition held (the latter checked only for {@code exhaustive} arm-sets).
+ * <p>
+ * Deliberately <em>not</em> the arm's declared exception: the declared exception
+ * is defined behaviour delivered at method entry, whereas this violation reports
+ * a broken <em>implementation</em> of the contract — late-throwing the declared
+ * exception would masquerade the bug as defined behaviour.
+ *
+ * @see AssertionViolation
+ * @since 6.0.0
+ */
+public class ThrowsIfViolation extends AssertionViolation {
+
+ /**
+ * Creates a throws-if violation without an explicit detail message.
+ */
+ public ThrowsIfViolation() {
+ }
+
+ /**
+ * Creates a throws-if violation with an object-valued detail.
+ *
+ * @param o the detail object
+ */
+ public ThrowsIfViolation(Object o) {
+ super(o);
+ }
+
+ /**
+ * Creates a throws-if violation with a boolean detail.
+ *
+ * @param b the detail value
+ */
+ public ThrowsIfViolation(boolean b) {
+ super(b);
+ }
+
+ /**
+ * Creates a throws-if violation with a char detail.
+ *
+ * @param c the detail value
+ */
+ public ThrowsIfViolation(char c) {
+ super(c);
+ }
+
+ /**
+ * Creates a throws-if violation with an int detail.
+ *
+ * @param i the detail value
+ */
+ public ThrowsIfViolation(int i) {
+ super(i);
+ }
+
+ /**
+ * Creates a throws-if violation with a long detail.
+ *
+ * @param l the detail value
+ */
+ public ThrowsIfViolation(long l) {
+ super(l);
+ }
+
+ /**
+ * Creates a throws-if violation with a float detail.
+ *
+ * @param f the detail value
+ */
+ public ThrowsIfViolation(float f) {
+ super(f);
+ }
+
+ /**
+ * Creates a throws-if violation with a double detail.
+ *
+ * @param d the detail value
+ */
+ public ThrowsIfViolation(double d) {
+ super(d);
+ }
+}
diff --git a/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/ThrowsIfASTTransformation.java b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/ThrowsIfASTTransformation.java
new file mode 100644
index 0000000000..d2d5d1131a
--- /dev/null
+++ b/subprojects/groovy-contracts/src/main/java/org/apache/groovy/contracts/ast/ThrowsIfASTTransformation.java
@@ -0,0 +1,287 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.contracts.ast;
+
+import groovy.contracts.ThrowsIf;
+import org.apache.groovy.contracts.ThrowsIfSupport;
+import org.codehaus.groovy.ast.ASTNode;
+import org.codehaus.groovy.ast.AnnotationNode;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.MethodNode;
+import org.codehaus.groovy.ast.Parameter;
+import org.codehaus.groovy.ast.expr.ArrayExpression;
+import org.codehaus.groovy.ast.expr.ClassExpression;
+import org.codehaus.groovy.ast.expr.ClosureExpression;
+import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
+import org.codehaus.groovy.ast.expr.ConstantExpression;
+import org.codehaus.groovy.ast.expr.Expression;
+import org.codehaus.groovy.ast.expr.VariableExpression;
+import org.codehaus.groovy.ast.stmt.BlockStatement;
+import org.codehaus.groovy.ast.stmt.CatchStatement;
+import org.codehaus.groovy.ast.stmt.ExpressionStatement;
+import org.codehaus.groovy.ast.stmt.Statement;
+import org.codehaus.groovy.ast.stmt.TryCatchStatement;
+import org.codehaus.groovy.control.CompilePhase;
+import org.codehaus.groovy.control.SourceUnit;
+import org.codehaus.groovy.transform.ASTTransformation;
+import org.codehaus.groovy.transform.GroovyASTTransformation;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.codehaus.groovy.ast.tools.GeneralUtils.args;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.assignS;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.block;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.boolX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.classX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.constX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.declS;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.equalsNullX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.ifS;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.nullX;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.throwS;
+import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
+
+/**
+ * Handles a method's {@link ThrowsIf} arm-set. Processed once per method (the
+ * transformation fires per annotation, so repeats are deduplicated via node
+ * metadata) because the semantics are per-<em>set</em>: guards are generated in
+ * declaration order, and the {@code checked} wrapper judges an escaping throw
+ * against <em>every</em> arm.
+ * <p>
+ * For each {@code WOVEN}-origin arm the guard-throw is generated at method
+ * entry, so that conceptually:
+ * <pre>
+ * @ThrowsIf(value = { b == 0 }, exception = ArithmeticException)
+ * int divide(int a, int b) { a.intdiv(b) }
+ * </pre>
+ * compiles as:
+ * <pre>
+ * int divide(int a, int b) {
+ * if (b == 0) throw new ArithmeticException('@ThrowsIf: b == 0')
+ * a.intdiv(b)
+ * }
+ * </pre>
+ * — the general form of the pattern {@code groovy.transform.NullCheck} provides
+ * for the null-check special case. Arms with {@code woven = false} generate no
+ * guard — the throw already exists, in the body ({@code direct = true}, the
+ * default) or in invoked code ({@code direct = false}); identical bytecode, the
+ * {@code direct} distinction is information for tools and is not read here.
+ * <p>
+ * When any arm is {@code checked}, the conditions are additionally snapshot on
+ * entry and the body is wrapped so that, conceptually:
+ * <pre>
+ * boolean $c0 = <cond0>; ... // entry snapshot, every arm
+ * if ($c0) throw new E0(...) // woven arms, in declaration order
+ * Throwable $t = null
+ * try { <original body> }
+ * catch (Throwable caught) {
+ * $t = caught
+ * throw ThrowsIfSupport.onlyWhen(caught, [$c0, ...], [E0, ...], [texts], allExhaustive)
+ * } finally {
+ * if ($t == null) ThrowsIfSupport.mustThrow([unwoven $ci ...], [texts]) // normal return only
+ * }
+ * </pre>
+ * A justified throw propagates untouched (defined behaviour); a broken
+ * implementation raises {@link org.apache.groovy.contracts.ThrowsIfViolation},
+ * never the declared exception. Non-woven arms with no {@code checked} flag
+ * anywhere generate nothing — runtime-retained metadata for tools.
+ *
+ * @since 6.0.0
+ * @see ThrowsIf
+ * @see ThrowsIfSupport
+ */
+@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
+public class ThrowsIfASTTransformation implements ASTTransformation {
+
+ private static final String PROCESSED_KEY = "org.apache.groovy.contracts.THROWS_IF_PROCESSED";
+ private static final ClassNode THROWS_IF_TYPE = ClassHelper.make(ThrowsIf.class);
+ private static final ClassNode SUPPORT_TYPE = ClassHelper.make(ThrowsIfSupport.class);
+ private static final AtomicLong COUNTER = new AtomicLong();
+
+ /** One parsed arm of the method's {@code @ThrowsIf} set. */
+ private static final class Arm {
+ Expression condition;
+ String conditionText;
+ ClassNode exceptionType;
+ boolean woven; // non-woven arms generate no guard (`direct` is tool metadata, unread here)
+ boolean checked;
+ boolean exhaustive;
+ }
+
+ @Override
+ public void visit(final ASTNode[] nodes, final SourceUnit source) {
+ if (nodes.length != 2) return;
+ if (!(nodes[0] instanceof AnnotationNode)) return;
+ if (!(nodes[1] instanceof MethodNode method)) return; // covers constructors (ConstructorNode)
+ if (method.isAbstract() || method.getCode() == null) return;
+ if (method.getNodeMetaData(PROCESSED_KEY) != null) return; // per-set semantics: fire once
+ method.putNodeMetaData(PROCESSED_KEY, Boolean.TRUE);
+
+ List<Arm> arms = collectArms(method);
+ if (arms.isEmpty()) return;
+
+ boolean anyChecked = arms.stream().anyMatch(a -> a.checked);
+ // A constructor's explicit super(...)/this(...) must stay the FIRST statement (else Groovy
+ // stops recognising it as the special call and inserts an implicit super()): split it off,
+ // weave into the remainder, and re-attach it up front. The guard consequently runs just
+ // after the explicit constructor call — a language constraint, documented on the annotation.
+ Statement specialCall = null;
+ Statement originalBody = method.getCode();
+ if (originalBody instanceof BlockStatement blockStatement && !blockStatement.getStatements().isEmpty()
+ && isSpecialConstructorCall(blockStatement.getStatements().get(0))) {
+ specialCall = blockStatement.getStatements().get(0);
+ BlockStatement remainder = new BlockStatement(
+ new ArrayList<>(blockStatement.getStatements().subList(1, blockStatement.getStatements().size())),
+ blockStatement.getVariableScope());
+ remainder.setSourcePosition(blockStatement);
+ originalBody = remainder;
+ }
+ List<Statement> prologue = new ArrayList<>();
+ if (specialCall != null) prologue.add(specialCall);
+ String suffix = Long.toString(COUNTER.getAndIncrement());
+
+ if (!anyChecked) {
+ // Guards only, in declaration order.
+ int before = prologue.size();
+ for (Arm arm : arms) {
+ if (arm.woven) prologue.add(guardFor(arm, arm.condition.transformExpression(e -> e)));
+ }
+ if (prologue.size() == before) return; // nothing woven, nothing checked — metadata only
+ prologue.add(originalBody);
+ } else {
+ // Snapshot every arm's condition on entry (the only-when judgement needs all of them),
+ // reuse the snapshots for the woven guards, then wrap the body with the checks.
+ List<Expression> heldVars = new ArrayList<>();
+ for (int i = 0; i < arms.size(); i++) {
+ VariableExpression held = localVarX("$_gc_ti_c" + i + "_" + suffix, ClassHelper.boolean_TYPE);
+ prologue.add(declS(held, boolX(arms.get(i).condition.transformExpression(e -> e))));
+ heldVars.add(varX(held));
+ }
+ for (int i = 0; i < arms.size(); i++) {
+ Arm arm = arms.get(i);
+ if (arm.woven) prologue.add(guardFor(arm, heldVars.get(i)));
+ }
+ boolean allExhaustive = arms.stream().allMatch(a -> a.exhaustive);
+ List<Expression> types = new ArrayList<>();
+ List<Expression> texts = new ArrayList<>();
+ List<Expression> unwovenHeld = new ArrayList<>();
+ List<Expression> unwovenTexts = new ArrayList<>();
+ for (int i = 0; i < arms.size(); i++) {
+ Arm arm = arms.get(i);
+ types.add(classX(arm.exceptionType));
+ texts.add(constX(arm.conditionText));
+ if (!arm.woven) { // checked is SET-level: every non-woven arm is must-throw
+ // checked (woven arms hold must-throw by construction) — a sibling must not
+ // silently opt out while still serving as an only-when justifier
+ unwovenHeld.add(heldVars.get(i));
+ unwovenTexts.add(constX(arm.conditionText));
+ }
+ }
+ VariableExpression thrown = localVarX("$_gc_ti_t_" + suffix, ClassHelper.make(Throwable.class));
+ prologue.add(declS(thrown, nullX()));
+ Parameter caught = new Parameter(ClassHelper.make(Throwable.class), "$_gc_ti_caught_" + suffix);
+ Statement catchBody = block(
+ assignS(varX(thrown), varX(caught)),
+ throwS(callX(SUPPORT_TYPE, "onlyWhen", args(
+ varX(caught),
+ arrayOf(ClassHelper.boolean_TYPE, heldVars),
+ arrayOf(ClassHelper.CLASS_Type.getPlainNodeReference(), types),
+ arrayOf(ClassHelper.STRING_TYPE, texts),
+ constX(allExhaustive, true)))));
+ Statement finallyBody = ifS(equalsNullX(varX(thrown)),
+ stmt(callX(SUPPORT_TYPE, "mustThrow", args(
+ arrayOf(ClassHelper.boolean_TYPE, unwovenHeld),
+ arrayOf(ClassHelper.STRING_TYPE, unwovenTexts)))));
+ TryCatchStatement wrapper = new TryCatchStatement(originalBody, block(finallyBody));
+ wrapper.addCatch(new CatchStatement(caught, catchBody));
+ prologue.add(wrapper);
+ }
+
+ BlockStatement newBody = block(prologue.toArray(Statement[]::new));
+ newBody.setSourcePosition(originalBody);
+ method.setCode(newBody);
+
+ // The conditions' variable references came from annotation closures and may not have been
+ // resolved; re-run scope analysis now that they are real method-body expressions so
+ // @TypeChecked/@CompileStatic can see declared types.
+ LoopContractSupport.resolveVariableScopes(source);
+ }
+
+ /** All well-formed {@code @ThrowsIf} arms on the method, in declaration order. */
+ private static List<Arm> collectArms(final MethodNode method) {
+ List<Arm> arms = new ArrayList<>();
+ for (AnnotationNode annotation : method.getAnnotations(THROWS_IF_TYPE)) {
+ Expression value = annotation.getMember("value");
+ if (!(value instanceof ClosureExpression closureExpression)) continue;
+ Expression condition = MethodVariantASTTransformation.extractExpression(closureExpression);
+ if (condition == null) continue;
+ Arm arm = new Arm();
+ arm.condition = condition;
+ arm.conditionText = condition.getText();
+ arm.exceptionType = exceptionType(annotation);
+ arm.woven = !isFalse(annotation.getMember("woven"));
+ arm.checked = isTrue(annotation.getMember("checked"));
+ arm.exhaustive = !isFalse(annotation.getMember("exhaustive"));
+ arms.add(arm);
+ }
+ return arms;
+ }
+
+ /** {@code if (<held>) throw new <exception>('@ThrowsIf: <condition>')} */
+ private static Statement guardFor(final Arm arm, final Expression held) {
+ Statement guard = ifS(boolX(held),
+ throwS(ctorX(arm.exceptionType, args(constX("@ThrowsIf: " + arm.conditionText)))));
+ guard.setSourcePosition(arm.condition);
+ return guard;
+ }
+
+ /** True when the statement is a constructor's explicit {@code super(...)}/{@code this(...)} call. */
+ private static boolean isSpecialConstructorCall(final Statement statement) {
+ return statement instanceof ExpressionStatement expressionStatement
+ && expressionStatement.getExpression() instanceof ConstructorCallExpression call
+ && call.isSpecialCall();
+ }
+
+ private static Expression arrayOf(final ClassNode elementType, final List<Expression> elements) {
+ return new ArrayExpression(elementType, elements);
+ }
+
+ private static ClassNode exceptionType(final AnnotationNode annotation) {
+ Expression member = annotation.getMember("exception");
+ if (member instanceof ClassExpression classExpression) {
+ return classExpression.getType();
+ }
+ return ClassHelper.make(Throwable.class);
+ }
+
+ private static boolean isTrue(final Expression e) {
+ return e instanceof ConstantExpression constant && Boolean.TRUE.equals(constant.getValue());
+ }
+
+ private static boolean isFalse(final Expression e) {
+ return e instanceof ConstantExpression constant && Boolean.FALSE.equals(constant.getValue());
+ }
+}
diff --git a/subprojects/groovy-contracts/src/spec/doc/contracts-userguide.adoc b/subprojects/groovy-contracts/src/spec/doc/contracts-userguide.adoc
index 6629c01f9a..2a1fbf83f0 100644
--- a/subprojects/groovy-contracts/src/spec/doc/contracts-userguide.adoc
+++ b/subprojects/groovy-contracts/src/spec/doc/contracts-userguide.adoc
@@ -270,6 +270,133 @@ parameter names re-mapped to the override's); an override may declare its own
same unit; an override of a method from a precompiled (binary) supertype is not yet
instrumented.
+== Exceptional contracts with @ThrowsIf
+
+`@ThrowsIf` declares a method's _exceptional contract_: the method throws the given
+exception when the given condition holds on entry. It is the exceptional counterpart
+of `@Requires` — a precondition says _the caller must not do this_ (violating it
+is the caller's bug), whereas a `@ThrowsIf` arm says _this input is handled, by
+throwing_: it is *defined behaviour*, part of the contract, that callers may rely on
+(and catch). Guard clauses of this shape are among the most common contract-shaped
+code written by hand (`if (b == 0) throw ...`, `Objects.requireNonNull(y)`,
+Guava's `Preconditions`); `@ThrowsIf` makes that behaviour a first-class,
+machine-readable annotation. The condition is a closure over the method's
+parameters, using the same conventions as `@Requires`, and the annotation is
+repeatable — each _arm_ pairs one condition with one exception type.
+
+The contract is read as an _iff_: the method throws a matching exception _exactly
+when_ some arm's condition holds. Two attributes generate code; the others are
+runtime-retained metadata for readers and tools (documentation generators, static
+analysers, verifiers, AI coding agents):
+
+[cols="1,4"]
+|===
+|Member |Effect on generated code
+
+|`woven`
+|`true` (default): the guard — `if (cond) throw new E(...)` — is inserted at
+method entry (the general form of the pattern `groovy.transform.NullCheck` provides
+for the null-check special case). `false`: nothing is generated — the throw
+already exists.
+
+|`checked`
+|`true`: a verification wrapper is generated (see below). `false` (default): nothing.
+
+|`exception`
+|The type the woven guard constructs (it should provide a `(String)` constructor, as
+the standard exceptions do), and the type the checked wrapper matches escaping throws
+against.
+
+|`exhaustive`
+|Nothing on its own. Under `checked = true` it gates the escaping-throw check:
+`false` says the method may throw the same exception for other, unlisted reasons, so
+escaping throws are never judged.
+
+|`direct`
+|Nothing, ever — pure information: `true` (default) says a hand-written `throw`
+statement lives in this body; `false` says the exception arises from code the method
+_executes_ (a call, possibly transitive, or a runtime operation), so there is no
+throw statement in this body to find. Ignored (implicitly `true`) for woven arms.
+This is documentation for a human reader but exists primarily for tools - if you
+are not using a tool that needs it, you can safely ignore it.
+|===
+
+=== Woven guards
+
+With the defaults, the annotation _is_ the guard:
+
+[source,groovy]
+----
+include::../test/ContractsTest.groovy[tags=throwsif_woven_example,indent=0]
+----
+
+On a constructor whose first statement is an explicit `super(...)` or `this(...)`
+call, the guard is inserted immediately _after_ that call, which must stay first
+— a (current) language constraint.
+
+=== Documenting an existing throw
+
+With `woven = false` nothing is generated; the annotation is checkable documentation
+of a guard that is already there:
+
+[source,groovy]
+----
+include::../test/ContractsTest.groovy[tags=throwsif_body_example,indent=0]
+----
+
+When the throw originates in code the method merely _calls_ (a third-party library),
+add `direct = false` — there is no throw statement in this body to find, and
+weaving a wrong claim about invoked code would silently change behaviour, which is
+why such arms are never woven:
+
+[source,groovy]
+----
+include::../test/ContractsTest.groovy[tags=throwsif_indirect_example,indent=0]
+----
+
+Most users never set `direct`: the defaults are right for woven arms and hand-written
+guards alike, and the usual prompt to add `direct = false` is a verification or
+analysis tool reporting that it cannot find the promised throw in the body.
+
+=== Runtime checking
+
+Weaving _implements_ the contract; `checked = true` additionally _verifies_ it at
+runtime, in the same assertion style as `@Ensures`: on a normal return, no non-woven
+arm's condition may have held on entry (_must-throw_), and an escaping exception
+matching some arm's type must be justified by a matching arm's condition having held
+(_only-when_ — checked only for `exhaustive` arm-sets). A broken implementation
+raises `ThrowsIfViolation` — never the declared exception, which is defined
+behaviour delivered at entry; a justified throw always propagates untouched:
+
+[source,groovy]
+----
+include::../test/ContractsTest.groovy[tags=throwsif_checked_example,indent=0]
+----
+
+`checked` is _set-level_: if any arm is `checked`, the whole arm-set is checked
+— every non-woven arm is must-throw checked, and every arm serves as an
+only-when justifier.
+
+=== Rules for @ThrowsIf closures
+
+* The closure is a boolean expression over the method's parameters (the same
+ conventions as `@Requires`; it cannot reference `result` or `old`).
+* Multiple arms are independent must-throws; the only-when direction is a property
+ of the whole arm-set. One `exhaustive = false` arm disclaims it for the set.
+* Exhaustiveness is (at most) over the _conditions for the exception types
+ mentioned_, never over exception _types_: declaring an `ArithmeticException` arm
+ says nothing about whether the method can throw anything else.
+* No claim, however `exhaustive`, reasons about VM resource conditions: an
+ `OutOfMemoryError` or `StackOverflowError` is outside contract semantics, and the
+ checked wrapper passes any `VirtualMachineError` through unjudged.
+* When both apply on the same input, a `@Requires` violation is reported first
+ (`PreconditionViolation`): the caller's obligation is judged before the method's
+ defined behaviour.
+
+NOTE: `@ThrowsIf` is incubating in Groovy 6.0.0. The attribute set — in
+particular the `direct` metadata member and the set-level `checked` rule — may
+be refined in a future release based on usage feedback.
+
== Frame Conditions with @Modifies
The `@Modifies` annotation declares which fields or parameters a method is allowed to modify.
diff --git a/subprojects/groovy-contracts/src/spec/test/ContractsTest.groovy b/subprojects/groovy-contracts/src/spec/test/ContractsTest.groovy
index 80a66748c5..3dfddec6d6 100644
--- a/subprojects/groovy-contracts/src/spec/test/ContractsTest.groovy
+++ b/subprojects/groovy-contracts/src/spec/test/ContractsTest.groovy
@@ -239,6 +239,81 @@ class ContractsTest extends GroovyTestCase {
'''
}
+ void testThrowsIfWoven() {
+ runScript '''
+ // tag::throwsif_woven_example[]
+ import groovy.contracts.ThrowsIf
+ import static groovy.test.GroovyAssert.shouldFail
+
+ class Calculator {
+ @ThrowsIf(value = { b == 0 }, exception = ArithmeticException)
+ static int divide(int a, int b) { a.intdiv(b) }
+ }
+
+ assert Calculator.divide(4, 2) == 2
+ shouldFail(ArithmeticException) { Calculator.divide(1, 0) } // the woven guard
+ // end::throwsif_woven_example[]
+ '''
+ }
+
+ void testThrowsIfBody() {
+ runScript '''
+ // tag::throwsif_body_example[]
+ import groovy.contracts.ThrowsIf
+ import static groovy.test.GroovyAssert.shouldFail
+
+ class MathUtil {
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false)
+ static int fact(int n) {
+ if (n < 0) throw new IllegalArgumentException('negative') // the guard is already here
+ n <= 1 ? 1 : n * fact(n - 1)
+ }
+ }
+
+ assert MathUtil.fact(4) == 24
+ shouldFail(IllegalArgumentException) { MathUtil.fact(-1) }
+ // end::throwsif_body_example[]
+ '''
+ }
+
+ void testThrowsIfIndirect() {
+ runScript '''
+ // tag::throwsif_indirect_example[]
+ import groovy.contracts.ThrowsIf
+
+ class Wrapper {
+ @ThrowsIf(value = { s == null }, exception = NullPointerException, woven = false, direct = false)
+ static Object describe(Object s) {
+ Objects.requireNonNull(s) // the library throws; the annotation records the contract
+ "value: $s"
+ }
+ }
+
+ assert Wrapper.describe('x') == 'value: x'
+ // end::throwsif_indirect_example[]
+ '''
+ }
+
+ void testThrowsIfChecked() {
+ runScript '''
+ // tag::throwsif_checked_example[]
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+ import static groovy.test.GroovyAssert.shouldFail
+
+ class Broken {
+ // the body SHOULD throw when n < 0 but does not — a broken implementation,
+ // reported as a violation (never the declared exception)
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false, checked = true)
+ static int identity(int n) { n }
+ }
+
+ assert Broken.identity(5) == 5
+ shouldFail(ThrowsIfViolation) { Broken.identity(-5) }
+ // end::throwsif_checked_example[]
+ '''
+ }
+
private static void runScript(String scriptText) {
new GroovyShell().run(scriptText, 'ScriptSnippet', [] as String[])
}
diff --git a/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/other/ThrowsIfTests.groovy b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/other/ThrowsIfTests.groovy
new file mode 100644
index 0000000000..e9ab9a9a9f
--- /dev/null
+++ b/subprojects/groovy-contracts/src/test/groovy/org/apache/groovy/contracts/tests/other/ThrowsIfTests.groovy
@@ -0,0 +1,522 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.contracts.tests.other
+
+import org.apache.groovy.contracts.tests.basic.BaseTestClass
+import org.junit.jupiter.api.Test
+
+import static groovy.test.GroovyAssert.assertScript
+
+/**
+ * Tests for {@code @ThrowsIf}, the exceptional contract: the method throws the
+ * given exception when the given condition holds. The default {@code woven = true}
+ * generates the guard-throw at method entry; unwoven arms generate nothing —
+ * {@code direct} says where the existing throw lives (body vs invoked code),
+ * pure information for readers and tools.
+ */
+class ThrowsIfTests extends BaseTestClass {
+
+ @Test
+ void wovenGuardThrowsWhenConditionHolds() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @ThrowsIf(value = { b == 0 }, exception = ArithmeticException)
+ static int divide(int a, int b) { a.intdiv(b) }
+ }
+ assert C.divide(4, 2) == 2
+ try {
+ C.divide(1, 0)
+ assert false, 'expected the woven guard to throw'
+ } catch (ArithmeticException e) {
+ assert e.message.contains('b == 0')
+ }
+ '''
+ }
+
+ @Test
+ void wovenGuardWorksUnderCompileStatic() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import groovy.transform.CompileStatic
+
+ @CompileStatic
+ class C {
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException)
+ static int half(int n) { n.intdiv(2) }
+ }
+ assert C.half(8) == 4
+ try {
+ C.half(-2)
+ assert false, 'expected the woven guard to throw'
+ } catch (IllegalArgumentException expected) {
+ }
+ '''
+ }
+
+ @Test
+ void unwovenArmGeneratesNothing() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // woven = false (direct defaults true): the body is expected to implement the throw; here it
+ // deliberately does not, demonstrating that no guard was generated.
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false)
+ static int identity(int n) { n }
+ }
+ assert C.identity(-5) == -5
+ '''
+ }
+
+ @Test
+ void trustedArmGeneratesNothing() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // direct = false: the throw would originate in invoked code; never woven.
+ @ThrowsIf(value = { s == null }, exception = NullPointerException, woven = false, direct = false)
+ static Object passThrough(Object s) { s }
+ }
+ assert C.passThrough(null) == null
+ '''
+ }
+
+ @Test
+ void repeatedArmsEachGuardIndependently() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @ThrowsIf(value = { x == null }, exception = NullPointerException)
+ @ThrowsIf(value = { y < 0 }, exception = IllegalArgumentException)
+ static String tag(Object x, int y) { "$x:$y" }
+ }
+ assert C.tag('a', 1) == 'a:1'
+ try {
+ C.tag(null, 1)
+ assert false
+ } catch (NullPointerException expected) {
+ }
+ try {
+ C.tag('a', -1)
+ assert false
+ } catch (IllegalArgumentException expected) {
+ }
+ '''
+ }
+
+ @Test
+ void mixedWovenAndUnwovenArms() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @ThrowsIf(value = { x == null }, exception = NullPointerException) // woven
+ @ThrowsIf(value = { y == null }, exception = NullPointerException, woven = false) // body's job (deliberately absent here)
+ static String pair(Object x, Object y) { "$x:$y" }
+ }
+ assert C.pair('a', 'b') == 'a:b'
+ try {
+ C.pair(null, 'b')
+ assert false
+ } catch (NullPointerException expected) {
+ }
+ assert C.pair('a', null) == 'a:null' // unwoven arm generated nothing
+ '''
+ }
+
+ @Test
+ void constructorGuard() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class Account {
+ int balance
+ @ThrowsIf(value = { opening < 0 }, exception = IllegalArgumentException)
+ Account(int opening) { balance = opening }
+ }
+ assert new Account(10).balance == 10
+ try {
+ new Account(-1)
+ assert false
+ } catch (IllegalArgumentException expected) {
+ }
+ '''
+ }
+
+ @Test
+ void armsAreRuntimeRetainedStructuredMetadata() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @ThrowsIf(value = { s == null }, exception = NumberFormatException, woven = false, direct = false, exhaustive = false)
+ @ThrowsIf(value = { radix < 2 }, exception = IllegalArgumentException, woven = false)
+ static int parse(String s, int radix) { Integer.parseInt(s, radix) }
+ }
+ def arms = C.getDeclaredMethod('parse', String, int).getAnnotationsByType(ThrowsIf)
+ assert arms.length == 2
+ def byExc = arms.collectEntries { [(it.exception().simpleName): it] }
+ assert !byExc.NumberFormatException.exhaustive() && !byExc.NumberFormatException.direct()
+ assert byExc.IllegalArgumentException.exhaustive() && byExc.IllegalArgumentException.direct() && !byExc.IllegalArgumentException.woven()
+ '''
+ }
+
+ @Test
+ void checkedMustThrowViolationOnSilentReturn() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class C {
+ // checked + unwoven: the body SHOULD throw when n < 0 but doesn't — a broken
+ // implementation, reported as a violation (never the declared exception).
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false, checked = true)
+ static int identity(int n) { n }
+ }
+ assert C.identity(5) == 5
+ try {
+ C.identity(-5)
+ assert false, 'expected ThrowsIfViolation'
+ } catch (ThrowsIfViolation e) {
+ assert e.message.contains('returned normally')
+ }
+ '''
+ }
+
+ @Test
+ void checkedOnlyWhenViolationOnUnjustifiedThrow() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class C {
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false, checked = true)
+ static int f(int n) {
+ if (n < 0) throw new IllegalArgumentException('negative')
+ if (n > 100) throw new IllegalArgumentException('too big') // unlisted reason
+ n
+ }
+ }
+ assert C.f(5) == 5
+ try {
+ C.f(200)
+ assert false, 'expected ThrowsIfViolation'
+ } catch (ThrowsIfViolation e) {
+ assert e.message.contains('no matching condition')
+ }
+ '''
+ }
+
+ @Test
+ void checkedJustifiedThrowPropagatesUntouched() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false, checked = true)
+ static int f(int n) {
+ if (n < 0) throw new IllegalArgumentException('negative')
+ n
+ }
+ }
+ // the defined behaviour must reach the caller as-is — checking never swallows it
+ try {
+ C.f(-1)
+ assert false
+ } catch (IllegalArgumentException e) {
+ assert e.message == 'negative'
+ }
+ '''
+ }
+
+ @Test
+ void checkedNonExhaustiveSetSkipsOnlyWhen() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // exhaustive = false: one-directional — an unlisted throw reason is in-contract,
+ // so only-when is not checked (must-throw still is).
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false, checked = true, exhaustive = false)
+ static int f(int n) {
+ if (n < 0) throw new IllegalArgumentException('negative')
+ if (n > 100) throw new IllegalArgumentException('too big')
+ n
+ }
+ }
+ try {
+ C.f(200)
+ assert false
+ } catch (IllegalArgumentException e) {
+ assert e.message == 'too big' // propagated, not a violation
+ }
+ '''
+ }
+
+ @Test
+ void checkedWithWovenArmStillChecksOnlyWhen() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class C {
+ // woven + checked: the guard implements must-throw; only-when is still verified.
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, checked = true)
+ static int f(int n) {
+ if (n > 100) throw new IllegalArgumentException('too big') // unlisted reason
+ n
+ }
+ }
+ assert C.f(5) == 5
+ try {
+ C.f(-1)
+ assert false
+ } catch (IllegalArgumentException e) {
+ assert e.message.contains('n < 0') // the woven guard, propagated through the checker
+ }
+ try {
+ C.f(200)
+ assert false
+ } catch (ThrowsIfViolation expected) {
+ }
+ '''
+ }
+
+ @Test
+ void checkedTrustedArmValidatesTheThirdPartyClaim() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class C {
+ // direct = false (never woven) + checked: the claim about invoked code is validated at runtime —
+ // here the callee does NOT actually throw, so the trusted claim is exposed as wrong.
+ @ThrowsIf(value = { s == null }, exception = NullPointerException, woven = false, direct = false, checked = true)
+ static Object passThrough(Object s) { s }
+ }
+ assert C.passThrough('x') == 'x'
+ try {
+ C.passThrough(null)
+ assert false, 'expected ThrowsIfViolation'
+ } catch (ThrowsIfViolation expected) {
+ }
+ '''
+ }
+
+ @Test
+ void preconditionViolationFiresBeforeTheWovenGuard() {
+ assertScript '''
+ import groovy.contracts.Requires
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.PreconditionViolation
+
+ class C {
+ @Requires({ n >= 0 })
+ @ThrowsIf(value = { n < -10 }, exception = IllegalArgumentException)
+ static int f(int n) { n }
+ }
+ // an input violating BOTH: the caller's obligation is judged first — the @Requires
+ // assertion weaves ahead of the @ThrowsIf guard, so a caller bug is reported as one
+ try {
+ C.f(-20)
+ assert false
+ } catch (PreconditionViolation expected) {
+ }
+ '''
+ }
+
+ @Test
+ void requiresEvaluationThrowIsNotMisjudgedByCheckedArms() {
+ assertScript '''
+ import groovy.contracts.Requires
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // the @Requires EVALUATION itself throws ArithmeticException for d == 0; a checked
+ // ArithmeticException arm must not misjudge that pre-body throw as a contract
+ // violation — the precondition assertion weaves outside the checked wrapper
+ @Requires({ 1.intdiv(d) >= 0 })
+ @ThrowsIf(value = { d < 0 }, exception = ArithmeticException, woven = false, checked = true)
+ static int g(int d) {
+ if (d < 0) throw new ArithmeticException('negative')
+ d
+ }
+ }
+ try {
+ C.g(0)
+ assert false
+ } catch (ArithmeticException e) {
+ assert e.message.contains('/ by zero') // the raw evaluation throw, untouched
+ }
+ '''
+ }
+
+ @Test
+ void directIsIgnoredForWovenArms() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // direct is implicitly true for woven code — setting it changes nothing
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, direct = false)
+ static int half(int n) { n.intdiv(2) }
+ }
+ assert C.half(8) == 4
+ try {
+ C.half(-2)
+ assert false, 'the guard weaves regardless of direct'
+ } catch (IllegalArgumentException expected) {
+ }
+ '''
+ }
+
+ @Test
+ void vmErrorsAreNeverJudgedByCheckedArms() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ // even a broad, exhaustive, checked arm never judges a VM error: resource
+ // conditions are outside contract semantics — the error propagates untouched
+ @ThrowsIf(value = { n < 0 }, exception = Throwable, woven = false, checked = true)
+ static int f(int n) {
+ if (n < 0) throw new IllegalStateException('negative')
+ if (n > 100) throw new StackOverflowError('simulated')
+ n
+ }
+ }
+ try {
+ C.f(200)
+ assert false
+ } catch (StackOverflowError e) {
+ assert e.message == 'simulated' // no ThrowsIfViolation masking it
+ }
+ '''
+ }
+
+ @Test
+ void explicitSuperCallStaysFirstUnderWovenGuard() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class Base { int b; Base(int b) { this.b = b } }
+ class Derived extends Base {
+ @ThrowsIf(value = { opening < 0 }, exception = IllegalArgumentException)
+ Derived(int opening) {
+ super(opening * 2)
+ }
+ }
+ assert new Derived(5).b == 10
+ try {
+ new Derived(-1)
+ assert false
+ } catch (IllegalArgumentException expected) { // guard runs just after the super call
+ }
+ '''
+ }
+
+ @Test
+ void explicitSuperCallStaysFirstUnderCheckedArm() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class Base2 { int b; Base2(int b) { this.b = b } }
+ class Derived2 extends Base2 {
+ @ThrowsIf(value = { opening < 0 }, exception = IllegalArgumentException, woven = false, checked = true)
+ Derived2(int opening) {
+ super(opening * 2)
+ }
+ }
+ assert new Derived2(5).b == 10
+ try {
+ new Derived2(-1) // body never throws: must-throw violation, after the super call
+ assert false
+ } catch (ThrowsIfViolation expected) {
+ }
+ '''
+ }
+
+ @Test
+ void thisDelegationStaysFirstUnderWovenGuard() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+
+ class Box {
+ int v
+ Box() { this(1) }
+ @ThrowsIf(value = { v < 0 }, exception = IllegalArgumentException)
+ Box(int v) { this.v = v }
+ }
+ assert new Box().v == 1
+ try {
+ new Box(-1)
+ assert false
+ } catch (IllegalArgumentException expected) {
+ }
+ '''
+ }
+
+ @Test
+ void checkedIsSetLevelForMustThrow() {
+ assertScript '''
+ import groovy.contracts.ThrowsIf
+ import org.apache.groovy.contracts.ThrowsIfViolation
+
+ class C {
+ // only the second arm says checked = true — but checked is SET-level, so the
+ // first (unwoven, unchecked) arm is must-throw checked too: it cannot silently
+ // opt out while serving as an only-when justifier
+ @ThrowsIf(value = { n < 0 }, exception = IllegalArgumentException, woven = false)
+ @ThrowsIf(value = { n > 100 }, exception = IllegalArgumentException, woven = false, checked = true)
+ static int f(int n) { n }
+ }
+ assert C.f(5) == 5
+ try {
+ C.f(-1) // the UNCHECKED sibling's condition — still a must-throw violation
+ assert false
+ } catch (ThrowsIfViolation expected) {
+ }
+ '''
+ }
+
+ @Test
+ void guardComposesWithRequires() {
+ assertScript '''
+ import groovy.contracts.Requires
+ import groovy.contracts.ThrowsIf
+
+ class C {
+ @Requires({ a >= 0 })
+ @ThrowsIf(value = { b == 0 }, exception = ArithmeticException)
+ static int divide(int a, int b) { a.intdiv(b) }
+ }
+ assert C.divide(4, 2) == 2
+ try {
+ C.divide(4, 0)
+ assert false
+ } catch (ArithmeticException expected) {
+ }
+ '''
+ }
+}