Substructural type system

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.[1]: 4 

Different substructural type systems

Several type systems have emerged by discarding some of the structural rules of exchange, weakening, and contraction:

Exchange Weakening Contraction Use
Ordered Exactly once in order
Linear Allowed Exactly once
Affine Allowed Allowed At most once
Relevant Allowed Allowed At least once
Normal Allowed Allowed Allowed Arbitrarily
  • Ordered type systems (discard exchange, weakening and contraction): Every variable is used exactly once in the order it was introduced.
  • Linear type systems (allow exchange, but neither weakening nor contraction): Every variable is used exactly once.
  • Affine type systems (allow exchange and weakening, but not contraction): Every variable is used at most once.
  • Relevant type systems (allow exchange and contraction, but not weakening): Every variable is used at least once.
  • Normal type systems (allow exchange, weakening and contraction): Every variable may be used arbitrarily.

The explanation for affine type systems is best understood if rephrased as “every occurrence of a variable is used at most once”.

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).[1]: 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,[1]: 6  or to design software interfaces that guarantee a resource cannot be used once it has been closed or transitioned to a different state.[2]

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.[1]: 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 x can appear exactly once in a term.[3]

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.[4]

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

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.

Disowning move Obligatory move Move quantification Enforcible function call state machine
Normal type No No Any number of times Topological ordering
Affine type Yes No At most once Ordering
Linear type Yes Yes Exactly once Ordering and completion

Resource-affine types

Under the resource interpretation, an affine type can not 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:

Vending machine
English Logic Rust
A coin can buy you
a piece of candy, a drink,
or go out of scope.
Coin ⊸ Candy
Coin ⊸ Drink
Coin ⊸ ⊤
fn buy_candy(_: Coin) -> Candy { Candy{} }
fn buy_drink(_: Coin) -> Drink { Drink{} }

What it means for Coin to be an affine type in this example (which it is unless it implements the Copy trait) is that trying to spend the same coin twice is an invalid program that the compiler is entitled to reject:

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.

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:

// 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)?;
}

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.

{
    // 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.
}

An attraction with linear types is that destructors become regular functions that can take arguments, can fail and so on.[5] 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.[6]

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.

auto coin = std::unique_ptr<Coin>();
auto candy = buy_candy(std::move(coin));
auto drink = buy_drink(std::move(coin)); // This is valid C++.

Programming languages

The following programming languages support linear or affine types[citation needed]:

See also

References

  1. ^ a b c d Walker, David (2002). "Substructural Type Systems". In Pierce, Benjamin C. (ed.). Advanced Topics in Types and Programming Languages (PDF). MIT Press. pp. 3–43. ISBN 0-262-16228-8.
  2. ^ Bernardy, Jean-Philippe; Boespflug, Mathieu; Newton, Ryan R; Peyton Jones, Simon; Spiwack, Arnaud (2017). "Linear Haskell: practical linearity in a higher-order polymorphic language". Proceedings of the ACM on Programming Languages. 2: 1–29. arXiv:1710.09756. doi:10.1145/3158093. S2CID 9019395.
  3. ^ Baez, John C.; Stay, Mike (2010). "Physics, Topology, Logic and Computation: A Rosetta Stone". In Springer (ed.). New Structures for Physics (PDF). pp. 95–174.
  4. ^ Ambler, S. (1991). First order logic in symmetric monoidal closed categories (PhD). U. of Edinburgh.
  5. ^ "Vale's Vision". Retrieved 6 December 2023. Higher RAII, a form of linear typing that enables destructors with parameters and returns.
  6. ^ "Go by Example: Defer". Retrieved 5 December 2023. 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.
  7. ^ "6.4.19. Linear types — Glasgow Haskell Compiler 9.7.20230513 User's Guide". ghc.gitlab.haskell.org. Retrieved 2023-05-14.
  8. ^ Hudson @twostraws, Paul. "Noncopyable structs and enums – available from Swift 5.9". Hacking with Swift.

Read other articles:

Aanloop tot de Russische invasie van Oekraïne in 2022 Onderdeel van Russisch-Oekraïense Oorlog Kaart met aanduiding van Russische troepen in de Russisch-Oekraïense grensstreek (december 2021) Datum 3 maart 2021 – 24 februari 2022 Strijdende partijen  Rusland  Wit-Rusland  Oekraïne Leiders en commandanten Vladimir Poetin Aleksandr Loekasjenko Volodymyr Zelensky Troepensterkte 900.000 actief personeel; 2.000.000 reservisten[1], 175.000[2] – 190.000[3&#...

 

Maltese Pioneers Historia Państwo Zjednoczone Królestwo Wielkiej Brytanii i Irlandii Sformowanie 1800 Rozformowanie 1801 Dowódcy Pierwszy Lieutenant Francesco Rivarola Działania zbrojne Wojny rewolucyjnej Francji kampania egipska Organizacja Rodzaj sił zbrojnych British Army Rodzaj wojsk wojska inżynieryjne Maltese Pioneers (pol. Maltański Korpus Saperów) – korpus saperów w składzie British Army, który istniał od 1800 do 1801. W grudniu 1800 sir Ralph Abercromby polecił po...

 

Avery Robert Dulles Cardeal da Santa Igreja Romana Presbítero da Companhia de Jesus Atividade eclesiástica Congregação Companhia de Jesus Ordenação e nomeação Ordenação presbiteral 16 de junho de 1956por Francis Joseph Cardeal Spellman Cardinalato Criação 21 de fevereiro de 2001 por Papa João Paulo II Ordem Cardeal-diácono Título Santíssimos Nomes de Jesus e Maria na Via Lata Brasão Lema Scio cui credidi Dados pessoais Nascimento Auburn24 de agosto de 1918 Morte New York12 de...

Nama ini menggunakan cara penamaan Spanyol: nama keluarga pertama atau paternalnya adalah Tafur dan nama keluarga kedua atau maternalnya adalah Náder. Gabriela TafurLahirGabriela Tafur Náder07 Juli 1995 (umur 28)Cali, ColombiaAlmamaterUniversitas Los AndesTinggi179 m (587 ft 3 in)Pemenang kontes kecantikanGelarSrta. Colombia 2018Warna rambutCoklatWarna mataCoklatKompetisiutamaMiss Colombia 2018(Pemenang)Miss Universe 2019(5 besar) Gabriela Tafur Náder (lahir 7 Juli...

 

1960 filmGoliath and the DragonDirected byVittorio CottafaviScreenplay by Marcello Baldi Duccio Tessari Mario Ferrari Nicolo Ferrari Fabio Carpi Ennio De Concini Franco Rossetti[2] Story by Marcello Baldi Nicolo Ferrari[2] Produced by Gianni Fuchs Achille Piazzi[2] Starring Mark Forest Broderick Crawford Gaby André Renato Terra CinematographyMario Montuori[2]Music byAlexandre Derevitsky[2]Productioncompanies Achille Piazzi Produzioni Cinematografica Pr...

 

Vowel sound represented by ⟨ɐ⟩ in IPA Near-open central vowelɐIPA Number324Audio sample source · helpEncodingEntity (decimal)&#592;Unicode (hex)U+0250X-SAMPA6Braille Image IPA: Vowels Front Central Back Close i y ɨ ʉ ɯ u Near-close ɪ ʏ ʊ Close-mid e ø ɘ ɵ ɤ o Mid e̞ ø̞ ə ɤ̞ o̞ Open-mid ɛ œ ɜ ɞ ʌ ɔ Near-open æ ɐ Open a ɶ ä ɑ ɒ IPA help  audio full chart template Legend: unrounded • rounded The near-open central vowel, or...

Not to be confused with Beaufort, South Carolina or Beaufort County, North Carolina. Town in North Carolina, United StatesBeaufort, North CarolinaTownDowntown Beaufort FlagSealLocation of Beaufort, North CarolinaCoordinates: 34°43′21″N 76°39′01″W / 34.72250°N 76.65028°W / 34.72250; -76.65028CountryUnited StatesStateNorth CarolinaCountyCarteretNamed forHenry Somerset, Duke of BeaufortArea[1] • Total7.84 sq mi (20.31 km2)...

 

European Network on Debt and DevelopmentAbbreviationEurodadFormation1990TypeCoalition of NGOsHeadquartersRue d’Edimbourg, 18 – 26,LocationBrusselsDirectorJean SaldanhaWebsitewww.eurodad.org Eurodad (European Network on Debt and Development) is a network of 53 non-governmental organisations and seven statutory allies from 29 European countries.[1] Eurodad and its members make up a network, this network researches and works on issues that are related to debt, development finance and...

 

2004 film by Alfonso Cuarón Harry Potter and the Prisoner of AzkabanTheatrical release posterDirected byAlfonso CuarónScreenplay bySteve KlovesBased onHarry Potter and the Prisoner of Azkabanby J. K. RowlingProduced by David Heyman Chris Columbus Mark Radcliffe Starring Daniel Radcliffe Rupert Grint Emma Watson Robbie Coltrane Michael Gambon Richard Griffiths Gary Oldman Alan Rickman Fiona Shaw Maggie Smith Timothy Spall David Thewlis Emma Thompson Julie Walters CinematographyMichael Seresi...

National sports governing body for basketball in Great Britain This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help to improve this article by introducing more precise citations. (May 2018) (Learn how and when to remove this template message) British Basketball FederationAbbreviationBBFPredecessorBritish & Irish Basketball FederationFormation2006TypeNational sports governing bodyLegal ...

 

Operation MerlynPart of the South African Border WarLocationNamibiaTsumebGrootfonteinWindhoekRunduOshakatiEenhanaOperation Merlyn (Namibia)ObjectivePrevent the incursion of PLAN (SWAPO) insurgents into South West Africa/Namibia in contravention to a ceasefire which came into effect on 1 April 1989.Date1–9 April 1989 vteSouth African Border War 1960s Blouwildebees 1970s Alcora Exercise Savannah Quifangondo Seiljag Bruilof Reindeer Cassinga Rekstok Saffraan 1980s Sceptic Klipklop Wishbone Bea...

 

Nazi coverup of the Holocaust that fooled the Red Cross During World War II, the Theresienstadt concentration camp was used by the Nazi SS (German: Schutzstaffel) as a model ghetto[1] for fooling Red Cross representatives about the ongoing Holocaust and the Nazi plan to murder all Jews. The Nazified German Red Cross visited the ghetto in 1943 and filed the only accurate report on the ghetto, describing overcrowding and undernourishment. In 1944, the ghetto was beautified in preparatio...

American journalist Larry BenskyBensky in 2005Born (1937-05-01) May 1, 1937 (age 86)OccupationJournalist Larry Bensky (born May 1, 1937) is a literary and political journalist with experience in both print and broadcast media, as well as a teacher and political activist. He is known for his work with Pacifica Radio station KPFA-FM in Berkeley, California, and for the nationally-broadcast hearings he anchored for the Pacifica network. A native of New York City, Bensky graduated from Stuyv...

 

SDN 5 TilongkabilaSekolah Dasar Negeri 5 TilongkabilaInformasiAkreditasiBKepala SekolahJusra LadikuJumlah kelas11Rentang kelasI-VIStatusNegeriAlamatLokasiJln. HB. Yasin, Bone Bolango, Gorontalo, IndonesiaKoordinat0°33′00″N 123°07′49″E / 0.5500000°N 123.1302000°E / 0.5500000; 123.1302000Moto SD Negeri 5 Tilongkabila atau nama lengkapnya Sekolah Dasar Negeri 5 Tilongkabila adalah sebuah sekolah dasar umum yang terletak di jalan HB. Yasin, desa Mouto...

 

Italian painter (1569–1633) Lucio MassariThe Holy FamilyBorn22 January 1569BolognaDied3 November 1633(1633-11-03) (aged 64)NationalityItalianKnown forPaintingMovementMannerism and Baroque Lucio Massari (22 January 1569 – 3 November 1633) was an Italian painter of the School of Bologna. He can be described as painting during both Mannerist and early-Baroque periods. Life and work He was born in Bologna, where he initially apprenticed with an unknown painter by the name of Spi...

Maltz Opera HouseThe Maltz in 1988, as the State TheaterFormer namesAMC Classic State 3 Carmike State Cinemas 3 State Theater Maltz TheaterAddress206 North 2nd AvenueAlpena, MichiganUnited StatesCoordinates45°3′46.415″N 83°25′56.237″W / 45.06289306°N 83.43228806°W / 45.06289306; -83.43228806ConstructionBroke ground1876OpenedNovember 11, 1879; 144 years ago (1879-11-11)Rebuilt1925 The Maltz Opera House is a theater in Alpena, Michigan, name...

 

2015 American filmClingerDirected byMichael StevesWritten byGabi Chennisi DuncombeBubba FishMichael StevesStarringVincent MartellaJennifer LaporteJulia AksLisa WilcoxCinematographyGabi Chennisi DuncombeEdited byBubba FishMusic byMisha SegalProductioncompanyClinger The MovieRelease date January 12, 2015 (2015-01-12) (Slamdance Film Festival) Running time81 minutesCountryUnited StatesLanguageEnglish Clinger is a 2015 comedy horror film and the feature film directorial debut o...

 

Constituency of the State Duma of the Russian Federation Artyom single-member constituency Constituency of the Russian State DumaDeputyVladimir NovikovUnited RussiaFederal subjectPrimorsky KraiDistrictsArtyom, Bolshoy Kamen, Chernigovsky, Fokino, Khorolsky, Mikhaylovsky, Shkotovsky, Spassk-Dalny, Spassky, Vladivostok (Pervorechensky, Sovetsky)[1]Voters472,391 (2021)[2] The Artyom constituency (No.63) is a Russian legislative constituency in Primorsky Krai. The constituency was...

سانت هيلير   الإحداثيات 48°00′47″N 96°12′51″W / 48.013055555556°N 96.214166666667°W / 48.013055555556; -96.214166666667  [1] تقسيم إداري  البلد الولايات المتحدة[2]  التقسيم الأعلى مقاطعة بينينغتون، مينيسوتا  خصائص جغرافية  المساحة 2.185584 كيلومتر مربع2.163853 كيلومتر مربع (1 أبريل ...

 

For the former school at Mamhead, see Mamhead House. Academy in Dawlish, Devon, EnglandDawlish CollegeAddressElm Grove RoadDawlish, Devon, EX70BYEnglandCoordinates50°35′03″N 3°27′46″W / 50.584187°N 3.462659°W / 50.584187; -3.462659InformationTypeAcademyLocal authorityDevon County CouncilTrustIvy Education TrustDepartment for Education URN147643 TablesOfstedReportsHead of SchoolSam BanksExecutive PrincipalPaul CornishGenderCoeducationalAge11 to 16Website...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!