//////////////////////////////////////////

  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.

//////////////////////////////////////////

= Groovy Contracts – design by contract support for Groovy

This module provides contract annotations that support the specification of class-invariants,
pre- and post-conditions on Groovy classes and interfaces, loop invariants on
`for`, `while`, and `do-while` loops, and frame conditions declaring which fields a method may modify.
Special support is provided so that post-conditions may refer to the old value of variables
or to the result value associated with calling a method.

== Applying @Invariant, @Requires and @Ensures

With Groovy contracts in your classpath, contracts can be applied on a Groovy
class or interface by using one of the annotations found in the `groovy.contracts`
package.

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=basic_example,indent=0]
----

== More Features

Groovy contracts supports the following feature set:

* definition of class invariants, pre- and post-conditions via @Invariant, @Requires and @Ensures
* definition of loop invariants on `for`, `while`, and `do-while` loops via @Invariant
* declaration of frame conditions (which fields a method may modify) via @Modifies
* inheritance of class invariants, pre- and post-conditions of concrete predecessor classes
* inheritance of class invariants, pre- and post-conditions in implemented interfaces
* usage of old and result variable in post-condition assertions
* assertion injection in Plain Old Groovy Objects (POGOs)
* human-readable assertion messages, based on Groovy power asserts
* enabling contracts at package- or class-level with @AssertionsEnabled
* enable or disable contract checking with Java's -ea and -da VM parameters
* annotation contracts: a way to reuse reappearing contract elements in a project domain model
* detection of circular assertion method calls

== The Stack Example

Currently, Groovy contracts supports 3 annotations: @Invariant, @Requires and @Ensures – all of them work
as annotations with closures, where closures allow you to specify arbitrary code pieces as annotation parameters:

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=stack_example,indent=0]
----

The example above specifies a class-invariant and methods with pre- and post-conditions.
Note, that preconditions may reference method arguments and post-conditions have access
to the method’s result with the result variable and old instance variables values with old.

Indeed, Groovy AST transformations change these assertion annotations into Java assertion
statements (can be turned on and off with a JVM param) and inject them at appropriate places,
e.g. class-invariants are used to check an object's state before and after each method call.

== Annotation closure rules

* Invariants should reference class fields only.
* Preconditions may reference class fields and arguments.
* Postconditions may reference class fields, arguments, the `result` and
the old value of class fields using the syntax `old.fieldname`.

Old values of class fields will only be stored where Groovy
contracts knows how to make a copy. Currently, this means
fields with a `Cloneable` class type, primitives, the primitive
wrapper types, `BigInteger`, `BigDecimal`, and G/Strings.

== Use within scripts

Currently, Groovy contracts intentionally doesn't support scripts,
but you can use them with JEP-445 compatible scripts from Groovy 5
as shown in this example:

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=jep445_example,indent=0]
----

You could even place an `@Invariant` annotation on the `main` method
and it will be moved to the generated script class.

== Loop Invariants

In addition to class-level invariants, `@Invariant` can be placed directly on
`for`, `while`, and `do-while` loops. A loop invariant is a condition that must
hold at the start of each iteration. If the condition is violated, a
`LoopInvariantViolation` (a subclass of `AssertionError`) is thrown.

This is inspired by design-by-contract constructs found in languages like Dafny
and Eiffel.

=== For loop

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=loop_invariant_for_example,indent=0]
----

=== While loop

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=loop_invariant_while_example,indent=0]
----

=== Multiple invariants

Multiple `@Invariant` annotations can be stacked on a single loop, and each
condition is checked independently at the start of every iteration:

[source,groovy]
----
include::../test/ContractsTest.groovy[tags=loop_invariant_multiple_example,indent=0]
----

=== Rules for loop invariant closures

* The closure should be a boolean expression (or multiple expressions).
* The closure may reference any variables visible in the enclosing scope,
  including the loop variable.
* Assignment operators and state-changing postfix/prefix operators are
  not supported inside the closure.

== Frame Conditions with @Modifies

The `@Modifies` annotation declares which fields or parameters a method is allowed to modify.
All other state is implicitly declared unchanged. This is known as a _frame condition_ in
design-by-contract terminology, inspired by similar constructs in Dafny and JML.

`@Modifies` does not generate runtime assertion code — it serves as a specification
for humans and tools (including AI) to reason about what a method changes.

=== Basic usage

Use `this.fieldName` to declare that a field may be modified:

[source,groovy]
----
@Modifies({ this.items })
void addItem(String item) {
    items.add(item)
}
----

For multiple fields, use a list expression:

[source,groovy]
----
@Modifies({ [this.items, this.count] })
void addAndCount(String item) {
    items.add(item)
    count++
}
----

Or use multiple `@Modifies` annotations (via `@Repeatable`):

[source,groovy]
----
@Modifies({ this.items })
@Modifies({ this.count })
void addAndCount(String item) { ... }
----

=== Parameter references

Method parameters can also be declared as modifiable:

[source,groovy]
----
@Modifies({ arr })
void fillArray(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i
    }
}
----

=== Interaction with @Ensures

When both `@Modifies` and `@Ensures` are present on a method, a compile-time check
ensures that the `old` variable in the postcondition only references fields declared
in `@Modifies`. Referencing a field via `old` that is not in the modification set
produces a compile error:

[source,groovy]
----
@Modifies({ this.items })
@Ensures({ old -> old.items.size() < items.size() })  // OK: items is declared
void addItem(String item) { ... }

@Modifies({ this.items })
@Ensures({ old -> old.count == count })  // ERROR: count not declared in @Modifies
void addItem(String item) { ... }
----

=== Compile-time validation

The `@Modifies` annotation validates at compile time that:

* Field references (`this.fieldName`) refer to fields that exist on the class.
* Parameter references refer to actual parameters of the method.
* If `@Ensures` is also present, `old.fieldName` references only access fields
  declared in `@Modifies`.

=== Rules for @Modifies closures

* The closure must contain a single field reference (`this.field`), parameter
  reference (`param`), or a list of such references.
* Field references use the `this.fieldName` syntax.
* Parameter references use the bare parameter name.
* The closure is not executed at runtime — it is only analyzed at compile time.

=== Verifying method bodies with ModifiesChecker

While `@Modifies` alone is a compile-time-checked specification (validating field/parameter
existence and `@Ensures` consistency), it does not verify the method body itself. For that,
the `groovy-typecheckers` module provides the `ModifiesChecker` type checking extension:

[source,groovy]
----
@TypeChecked(extensions = 'groovy.typecheckers.ModifiesChecker')
----

When enabled, the checker verifies that method bodies only modify fields declared in
`@Modifies`, and that method calls on non-modifiable receivers use only non-mutating
operations. See the _Type Checkers_ documentation for details.

