Since we've kicked off the implementation effort for this effort, let me make a thread for organizing the implementation design. I want to start us off with a bunch of AST design points. This isn't exhaustive of the things we have to talk about, but it was as much as I could write before I got exhausted, so.
AST design requirements
I want to run through what we need at a high level and then talk about some practical engineering questions about them.
Function scope parameters and arguments
Functions can have a scope signature, i.e. a list of scope parameters and (eventually) requirements on them.
We expect to synthesize a large number of scope parameters. Non-escapable types in the signature generally need to be "saturated" by providing scope arguments. In the parameter list, this will typically involve synthesizing a new scope parameter for each position that isn't explicitly constrained in source. This includes ownership positions: a borrowing parameter is borrowed for some scope, and so there's a scope parameter associated with that. In results and yields, there will be a default-dependency rule that allows certain results to be implicitly constrained to e.g. the borrow scope of the self parameter; otherwise, it'll probably have to generally be an error for the programmer to fail to saturate that type. (See below for implementation considerations about this inference.)
Just like function generic signatures, we do not expect that source code will have a syntax for explicitly providing scope arguments to calls or function references. (We may (eventually) have a Scope type that can be used as an ordinary argument, similar to how metatype arguments can be used to suggest a binding for a type parameter.) As far as functions are concerned, scope arguments can therefore be represented as a parallel list to the scope parameters.
Unlike function generic signatures, we do need to (eventually) handle function values that remain scope-polymorphic. For essentially the same reasons, scope signatures can be nested in types, and we will also need to handle substituting outer signatures through scope signatures (see below).
The only requirement on scopes (by themselves) that we expect to ever have is that one scope can be required to "outlast" (last at least as long as) another scope. This requirement can only usefully be between two scope variables. This is because the only globally-expressible scope, the immortal scope, trivializes this relationship in either position: the immortal scope outlasts every scope, and a scope constrained to outlast the immortal scope must be the immortal scope. However, either of these variables could potentially be bound in an enclosing context; they do not have to be parameters of the current scope signature.
Scope signatures can be nested, and we do need to make substitution work through them (see below).
We may (eventually) need the concept of a scope parameter pack, similarly to type parameter packs, in order to deal with things like packs of spans. Of course, these packs will be dynamically erased just like everything else with scopes.
Type scope parameters and arguments
Types can also have a scope signature.
It's unclear whether we will be inferring scope parameters for type signatures. We will likely need to for source compatibility with existing declarations of ~Escapable types. There are several cases for this, however. Types that are unconditionally ~Escapable must have at least one scope parameter, but it may be more appropriate for them to have two or more, e.g. if they store several independent non-escapable values. Conditionally ~Escapable must not have scope parameters; their scope constraints are expressed in the structure of their type arguments.
Scope arguments on types cannot simply be positionally ordered because that makes things like declaration order part of the source and ABI signature of the type. Instead, scope arguments need to be named. On the other hand, we do not want the predominant case of a single scope parameter to require a name to be written out. This could be special-cased either by the number of scope parameters or by allowing a single scope parameter to be "primary". Primary parameters have the advantage of theoretically allowing scope parameters to be added and defaulted in latter evolutions of the type, although it is unclear whether this is really a useful idea.
In any event, we can probably get away with making the representation of scope parameters and arguments positional in the AST, picking an arbitrary linearization in the declaration and then matching it when checking uses.
There are a number of language design questions open here that will impact the eventual implementation, but I don't think this affects the representation too much given that arbitrary-linearization approach.
If we have to infer scope parameters from the members of the type, that will be a serious circularity and compatibility problem. It is unclear which members to consider, for example: just stored properties? Just at the top level of the type?
Even if we don't infer scope parameters, saturating ~Escapable types used in the struct definition is a thorny problem. Types used in method signatures, of course, can be saturated using the inference rule for functions. We can saturate positions in the types of stored properties using the containing struct's scope parameter, but is that okay? Is it okay to fill multiple positions in the same type? Is it okay to fill positions in multiple properties? And should computed properties use the function rule or the stored-property rule, given that using the function rule probably makes it difficult to evolve back-and-forth between stored and computed properties of ~Escapable type?
Implementation concerns
Representational efficiency of inferred scope parameters
Every non-consuming parameter has a corresponding scope parameter for its ownership. Even if it's not used within the signature, it can be referenced within the body. We really don't want to have to represent those parameters explicitly; it would be a dramatic inflation in memory use. We can probably use a system where these parameters are implicit, just identified by depth and index.
Similarly, we don't want to have to represent scope arguments for these. This is more annoying because we do need to fill in something if we e.g. inline the function in SIL and see a reference to the implicit scope parameter. Ideally, we will be able to infer the scope argument from SIL structure rather than having to represent it explicitly in every SIL call that merely involves non-consumed parameters.
Representational efficiency of scope variables in general
We expect to generate a lot of scope variables within functions as well. Some of these will be the "concrete" scopes of specific borrows and mutating accesses, but a lot of them will be temporary, unresolved variables around e.g. specific function calls. The type-checker's constraint solver introduces arena-allocated type variables for this latter purpose, which it can safely throw away after type-checking is complete. But there isn't such an obvious time limit for these unresolved scope variables because of the way we intend to generate and resolve them across different SIL passes. Moreover, some of them (the "holes" of flow-sensitively checked local variables) may never be completely eliminated from SIL.
We therefore need a representation for these scope variables which allows them to be quickly "allocated" within a context without actually taking up memory that we have no reasonable way to reuse. The obvious option is some kind of integer value that the scope environment can keep information about in a side-table. (It may be convenient to use several different integer sequences, but ultimately this should be a compact, at-most-64-bit representation). We can encapsulate the structure of this value so that code within the compiler is generally not exposed to it. The main impact is that the scope variable will generally not be able to answer questions about itself (such as its known scope relationships), and instead this sort of state will have to be kept in side-tables in the active scope environment, which can be kept in the DeclContext or SILFunction. As long as such data is relatively sparse, this should still minimize the memory overhead.
ABI stability for function scope parameters
Like function generic signatures, it is probably not important that two logically-equivalent scope-polymorphic functions actually canonicalize the same way.
However, unlike other generics, we are likely to extensively infer scope parameters, and we should make some effort to ensure that writing these scope parameters explicitly doesn't break the ABI of the function. The straightforward way to do this is to number the parameters in some canonical order based on their first use in the function signature, since the structure of the function signature is easily linearized and must contain a reference to every scope parameter.
There are some annoying complexities here around sugared types. An application of a typealias might have a different order of reference from its underlying type. The number should consider the underlying type so that the ABI doesn't become sensitive to the use of the typealias.
In fact, an application of a typealias might have a scope argument that doesn't even appear in the underlying type, and we have to decide how scope parameter inference handles that. It might be acceptable to fill in the scope parameter with immortal; otherwise, we might have to diagnose it.
Dealing with first-class scope polymorphism
Dealing with first-class scope polymorphism mostly means that merely having a reference to a scope-polymorphic function value should not immediately "open" the scope signature. Instead, the signature is only opened when it is used in specific ways. Calls, obviously, must open the signature and provide all the necessary scope arguments. Conversions can also require opening the signature and binding the scope parameters. Values of scope-polymorphic function type can be converted to either polymorphic or non-polymorphic function types, and in general, the conversion is valid if a forwarding call would be valid.
Converting between polymorphic types this way permits scope changes that represent significant narrowings of the original function's scope signature. However, it's also useful for other reasons: it also papers over differences between signature canonicalizations that are non-obviously equivalent.
A function may be scope-polymorphic, and this includes closures. Whether the function created by a closure expression is scope-polymorphic is completely orthogonal to whether it captures scope parameters or ~Escapable values from its enclosing function: you can have a scope-polymorphic closure defined in a context with no scope parameters, and conversely you can have a closure with no scope parameters defined in a scope-polymorphic function.
Scope parameters referenced from the enclosing context are not scope parameters of the function created by the closure expression. They are captures, just like type parameters of the enclosing context are captures. Since they are scope-restricted, they can be referenced only in non-escaping closures.
At the SIL level, however, these scope parameters will still be scope parameters of the lowered closure function (again, just like type parameters of the enclosing function are). Since the function created by the closure may still be scope-polymorphic, we must be able to partial_apply part of the lowered function's scope signature in SIL.
Substituting nested scope signatures
Probably the biggest issue with dealing with scope-polymorphic values is that scope signatures can appear in nested positions in types, which implies that substituting outer signatures needs to be able to descend into nested signatures. This introduces the risk that substitution will introduce a scope variable reference within the scope signature that will be "captured" by the signature, when what was really meant was for it to refer to something bound in an outer environment. There are no perfect solutions to this problem; every approach adds complexity to the representation and/or substitution.
These problems are especially real given that we intend to use a lightweight, integer-based representation for scope variables. Freshly-allocated variables would not be completely immune to capture bugs, but they would at least make them significantly less likely.
The two main alternatives here are generally called de Bruijn indices and de Bruijn levels. (Technically, I think we would have a two-dimensional approach where there's also an index within a level, which would generally not need to be be adjusted by substitution.)
de Bruijn indices number depth from the inside out. Therefore:
- The meaning of "variable at depth 0 and index 2" can change at different depths in the same type expression, so clients walking a type will generally need to track all the signatures they've passed through and remember what depth a particular type was written at.
- Variables that are not replaced by a substitution can always be left alone.
- If the replacement of a type or scope variable includes a reference to a scope variable that is not bound within the replacement, and the substitution has passed through one or more scope signatures, the replacement must be rewritten to use a scope variable with a different depth.
de Bruijn levels number depth from the outside in. Therefore:
- The meaning of a type variable doesn't change by the depth of a type expression.
- Variables that are not replaced by a substitution may still need to be rewritten if the substitution is changing the level of depth of the overall type expression.
- If the replacement of a type contains a scope signature, the scope signature and any scope variable references within it must be rewritten to have the proper depth.
On balance, I think de Bruijn levels are probably the way to go here.
Representing scope arguments on types
The chief question here is whether scope arguments should be an adjustment to a type node or part of the type node. Suppose we have this concete type:
struct IntSpan: ~Escapable {}
IntSpan has an implicit scope parameter. For sake of argument, let's assume that's spelled @_scoped(S) IntSpan in source code. Where is this reference to the scope variable S stored?
In the current compiler, IntSpan is represented as a StructType with a reference to the StructDecl* and no other structure. In the new world, this represents an unsaturated type, and we will continue to need to be able to represent it, for several reasons:
Firstly, we will have the ability to abstract over unsaturated types in the language. You can't have a variable with the unsaturated type IntSpan, but you can use the unsaturated type IntSpan for certain specific type arguments or associated types. One such associated type is Iterable.BorrowingIterator. This associated type does not carry a specific scope restriction on the iterator that can be derived from the type that conforms to Iterable. That is because individual iterator values are restricted more narrowly than the type of the original container: we want makeBorrowingIterator() to return an iterator that's restricted to the scope of this specific borrow of the container.[1] So the associated type is still scope-polymorphic, and we expect to saturate it whenever we write it, either with an explicit scope specifier or just with scope signature inference.
Secondly, the current request is that the type-checker shouldn't have to deal with scope arguments. This means that we want to do constraint solving in a mode that strips scope arguments from types. So the type of a call to a function that returns an IntSpan will still just be IntSpan coming out of the type-checker, and then we will saturate it with scope arguments later.
Finally, all of this work is experimental, and we don't want it to change the existing behavior of the compiler. So current language modes need to continue to represent this as IntSpan until we get to the point that we're satisfied that we can compatibly rebase the current handling of non-escapable types on top of the new infrastructure we're adding.
Still, we do also need to be able to represent @_scoped(S) IntSpan in the type system. We could do this with a separate ScopeRestrictedType node that wraps the StructType, but that would mean that we'd need to preserve that node in a bunch of places that currently expect a NominalType. We could this with a ScopeRestrictedStructType node, but then we'll have to deal with that node in all the places that expect StructType, exactly like already do with the StructType / BoundGenericStructType distinction.[2] Also, since bound-generic types can also carry scope restrictions, we'd really need two new such nodes. I think a better approach would be to allow StructType to just carry scope arguments directly.
In contrast, if
Elementwere~Escapable, we would want it to be a saturated associated type: we expect the type of the container to tell us the scope restrictions on the elements it stores, probably expressed in a generic argument of the tye, and we can't change those restrictions in random places where we writeElement. ↩︎Eventually, I think we should get rid of this as well and just allow
StructTypeto carry generic arguments (ideally as aSubstitutionMap). ↩︎