{{Short description|Family of type systems based on substructural logic}} <!--{{One source|date=February 2018}}--> {{Type systems}}
'''Substructural type systems''' are a family of type systems analogous to substructural logics where one or more of the structural rules are absent or only allowed under controlled circumstances. Such systems can constrain access to system resources such as files, locks, and memory by keeping track of changes of state and prohibiting invalid states.<ref name="Walker">{{cite book |first=David |last=Walker |editor1-first=Benjamin C. |editor1-last=Pierce |editor1-link=Benjamin C. Pierce |year=2002 |title=Advanced Topics in Types and Programming Languages |publisher=MIT Press |isbn=0-262-16228-8 |chapter=Substructural Type Systems |pages=3–43 |url=https://mitpress-request.mit.edu/sites/default/files/titles/content/9780262162289_sch_0001.pdf}}</ref>{{rp|p=4}}
== Different substructural type systems == Several type systems have emerged by discarding some of the structural rules of exchange, weakening, and contraction: {{table alignment}} {| class="wikitable defaultcenter col5left" |+ !Type systems !Exchange !Weakening !Contraction !Use |- ! {{rh|align=right}} | Ordered |{{N/A}} |{{N/A}} |{{N/A}} |Exactly once, in the order<br/>it was introduced |- ! {{rh|align=right}} |Linear |Allowed |{{N/A}} |{{N/A}} |Exactly once |- ! {{rh|align=right}} |Affine |Allowed |Allowed |{{N/A}} |At most once{{efn|The explanation for affine type systems is best understood if rephrased as “every ''occurrence'' of a variable is used at most once”.}} |- ! {{rh|align=right}} |Relevant |Allowed |{{N/A}} |Allowed |At least once |- ! {{rh|align=right}} |Normal |Allowed |Allowed |Allowed |Arbitrarily{{efn|Every variable may be used arbitrarily.}} |}
=== Ordered type system === ''Ordered types'' correspond to noncommutative logic where exchange, contraction and weakening are discarded. This can be used to model stack-based memory allocation (contrast with linear types which can be used to model heap-based memory allocation).<ref name="Walker"/>{{rp|pp=30–31}} Without the exchange property, an object may only be used when at the top of the modelled stack, after which it is popped off, resulting in every variable being used exactly once in the order it was introduced.
=== Linear type systems === ''Linear types'' correspond to linear logic and ensure that objects are used exactly once. This allows the system to safely deallocate an object after its use,<ref name="Walker"/>{{rp|p=6}} or to design software interfaces that guarantee a resource cannot be used once it has been closed or transitioned to a different state.<ref name="BernardyEtAl">{{cite journal |title=Linear Haskell: practical linearity in a higher-order polymorphic language |last1=Bernardy |first1=Jean-Philippe |last2=Boespflug |first2=Mathieu |last3=Newton |first3=Ryan R |last4=Peyton Jones |first4=Simon |author4-link=Simon Peyton Jones |last5=Spiwack |first5=Arnaud |journal=Proceedings of the ACM on Programming Languages |volume=2 |year=2017 |pages=1–29 |doi=10.1145/3158093 |arxiv=1710.09756 |s2cid=9019395 |url=https://dl.acm.org/doi/pdf/10.1145/3158093}}</ref>
The Clean programming language makes use of uniqueness types (a variant of linear types) to help support concurrency, input/output, and in-place update of arrays.<ref name="Walker"/>{{rp|p=43}}
Linear type systems allow references but not aliases. To enforce this, a reference goes out of scope after appearing on the right-hand side of an assignment, thus ensuring that only one reference to any object exists at once. Note that passing a reference as an argument to a function is a form of assignment, as the function parameter will be assigned the value inside the function, and therefore such use of a reference also causes it to go out of scope.
The single-reference property makes linear type systems suitable as programming languages for quantum computing, as it reflects the no-cloning theorem of quantum states. From the category theory point of view, no-cloning is a statement that there is no diagonal functor which could duplicate states; similarly, from the combinatory logic point of view, there is no K-combinator which can destroy states. From the lambda calculus point of view, a variable <code>x</code> can appear exactly once in a term.<ref name="Baez">{{cite book |last1=Baez |first1=John C. |last2=Stay |first2=Mike |url=http://math.ucr.edu/home/baez/rosetta/rose3.pdf |chapter=Physics, Topology, Logic and Computation: A Rosetta Stone |date=2010 |title=New Structures for Physics |editor=Springer |pages=95–174}}</ref>
Linear type systems are the internal language of closed symmetric monoidal categories, much in the same way that simply typed lambda calculus is the language of Cartesian closed categories. More precisely, one may construct functors between the category of linear type systems and the category of closed symmetric monoidal categories.<ref name="Ambler">{{cite thesis |title=First order logic in symmetric monoidal closed categories |last=Ambler |first=S. |date=1991 |publisher=U. of Edinburgh |type=PhD |url=http://www.lfcs.inf.ed.ac.uk/reports/92/ECS-LFCS-92-194/}}</ref>
=== Affine type systems === ''Affine types'' are a version of linear types allowing to ''discard'' (i.e. ''not use'') a resource, corresponding to affine logic. An affine resource ''can'' be used ''at most'' once, while a linear one ''must'' be used ''exactly'' once.
=== Relevant type system === ''Relevant types'' correspond to relevant logic which allows exchange and contraction, but not weakening, which translates to every variable being used at least once.
== The resource interpretation ==
{{see-also|Linear logic#The resource interpretation}}
The nomenclature offered by substructural type systems is useful to characterize resource management aspects of a language. Resource management is the aspect of language safety concerned with ensuring that each allocated resource is deallocated exactly once. Thus, '''the resource interpretation''' is only concerned with uses that transfer ownership – ''moving'', where ownership is the responsibility to free the resource.
Uses that don't transfer ownership – ''borrowing'' – are not in scope of this interpretation, but ''lifetime semantics'' further restrict these uses to be between allocation and deallocation.
{| class="wikitable" |+ !Type !Disowning move !Obligatory move !Move quantification !Enforcible function call state machine |- ! {{rh|align=right}} | Normal |{{No}} |{{No}} |{{Any}} number of times |Topological ordering |- ! {{rh|align=right}} | Affine |{{Yes}} |{{No}} |At most once |Ordering |- ! {{rh|align=right}} | Linear |{{Yes}} |{{Yes}} |Exactly once |Ordering and completion |}
=== Resource-affine types ===
Under the resource interpretation, an ''affine'' type cannot be spent more than once.
As an example, the same variant of Hoare's vending machine can be expressed in English, logic and in Rust:
{| class="wikitable" |+ Vending machine |- ! English !! Logic !! Rust |- | A coin can buy you<br />a piece of candy, a drink,<br /> or go out of scope. || Coin ⊸ Candy<br />Coin ⊸ Drink<br />Coin ⊸ ⊤ || <syntaxhighlight lang="rust"> fn buy_candy(_: Coin) -> Candy { Candy{} } fn buy_drink(_: Coin) -> Drink { Drink{} } </syntaxhighlight> |}
What it means for {{mono|Coin}} to be an affine type in this example (which it is unless it implements the {{mono|Copy}} trait) is that trying to spend the same coin twice is an invalid program that the compiler is entitled to reject:
<syntaxhighlight lang="rust"> let coin = Coin {}; let candy = buy_candy(coin); // The lifetime of the coin variable ends here. let drink = buy_drink(coin); // Compilation error: Use of moved variable that does not possess the Copy trait. </syntaxhighlight>
In other words, an affine type system can express the typestate pattern: Functions can consume and return an object wrapped in different types, acting like state transitions in a state machine that stores its state as a type in the caller's context – a ''typestate''. An API can exploit this to statically enforce that its functions are called in a correct order.
What it doesn't mean, however, is that a variable can't be used without using it up:
<syntaxhighlight lang="rust"> // This function just borrows a coin: The ampersand means borrow. fn validate(_: &Coin) -> Result<(), ()> { Ok(()) }
// The same coin variable can be used infinitely many times // as long as it is not moved. let coin = Coin {}; loop { validate(&coin)?; } </syntaxhighlight>
What Rust is not able to express is a coin type that cannot go out of scope – that would take a linear type.
=== Resource-linear types ===
Under the resource interpretation, a ''linear'' type not only ''can'' be moved, like an affine type, but ''must'' be moved – going out of scope is an invalid program.
<syntaxhighlight lang="rust"> { // Must be passed on, not dropped. let token = HotPotato {};
// Suppose not every branch does away with it: if !queue.is_full() { queue.push(token); }
// Compilation error: Holding an undroppable object as the scope ends. } </syntaxhighlight>
An attraction with linear types is that destructors become regular functions that can take arguments, can fail and so on.<ref>{{cite web |title=Vale's Vision |url=https://vale.dev/vision/vision |access-date=6 December 2023 |quote=Higher RAII, a form of linear typing that enables destructors with parameters and returns.}}</ref> This may for example avoid the need to keep state that is only used for destruction. A general advantage of passing function dependencies explicitly is that the order of function calls – destruction order – becomes statically verifiable in terms of the arguments' lifetimes. Compared to internal references, this does not require lifetime annotations as in Rust.
As with manual resource management, a practical problem is that any early return, as is typical of error handling, must achieve the same cleanup. This becomes pedantic in languages that have stack unwinding, where every function call is a potential early return. However, as a close analogy, the semantic of implicitly inserted destructor calls can be restored with deferred function calls.<ref name="defer">{{cite web |title=Go by Example: Defer |url=https://gobyexample.com/defer |access-date=5 December 2023 |quote=Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ''ensure'' and ''finally'' would be used in other languages.}}</ref>
=== Resource-normal types ===
Under the resource interpretation, a ''normal'' type does not restrict how many times a variable can be moved from. C++ (specifically nondestructive move semantics) falls in this category.
<syntaxhighlight lang="C++"> auto coin = std::unique_ptr<Coin>(); auto candy = buy_candy(std::move(coin)); auto drink = buy_drink(std::move(coin)); // This is valid C++. </syntaxhighlight>
== Programming languages == The following programming languages support linear or affine types{{Cn|date=September 2023}}: {{div col}} * ATS * Clean * Idris * Mercury * F* * [https://github.com/pikatchu/LinearML LinearML] * [http://users.eecs.northwestern.edu/~jesse/pubs/alms/ Alms] * Haskell with Glasgow Haskell Compiler (GHC) 9.0.1 or above<ref>{{Cite web |title=6.4.19. Linear types — Glasgow Haskell Compiler 9.7.20230513 User's Guide |url=https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/linear_types.html |access-date=2023-05-14 |website=ghc.gitlab.haskell.org}}</ref> * [https://granule-project.github.io/ Granule] * Rust * Swift 5.9 and above<ref>{{Cite web|url=https://www.hackingwithswift.com/swift/5.9/noncopyable-structs-and-enums|title=Noncopyable structs and enums – available from Swift 5.9|first=Paul|last=Hudson @twostraws|website=Hacking with Swift}}</ref>{{div col end}}
==See also== * Effect system * Linear logic * Affine logic
==Notes== {{Notelist|2}}
== References == {{Reflist|2}}
Category:Type theory Category:Articles with example Rust code