<a id="reference-expression-label"></a>

# Expression

An *expression* is a typed formal statement that evaluates to a value.
Expressions are present in two cases:

* In formal [Requirement](entity.md#reference-requirement-label) to express a property that must hold
* In [Attribute](entity.md#reference-attribute-label) definition to express the domain of the attribute

An expression composes several [attributes](entity.md#reference-attribute-label) in order to formulate assertions that constrain the used attributes.

#### ATTENTION
An expression is not an algorithm. There are no instructions or sequences of actions —
only properties that must hold.

## Formalism

req uses several formalisms in conjunction to produce expressions:

#### Allowed formalisms

| Name                | Examples                        |
|---------------------|---------------------------------|
| Propositional logic | `and`, `or`                     |
| LTL (discrete-time) | `always`, `eventually`          |
| FOL                 | `all … for`, `any … for`        |
| Set theory          | `includes`, `in`, `{ … for … }` |
| Common algebra      | `+`, `-`, `sum`, `max`          |

#### NOTE
The current set of formalisms is a deliberate subset of what a specification may require.
req will progressively be extended with additional constructs: the guiding criterion is
that any new construct must be expressible in standard formal notation and relevant for
systems engineers.

In req, every attribute is treated as a signal that may change over time — similar to a measured
variable in a control system or a recorded parameter in a flight data recorder. Formally, the
attributes used in expressions are considered time-dependent functions.

Suppose an attribute is defined by a requirement as:

$$
x = f(y, z)
$$

where $f$ denotes an expression. It is assumed that $x$, $y$, and $z$
are functions of time, i.e.:

$$
\forall t\quad x(t) = f(y(t), z(t))
$$

As a corollary, $x$ is constant if and only if $y$ and $z$ are constants
(such as literals).

In the following, we will use the notation $x(t)$ and $x_t$ interchangeably.

#### NOTE
Unless explicitly stated by temporal operators, attribute constraints hold for all $t$ —
that is, across the entire system lifecycle and all operating conditions. This scope can be
narrowed by introducing attributes that represent specific operating conditions or lifecycle phases.

## Type system

The *type* of an expression defines which operators can be applied to it.
An [attribute](entity.md#reference-attribute-label) has a type that is inferred from its domain definition.

Operators in req are strictly typed: applying an operator to an expression of an incompatible type is not allowed.

If a type cannot be inferred, the expression has the type *undefined*, which is not a true
type but denotes the absence of typing information.

#### NOTE
The only types a specification can define are enumerations, with a [type](entity.md#reference-type-label) entity.

<a id="reference-type-number-label"></a>

### Number

The type `Number` covers all numerical values, including integers and real numbers.
No distinction is made between them in the type system.

<a id="reference-type-boolean-label"></a>

### Boolean

The type `Boolean` is applied to any boolean expression.

<a id="reference-type-set-label"></a>

### Set

The type `Set(T)` is applied to any expression that evaluates to a set.
Sets are homogeneous in the sense that they can only contain elements of the same type.

<a id="reference-type-enumeration-label"></a>

### Enumeration

An enumeration type is defined by a [type](entity.md#reference-type-label) entity. Its values are the
members of the type, written with the path of the type: `Door_state::closed`. They can be compared
with `=` and `<>` and gathered in sets.

## Literals

A *literal* is a value written directly in the expression source.

### Numbers

Numbers are written in decimal format and may use exponential notation.

**Example of numbers**

```none
 2
 3.14
 10e7
```

`infinity` represents an infinite value. Values are of type [Number](#reference-type-number-label).

#### NOTE
No distinction is made between integers and real numbers at the type level.
Fractional expressions such as `1/3` are evaluated as arithmetic operations, not
written as decimal literals.

### Boolean

The Boolean literals `true` and `false` represent the two truth values.

**Booleans**

```none
 true
 false
```

Values are of type [Boolean](#reference-type-boolean-label).

### Set

The set literal allows creating an ad-hoc set with a finite number of elements:

**Syntax of set**

```none
{ EXPRESSION (, EXPRESSION)* }
```

**Example of set literal**

```req
{1, 2, 3}
```

Values are of type [Set](#reference-type-set-label). Expressions must have the same type.

<a id="reference-interval-label"></a>

### Interval

An *interval* is the set of the numbers between two bounds. A bracket that faces its bound includes it,
a bracket turned away from it excludes it:

#### Intervals

| Syntax   | Description                | Formal equivalence           |
|----------|----------------------------|------------------------------|
| `[a, b]` | Closed interval            | $\{x \mid a \leq x \leq b\}$ |
| `]a, b[` | Open interval              | $\{x \mid a < x < b\}$       |
| `[a, b[` | Includes `a`, excludes `b` | $\{x \mid a \leq x < b\}$    |
| `]a, b]` | Excludes `a`, includes `b` | $\{x \mid a < x \leq b\}$    |

Values are of type `Set(Number)`.

**Example of intervals**

```req
]0, 30]
[0, infinity[
```

<a id="reference-range-label"></a>

### Range

A *range* is the set of the integers between two bounds, both included:

#### Range

| Syntax     | Description                  | Formal equivalence                          |
|------------|------------------------------|---------------------------------------------|
| `[[a, b]]` | The integers from `a` to `b` | $\{n \in \mathbb{Z} \mid a \leq n \leq b\}$ |

Values are of type `Set(Number)`.

### Built-in set

A built-in set is a keyword that denotes a well-known set:

**Built-in sets**

```none
real
boolean
integer
```

#### NOTE
Built-in sets are most commonly used as the domain of an
[attribute](entity.md#reference-attribute-label).

Values are of type [Set](#reference-type-set-label). Element type varies according to the built-in set.

## Operators

An *operator* is an expression that contains one or more operands (attributes or literals).
Each operator is paired with a formal equivalent that translates the req expression into standard mathematical notation.

#### NOTE
Throughout this section, lowercase `x` and `y` denote scalar values, and uppercase `X` and `Y` denote sets (domains).

### Grouping

Any sub-expression may be enclosed in parentheses to make evaluation order explicit:

**Syntax**

```none
 ( EXPRESSION )
```

Parentheses always override the default precedence and associativity rules described in the
[Precedence](#reference-expression-precedence-label) section below.

### Arithmetic

Arithmetic operators act on [Number](#reference-type-number-label) and evaluate to [Number](#reference-type-number-label).

#### Arithmetic operators

| Syntax   | Description    | Formal equivalence   |
|----------|----------------|----------------------|
| `x + y`  | Addition       | $x + y$              |
| `x - y`  | Subtraction    | $x - y$              |
| `x * y`  | Multiplication | $x \cdot y$          |
| `x / y`  | Division       | $x / y$              |
| `x % y`  | Remainder      | $x \bmod y$          |
| `x ^ y`  | Exponentiation | $x^{y}$              |
| `-x`     | Unary negation | $-x$                 |
| `+x`     | Unary identity | $+x$                 |
| `x!`     | Factorial      | $x!$                 |

### Equality

Equality operators act on every type and evaluate to [Boolean](#reference-type-boolean-label).
In req, equality is always by value, the concept of reference does not exist.

#### Equality operators

| Syntax   | Description                                                               | Formal equivalence                                                              |
|----------|---------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| `x = y`  | True if x and y are equal                                                 | $x = y$                                                                         |
| `x <> y` | True if x and y are not equal                                             | $x \neq y$                                                                      |
| `x := y` | True if x holds the value of y immediately after the assertion must hold. | $\forall P P \Rightarrow x := y_t$ where t is the instant where P becomes true. |
| `x °= y` | True if x initially holds the value of y.                                 | $x_0 = y_0$                                                                     |

#### ATTENTION
In req, `=` is an equality test, not an assignment. The expression
`altitude = 120` in a requirement body means “altitude shall be equal to 120”, not “set the altitude to 120”.

The `:=` operator is named *fix* and notably allows to assert that an assignment has occurred.
It can therefore be used to specify recursive properties such as `x := x + 1`.
If the fix is not used with a condition, the initial value of y is taken.

### Comparison

Comparison operators act on [Number](#reference-type-number-label) and evaluate to
[Boolean](#reference-type-boolean-label).

#### Comparison operators

| Syntax   | Description                             | Formal equivalence   |
|----------|-----------------------------------------|----------------------|
| `x < y`  | True if x is strictly less than y       | $x < y$              |
| `x > y`  | True if x is strictly greater than y    | $x > y$              |
| `x <= y` | True if x is less than or equal to y    | $x \leq y$           |
| `x >= y` | True if x is greater than or equal to y | $x \geq y$           |

### Propositional logic

Propositional logic operators act on [Boolean](#reference-type-boolean-label) and evaluate to [Boolean](#reference-type-boolean-label).

#### Propositional logic operators

| Syntax        | Description                               | Formal equivalence    |
|---------------|-------------------------------------------|-----------------------|
| `x and y`     | True if both x and y are true             | $x \wedge y$          |
| `x or y`      | True if at least one of x or y is true    | $x \vee y$            |
| `x xor y`     | True if exactly one of x or y is true     | $x \oplus y$          |
| `x implies y` | True if x is false or x and y are true    | $x \Rightarrow y$     |
| `x iff y`     | True if x and y have the same truth value | $x \Leftrightarrow y$ |
| `not x`       | True if x is false                        | $\neg x$              |

### Set

The following operators act on [Set](#reference-type-set-label) and evaluate to [Set](#reference-type-set-label).

#### Set algebra operators

| Syntax             | Description                        | Formal equivalence                             |
|--------------------|------------------------------------|------------------------------------------------|
| `X union Y`        | Elements belonging to X or Y       | $X \cup Y$                                     |
| `X intersection Y` | Elements belonging to both X and Y | $X \cap Y$                                     |
| `X difference Y`   | Symmetric difference of X and Y    | $X \Delta Y = (X \cup Y) \setminus (X \cap Y)$ |
| `X complement Y`   | Elements of X that are not in Y    | $X \setminus Y$                                |

The following operators act on [Set](#reference-type-set-label) and evaluate to [Boolean](#reference-type-boolean-label).

#### Set predicate operators

| Syntax         | Description                  | Formal equivalence   |
|----------------|------------------------------|----------------------|
| `x in X`       | True if x is an element of X | $x \in X$            |
| `X includes Y` | True if Y is a subset of X   | $Y \subseteq X$      |

<a id="reference-tolerance-label"></a>

### Tolerance

The *tolerance* operator acts on [Number](#reference-type-number-label) and evaluates to `Set(Number)`: the
numbers that are within a tolerance of a nominal value.

#### Tolerance operator

| Syntax    | Description                                        | Formal equivalence   |
|-----------|----------------------------------------------------|----------------------|
| `x tol y` | The numbers between x - y and x + y, both included | $[x - y, x + y]$     |

**Example of tolerance**

```req
Shaft::speed in 3000 tol 50
```

### Temporal logic

Temporal logic operators act on [Boolean](#reference-type-boolean-label) and evaluate to
[Boolean](#reference-type-boolean-label). They express properties over a discrete sequence
of time steps. See LTL for the underlying formalism.

#### Temporal logic operators

| Syntax         | Description                                                                | Formal equivalence          |
|----------------|----------------------------------------------------------------------------|-----------------------------|
| `always x`     | True if x holds at every future time step                                  | $\square x$                 |
| `eventually x` | True if x holds at some future time step                                   | $\lozenge x$                |
| `previously x` | True if x held at the immediately preceding time step                      | $\ominus x$                 |
| `rising x`     | True at the first time step where x becomes true                           | $\neg x_{t-1} \wedge x_{t}$ |
| `falling x`    | True at the first time step where x becomes false                          | $x_{t-1} \wedge \neg x_{t}$ |
| `x since y`    | True if x has been true at every step since the last step where y was true | $x \,\mathcal{S}\, y$       |

#### NOTE
The notion of time step does not refer to a particular time division or sampling rate.
Time steps can be thought of as an arbitrary division that splits continuous time into
event points at which state changes occur (i.e., the values of the attributes change).

<a id="reference-aggregator-label"></a>

### Aggregator

An *aggregator* reduces a list of values, or the values of an expression over a domain, to a single value:

**Syntax**

```none
AGGREGATOR EXPRESSION (, EXPRESSION)* end
AGGREGATOR EXPRESSION for IDENTIFIER in EXPRESSION (such that EXPRESSION)? end
```

#### Aggregators

| Aggregator              | Description                                                                  |
|-------------------------|------------------------------------------------------------------------------|
| `all`, `any`            | True if every value, at least one value, is true                             |
| `one`                   | True if exactly one value is true                                            |
| `max`, `min`            | The greatest, the smallest value                                             |
| `sup`, `inf`            | The least upper bound, the greatest lower bound                              |
| `sum`, `prod`           | The sum, the product of the values                                           |
| `argmax`, `argmin`      | The values of the variable where the greatest, the smallest value is reached |
| `union`, `intersection` | The union, the intersection of the sets                                      |
| `choose`                | One of the values                                                            |

Over a domain, `all` and `any` are the quantifiers of first-order logic:

$$
\texttt{all}\ Q(x)\ \texttt{for}\ x\ \texttt{in}\ X\ \texttt{such that}\ P(x)\ \texttt{end} \iff \forall x \in X,\ P(x) \Rightarrow Q(x)
$$

$$
\texttt{any}\ Q(x)\ \texttt{for}\ x\ \texttt{in}\ X\ \texttt{such that}\ P(x)\ \texttt{end} \iff \exists x \in X,\ P(x) \wedge Q(x)
$$

**Example of aggregations**

```req
sum Battery::cell_1, Battery::cell_2 end
max p for p in { 8, 14, 20 } such that p <= 15 end
all Battery::cell_1 >= 3, Battery::cell_2 >= 3 end
```

#### NOTE
Boolean aggregators are the list counterparts of `and` and `or`: `all e1, e2 end` is
equivalent to `e1 and e2`, and `any e1, e2 end` is equivalent to `e1 or e2`.

### Function call

A function call applies an expression to a list of arguments:

**Syntax**

```none
 EXPRESSION ( (EXPRESSION (, EXPRESSION)*)? )
```

#### ATTENTION
Function calls are recognised by the parser but are not yet type-checked or evaluated
by the compiler. This construct is reserved for future use.

## Conditional

A *conditional* is a notation for expressing a requirement that depends on one or more conditions.
It is a direct equivalent of a propositional pattern and does not add expressive power — only readability.

### When

The *when* conditional is an expression governed by a set of unordered conditions:

**Syntax**

```none
 when
   EXPRESSION then EXPRESSION
   (, EXPRESSION then EXPRESSION)*
   (, otherwise EXPRESSION)?
 end
```

**Example of when**

```req
 when
   Doors::open then Motion::speed = 0,
   Weather::bad then Motion::speed < 10,
   otherwise Motion::speed < 25
 end
```

Let $c_i$ denote the conditions, $x_i$ the consequences for each condition and $y$ the fallback. The when expression is strictly equivalent to:

$$
\left(\bigwedge_i c_i \Rightarrow x_i\right) \wedge \left(\left(\bigwedge_i \neg c_i\right) \Rightarrow y\right)
$$

If the otherwise branch is not defined, $y$ is taken equal to true by convention, which simplifies the expression:

$$
\bigwedge_i c_i \Rightarrow x_i
$$

The conditions are not ordered: every case whose condition holds applies. A single case with an otherwise
branch reads as an if-then-else: `when c then x, otherwise y end`.

All expressions must be of type [Boolean](#reference-type-boolean-label).

#### NOTE
This construct is particularly useful when multiple conditions govern a requirement simultaneously —
for instance, when specifying an event-action mechanism such as a state machine.

<a id="reference-comprehension-label"></a>

## Comprehension

A *comprehension* builds a set from the elements of another set, its *domain*:

**Syntax**

```none
 { EXPRESSION for IDENTIFIER in EXPRESSION (such that EXPRESSION)? }
```

By convention, in this section, $x$ denotes the identifier, $X$ the domain (expression after the `in`),
$P(x)$ the filter (expression after the `such that`) and $f(x)$ the expression before `for`.
The comprehension is strictly equivalent to:

$$
\{f(x) \mid x \in X,\ P(x)\}
$$

When the `such that` clause is omitted, $P(x)$ is taken equal to $\text{true}$.

**Example of comprehension**

```req
package Wifi
  part Radio
    let channel in [[ 1, 13 ]]
  part

  requirement Regional_band top
    on Radio
  is
    @@
      The [[Radio]] shall only use channels that do not overlap.
    @@
  requirement

  requirement Non_overlapping_channels bottom
    on Radio::channel
    refines Regional_band
  is
    Radio::channel in { 5 * k + 1 for k in [[ 0, 2 ]] }
  requirement
package
```

<a id="reference-expression-precedence-label"></a>

## Precedence

The table below lists all operators from lowest to highest precedence. Operators on the same
row have equal precedence. When in doubt, use parentheses to make evaluation order explicit.

#### Operator precedence (lowest to highest)

| Operators                                                             | Associativity   |
|-----------------------------------------------------------------------|-----------------|
| `iff`  `implies`                                                      | Left            |
| `or`  `xor`                                                           | Left            |
| `and`                                                                 | Left            |
| `not`  *(prefix)*                                                     | —               |
| `always`  `eventually`  `previously`  `rising`  `falling`  *(prefix)* | —               |
| `since`                                                               | Left            |
| `in`  `includes`                                                      | Left            |
| `union`  `difference`                                                 | Left            |
| `intersection`                                                        | Left            |
| `complement`                                                          | Left            |
| `tol`                                                                 | Left            |
| `=`  `<>`  `:=`  `°=`                                                 | Left            |
| `<`  `>`  `<=`  `>=`                                                  | Left            |
| `+`  `-`                                                              | Left            |
| `*`  `/`  `%`                                                         | Left            |
| `^`                                                                   | Right           |
| Unary `-`  `+`  *(prefix)*                                            | —               |
| `x!`  *(postfix)*                                                     | —               |
| `f(...)`                                                              | Left            |
