text:
# Static analysis of Go programs
Based on the operations described in the previous section, a static analyser can be written that ensures that the rules of linearity are respected. This static analysis can be done in the form of an abstract interpreter; that is, an interpreter that does not operate on concrete values, but abstract values and tries to interpret all possible paths through a program.
\label{chap:interpreter}

We will introduce a store mapping variables to permissions with some operations, an expression evaluator $\leadsto$, and a statement evaluator $\rightarrow$. There will also be several
important helper functions like $moc$ which moves or copies a value, depending on which action is applicable, and `defineOrAssign` which takes care of defining and assigning values. Most
of the chapter will be in the form of a operational semantics, though some more complex cases will be discussed in code form for better readability.

In the `github.com/julian-klode/lingolang` reference implementation, the permissions and operations are provided in the package called `capabilities` for historic reasons. A better name might have been `interpreter`.

## Overview
The abstract interpreter acts on a store which maps variables to permissions. Evaluating an expressions in a store yields a permission for the object returned by the expression,
a new store, and an _owner_ and _dependencies_ - these two deserve some explanation:

An _owner_ here means the variable from which the object the evaluation evaluates to has been reached, and its effective permission at the time it was reached. When an identifier is evaluated,
the variable and its effective permission become the owner, and the original variable is rendered unusable (by converting it to `n`).
The owner will be important in some places later on. For example, when a part of an object is made immutable, we also want to make the whole object - the owner - immutable (or more specifically, we would
like to note that the part is now immutable, but we need the owner anyway).
Not every expression has an owner: For example, an addition never has an owner: The returned value is freshly created, it is not part of another value.

A _dependency_ is similar to an owner. It is another variable that has been used in the expression, alongside its effective permission. A list of dependencies could also contain owners: For example, in `a[b]`,
the owners and dependencies of `b` would be some of the dependencies of the complete expression (the others are the dependencies of `a`).

Owners and dependencies can be released back to the store when they are no longer needed. For example, when `a + b` is evaluated, the owners and dependencies for `a` and `b` can be released
after `a + b` has been evaluated. Sometimes, a value is moved, then its owner and dependencies are not released - they become consumed by the operation, so to speak.

The abstract interpreter for statements evaluates the statement in a store and a current function -- the latter is needed for some lookups, like return values. Multiple branches are handled by
returning a set of stores, rather than just one. Statements also have early exits like `return` statements. We handle these by including
the statement that abnormally terminated a statement alongside the store. For example, a `return` statement would have one _exit_: a pair of its store and itself. A block statement with a `return`
statement would have the exit of the `return` statement, and maybe others.\label{sec:exit-0}

## The store
The store is an essential part of the interpreter. It maps variable names $\in V$ to: \label{sec:store}

1. An effective permission
2. A maximum permission
3. A use count

The maximum permission restricts the effective permission. It can be used to prevent re-assignment of variables by revoking the write permission there. The uses count will be used later when evaluating function literals to see which values have been captured in the closure of the literal.

The store has several operations:

1. `GetEffective`, written $S[v]$, returns the effective permission of $v$ in $S$.
1. `GetMaximum`, written $S[\overline{v}]$, returns the maximum permission of $v$ in $S$.
1. `Define`, written $S[v := p]$, is a new store where a new $v$ is defined if none is in the current block, otherwise, it is the same as $S[v = p]$.
1. `SetEffective`, written $S[v = p]$, is a new store where $v$'s effective permission is set to $merge_{\cap}(S[\overline{v}], p)$
1. `SetMaximum`, written $S[\overline{v} = p]$, is a new store where $v$'s maximum permission is set to $p$. It also performs $S[v = merge_{\cap}(p, S[\overline{v}])]$ to ensure that the effective permission is weaker than the maximum permission.
1. `Release`, written $S[=D]$, where $D$ is a set of tuples $V \times {\cal P}$ is the same as setting the effective permissions of all $(v, p) \in D$ in S. We call that _releasing_ D, because $D$ will be a set of dependencies we borrowed from the store.
1. `BeginBlock`, written $S[+]$, is a store where a new block has begun
1. `EndBlock`, written $S[-]$, is S with the most recent block removed
1. `Merge`, written $S \cap S'$, where S and S' have the same length and variables in the same order, is the result of intersecting all permissions in S with the ones at the same position in S'.

In the code, the store is a slice of structs where each struct contains a name, an effective permission, a maximum permission, and the number of times the variable has been referenced so far. Defining a new variable or beginning a new block scope prepends to the store.

```go
type Store []struct {
	name string
	eff  permission.Permission
	max  permission.Permission
	uses int
}
```
The beginning of a block scope is marked by a struct where the fields have their zero values, that is `{"", 0, 0, 0}`. More specifically,
such a block marker is identified by checking if the name field is empty. When exiting a block, we simply find the first such marker, and then create a slice starting with the element following it.

## Expressions
The function $\leadsto : Expr \times Store \to Permission \times (Variable, Permission) \times \text{set of } (Variable, Permission) \times Store$ (also called `VisitExpr` in the code)  abstractly interprets an expression in a store, checking permissions. It yields a new permission, an owner, a set of variables borrowed by the expression, and a new store.

The types `Borrowed` and `Owner` are pairs of a variable name and a permission, as mentioned before. There is a special `NoOwner` value of type `Owner` that represents that no owner exists for a particular expression.

The `Owner` vs `Borrowed` distinction is especially important with deferred function calls and the go statement. We will later see that the owner is the function (which may be a closure with a bound receiver), while any owners and dependencies of the arguments are forgotten.

There also is a sister function, `VisitExprOwnerToDeps` which does not return a owner, but instead inserts the owner into the list of dependencies. This is helpful in places where the owner is not interesting (it is not used in the formal notation, but will be seen in some code excerpts later).

In the following, we will look at the individual expressions and check how they evaluate.

#### Identifier: `id`

There are three cases of identifiers:

1. `nil` evaluates to the `nil` permission, it was created just for `nil` literals, since nil literals can be assigned to any nilable value (compare \fref{sec:ass-nil}).
2. `true` and `false` evaluate to the `om` permission, since they are just primitive values. They could just as well evaluate to any other (readable) base permission, but `om` has all bits set, making it the "strongest" one.
3. Any other identifier $id$ evaluates to the effective permission $e$ in the store. The effective permission in the store is replaced with an unusable one (converted to `n`), and the owner becomes $(id, e)$. The owner can later be released when
   the variable is no longer needed.

\begin{align*}
    \langle \textbf{nil}, s \rangle &\leadsto (nil, NoOwner, \emptyset, s) & \text{(P-Nil)}\\
    \langle \textbf{true}, s \rangle &\leadsto (om, NoOwner, \emptyset, s) & \text{(P-True)}\\
    \langle \textbf{false}, s \rangle &\leadsto (om, NoOwner, \emptyset, s)  & \text{(P-False)}\\
    \langle id, s \rangle &\leadsto (s[id], (id, s[id]), \emptyset, s[id = ctb(s[id], n)])  & \text{(P-Ident)}
\end{align*}

For a comparison, the code implementing this is shown in listing \ref{visitIdent}.

```{#visitIdent .go caption="Abstract interpreter for identifiers" float=t frame=tb}
func (i *Interpreter) visitIdent(st Store, e *ast.Ident) (permission.Permission, Owner, []Borrowed, Store) {
	if e.Name == "nil" {
		return &permission.NilPermission{}, NoOwner, nil, st
	}
	if e.Name == "true" || e.Name == "false" {
		return permission.Mutable | permission.Owned, NoOwner, nil, st
	}
	perm := st.GetEffective(e.Name)
	if perm == nil {
		i.Error(e, "Cannot borow %s: Unknown variable in %s", e, st)
	}
	owner := Owner{e, perm}
	dead := permission.ConvertToBase(perm, permission.None)
	st, err := st.SetEffective(e.Name, dead)
	if err != nil {
		i.Error(e, "Cannot borrow identifier: %s", err)
	}
	return perm, owner, nil, st
}
```
\label{sec:visitIdent}

#### Star Expression: `*E`
The star expression dereferences a pointer. Therefore we must evaluate the expression `E` and then dereference
the permission it returns, that is, return the target permission. For example:
```go
// E has permission om * l
*E  // permission l
```

\begin{align*}
    \frac{
        \langle E, s \rangle \leadsto (a * A, o, d, s') \text{ for some } a \subset {\cal R}, A \in {\cal P}}
    {
        \langle *E, s \rangle \leadsto (A, o, d, s')} && \text{(P-Star)
    }
\end{align*}

#### Binary expression: `A op B`
First a is evaluated in $s$, yielding $(P_a, o_a, d_a, s_a)$. The borrowed objects in $o_a$ and $d_a$ are released, yielding $s_a'$, and then b is evaluated in $s_a'$, yielding: $(P_b, o_b, d_b, s_b)$.
Its dependencies and owner are released as well, yielding $s_b'$.

For logical operators, that is $op \in \{\text{\lstinline/&&/}, \text{\lstinline/||/} \}$, the resulting store is generated by intersecting the store $s_a'$ with $s_b'$. This ensures that any code
executed after `A && B` is valid both if only `A` was executed (and false), and if both `A` and `B` were executed (because A was true).
\begin{align*}
\frac{\langle A, s\rangle \leadsto (P_a, o_a, d_a, s_a)  \qquad \langle B, s_a[=d_a \cup \{o_a\}] \rangle \leadsto (P_b, o_b, d_b, s_b) \qquad r \in P_a, P_b}{\langle A \text{ op } B, s \rangle \leadsto (om, NoOwner, \emptyset, s_a[=d_a \cup \{o_a\}] \cap s_b[= d_b \cup \{o_b\}])}   \\
    (\text{P-Logic, for all short-circuiting binary operators } op)
\end{align*}

For other operators, that is $op \not\in \{\text{\lstinline/&&/}, \text{\lstinline/||/} \}$, the resulting store is just the store after executing B, as there is no "short circuiting".
\begin{align*}
\frac{\langle A, s\rangle \leadsto (P_a, o_a, d_a, s_a)  \qquad \langle B, s_a[=d_a \cup \{o_a\}] \rangle \leadsto (P_b, o_b, d_b, s_b) \qquad r \in P_a, P_b}{\langle A \text{ op } B, s \rangle \leadsto (om, NoOwner, \emptyset, s_b[= d_b \cup \{o_b\}])}    \\
    (\text{P-Binary, for all not short-circuiting binary operators } op)
\end{align*}

In both cases, the result has no owner and no dependencies, and the permission `om`, as all binary operators produce primitive values, either boolean or numeric.

Examples:

```go
5 + 5       // om, no owner
a + b       // om, no owner
```

#### Index expression: `A[B]`
The index operator indexes an array, a slice, or a map (by the key type of the map). It can appear on the left-hand side of an assignment expression,
and it is also addressable (except for maps): It is legal to take its address with the `&` operator. Having it appear on the left-hand side means that
a map expression must move or copy the key into the map - we are storing a new value after all.
```go
someMap[someKey] = someValue        // someKey is either moved or copied into the map, as is someValue
```

We first evaluate the left side, then the index. If the left side is an array or a slice, the right side is a primitive value, so we can release its owner
and dependency if any (it is just an offset into an array), and then return the permission for the elements in the array or slice, with `A` being the owner
(as `A[B]` is part of A).
\begin{align*}
    \frac{
        \langle A, s \rangle \leadsto (p_a [] P_a, o_a, d_a, s_a)
        \quad \langle B, s_a \rangle \leadsto (P_b, o_b, d_b, s_b)
        \quad r \in p_a, p_b
    }{
        \langle A[B], s \rangle \leadsto (P_a, o_a, d_a, s_b[= o_b \cup d_b])
    } && \text{(P-SIdx)} \\
    \frac{
        \langle A, s \rangle \leadsto (p_a [\_] P_a, o_a, d_a, s_a)
        \quad \langle B, s_a \rangle \leadsto (P_b, o_b, d_b, s_b)
        \quad r \in p_a, p_b
    }{
        \langle A[B], s \rangle \leadsto (P_a, o_a, d_a, s_b[= o_b \cup d_b])
    } && \text{(P-AIdx)} \\
\end{align*}

In order to handle indexing maps, we need to take care of the left-hand-side situation mentioned above: The key must be copied or moved into the map. Since
we do not know whether the expression is on a left-hand or right-hand side, we must be conservative and assume it is on the left-hand side.

We can define a helper function, called `moveOrCopy` (listing \ref{moveOrCopy}), or short $moc$ (cases checked in order, top to bottom). $moc$ tries to
copy first, and then falls back to moving it or (in case of assigning an object of mutable linear permission to a non-linear one), making it immutable and then copying the value.

\begin{align*}
    moc(st, F, T, o, d) := \begin{cases}
        (st[= d \cup \{o\}], NoOwner, \emptyset) & \text{ if } ass_{cop}(F, T) \\
        \bot & \text{ if not } ass_{mov}(F, T) \\
        (st, o, d)  & \text{ if } o \not\in base(T) \\
        (st[= d \cup \{unlinear(o)\}], & \text{ if } lin(F) \\
                                       & \text{ and not } lin(T) \\
        (st, NoOwner, \emptyset) & \text{ else } \\
    \end{cases} \\
    \textbf{where }  unlinear(o) := \begin{cases}
        o & \text{ if } o = NoOwner \\
        (v, ctb(p, base(p) \setminus \{R,W,w\})) & \text{ else, } \exists $v$, $p$: o = (v, p)
    \end{cases}
\end{align*}

Explanations for each case:

1. The permission $F$ is copyable to $T$. This means that we can release the owner and dependencies back to the store - they no longer need to be borrowed.
2. The permission $F$ is not movable. This is an error case, all later cases require movability.
3. The target permission is unowned. We are just temporarily borrowing the object, so we keep the owner and dependencies around
4. We are moving a linear value to a non-linear value.
   This means we need to "freeze" the value, and any object containing it, that is make them immutable and non-linear.\label{sec:coarse-part-move}
5. We are doing any other kind of move. Since we handled copying in case 1, this means that we are moving a linear value to a linear value (a non-linear value
   would be copyable). Therefore, the owner and dependencies borrowed for $F$ will be forgotten, ensuring we cannot reach $F$
   via an alias once we moved it to $T$.

```{#moveOrCopy .go caption="The essential \lstinline|moveOrCopy| helper function" float=!hbt frame=tb}
func (i *Interpreter) moveOrCopy(e ast.Node, st Store, from, to permission.Permission, owner Owner, deps []Borrowed) (Store, Owner, []Borrowed, error) {
    switch {
    // If the value can be copied into the caller, we do not need to borrow it
    case permission.CopyableTo(from, to):
        st = i.Release(e, st, []Borrowed{Borrowed(owner)})
        st = i.Release(e, st, deps)
        owner = NoOwner
        deps = nil
    // The value cannot be moved either, error out.
    case !permission.MovableTo(from, to):
        return nil, NoOwner, nil, fmt.Errorf("Cannot copy or move: Needed %s, received %s", to, from)

    // All borrows for unowned parameters are released after the call is done.
    case to.GetBasePermission()&permission.Owned == 0:
    // Write and exclusive permissions are stripped when converting a value from linear to non-linear
    case permission.IsLinear(from) && !permission.IsLinear(to):
        if owner != NoOwner {
            owner.perm = permission.ConvertToBase(owner.perm, owner.perm.GetBasePermission()&^(permission.ExclRead|permission.ExclWrite|permission.Write))
        }
        st = i.Release(e, st, []Borrowed{Borrowed(owner)})
        st = i.Release(e, st, deps)
        owner = NoOwner
        deps = nil
    // The value was moved, so all its deps are lost
    default:
        deps = nil
        owner = NoOwner
    }

    return st, owner, deps, nil
}
```

With $moc$ defined, we are able to define $\leadsto$ for indexing maps. After evaluating the map and the key, we use $moc$
to copy or move the key into the map, and the permission for values of the map is returned (and the owner is the map).
\begin{align*}
    \frac{
        \langle A, s \rangle \leadsto (p_a \textbf{map}[K] V, o_a, d_a, s_a)
        \quad \langle B, s_a \rangle \leadsto (P_b, o_b, d_b, s_b)
        \quad r \in p_a, p_b
    }{
        \langle A[B], s \rangle \leadsto (V, o_a, d_a, s_b') \text{ where } s_b', o_b', d_b' = moc(s_b, P_b, K, o_b, d_b)
    } && \text{(P-MIdx)}
\end{align*}
As can be seen, if any owner and dependencies are remaining for $B$ after $moc$, these are forgotten too. This only affects
maps with unowned keys, as $moc$ otherwise always returns no owner and an empty dependency set.\label{sec:index-map}

One thing missing is indexing strings, which yields characters. Strings are represented as base permissions currently, but
probably deserve their own permission type.\label{sec:index-string}

#### Unary expressions
We have already seen one unary expression, the star expression. For unknown reasons, it is its own category of syntax node
in Go, while all the other unary expressions share a common type.

The first unary expression to discuss is `&E`, the _address-of_ operator. Taking the address of `E` constructs a pointer to it,
currently simply by wrapping it in an `om *`.
\begin{align*}
    \frac{
        \langle E, s \rangle \leadsto (P_e, o_e, d_e, s_e)
    } {
        \langle \&E, s \rangle \leadsto (om * P_e, o_e, d_e, s_e)
    } && \text{(P-Addr)}
\end{align*}
There is a problem with that approach and how assignment is handled: Given a variable `v` that is mutable, `&v` moves the
permission from the store to the expression, but only the effective permission is moved, as we saw in the definition for
identifiers before. This causes problems later when introducing assignment statements: They check the maximum permissions.
What should happen here is that we also take away the maximum permission of the owner, preventing any future re-assignment
and restoration of its effective permissions .\label{sec:address-of}

The next operation is `<-E`, the channel receive operation. The expression `E` is a channel, and the next value in it
is to be retrieved. The owner and the dependencies of the channel are essentially irrelevant: The value received from
the channel is not owned by the channel, but its owned by whatever is receiving it; the owner and dependencies can
thus be released immediately after evaluating the expression.

\begin{align*}
    \frac{
        \langle E, s \rangle \leadsto (p_e \textbf{ chan } P_e, o_e, d_e, s_e)
    } {
        \langle \leftarrow E, s \rangle \leadsto (P_e, NoOwner, \emptyset, s_e[= d_e \cup \{o_e\}])
    } && \text{(P-Recv)}
\end{align*}

Finally we have the "boring" case of other unary operators, like plus and minus. These are just working on primitive values, so
we can just return a new primitive owned mutable permission `om` and have no owner, since these construct new primitive values.
\begin{align*}
    \frac{
        \langle E, s \rangle \leadsto (P_e, o_e, d_e, s_e)
    } {
        \langle op\ E, s \rangle \leadsto (om, NoOwner, \emptyset, s_e[= d_e \cup \{o_e\}])
    } && \text{(P-Unary)}
\end{align*}

#### Basic literals
A basic literal `lit` just evaluates to an `om` permission, and obviously has no owner or dependencies.
\begin{align*}
    \langle lit, s \rangle \leadsto (om, NoOwner, \emptyset, s) && \text{(P-Lit)}
\end{align*}

#### Function calls
A function call $E(A_0, \ldots, A_n)$ is fairly simple: First of all, the function is evaluated, then the arguments, from left to right.
Owners and dependencies are collected until the end of the call, when they can be released. A special case in a function call are `go` statements and defer statements:
Here, no permissions are released, and the owner and the dependencies of the function become the owner and dependencies of the function expression.
This is needed: For deferred statement, the arguments are bound in place of the statement, but the function is only executed when unwinding the call stack,
hence these parameters need to be unreachable in the function where the statement is located. The Go statement is similar, except that execution is not
done when the stack unwinds, but on a different goroutine.
We define $\leadsto_{go/defer}$ for these cases, which is identical to $\leadsto$, except for the call expression, as specified below.

\begin{align*}
    \langle E, s \rangle &\leadsto (e \textbf{ func } (P_0, \ldots, P_n) (R_0, \ldots, R_r), o, d, s_{-1}) \\
    \langle A_i, s_{i-1} \rangle &\leadsto (P_{A_i}, o'_{i}, d'_{i}, s'_{i})   \\
    s_{i}, o_i, d_i &= moc(s'_{i}, P_{A_i}, P_i, o'_i, d'_i) \\
    \hline
    \langle E(A_0, \ldots, A_n), s \rangle &\leadsto_{go/defer} (results, o, d, s_{n})  & \text{if deferred or go}  \\
    \langle E(A_0, \ldots, A_n), s \rangle &\leadsto (results, NoOwner, \emptyset, rel(s_{n}))  & \text{else} \\
    \text{where } rel(s) &= s\left[= \{o\} \cup d \cup \bigcup\limits_{i=0}^{n} (d_i \cup \{o_i\})\right] \\
     results &= \begin{cases}
        R_0         & \text{if } r = 0 \\
        (R_0, \ldots, R_n) & \text{else}
    \end{cases}
\end{align*}\label{sec:functioncall}

One seemingly odd result of the rules is that an argument is moved into a deferred call or go call even if the parameter is unowned. Under normal circumstances binding an argument to an unowned parameter would just temporarily borrow it. But with a deferred call or go call, there is no clear point at which the call ends, hence it is not possible to release them again:

```go
// Case 1: deferred function call or go statement
defer function(arg)     // arg is linear and not copyable

// should not be able to use arg here, even if function parameter is unowned

// Case 2: Normal function call
function(arg)     // arg is linear and not copyable

// arg released (if parameter is unowned), should be able to use it
```

#### Slice expressions
The slice expression `A[L:H:M]` (where `L` - low, `H` - high, `M` - maximum (capacity of the slice) are optional) is simply evaluated left to right. For the purpose of this definition, let us assume that they all are specified. If either are unspecified, their owner would be `NoOwner`, their dependencies empty, and the store identical to the left-hand-side store.

\begin{align*}
\intertext{Therefore, if:}
    \langle A, s \rangle   &\leadsto (P_a, o_a, d_a, s_a) \\
    \langle L, s_a \rangle &\leadsto (P_l, o_l, d_l, s_l)      \qquad \text{ and } r \in base(P_l) \\
    \langle H, s_l \rangle &\leadsto (P_h, o_h, d_h, s_h)     \qquad \text{ and } r \in base(P_h)\\
    \langle M, s_m \rangle &\leadsto (P_m, o_m, d_m, s_m)      \qquad \text{ and } r \in base(P_m)\\
\intertext{Then, f $P_a$ is an array (has the form $a\ [\_]E$), the result becomes a slice of $E$s:}
    \langle A[L:H:M], s \rangle &\leadsto (om []E, o_m, d_m, s_m[= d_l \cup d_h \cup d_m \cup \{o_l, o_h, o_m\}]) \\
\intertext{Otherwise, if $P_a$ is a slice already, it stays one:}
    \langle A[L:H:M], s \rangle &\leadsto (P_a, o_m, d_m, s_m[= d_l \cup d_h \cup d_m \cup \{o_l, o_h, o_m\}])
\end{align*}

This is overly pessimistic: All owners and dependencies are only released at the end, they could be released earlier.\label{sec:slice}

##### Selector expression
The selector expression `E.I`, where `E` is an expression and `I` is an identifier seems simple. But Go allows embedding structs in others and accessing the fields of embedded structs without explicitly referencing the embedded struct:
```
type T struct { x int }
type U struct { T }

var u U

// u.x is u.T.x
```

Hence any such expression actually has to traverse a path.

Go defines three types of selections:

1. `FieldVal`, field values - a value indexed by a field name
2. `MethodVal`, method values - a value indexed by a method name
3. `MethodExpr`, method expressions - a type indexed by a method name

The type of selection really only applies to the last element in the path though: When selecting a path like `u.T.x` above, `T` must be a struct - a function (which the other cases would produce) cannot be selected.

It also provides a library function to translate a selection expression to a path of integers, referencing the fields / methods in the object that is being selected from. Let this function
produce a path $index_i$ ($0 \le i < n$) and $selectionKind$, one of the three selection kinds.

First of all, if we can evaluate the statement:

$$\langle E, s \rangle \leadsto (P_{-1}, o_{-1}, d_{-1}, s_{-1})$$

And next, can, for each step $i \ge 0$ in the path, perform a selection:

\begin{align*}
    (P_i, o_i, d_i, s_i) :&= selectOne(s_{i-1}, P_{i-1}, index_{i}, kind_i, o_{i-1}, d_{i-1}) \\
    \text{where } kind_i &= \begin{cases}
        selectionKind    & \text{if } i == n - 1 \\
        \text{\lstinline|FieldVal|}         & \text{else (as explained before)}
    \end{cases} \\
    \text{and } & selectOne() \text{ will be defined later}
\end{align*}

Then:
$$\langle E.I, s \rangle \leadsto (P_{n-1}, o_{n-1}, d_{n-1}, s_{n-1})$$

Now, $selectOne$ is tricky. Field values are simple, with one complication: Pointers are handled transparently - selecting a field in a pointer selects a field in the struct, as the language requires that.

\begin{align*}
    selectOne&(s, a * A, idx, \text{\lstinline|FieldVal|}, o, d)  \\
    &:= selectOne(s, A, idx, \text{\lstinline|FieldVal|}, o, d) \\
    selectOne&(s, a \textbf{ struct } \{A_0, \ldots, A_n\}, idx, \text{\lstinline|FieldVal|}, o, d) \\
         &:= (A_{idx}, o, d, s) \\
\intertext{Method expressions simply find the method, and prepend the receiver permission to the parameter permissions}
    selectOne&(s, a \textbf{ interface } \{A_0, \ldots, A_n\}, idx, \text{\lstinline|MethodExpr|}, o, d) \\
         &:= (recvToParams(A_{idx}), NoOwner, \emptyset, s[= d \cap \{o\}]) \\
         \text{where } & recvToParams(a (R) \textbf{ func } (P_0, \ldots, P_n) (R_0, \ldots, R_r)) \\
            &:= a \textbf{ func } (R, P_0, \ldots, P_n) (R_0, \ldots, R_r) \\
\intertext{For method values, we reuse the $moc$ function defined earlier to move or copy the lhs into the receiver. If we are binding an unowned receiver, the bound method value will be unowned too, to ensure we do not store an unowned value in an owned function value, as they have different lifetimes.}
    selectOne&(s, \overbrace{a \textbf{ interface } \{A_0, \ldots, A_n\}}^{= In}, idx, \text{\lstinline|MethodVal|}, o, d) \\
         &:= (stripRecv(maybeUnowned(A_{idx})), o', d', s') \\
         \text{where } & stripRecv(a (R) \textbf{ func } (P_0, \ldots, P_n) (R_0, \ldots, R_r)) \\
            &:= a \textbf{ func } (P_0, \ldots, P_n) (R_0, \ldots, R_r) \\
            & maybeUnowned(In, R) \\
            &:= \begin{cases}
                In & \text{if } o \in base(R) \\
                ctb(In, base(In) \setminus \{o\}) & \text{if } o \not\in base(R)
            \end{cases} \\
             (s', o', d') &:= moc(s, In, R, o, d)
\end{align*}

Method values and method expressions also exist on named types, but named types do not have an equivalent permission yet, and therefore, they are not implemented for these types. Introducing a permission equivalent to named types would have caused significant changes in the abstract interpreter and it was too late for that. An alternative would have been to associate method sets from named types with the permissions for their underlying types (for example, a pointer to struct). It is unclear how they would have to be handled on assignments, though. Can they be just ignored? More work is needed here.

#### Composite Literals

A composite literal `T {E_0, ..., E_n}` is fairly similar to a function calls. All values are moved or copied to their relevant position in the generated struct. However, dependencies are not released. There naturally is no owner, since the result is not part of a value reached from a variable.

There is one complication: The individual expressions may also be key-value expressions. Let's just assume that we have two functions $index(E_i)$ returning the index in the generated struct (which is $i$ if it is not a key-value expression, and $value(E_i)$ representing the permission of the value of the expression (which is just $E_i$ if it is not a key-value expression). These functions can be trivially implemented by looking at the type information provided by the `go/types` package.

The final algorithm looks like this:

1. Evaluate the type
2. Evaluate each argument, and move it to the corresponding position in the struct
3. Return the type's permission, with dependencies collected from the parameters.

\begin{align*}
    \langle T, s \rangle          &\leadsto (\overbrace{a \textbf{ struct } \{ A_0, \ldots, A_k \}}^{= P}, o_{-1}, d_{-1}, s_{-1})  \qquad k \ge n\\
    \langle value(E_i), s'_{i-1} \rangle &\leadsto (P_i, o_i, d_i, s_i) \\
\hline
    \langle T \{ E_0, \ldots, E_n\}, s \rangle &\leadsto \left(P, NoOwner, \bigcup\limits_{i=0}^{i \le n} d'_i \cup \{o'_i\}, s'_{n} \right) \\
        \text{where } (s'_{-1}, o'_{-1} d'_{-1}) &= (s_{-1}[= d_{-1} \cup \{o_{-1}\}], NoOwner, \emptyset) \\
                      (s'_i, o'_i, d'_i) &= moc(s_i, P_i, A_{index(E_i)}, o_i, d_i)
\end{align*}

An alternative approach that was considered is to construct the struct permission simply using the arguments, without the type info - just evaluate each argument and make a list of their permissions, essentially. This fails in two ways however: A composite literal may be incomplete, so the struct would have less fields then expected, and would thus not be assignable to the permission for the real type. Also, key-value expressions could not be handled without type info: It would not be clear where to put the permissions in the struct permission.

#### Function literals

Function literals will be handled in the statement section, since they require a lot of knowledge about statements.

## Statements
Statements are slightly more complex than expressions, (1) because they allow introducing new variable bindings in the current scope; and (2) because they allow jumping: There can be `return`, `goto`, `break`, `fallthrough` and all other kinds of statements in there.

There are two common ways to handle "early" exits in an interpreter:

1. Raise an exception (for example, a ContinueException, or BreakException)
2. Return a value for a block statement describing where the statement exited, and pass that through

In an abstract interpreter, option 1 does not work - there may be multiple exits involved; some leaving the block normally (by falling out of it), some with a branching statement.
The second option is applicable, with the change that instead of returning one value we return multiple ones. Each statement visitor returns pairs of

1. a new store, with the changes the statement made
2. an indicator of how the block was left (in this implementation, it is either nil or a pointer to the `ReturnStmt` or `BranchStmt` (`goto`, `break`, `continue`, `falltrough`)) \label{sec:exit-1}

Most statements return just one such pair, but if control flow is involved, there might be multiple, representing the individual paths.

Evaluating statements also needs access to the current function's permission. As such, we evaluate triplets of statement, store, and a function permission. The following sections refer to the statement evaluation function as

$$\rightarrow : Stmt \times Store \times \underbrace{FuncPermission}_\text{active function} \to \text{ set of } (\underbrace{Store}_\text{resulting store} \times \underbrace{(Stmt \cup \{nil\})}_{\text{jump/return, if any}}).$$

Some parts (assignments, blocks, and loops) are not easily to define in such a formal notation. They are explained as Go functions in literate programming style.

#### Simple statements
An expression statement simply evaluates the expressions, releases owners and dependencies afterwards, and returns the new store yielded by the expression.
\begin{align*}
    \frac{
        \langle E, s \rangle \leadsto (P, o, d, s')
    } {
        \langle ExprStmt(E), s, f \rangle \rightarrow \{(s'[= d \cup \{o\}], nil)\}
    }   && \text{(P-ExprStmt)}
\intertext{An increase/decrease statement like \lstinline|E++| needs read and write permissions for the expression \lstinline|E|.  Assign statements: `a := b` and `a = b` (the former defines the variable if not defined in the current block)
2. Declaration statement: `var a = b`, `var a` (the latter creates zero values)

Both of them share most of the implementation in the form of two functions: `defineOrAssign` which handles a single LHS expression[^lhs-expression] and a single RHS permission, and `defineOrAssignMany` which takes care of defining or assigning multiple (or zero) RHS to one or more LHS values.

The function `defineOrAssign` is the core function responsible for evaluating definitions and assignment.
The function starts by checking that the left-hand side is an identifier and defining it as necessary (or, if the identifier is `_`, by returning). Afterwards it evaluates the left-hand side (which is now defined), and then performs a move-or-copy from the right permission to the left.
```go
func (i *Interpreter) defineOrAssign(st Store, stmt ast.Stmt, lhs ast.Expr, rhs permission.Permission, owner Owner, deps []Borrowed, isDefine bool, allowUnowned bool) (Store, Owner, []Borrowed) {
	var err error

    <<define or assign lhs>>

	// Ensure we can do the assignment. If the left-hand side is an identifier, this should always be
	// true - it is either Defined to the same value, or set to something less than it in the previous block.

	perm, _, _ := i.visitExprOwnerToDeps(st, lhs) // We just need to know permission, do not care about borrowing.
	if !allowUnowned {
		i.Assert(lhs, perm, permission.Owned) // Make sure it is owned, so we do not move unowned to it.
	}

	// Input deps are nil, so we can ignore them here.
	st, owner, deps, err = i.moveOrCopy(lhs, st, rhs, perm, owner, deps)
	if err != nil {
		i.Error(lhs, "Could not assign or define: %s", err)
	}

	log.Println("Assigned", lhs, "in", st)

	return st, owner, deps
}
```

[^lhs-expression]: While the abstract syntax tree just has expressions in general on the left-hand side of an assignment, only certain expressions are allowed in practice (variables, indexing, field access, pointer dereference, wildcard).

The code handling defining or assigning the permission of the lhs first handles the underscore case, and then handles the define or assign:
```go
<<define or assign lhs>>=
// Define or set the effective permission of the left-hand side to the right-hand side. In the latter case,
// the effective permission will be restricted by the specified maximum (initial) permission.
if ident, ok := lhs.(*ast.Ident); ok {
    <<handle _>>

    if isDefine {
        <<define value>>
    } else {
        <<set value>>
    }

    if err != nil {
        i.Error(lhs, "Could not assign or define: %s", err)
    }
} else if isDefine {
    i.Error(lhs, "Cannot define: Left-hand side is not an identifier")
}
```

Handling the underscore case is simple: An assignment to `_` would be equivalent to just executing the expression on the right-hand side, that is, we can release owner and dependencies - it is not going to be moved anywhere.
```go
<<handle _>>=
if ident.Name == "_" {
    i.Release(stmt, st, []Borrowed{Borrowed(owner)})
    i.Release(stmt, st, deps)
    return st, NoOwner, nil
}
```

If we are evaluating a define statement, an annotation may be present. In that case, the actual RHS permission is converted (recall  \fref{sec:ctb} and \fref{sec:convert}) to the annotated permission to create the LHS permission. Otherwise, the LHS permission is the RHS permission (possibly subject to limits if the variable is already defined and we are in fact reassigning).\label{sec:annotated-permissions}
```go
<<define value>>=
log.Println("Defining", ident.Name)
if ann, ok := i.AnnotatedPermissions[ident]; ok {
    if ann, err = permission.ConvertTo(rhs, ann); err != nil {
        st, err = st.Define(ident.Name, ann)
    }
} else {
    st, err = st.Define(ident.Name, rhs)
}
```

Otherwise, when assigning rather than defining, we just set the effective permission to either the maximum permission the variable can hold (if it can be copied to it) or to the RHS permission (limited by the maximum permission, see \fref{sec:store}). The maximum case allows us to add permissions when copying, which is a property copying was designed to have (see \fref{sec:assign}).\label{sec:assign-set-value-max}
```go
<<set value>>=
if permission.CopyableTo(rhs, st.GetMaximum(ident.Name)) {
    st, err = st.SetEffective(ident.Name, st.GetMaximum(ident.Name))
} else {
    st, err = st.SetEffective(ident.Name, rhs)
}
```

The function `defineOrAssign` allows us to do 1:1 definitions and assignments, that is, cases where we have one value and one variable. There are more cases though: Tuples representing multiple return values can be unpacked, and there might simply be no values at all when defining (which would create zero values for their respective type, like `null` for a pointer type).

The function `defineOrAssignMany` takes care of that. It takes multiple LHS expressions and multiple RHS expressions, and then unpacks the RHS expressions into a list of permissions and a list of dependencies.
If there are less RHS expressions than LHS expressions, the missing ones are substituted with permissions for zero values, so we can handle cases like `var x int` where no values are specified.
Finally, `defineOrAssign` is called for each pair of LHS expression and `RHS` permissions.

```go
func (i *Interpreter) defineOrAssignMany(st Store, stmt ast.Stmt, lhsExprs []ast.Expr, rhsExprs []ast.Expr, isDefine bool, allowUnowned bool) Store {
	var deps []Borrowed
	var rhs []permission.Permission
	if len(rhsExprs) == 1 && len(lhsExprs) > 1 {
		<<unpack tuple>>
	} else {
        <<unpack multiple>>
	}

    <<fill rhs up with zero values>>
	if len(rhs) != len(lhsExprs) {
		i.Error(stmt, "Expected same number of arguments on both sides of assignment (or one function call on the right): Got rhs=%d lhs=%d", len(rhs), len(lhsExprs))
	}

	for j, lhs := range lhsExprs {
		st, _, _ = i.defineOrAssign(st, stmt, lhs, rhs[j], NoOwner, nil, isDefine, allowUnowned)
	}

	st = i.Release(stmt, st, deps)

	return st
}
```

Unpacking a tuple is simple: We evaluate the single RHS expression, and then take the tuple elements as the RHS dependencies. Since a tuple is the result of a function call (you might have noticed that is the only evaluation that can cause a tuple permission to be created) we do not really need to care about owners or dependencies, so we just collect them for releasing later.
```go
<<unpack tuple>>=
// These really cannot have owners.
rhs0, rdeps, store := i.visitExprOwnerToDeps(st, rhsExprs[0])
st = store
tuple, ok := rhs0.(*permission.TuplePermission)
if !ok {
    i.Error(stmt, "Left side of assignment has more than one element but right hand only one, expected it to be a tuple")
}
deps = append(deps, rdeps...)
rhs = tuple.Elements
```

When unpacking multiple RHS expressions, the idea is that all RHS values are asssigned to a temporary variable, and the temporary variables are assigned to the final ones later. The reason for that is that an operation like `a, b = b, a` -- or `(a,b) = (b,a)` in languages with more syntax -- swaps the variables, rather than making both be `b` afterwards.
```go
<<unpack multiple>>=
for _, expr := range rhsExprs {
    log.Printf("Visiting expr %#v in store %v", expr, st)
    perm, ownerThis, depsThis, store := i.VisitExpr(st, expr)
    log.Printf("Visited expr %#v in store %v", expr, st)
    st = store
    rhs = append(rhs, perm)

    // Screw this. This is basically creating a temporary copy or (non-temporary, really) move of the values, so we
    // can have stuff like a, b = b, a without it messing up.
    store, ownerThis, depsThis, err := i.moveOrCopy(expr, st, perm, perm, ownerThis, depsThis)
    st = store

    if err != nil {
        i.Error(expr, "Could not move value: %s", err)
    }

    deps = append(deps, Borrowed(ownerThis))
    deps = append(deps, depsThis...)
}
```

Finally, we fill up missing elements on the right with default permissions for their type - these will be zero values, as mentioned before.
```go
<<fill rhs up with zero values>>=
// Fill up the RHS with zero values if it has less elements than the LHS. Used for var x, y int; for example.
for elem := len(rhs); elem < len(lhsExprs); elem++ {
    var perm permission.Permission

    perm = i.typeMapper.NewFromType(i.typesInfo.TypeOf(lhsExprs[elem]))
    perm = permission.ConvertToBase(perm, perm.GetBasePermission()|permission.Owned)

    rhs = append(rhs, perm)

}
```

Now, as for the actual statements:

Assign and define (`=` and `:=`) are equivalent to `defineOrAssignMany`. They set the `isDefine` parameter to true if the token of the statement was `:=`, otherwise it is false. Unowned values are not allowed.

```go
func (i *Interpreter) visitAssignStmt(st Store, stmt *ast.AssignStmt) []StmtExit {
	return []StmtExit{{i.defineOrAssignMany(st, stmt, stmt.Lhs, stmt.Rhs, stmt.Tok == token.DEFINE, false), nil}}
}
```

Declaration statements of the form `var x, y = a, b` or just `var x, y` are more complicated. The declaration has a list of specifications, and each specification has a list of names and values. We therefore need to call `defineOrAssignMany` once per specification (there could also be other specifications). Unowned values are not allowed, and `isDefine` is always true.
```go
func (i *Interpreter) visitDeclStmt(st Store, stmt *ast.DeclStmt) []StmtExit {
    <<boring setup code>>

	for _, spec := range decl.Specs {
		switch spec := spec.(type) {
        case *ast.ValueSpec:
            names := <<convert spec.Names into a slice of expressions>>
			st = i.defineOrAssignMany(st, stmt, names, spec.Values, true, false)
		default:
			continue
		}
	}
	return []StmtExit{{st, nil}}
}
```

#### Special function calls: Go / Deferred
The go and defered statements are fairly simple. They consist of a call expression which is evaluated in go/defer
mode. If you recall the definition of function calls from \fref{sec:functioncall}, you will remember that the
dependencies of a deferred call are the dependencies of the function.

Now, there is one difference between `go` and `defer` calls: While neither release their owner, a `defer` call
releases unowned dependencies. As we have established before in \fref{sec:functioncall}, the dependencies of
a `go` or `defer` call are the dependencies of the function.

This has one important effect: If the function called is a function literal, the dependencies will correspond
to the captured variables. We can thus continue to work with unowned parameters in the function containing the
`defer` statement, even if the deferred call's literal captures the parameter.
```go
// @perm func(m * m)
function fooDefer(bar *int) {
    defer function() {
        ... bar ... // captured
    }
    ... bar ... // still works
}
// @perm func(m * m)
function fooGo(bar *int) {
    go function() {
        ... bar ... // captured
    }
    ... bar ... // does not work: bar is unusable after the go statement
}
```
This is legal because any unowned parameter will still be usable when the function exits.

\begin{align*}
\frac{
    \langle E(A_0, \ldots, A_n), s \rangle \leadsto_{go/defer} (P, o, d, s')
} {
    \langle \textbf{go } E(A_0, \ldots, A_n), s, f \rangle \rightarrow \{(s', nil)\}
}   && \text{(P-GoStmt)} \\
\frac{
    \langle E(A_0, \ldots, A_n), s \rangle \leadsto_{go/defer} (P, o, d, s')
} {
    \langle \textbf{defer } E(A_0, \ldots, A_n), s, f \rangle \rightarrow \{(s'[= \{(v, p) \in d | o \not\in p\}], nil)\}
}   && \text{(P-DeferStmt)}
\end{align*}

#### Branch and return statements
A branch statement is one of the statements `break`, `continue`, `goto`, or `fallthrough`. Evaluating it has no effect on the
store, but the statement is the statement in the result pair of $\rightarrow$.
\begin{align*}
    \langle B, s, f \rangle \rightarrow \{(s, B)\} \text{ for all branch statements } B    && \text{(P-BranchStmt)}
\end{align*}
A return statement is more complex: It might have 0 or more arguments, corresponding to the number of return values of the current
function. Each argument is moved-or-copied into the return "position" before the next argument is evaluated. The result is one pair:
the store after evaluating the last argument, and the return statement.

\begin{align*}
\frac{
    \langle A_i, s_{i-1} \rangle \leadsto (P_i, o'_i, d'_i, s'_i)   \quad s_i, o_i, d_i = moc(s_i', P_i, receivers(f)_i, o'_i, d'_i)
} {
    \langle \underbrace{\textbf{return } A_0, \ldots, A_n}_{=B}, s_{-1}, f \rangle \rightarrow \{(s_{n}, B)\}
}   && \text{(P-ReturnStmt)}
\end{align*}

#### Block statements
A block is generally evaluated like this: First begin a new block scope, then evaluate the statement list, and finally remove the block scope from all exits:

\begin{align*}
\cfrac{
    (s[+], [S_0, \ldots, S_n], false) \xrightarrow{visitStmtList} exits
}{
    \langle \{S_0; \ldots; S_n\}, s, f \rangle \rightarrow \{(s[-], b) | (s, b) \in exits\}
} && \text{(P-BlockStmt)}
\end{align*}

Now, interpreting the list of statements is difficult: The presence of `goto` statements can cause us to jump within the block, and `break`, `continue`, or `return` statements can jump out of the block. Instead of just iterating the statements in the block, we maintain a work stack and a seen set, each containing pairs of store and position (we call that the block manager. The block manager uses the seen set to determine if it should add work to the work stack, it will only add work it has not seen yet). As mentioned before, formal definition of `visitStmtList` will not be provided, only a literate programming style one.

The execution of blocks, switches, and loops all follow the same approach: First some setup is performed, and then, while there is work, the statement refered to by the work item is executed (after some pre and before some post code). One example is `visitStmtList` which handles non-loop lists of statements (block bodies, list of case clauses in switches and select statements):
```go
func (i *Interpreter) visitStmtList(initStore Store, stmts []ast.Stmt, isASwitch bool) []StmtExit {
    var bm blockManager // A helper type providing helper stuff

    <<setup>>
    for bm.hasWork() {
        item := bm.nextWork()   // pop a work item from the stack
        <<pre>>
        exits := i.visitStmt(work.Store, <<stmt>>) // interpret the statement
        <<post>>
    }

    return bm.exits
}
```
The `<<post>>` part usually splits the list of statement exits into exits of the block we are evaluating and further work, which gets added to the work stack (if not seen already). This means that it will evaluate the block for all possible inputs: For example, if we are evaluating a block with a conditional jump back to the beginning, it will follow the jump back and evaluate the block again for the state of the store before the jump. Since only unseen entries are added, the code will also terminate eventually.

Details:

The `<<setup>>` part just exits with the initial store if it there are no statements to execute. If it is a switch/select statement, the entry point is added as an exit, and each statement (which corrrespond to case clauses) is added to the work state. If it is just a normal block, we enter statement 0 in the block. We also collect all labels, building a map of strings to indices in the statement list:
```go
if len(stmts) == 0 {
    return []StmtExit{{initStore, nil}}
} else if isASwitch {
    bm.addExit(StmtExit{initStore, nil})
    for i := range stmts {
        bm.addWork(work{initStore, i})
    }
} else {
    bm.addWork(work{initStore, 0})
}
labels := collectLabels(stmts)
```

The `<<pre>>` part is empty.

The `<<stmt>>` is `stmts[item.int]`, that is, the statement in the list of statements at the index stored in the work item.

The `<<post>>` part is exciting. Each exit of the evaluated statement (inner exit) either becomes additional work or an exit of the current block. It depends on what the branch statement is:
```
    switch branch := exit.branch.(type) {
        <<case 1>>
        <<case 2>>
        <<case 3>>
    }
```
The cases are:

1.
    If the inner exit contains no branch or return statement, the next statement is added as work if we are not in a switch/select and there is at least one more statement in the list. Otherwise, the inner exit becomes an exit.
    ```go
    case nil:
        if len(stmts) > item.int+1 && !isASwitch {
                bm.addWork(work{exit.Store, item.int + 1})
            } else {
                bm.addExit(StmtExit{exit.Store, nil})
            }
    ```
2.
    If the inner exit contains a return statement, it becomes an exit of the current block:
    ```go
    case *ast.ReturnStmt:
        bm.addExit(exit) // Always exits the block
    ```
3.
    If the inner exit contains a branch statement:

    1. We are in a switch, it is a break, and the break applies to the current branch: Add the inner exit (without the branch statement) as an exit.
    1. We are in a switch, it is a fallthrough: The next case clause is added as work.
    1. It is a goto: If the target is in the current block, add it as work; otherwise, add the inner exit as an exit
    1. Otherwise, add the inner exit as an exit.

    ```go
    case *ast.BranchStmt:
        branchingThis := (branch.Label == nil || branch.Label.Name == "" /* | TODO current label */)
        switch {
        case isASwitch && branch.Tok == token.BREAK && branchingThis:
            bm.addExit(StmtExit{exit.Store, nil})
        case isASwitch && branch.Tok == token.FALLTHROUGH:
            bm.addWork(work{exit.Store, item.int + 1})
        case branch.Tok == token.GOTO:
            if target, ok := labels[branch.Label.Name]; ok {
                bm.addWork(work{exit.Store, target})
            } else {
                bm.addExit(exit)
            }
        default:
            bm.addExit(exit)
        }
    ```

#### The `for` loop
The evaluation of loops, either `for` or `range` statements
```go
for x := 0; x < 5; x++ { ... }
for key, val := range something { ... }
```
works the same way as `visitStmtList` from blocks, just with different `<<setup>>`, `<<pre>>` and `<<post>>` phases.

For the `for` statement, the `<<setup>>` consists of beginning a new block, and then visiting the initializing statement (`x := 0` in the example above).

```go
	initStore = initStore.BeginBlock()

	// Evaluate the container specified on the right-hand side.
	for _, entry := range i.visitStmt(initStore, stmt.Init) {
		if entry.branch != nil {
			i.Error(stmt.Init, "Initializer exits uncleanly")
		}
		bm.addWork(work{entry.Store, 0})
    }
```

The `<<pre>>` part consists of evaluating the condition in the store of the iteration, releasing its owner and dependencies (`visitExprOwnerToDeps` simply merges owner into dependencies), and adding the state after condition evaluation as an exit.
```go
    // Check condition
    perm, deps, st := i.visitExprOwnerToDeps(st, stmt.Cond)
    i.Assert(stmt.Cond, perm, permission.Read)
    st = i.Release(stmt.Cond, st, deps)
    // There might be no more items, exit
    bm.addExit(StmtExit{st, nil})
```

The `<<stmt>>` that will be evaluated is always `stmt.Body`, the body of the for loop. The position stored in the work item is thus not used at all.

The `<<post>>` part consists of classifying exits of the loop body into more iterations and direct exits, running the post statement for each next iteration in its store, and adding the direct exits to the loop's list of exits, after ending the block.
```go
    nextIterations, exits := i.collectLoopExits(exits)
    for _, nextIter := range nextIterations {
        for _, nextExit := range i.visitStmt(nextIter.Store, stmt.Post) {
            if nextExit.branch != nil {
                i.Error(stmt.Init, "Post exits uncleanly")
            }
            bm.addWork(work{nextExit.Store, 0})
        }
    }
    i.endBlocks(exits)
    bm.addExit(exits...)
```

The `collectLoopExits` function splits the exits of a loop's body into further iterations and exits of a loop.
```go
func (i *Interpreter) collectLoopExits(exits []StmtExit) ([]work, []StmtExit) {
	var nextIterations []work
	var realExits []StmtExit

	for _, exit := range exits {
		switch branch := exit.branch.(type) {
            <<case 1>>
            <<case 2>>
            <<case 3>>
		}
	}

	return nextIterations, realExits
}
```
The cases are:

1. No branch statement: The exit is another iteration

    ```go
    case nil:
        nextIterations = append(nextIterations, work{exit.Store, 0})
    ```
2. A return statement: The exit is a real exit

    ```go
    case *ast.ReturnStmt:
        realExits = append(realExits, exit)
    ```

3. A branch statement. A break of the current loop is an exit, a continue of the current loop a next iteration, anything else an exit.

    ```go
    case *ast.BranchStmt:
        branchingThis := branch.Label == nil || branch.Label.Name == "" /* | TODO current label */
        switch {
        case branch.Tok == token.BREAK && branchingThis:
            realExits = append(realExits, StmtExit{exit.Store, nil})
        case branch.Tok == token.CONTINUE && branchingThis:
            nextIterations = append(nextIterations, work{exit.Store, 0})
        default:
            realExits = append(realExits, exit)
        }
    ```

#### The `range` loop
The `range` statement is extremely similar to the `for` statement. It shares the `collectLoopExits` function, but there are a few differences related to it assigning values from a container. Notably, the block begins new for each iteration, and is released for all exits in the statement.

The `<<setup>>` part adds an exit for not entering the range (which will not evaluate the right-hand side at all, which might be wrong). It then evaluates the right-hand side, and defers the release of its dependencies until the end of the block. Finally, the permissions for key and values are extraced from the RHS, and the initial work is added.
```go
bm.addExit(StmtExit{initStore, nil})

// Evaluate the container specified on the right-hand side.
perm, deps, initStore := i.visitExprOwnerToDeps(initStore, stmt.X)
defer func() {
    if canRelease {
        for j := range rangeExits {
            rangeExits[j].Store = i.Release(stmt, rangeExits[j].Store, deps)
        }
    }
}()
i.Assert(stmt.X, perm, permission.Read)

var rkey permission.Permission
var rval permission.Permission

<<rhs permissions>>

bm.addWork(work{initStore, 0})
```

where `<<rhs permissions>>` determines the permissions for the key and value of what is being iterated:
```go
switch perm := perm.(type) {
case *permission.ArrayPermission:
    rkey = permission.Mutable
    rval = perm.ElementPermission
case *permission.SlicePermission:
    rkey = permission.Mutable
    rval = perm.ElementPermission
case *permission.MapPermission:
    rkey = perm.KeyPermission
    rval = perm.ValuePermission
}
```

The ``<<pre>>`` part begins a new block, and then uses `defineOrAssign` to define or assign (depending on whether it is a `for k, v := range` or a `for k, v = range` loop) the variables representing keys and values. This also modifies a `canRelease` variable that is used in the function deferred in `<<setup>>` - basically, if the LHS are owned, they are bound indefinitely, and we cannot release the container we are iterating over later.

```go
st = st.BeginBlock()
if stmt.Key != nil {
    st, _, _ = i.defineOrAssign(st, stmt, stmt.Key, rkey, NoOwner, nil, stmt.Tok == token.DEFINE, stmt.Tok == token.DEFINE)
    if ident, ok := stmt.Key.(*ast.Ident); ok {
        log.Printf("Defined %s to %s", ident.Name, st.GetEffective(ident.Name))
        if ident.Name != "_" {
            canRelease = canRelease && (st.GetEffective(ident.Name).GetBasePermission()&permission.Owned == 0)
        }
    } else {
        canRelease = false
    }
}
if stmt.Value != nil {
    st, _, _ = i.defineOrAssign(st, stmt, stmt.Value, rval, NoOwner, nil, stmt.Tok == token.DEFINE, stmt.Tok == token.DEFINE)
    if ident, ok := stmt.Value.(*ast.Ident); ok {
        log.Printf("Defined %s to %s", ident.Name, st.GetEffective(ident.Name))
        if ident.Name != "_" {
            canRelease = canRelease && (st.GetEffective(ident.Name).GetBasePermission()&permission.Owned == 0)
        }
    } else {
        canRelease = false
    }
}
```

As with `for`, the `<<stmt>>` is just the loop's body: `stmt.Body`.

The `<<post>>` step is shorter than for for loops, as there are no post statements. We can immediately end the block we began in `<<pre>>` (meaning the key and value variables are gone again), collect the exits. One difference here is that every next iteration is also a valid exit, since we might have just "reached" the end of the container.

```go
i.endBlocks(exits)
nextIterations, exits := i.collectLoopExits(exits)
bm.addExit(exits...)
// Each next iteration is also possible work. This might generate duplicate exits, but we have
// to do it this way, as we might otherwise miss some exits
for _, iter := range nextIterations {
    bm.addExit(StmtExit{iter.Store, nil})
}
bm.addWork(nextIterations...)
```

#### If statements and switches

An if statement consists of an initializer, a condition, a body, and an else case:
```go
if foo := 5; foo > bar {
    then
} else ...      // the ... is a statement as well. An else is optional
```

An if statement is evaluated as follows:

1. Create a new block
1. Evaluate the initializing statement. It must produce one exit (the syntax does not allow more, this simplifies thing)
1. Evaluate the condition expression. It must be readable, and its owner and dependencies are released.
1. Evaluate body and else part in the store that resulted from evaluating the condition.
1. Combine the exits of body and else to form the result, but remove the block we started at the beginning from their stores.

\begin{align*}
\cfrac{
    \langle S_0, s[+] \rangle \rightarrow \{(s_0, b_0)\} \qquad
    \langle E_1, s_0  \rangle \leadsto (P_1, o_1, d_1, s_1)    \quad r \in P_1
}{
    \cfrac{
        \quad \langle S_2, s_2, f \rangle \rightarrow exits_{then}
        \quad \langle S_3, s_2, f \rangle \rightarrow exits_{else}
    }{
        \langle \textbf{if } S_0; E_1 S_2 S_3, s, f \rangle \rightarrow \{(s[-], e) | (s, e) \in exits_{then} \cup exits_{else}\}
    }
} && \text{(P-IfStmt)}\\
\text{where }s_2 = s_1[= d_1 \cup \{o_1\}]
\end{align*}

A switch statement `switch INIT; TAG { BODY }`, where `BODY` is a list of case clauses, is evaluated like this:

1. Create a new scoping block
1. Evaluate the initializing statement.
1. For each possible exit: Evaluate the tag in the exit's store, and the body (with the cases being not entered, and entered for each case clause) in the store resulting from evaluating the tag.
1. For each exit of the body: Release the dependencies of the tag, and undo the block from the start.

\begin{align*}
\cfrac{
    \langle INIT, s[+] \rangle \rightarrow \{(s_0, b_0), \ldots, (s_n, b_n) \}
}{
    \cfrac{
        \langle TAG, s_i \rangle \leadsto (P_i, o_i, d_i, s'_i) \quad \forall 0 \le i \le n, r \in P_i
    }
    {
        \cfrac{
            (s'_i, BODY, true) \xrightarrow{visitStmtList} exits'_i \quad
            exits_i := \{(s[= d_i \cup \{o_i\}][-], e) | (s, e) \in exits'_i \}
        }{
            \langle \textbf{switch } INIT; TAG \{ BODY \}, s, f \rangle \rightarrow \bigcup\limits_{0 \le i \le n} exits_i
        }
    }
} \\ \text{(P-SwitchStmt)}
\end{align*}

It might be more readable in code form, as shown in listing \ref{visitSwitchStmt}.

```{#visitSwitchStmt .go caption="Abstract interpreter for switch statements" float=t frame=tb}
func (i *Interpreter) visitSwitchStmt(st Store, stmt *ast.SwitchStmt) []StmtExit {
	var exits []StmtExit

	st = st.BeginBlock()
	for _, exit := range i.visitStmt(st, stmt.Init) {
		st := exit.Store
		perm, deps, st := i.visitExprOwnerToDeps(st, stmt.Tag)
		if stmt.Tag != nil {
			i.Assert(stmt.Tag, perm, permission.Read)
		}

		for _, exit := range i.visitStmtList(st, stmt.Body.List, true) {
			exit.Store = i.Release(stmt.Tag, exit.Store, deps)
			exits = append(exits, exit)
		}
	}

	for i := range exits {
		exits[i].Store = exits[i].Store.EndBlock()
	}
	return exits
}
```

A case clause has the form `case E_0, ..., E_n: BODY` for some expression `E` and some statement `BODY`. The expressions are evaluated from left to right and the resulting stores are merged. Then the body is executed in the resulting store. Alternatively, the body could be executed for each store, but executing it once should be faster than executing it $n+1$ times.

\begin{align*}
\cfrac{
    \langle E_i, s_{i-1} \rangle \leadsto (P, o'_i, d'_i, s'_i)
    \quad r \in P
    \quad s_i = s'_i[=d'_i \cup \{o'_i\}]
}{
    \cfrac{
        \left(\bigcap\limits_{0 \le i \le n} s_i, BODY, false\right) \xrightarrow{visitStmtList} exits
    }{
        \langle \textbf{case } E_0, \ldots, E_n: BODY, s, f \rangle \rightarrow exits
    }
} && \text{(P-CaseClause)}
\end{align*}

#### Channel statements

The easiest channel statement is the send statement. Given a writable channel, and an object, we move-or-copy the object permission into the channel element permission. Any dependency and owner left over by $moc$ are then released.

\begin{align*}
\cfrac{
    \langle E_0, s \rangle \leadsto (c \textbf{ chan } C, o_0, d_0, s_0)
}{
\cfrac{
    \quad \langle E_1, s \rangle \leadsto (V, o'_1, d'_1, s'_1)
    \quad s_1, o_1, d_1 := moc(s'_1, V, C, o'_1, d'_1)
} {
    \langle E_0 \text{ \lstinline|<-| } E_1, s, f \rangle \rightarrow \{(s_1[= d_1 \cup \{o_1\}], nil)\}
}
}    && \text{(P-SendStmt)}
\end{align*}

There is arguably a bug here. We can send to a unowned channel containing unowned values, and the dependencies would be released. A channel containing unowned values should not exist in the first place, though, but sadly, it is entirely possible to define one at the moment.

The `select` statement allows waiting for non-blocking send/receive availability on a set of channels. It is thus similar to (and probably named after) the `select(2)` system call from 4.2BSD and POSIX.1-2001. The resulting exits will be the initial store (for the not-entered case), and those gained by jumping into each of the comm clauses in the body from the store (which is what `visitStmtList` does).

\begin{align*}
\cfrac{
    (s[+], BODY, true) \xrightarrow{visitStmtList} exits
} {
    \langle \textbf{select } \{ BODY \}, s, f \rangle \rightarrow \cup \{(s[-], e) for (s, e) \in exits\})\}
}    && \text{(P-SelectStmt)}
\end{align*}

A comm clause has the form `case STMT: BODY` for some statements `STMT` and `BODY`. First the statement is evaluated, and then the body is evaluated for each exit of the statement.

\begin{align*}
\cfrac{
    \langle STMT, s, f \rangle \rightarrow exits_0 \qquad
    exits := \bigcup\limits_{e \in exits_0} visitStmtList(store(e), BODY, false)
} {
    \langle \textbf{case } STMT: BODY, s, f \rangle \rightarrow exits
}  \\ \text{(P-CommClause)}
\end{align*}

#### Back to expressions: The function literal
Now that we have introduced statements, it's time to come back to the function literal expression which we deferred to a later point at the end of the expression section.
A function literal looks like a function, but without a name.

The first step is to get the type of the function literal to look up things like parameter names, swapping the currently active function (represented by the third element in the formal notation),
and then calling a helper function that builds a function.
```go
func (i *Interpreter) visitFuncLit(st Store, e *ast.FuncLit) (permission.Permission, Owner, []Borrowed, Store) {
	oldCurFunc := i.curFunc
	if i.typeMapper == nil {
		i.typeMapper = permission.NewTypeMapper()
	}
	typ := i.typesInfo.TypeOf(e).(*types.Signature)
	i.curFunc = i.typeMapper.NewFromType(typ).(*permission.FuncPermission)
	defer func() {
		i.curFunc = oldCurFunc
	}()
	return i.buildFunction(st, e, typ, e.Body)
}
```

The helper function `buildFunction` has been extracted because it will also be useful with function declarations in a package. It defines receivers and parameters, interprets the function body,
and then collects all captured variables and moves them "into" the closure, so they cannot be modified by the parent function. They are also added as dependencies, so the caller could still
release them back - if we recall, that's what happens for unowned variables if a function literal is deferred.
```go
func (i *Interpreter) buildFunction(st Store, node ast.Node, typ *types.Signature, body *ast.BlockStmt) (permission.Permission, Owner, []Borrowed, Store) {
	var deps []Borrowed
	var err error
	origStore := st
	perm := i.typeMapper.NewFromType(typ).(*permission.FuncPermission)
	perm.BasePermission |= permission.Owned

	st = st.BeginBlock()
	<<define stuff>>

	exits := i.visitStmtList(st, body.List, false)
	st = append(NewStore(), origStore...)
	for _, exit := range exits {
        <<collect captures>>
	}

	return perm, NoOwner, deps, st
}
```

Defining receivers and parameters is a rather boring affair. This should actually also define any named return values, but that's not
```
<<define stuff>>=
if len(perm.Receivers) > 0 {
		for _, recv := range perm.Receivers {
			st, err = st.Define(typ.Recv().Name(), recv)
			if err != nil {
				i.Error(node, "Cannot define receiver %s", err)
			}
		}
	}

	params := typ.Params()
	for j := 0; j < params.Len(); j++ {
		param := params.At(j)
		st, err = st.Define(param.Name(), perm.Params[j])
		if err != nil {
			i.Error(node, "Cannot define parameter %d called %s: %s", j, param.Name(), err)
		}
	}
```

Collecting the captured variables is a rather simple affair. We just visit every variable in the exit store that has a higher
use count than in the input store, and move it to the dependencies of the function permission. We also adjust the permission
of the literal: If we capture an unowned variable, the function becomes unowned too so we have the same narrower life time
(since unowned objects cannot be stored).
```
<<collect captures>>=
		exit.Store = exit.Store.EndBlock()
        <<verify that store has same length as before>>

		for j := range exit.Store {
            <<several safety checks>>
			if exit.Store[j].uses <= origStore[j].uses {
				continue
			}
			log.Printf("Borrowing %s = %s", st[j].name, exit.Store[j].eff)
			deps = append(deps, Borrowed{ast.NewIdent(st[j].name), st[j].eff})
			st[j].eff = permission.ConvertToBase(st[j].eff, 0)
			log.Printf("Borrowed %s is now %s", st[j].name, st[j].eff)
			st[j].uses = exit.Store[j].uses

			if exit.Store[j].eff.GetBasePermission()&permission.Owned == 0 && perm.GetBasePermission()&permission.Owned != 0 {
				log.Printf("Converting function to unowned due to %s", exit.Store[j].name)
				perm = permission.ConvertToBase(perm, perm.GetBasePermission()&^permission.Owned).(*permission.FuncPermission)
			}
		}
```

The use counting actually happens in the store, but it is buggy: It only happens for definitions and assignments, not for
read accesses (because the store is passed by value, and while we increase the count, that change is thus not visible outside
the function doing the lookup).

repository: julian-klode/lingolang

repo_name: julian-klode/lingolang


text:
# Notify Slack Lambda

Allow cloudwatch events to trigger a lambda and post a summary in to a slack channel.
Sourced and modified from https://github.com/terraform-aws-modules/terraform-aws-notify-slack

## To set up

Login to the AWS console and navigate to EC2. Down the bottom left of the screen, you can navigate to SYSTEMS MANAGER SHARED RESOURCES, Parameter Store.
Create a secure string Parameter which contains your Slack Webhook. This encrypts your webhook using KMS so that it is never stored in plaintext in AWS.
Use path based notation for your Parameter name i.e. `/$environment/lambda/slack_webhook_url`. You will need to pass this in as a variable to this module. Path based names allow you to apply granular permissions for who can access parameter store entries.

## To add alarms

Go to the `alarms` module and follow the existing template. The alarm that is currently provisioned is likely to fire once per day.

## Usage
This will list off any inputs that are required and whether or not they have a default variable.

| Variable name | Description | Default Y/N | Default value|
|---------------|-------------|-------------|--------------|
| lambda_function_name | The name of the Lambda function to create | Y | notify_slack |
| slack_webhook_url_ssm_path | The SSM paramether path to the URL of Slack webhook | N |  |
| slack_channel | The name of the channel in Slack for notifications (including the #) | N |  |
| slack_username | The username that will appear on Slack messages | N |  |
| slack_emoji | A custom emoji that will appear on Slack messages - including the `::` | Y | :aws: |
|  |  |  |  |

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
date: 2019-04-25
title: SDK Release 6.0.0
description: Release notes of the 6.0.0 version and other minor releases
categories:
  - releases
  - sdk
type: Document
---

## 6.4.9

- [External links]({{ site.baseurl }}{% post_url /development-guide/2020-05-18-external-links %})
- [Font support]({{ site.baseurl }}{% post_url /development-guide/2018-02-11-text %}) (for now only San Francisco and its variations)
- Support for [videos from files]({{ site.baseurl }}{% post_url /development-guide/2020-05-04-video-playing %})
- Picture frame support for any NFT from Open Sea
- Picture frame support for GIF NFTs
- [Open picture frame UI]({{ site.baseurl }}{% post_url /development-guide/2018-02-01-display-a-certified-nft %})
- New reflection texture on metallic materials
- Preview keeps loading even when browser window is inactive
- Hide/Show DCL UI by pressing the U key
- Several scene-loading optimizations

## 6.4.8

- Support for [audio streaming]({{ site.baseurl }}{% post_url /development-guide/2018-02-10-sounds %}#streaming-sound)
- Support for [video streaming]({{ site.baseurl }}{% post_url /development-guide/2020-05-04-video-playing %})
- Support for external texture URLs with upper and lower case

- Bug Fixes:
  - Fixed issue with flickering of textures while loading, which sometimes made objects transparent or partially transparent
  - An OnPointerDown component is no longer passed on to an entity's parents
  - Invisible entities no longer show on-hover click feedback.
  - On-hover click feedback no longer shown when entities are too far to click

## 6.4.7

- Support for 3rd person view in preview (use _v_ to toggle)
- Placeholder values for [user name an ID when in preview]({{ site.baseurl }}{% post_url /development-guide/2018-02-22-user-data %})

## 6.4.5

- [Obtain the server and layer of the player]({{ site.baseurl }}{% post_url /development-guide/2018-02-22-user-data %}#get-user-realm-data).
- Customize the [on-hover text]({{ site.baseurl }}{% post_url /development-guide/2018-02-14-click-events %}#pointer-event-components) on clickable entities.

- Bug Fixes:
  - NFT picture frames work
  - Various performance and stability improvements

## 6.4.4

- On-hover feedback for clickable entities [Button events]({{ site.baseurl }}{% post_url /development-guide/2018-02-14-click-events %})
- The rays of button events don't go through other entity's colliders.
- Mouse sensitivity improved, making it easier to point at small objects
- Bug Fixes:

* Camera rotation includes all axis again
* Player less likely to fall off moving platforms

## 6.4.3

- Optimized queuing of raycasting messages. See [Raycasting]({{ site.baseurl }}{% post_url /development-guide/2018-02-27-raycasting %}#recurrent-raycasting) for details.
- Fine tuned messaging budget per frame to handle more actions in the scene
- Bug fixes:

  - Players now take their time to fall, instead of falling instantly
  - Various animations fixes, including support for animations that are non-skeletal or that have rotations, colliders, or transitions with non-linear curves.
  - Fixed _uv_ mapping of textures created via code
  - Triangle count in the Panel now properly reflects true triangles being used.
  - Issue fixed with large animations that were timing out and not loaded into the scene
  - Issue fixed where cursor gets stuck for a few seconds when leaving the preview window and then returning.

## 6.4.2

- Material colors now support Color4 to include alpha values easily
- Bug fixes:

* The UITextInput now retunrs the provided text in the "value" field
* The player no longer loses control of the pointer when standing on a rotating platform
* The player no longer instantly teleports to the ground when falling off a cliff
* Transparent materials using AlphaTest mode now work as expected

## 6.4.1

- More detailed feedback when entities are out of scene bounds, marking mesh bounding boxes
- Various bug fixes:

* Original material for entities out of scene bounds is restored on hot reload
* Alpha clipping is fixed on 3D models that use partially transparent textures
* Players can jump from slanted ground
* Scene spawning points defined on `scene.json` work on preview
* Repeated 3D models with animations now all play
* P2P communication fixed between local isntances of a scene running in preview
* Large scene loading time performance improvements

## 6.4.0

- Raycasting
- Global `BUTTON_DOWN` and `BUTTON_UP` events
- Support for `PRIMARY` and `SECONDARY` button events (_E_ and _F_ keys, on a keyboard)
- If player is standing on an entity, they now move together with that entity
- Entities that extend outside scene boundaries are now marked as red
- Fixed bugs

  - Several bugs with entity lifecycle when adding and removing from engine
  - Several bugs with billboard mode

## 6.3.2

- Support for Billboard component
- Bug fixes related to scene loading & lifecycle

## 6.3.1

- Support for OnPointerDown and OnPointerUp events
- Camera height adjusted slightly, so avatars see each other eye-to-eye
- Support for hot-reload and export functionalities with the latest CLI version
- Bug fixes and performance improvements

## 6.3.0

- NFT picture frames support
- All shapes, including primitives, have collisions by default
- GLTFShapes can have collisions dissabled
- Several optimizations

## 6.2.4

- Entities that have `visible = false` can't be clicked
- Several optimizations
- Bug fixes - Fix parsing of materials on GLTFs (normal maps, emissive maps, roughness maps, etc)

## 6.2.3

- Bug fixes - Fix parsing of materials on GLTFs (emissive, specular, etc)

## 6.2.2

- Important optimizations, specially for scenes with multiple transforms updated on every frame
- Updated Unity engine to latest version: `2019.1.8.f1`
- Reduced fog levels and other art adjustments to materials
- Bug fixes: - Fix Z-fighting between surfaces that are close to each other - Entities that share a same shape component can be removed independently without affecting the other - Fix alignment of children of UIContainerStack components - Audio can now be looped - Audio sounds no longer start on the first frame if not explicitly played - Fixed exaggerated doppler effect, that was most notable when running - AnimationClip.Stop() now returns the model to the first frame of the animation

## 6.2.1

- Unlock cursor by pressing `Esc` only once (used to require pressing `Esc` twice)
- `Enter` key focuses or leaves from chat
- Change empty floor texture
- Bug fixes: - Fix UI positioning - `setParent(null)` now sets an entity to be a child of the scene object - Removed entity now can be re-added to engine

## 6.2

- Bug fixes: - Very large scenes disappear when walking too far from origin

## 6.1.5

- Serverless multiplayer: Send messages over content server, publish - subscribe
- Bug fixes: - Emissive and transparent materials for primitives fixed - Alignment of TextShape components - Audio fixed work as positional - UI positioning when set to invisible

## 6.1.3

- Bug fixes: - Emissive materials fixed for primitives - Camera.position & Camera.rotation fixed

## 6.1.2

- UI screen space limited to not use the top 10% of the screen
- Decentraland UI components always rendered on top layer, above screen-specific UIs
- Bug fixes

## 6.1.1

- Unity set as the default engine
- Various bug fixes

## 6.1

- Unity engine integration - Shadows - Various optimizations
- Components for player UIs, see [UI]({{ site.baseurl }}{% post_url /development-guide/2018-02-15-onscreen-ui %}) for details.

## 6.0.1 - Beta

- Fix a bug with entity positions out of bounds
- Rename the `AnimationClip` object to `AnimationState` for more clarity
- Rename the `BUTTON_A_DOWN` and `BUTTON_A_UP` events to `BUTTON_DOWN` and `BUTTON_UP`

## 6.0 - Beta

This release includes the following new features

- Each parcel now measures 16 x 16 meters. This was decided via a vote by the community. New scenes created with the CLI are 16 x 16, old scenes remain as 10 x 10, but we recommend migrating to a 16 x 16 format. Scene limitations per each parcel haven't changed since 5.0.

- Improved audio engine: Multiple audio samples can be played at once. Also, each audio sample has a specific location. See [Sounds]({{ site.baseurl }}{% post_url /development-guide/2018-02-10-sounds %}) for details.

```ts
const trevor = new Entity()

//Create audio clip
const audioClip = new AudioClip("sounds/Vexento.mp3")
audioClip.loop = true

//Create audio source
const audioSource = new AudioSource(audioClip)
trevor.addComponent(audioSource)

engine.addEntity(trevor)
```

- Custom events are now possible, using functions to emit and listen for them.

This version includes several bug fixes and optimizations. It also includes the following changes:

- 3D model animations are now handled by an `Animator` component, instead of by the `GLTFModel` component.

  ```ts
  let shark = new Entity()
  // Create Animator component
  const animator = new Animator()
  shark.addComponent(animator)

  // Create animation clips
  let clipSwim = new AnimationState("swim")
  let clipBite = new AnimationState("bite")
  animator.addClip(clipBite)
  animator.addClip(clipSwim)

  // Activate swim animation
  clipSwim.play()

  engine.addEntity(shark)
  ```

- Textures are now handled by a specialized `Texture` component, that can be referenced by a `Material` component.

  ```ts
  let wheel1 = new Entity()

  // Create texture
  const spiralTexture = new Texture("materials/hypno-wheel.png")

  // Create material
  let spiralMaterial = new Material()
  spiralMaterial.albedoTexture = spiralTexture

  // Add material to wheels
  wheel1.addComponent(spiralMaterial)

  engine.addEntity(wheel1)
  ```

- Billboard mode is now done via a separate specialized component, instead of by setting a property in shape components.

  ```ts
  let box = new Entity()
  box.addComponent(new BoxShape())
  box.addComponent(
    new Transform({
      position: new Vector3(5, 1, 5),
    })
  )
  box.addComponent(new Billboard())
  engine.addEntity(box)
  ```

* Basic commands for handling components are renamed for more clarity. For example `get` is now `getComponent`, `add` is now `addComponent` and `set` is now `addComponentOrReplace`.

See the []() migration guide for clear examples of how to migrate your code.

Read the [release announcement(https://decentraland.org/blog/announcements/introducing-sdk-6-beta/) blogpost for more details about these new features!

> Note: All 3D models are now rotated 180 degrees along the Y axis to follow standards that are consistent with most other platforms. Any 3D models in your scene will now be rendered facing backwards. You may have to reposition or rotate your entities to compensate for this new rotation. Also, we now check that 3D models are within scene bounds by looking at the bounding boxes, not at each individual vertex. This is a lot more efficient, but some 3D models may have empty bounding boxes that stretch far beyond the vertexes. If that's the case, you'll have to clean up the 3D model so that the bounding boxes more closely match the vertexes of the model.

repository: tmacha/documentation

repo_name: tmacha/documentation


text:
[![Build Status](https://travis-ci.org/boustrophedon/nqueens-various-rs.svg?branch=master)](https://travis-ci.org/boustrophedon/nqueens-various-rs)

A Rust library featuring structs for representing, doing stuff with, and solving [N-Queens problems](https://en.wikipedia.org/wiki/Eight_queens_puzzle).

I wanted to do this to test implementing some basic AI algorithms and also try out [rayon](https://github.com/nikomatsakis/rayon).

# TODO
Unify solvers into a trait with something like `solve_one` and `all_solutions` and a unified error type.

repository: boustrophedon/nqueens-various-rs

gha_language: Rust

repo_name: boustrophedon/nqueens-various-rs


text:
Represent youtube videos inside a modal in your gittbook
==============

![Link](screenshot1.png)

![Video](screenshot2.png)

This plugins requires gitbook `>=2.0.0`.

### How to use?

Add plugin to your `book.json`, then run `gitbook install`:

```
{
    plugins: ["modal-youtube-video"]
}
```

Add youtube video source and a label for the link after the space

```

{% modalYoutube %}https://www.youtube.com/watch?v=0fKg7e37bQE Look at this video!{% endmodalYoutube %}
```

The video will be replace by the link with given label which opens a modal when clicked.

### Add custom html code to appear in the modal header

It is also possible to add some custom html code which will appear in the modal's header. Imagine, you'd like some link to appear there.
Use pipe to separate youtube link from label and from your custom html header code:

```

{% modalYoutube %}https://www.youtube.com/watch?v=0fKg7e37bQE |Look at this video!|<a href="#">This is my custom header link!</a>{% endmodalYoutube %}
```
Your custom header will appear on the left of close button:

![Video](screenshot3.png)

repository: VishalMewadaPackt/Demo-Test

repo_name: VishalMewadaPackt/Demo-Test


text:
### 1. Tizen on RPi3 GBS build

#### Prerequisites

* Install SDB tool (https://developer.tizen.org/development/tizen-studio/download)

  It is required to send file to target, which is in Tizen Studio.

* Modify sources.list of Ubuntu

  It is a buil system to create Tizen RPM package.
  To install gbs in your system, it's required to add the Tizen tools repository to the source list
  ```
  $ sudo vim /etc/apt/sources.list
  ```

  In Ubuntu 16.04, append the following line to the source list:
  ``` bash
  deb [trusted=yes] http://download.tizen.org/tools/latest-release/Ubuntu_16.04/ /
  ```

  In Ubuntu 14.04, append the follwing line to the source list:
  ``` bash
  deb http://download.tizen.org/tools/latest-release/Ubuntu_14.04/ /
  ```

* Install GBS

  ``` bash
  sudo apt-get update
  sudo apt-get install gbs
  ```

* Prepare a GBS configuration file.

 You can use sample gbs configuration in config/tizen/sample.gbs.conf.

 See https://source.tizen.org/documentation/reference/git-build-system/configuration-file for details.

#### Building
* You can modify IoT.js build option on the spec file.
(config/tizen/packaging/iotjs.spec)

* Run gbsbuild.sh at first.
Compile:
``` bash
./config/tizen/gbsbuild.sh
```

The following options are provided.
```
--debug: Build output is 'debug'. If this option is not specified, it is 'release'.
--clean: Make a clean gbs build by deleting the old build root.
```

### 2. Bring up RPi3 with Tizen
Please see the following guide to bring up your RPI3 target with Tizen.
You can refer "Raspberry Pi 3" section of command-line-flash part.

https://developer.tizen.org/development/iot-preview/getting-started/flashing-tizen-images#command-line-flash

#### Setting up serial port
 Please refer the tizen wiki  https://wiki.tizen.org/Raspberry_Pi#Debugging

#### Setting up IP

You can set up IP using WiFi or Ethernet

* Setup IP on RPi3 target using WiFi:

  https://developer.tizen.org/development/iot-preview/getting-started/flashing-tizen-images#wifi-setup

* Setup IP on RPi3 target using ethernet
``` bash
 User id/passwd : root / tizen
 (target)$ ifconfig eth0 down
 (target)$ ifconfig eth0 <IP_ADDRESS> netmask <IP_ADDRESS> up
 (target)$ route add default gw <IP_ADDRESS>
```

  If you want to use your fixed ip when you reboot, add ip settings in /etc/profile.

  Please make sure to run before modifying /etc/profile.
```
(target) $ mount -o remount,rw /
```
``` bash
 (ubuntu)$ sdb pull /etc/profile
 (ubuntu)$ vi profile

 Adding the following configurations
 ifconfig eth0 down
 ifconfig eth0 <IP_ADDRESS> netmask <IP_ADDRESS> up
 route add default gw <IP_ADDRESS>

 (ubuntu)$ sdb push profile /etc/
```

#### SDB connection
 Now you can connect RPi3 on Ubuntu PC

``` bash
(ubuntu)$ sdb connect <IP_ADDRESS>
 ```

#### Install
Transfer iotjs binary and test file to the device:
``` bash
(ubuntu)$ sdb push  ~/GBS-ROOT/local/repos/tizen_unified_m1/armv7l/RPMS/iotjs-1.0.0-0.armv7l.rpm /tmp
(ubuntu)$ sdb push ./test/run_pass/test_console.js /home/owner/iotjs/
(ubuntu)$ sdb root on
(ubuntu)$ sdb shell
(target)$ cd /tmp
(only in headless Tizen 4.0 target)$ mount -o remount,rw /
(target)$ rpm -ivh --force iotjs-1.0.0-0.armv7l.rpm
```

#### Run the test:
``` bash
(ubuntu)$ sdb shell
(target)$ iotjs test_console.js
```

repository: TizenTeam/iotjs

gha_language: JavaScript

gha_license_id: NOASSERTION

repo_name: TizenTeam/iotjs


text:
//[colors-core](../../../index.md)/[com.chrynan.colors](../index.md)/[NamedColor](index.md)/[name](name.md)

# name

[common]\
fun [name](name.md)(languageCode: [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) = "en"): [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)?

Retrieves the first name for the provided [languageCode](name.md). If there are multiple [names](names.md) with the provided [languageCode](name.md), then the first one is returned. If there are no [names](names.md) for the provided [languageCode](name.md), then null is returned. The [languageCode](name.md) defaults to the value of "en".

repository: chRyNaN/colors

repo_name: chRyNaN/colors


text:
# Design Patterns

    Design Pattern: Design pattern is a general repeatable solution to a commonly occurring problem in software design.

    Types of design pattern:
        A. Creational Pattern: ~ is a way to create new objects which increases the flexibility and reusability of existing code.
        B. Structural Pattern: ~ is a way to assemble objects and classes into a large structure which keeps the structure flexible and efficient.
        C. Behavioral Pattern: ~ is a way to communicate between objects and the assignment of responsibilities between objects.
        D. Concurrency Pattern:

        A.Creational Pattern:
          1. Abstract Factory: Abstract Factory is a creational design pattern which provides an interface for creating families of related or
              dependent objects without specifying their concrete classes.
	      // ~ is a creational design pattern which creates factory method.
          2. Factory: Factory method is a creational design pattern which provides an interface for creating an object but let the subclasses decide which class
              to instantiate.
	     // ~ is a creational design pattern which creates another object. Also known as Virtual Constructor.
          3. Builder: Builder is a creational design pattern which separates the construction of a complex object from its representation so that
              the same construction process can create different representations.
          4. Lazy Initialization: Lazy Initialization is a way to delaying initialization of resources or objects until they’re actually needed to
	  	improve performance and save system resources.
          5. Singleton: Singleton is creational design pattern which creates one instance of a class in the duration of runtime.
          6. Prototype: Prototype is creational design pattern that lets you copy existing objects without making your code dependent on their classes.

        B. Structural Patter:
          1. Adapter: The Adapter pattern is a design pattern which converts the interface of a class into another interface clients expect.
              It is often used to make existing classes work with others without modifying their source code.
	      //Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.
          2. Decorator: The Decorator pattern is a design pattern which gives to add new functionality to an existing object without altering its stucture.
          3. Facade: Facade is a structural design pattern which gives us a simplified interface of a complex sub system.
          4. Bridge: Bridge is a structural design pattern that decouples an abstraction from its implementation so that the two can vary independently.
		//Bridge is a structural design pattern that lets split a large class or a set of closely related classes into two separate hierarchies—abstraction and
	  	implementation—which can be developed independently of each other.
          5. Proxy: Proxy is a structural design pattern which provides a substitute or placeholder for another object.
          6. Flyweight: Flyweight is a structural design pattern that allows programs to support vast quantities of objects by keeping their memory consumption low.
          7. Composite: Composite is a structural design pattern that allows composing objects into a tree-like structure and work with it as a singular object.

        C.Behavioral Pattern:
          1. Chain of Responsibility: Chain of Responsibility is a behavioral design pattern that lets us pass requests along a chain of handlers.
              Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
          2. Strategy Pattern: Strategy Pattern is a design pattern in which a class behavior or its algorithm can be changed at run time.
              //Define a family of algorithms, put each of then into a separate class and make their objects interchangeable.
          3. Iterator: Iterator is a behavioral design pattern that lets us traverse elements of a collection without exposing its underlying representation.
          4. Observer: Observer is a behavioral design pattern that lets us define a subscription mechanism to notify multiple objects about any events that
              happen to the object they're observing. //When one object change its state, all dependent objects are notified & updated automatically(Event-Subscriber-Listener).
          5. State: State is a behavioral design pattern that lets an object to alter its behavior when its internal state changes.
          6. Command: Command is a behavioral design pattern that converts a request into a stand-alone object that contains all information about the request.
          7. Template: Template is a behavioral design pattern that allows to define a skeleton of an algorithm in a base class and let subclasses override the steps without
	  	changing the overall algorithm’s structure.
          8. Visitor: Visitor is a behavioral design pattern that allows adding new behaviors to existing class hierarchy without altering any existing code.
          9. Interpreter:
          10. Mediator: Mediator is a behavioral design pattern that defines an object that encapsulates how a set of objects interact. It reduces the coupling between the
		classes communicating with each other.
          11. Memento: Memento pattern is a behavioral design pattern that provides the ability to restore an object to its previous state (undo via rollback).

    * The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object.
    Coupling: Coupling means the degree of one module depend on other module.
      	$storage = new Storage();
      	$user->new User($storage);//$user depend on $storage//

    Dependency Injection: Dependency Injection is where components are given through their constructor,method or directly into field as a dependency.
      	//storage components gives as constructor to user.

    Dispatch: Dispatch is a process of select a method at run time.
	  Trait: Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, cannot be instantiated on it’s own.

repository: kabircse/Design-Principle-Pattern

repo_name: kabircse/Design-Principle-Pattern


text:
# v0.1.3

* Add recipes for nginx, unicorn and database
* capify task will write nginx configs for each stage

# v0.1.2

* Fix a bug with stage being used outside of the cap instance

# v0.1.1

* Remove harded stages in config/deploy.rb
* Improvements to interactive configuration
* Make ssh user configurable, defaults to deployer

# v0.1.0

Released *rake capify* task. Provides an interactive version of capify.

# v0.0.1

Initial release.

* Provides capistrano, multistage capistrano and rvm capistrano gems