<p>Quoting one of <a href="https://langdev.stackexchange.com/a/2709/89">Alexis King's answers</a>:</p>
<blockquote>
<p>Many programming language researchers would call many things “type systems” that programmers probably don’t think of as type systems. Many forms of static analysis can be usefully viewed in the framework of type systems, but they may not have all that much to do with programmers’ notion of types.</p>
</blockquote>
<p>It’s not clear to me why this would be true. Why is the framework of formal type systems useful for modeling other things (particularly, other static analyses besides the standard notion of type-checking)? What are some examples of things modeled in that way?</p>
<p><sup>To make clear: the &quot;standard notion&quot; of types are things which are associated with each variable, expression or other language construct which can have, receive or produce a value, and which describe (usually lossily) or constrain the possible values those language constructs can have, receive or produce.</sup></p>

<types><static-analysis><type-systems>
How can type systems be a useful formal framework for modeling things other than type-checking?
CC BY-SA 4.0
2023-08-15T11:32:08.227Z
In C/C++, `const` allows verifying that data is not modified inside a function call, even if that call delegates to other functions. This is done through the type system, by pretending that non-`const` to `const` is a one-way type conversion.
Simon Richter
CC BY-SA 4.0
2023-08-15T14:04:30.783Z
So, what _is_ a type? (In programming languages.) A formal definition of _type system_ is in the answers. What about the programmer's notion?
Pablo H
<h2>Control-flow effects</h2>
<p>Consider a simple imperative language with statements as defined below; <span class="math-container">$e$</span>, <span class="math-container">$s$</span> and <span class="math-container">$i$</span> are for expressions, statements and identifiers respectively:</p>
<p><span class="math-container">$$
\begin{array}{lcl}
s &amp; ::= &amp; \mathsf{Expr}(e) \\
&amp;|&amp; \mathsf{Break} \\
&amp;|&amp; \mathsf{Return}(e) \\
&amp;|&amp; \mathsf{Sequence}(s, s) \\
&amp;|&amp; \mathsf{If}(e, s) \\
&amp;|&amp; \mathsf{Loop}(s) \\
&amp;|&amp; \mathsf{Function}(i, s) \\
\end{array}
$$</span></p>
<p>For simplicity, the &quot;Loop&quot; statement here is like a &quot;while true&quot; loop, and functions have no parameters and aren't void. (We won't concern ourselves with function return types, because we're not doing standard type-checking here.)</p>
<p>There are some requirements which we want to statically enforce:</p>
<ol>
<li>A break can't occur outside of a loop;</li>
<li>A return can't occur outside of a function;</li>
<li>A function must either return, or loop infinitely;</li>
<li>A break, return or infinite loop cannot be followed by another statement in sequence.</li>
</ol>
<hr />
<p>To formalise these requirements, we will assign a &quot;type&quot; to each statement. The &quot;types&quot; in this system are tuples <span class="math-container">$(n, b, r)$</span> of booleans, where <span class="math-container">$n$</span> indicates whether the statement can complete normally (without breaking or returning), <span class="math-container">$b$</span> indicates whether it can break, and <span class="math-container">$r$</span> indicates whether it can return.</p>
<p>Now we can write the rules for determining the &quot;type&quot; of each statement:</p>
<p><span class="math-container">$$
\begin{array}{l}\hline \vdash \mathsf{Expr}(e) : (\mathrm{true}, \mathrm{false}, \mathrm{false})\end{array}
\qquad
\begin{array}{l}\hline \vdash \mathsf{Break} : (\mathrm{false}, \mathrm{true}, \mathrm{false})\end{array}
\qquad
\begin{array}{l}\hline \vdash \mathsf{Return}(e) : (\mathrm{false}, \mathrm{false}, \mathrm{true})\end{array}
\qquad
\begin{array}{l}\vdash s_1 : (\mathrm{true}, b_1, r_1) \\ \vdash s_2 : (n, b_2, r_2) \\ \hline \vdash \mathsf{Sequence}(s_1, s_2) : (n, b_1 \lor b_2, r_1 \lor r_2)\end{array}
\qquad
\begin{array}{l}\vdash s : (n, b, r) \\ \hline \vdash \mathsf{If}(e, s) : (\mathrm{true}, b, r)\end{array}
\qquad
\begin{array}{l}\vdash s : (n, b, r) \\ \hline \vdash \mathsf{Loop}(s) : (b, \mathrm{false}, r)\end{array}
\qquad
\begin{array}{l}\vdash s : (\mathrm{false}, \mathrm{false}, r) \\ \hline \vdash \mathsf{Function}(i, s) : (\mathrm{true}, \mathrm{false}, \mathrm{false})\end{array}
$$</span></p>
<p>A few things are worth commenting on:</p>
<ul>
<li>For simplicity we're supposing that expressions cannot have control-flow effects. That's reasonable in a simple language which has no exceptions, and we aren't modelling exceptions in this example.</li>
<li>Break and return statements never complete normally.</li>
<li>An &quot;if&quot; statement can always complete normally, when the condition is false; and when the condition is true, the statement can throw or return if its body can. This conservatively assumes that the condition can be either true or false.</li>
<li>A loop can complete normally only if its body can break. Since the loop &quot;consumes&quot; breaks which occur within it, the loop statement itself cannot propagate a break. Hence its type is like <span class="math-container">$(b, \mathrm{false}, r)$</span>.</li>
<li>A function body must have type <span class="math-container">$(\mathrm{false}, \mathrm{false}, r)$</span> meaning it cannot break (satisfying requirement 1), and it cannot complete normally (i.e. complete without returning), satisfying requirement 3). The function declaration itself completes normally without breaking or returning, because declaring a function doesn't invoke it.</li>
<li>In a sequence of two statements, the first statement's type must be <span class="math-container">$(\mathrm{true}, b_1, r_1)$</span> because according to requirement 4, it must be able to complete normally. So the resulting type is like <span class="math-container">$(n, b_1 \lor b_2, r_1 \lor r_2)$</span> because it completes normally only if <span class="math-container">$s_2$</span> does, but it can break or return if either <span class="math-container">$s_1$</span> or <span class="math-container">$s_2$</span> can.</li>
</ul>
<p>Finally, we require the root statement (i.e. the top-level of the program) to have a type of the form <span class="math-container">$(n, \mathrm{false}, \mathrm{false})$</span>. This encodes requirement 2, and the rest of requirement 1.</p>
<hr />
<p>So, why model control-flow effects this way? Well, one reason is that it gives a formal specification which we can check our static analysis algorithm against.</p>
<p>Another is that the &quot;type&quot; of each statement becomes data which can be retained for other purposes, rather than existing only transiently during checking. That data might be useful for <a href="https://langdev.stackexchange.com/q/2660/89">program transformations</a> such as</p>
<p><span class="math-container">$$\mathsf{Loop}(\mathsf{Sequence}(s, \mathsf{Break})) \mapsto s$$</span></p>
<p>which is only valid when <span class="math-container">$s : (n, \mathrm{false}, r)$</span>, i.e. when <span class="math-container">$s$</span> cannot break. It also provides a safety net to sometimes catch incorrect transformations, since we can check that the type of the original statement is equal to the type of the transformed one.</p>

CC BY-SA 4.0
2023-08-14T23:45:08.373Z
2023-08-15T00:40:15.040Z
2023-08-15T00:40:15.040Z
kaya3
CC BY-SA 4.0
2023-08-14T23:56:32.533Z
I’m curious if you know of any existing presentations that model things this way, or if this is novel. It’s a neat example! Some nitpicking: your BNF grammar should have $s$ to the left of the $::=$, not $\mathsf{Statement}$. Also, I wouldn’t use `mathsf` for your booleans since they seem to be terms in the metalanguage rather than terms in the language.
Alexis King
CC BY-SA 4.0
2023-08-15T00:02:20.977Z
For what it’s worth, I would probably not expect to find this sort of thing represented this way, as booleans do not have very much structure. Instead, I would probably expect to see a set of labels $\overline{\ell}$ contained within a context and locally extended by $\mathbf{loop}$, and I’d expect $\mathbf{break}$ to be indexed by a label in the form $\mathbf{break}\ \ell$ or $\mathbf{break}_\ell$.
Alexis King
CC BY-SA 4.0
2023-08-15T00:05:34.057Z
I also don’t entirely understand the purpose of the $r$ element of your tuples; it seems to be left unconstrained by every rule.
Alexis King
CC BY-SA 4.0
2023-08-15T00:06:54.830Z
@AlexisKing Thanks for the nitpicking; I've edited to address it. The example comes from [something similar I'm doing](https://github.com/kaya3/MJr/blob/2864b6cfcefe6d9e2ee417c40a7c4b06a55a5441/src/ir/ir.ts#L88) in the compiler for my language MJr, where I'm using it for inference and transformations rather than checking. Good point about labels, I just tried to keep it simple in this example; the $r$ element is required to check that you can't return from the top-level, but I wasn't sure how to encode that.
kaya3
<p>Any static analysis that a compiler or programmer might be interested is a potential candidate for turning into a system of strong static programmer-visible guarantees.</p>
<p>Think of the way that some modern languages basically incorporate null reference checking into the type system, which was something that was previously an optimisation. Also consider Rust's static memory management (which was, of course, taken from Cyclone).</p>
<p>In <a href="https://mercurylang.org/" rel="nofollow noreferrer">Mercury</a>, a logic language, we used a static analysis system to enforce <a href="https://mercurylang.org/documentation/papers.html#p33-overton" rel="nofollow noreferrer">static strong modes</a> (i.e. dataflow) and <a href="https://mercurylang.org/documentation/papers.html#acsc96" rel="nofollow noreferrer">static strong determinism</a>.</p>
<p>Some ideas that have been under-explored:</p>
<ul>
<li>Strong static aliasing. (Disclaimer: I tried this once, in the context of Mercury, but it would also be extremely useful in a Fortran-like language.)</li>
<li>Strong static bounds checking. It's nice for a compiler to eliminate, say, array bounds checks when it can, but wouldn't it be even nicer if the compiler could statically guarantee that array bounds checks are not needed?</li>
<li>Strong static vectorisation/loop-parallelism.</li>
</ul>
<p>I feel like this is fertile ground for future research: compilers that <em>guarantee</em> that certain optimisations will occur.</p>

CC BY-SA 4.0
2023-08-15T02:13:32.107Z
2023-08-15T02:13:32.107Z
Pseudonym
CC BY-SA 4.0
2023-08-15T12:14:23.933Z
"Any static analysis" sounds like a strong claim ─ in Alexis's answer there are some stipulations about it being a judgement per term in the language (as opposed to e.g. a judgement which applies only to whole programs) and it being "at least mostly syntax-directed", presumably because typing rules are defined by structural recursion on the syntax. How should I square these two answers?
kaya3
CC BY-SA 4.0
2023-08-15T12:15:16.553Z
Also, could you clarify what the difference would be between a compiler being able to eliminate array bounds checks where it can, and being able to eliminate them where it can statically guarantee they are not needed? Isn't that what "where it can" means?
kaya3
CC BY-SA 4.0
2023-08-16T00:48:28.330Z
@kaya3 There is a difference between an optimisation and a guarantee. An optimisation might happen with certain compiler flags if the compiler can prove that the optimisation is safe, but the programmer can't rely on it always happening. Similarly, in a dynamically typed language, a compiler may be able to infer that some variable is always an integer, and optimise accordingly (e.g. basic computations are "unboxed" and use no heap), but in a statically typed language, that might be guaranteed, so a programmer can rely on that "optimisation" always happening.
Pseudonym
CC BY-SA 4.0
2023-08-16T00:56:59.170Z
Incidentally, the "at least mostly syntax-directed" qualification is likely for diagnostic reasons as much as anything. Programmers like it when errors and warnings are reported with specific reference to the program that they typed in. Nothing is more frustrating than a message which says in effect "your program is not type correct, but I have no idea what specific lines of code might be responsible".
Pseudonym
<h2><a href="https://en.wikipedia.org/wiki/Curry%E2%80%93Howard_correspondence" rel="nofollow noreferrer">Curry-Howard correspondance</a></h2>
<p>Type systems can be used to model <a href="https://discrete.openmathbooks.org/dmoi3/ch_logic.html" rel="nofollow noreferrer">formal logic</a>, and this is the basis of the &quot;Curry Howard correspondence&quot;.</p>
<p><strong>Each type represents a <a href="https://en.wikipedia.org/wiki/Propositional_calculus" rel="nofollow noreferrer">logical proposition</a>, and an instance of the type represents a proof of the proposition</strong>. Function types represent &quot;if&quot;/&quot;implies&quot; statements (which is why the syntax of function types uses <code>-&gt;</code> in many languages), product types (structures with multiple fields) represent conjunctions (AND), and sum types (&quot;enums&quot; with multiple variants) represent disjunctions (OR). FALSE is represented by a type with no instances (an enumeration with no variants), and TRUE is represented by a type with one instance (the unit type, a struct with no fields).</p>
<pre class="lang-hs prettyprint-override"><code>-- Basic rules
data True = True
data False
data And a b = And a b
data Or a b = OrL a | OrR b

-- We can define (type-safe) functions which are valid propositions
anythingImpliesTrue :: a -&gt; True
anythingImpliesTrue anything = True

falseImpliesAnything :: False -&gt; a
-- How does this typecheck? Here we do &quot;standard&quot; case analysis on `False`,
-- except it has no cases! Since there are no cases, every case returns an
-- instance of `a` (`∀ f, all f [] = true`), thus the entire case expression
-- is an instance of `a`
falseImpliesAnything False = case False of {}

-- We can compose predicates, do everything a regular language supports
trueAndFalseImpliesFalse :: And (True False) -&gt; False
trueAndFalseImpliesFalse (And true false) = falseImpliesAnything false

-- We can also compose types
type Not a = a -&gt; False
trueOrFalseDoesntImplyFalse :: Not (Or (True False) -&gt; False)
trueOrFalseDoesntImplyFalse f = falseImpliesAnything (OrL True)

-- However, we can't define functions which are invalid propositions
-- UNLESS we cheat with a value like `error msg`
trueImpliesFalse :: True -&gt; False
trueImpliesFalse True = error &quot;cheating&quot;

-- OR write a function which never terminates
trueImpliesFalse' :: True -&gt; False
trueImpliesFalse' True = trueImpliesFalse' True
</code></pre>
<p>Sticking to this representation, we can only create type-checking values which are valid propositions, <strong>we can't create values which type-check and represent invalid propositions. <em>Except</em> for</strong>:</p>
<ul>
<li>Operations which may error (exceptions, undefined behavior)</li>
<li>Failable type-casts or type-casts which may invoke undefined behavior</li>
<li>Unsound typing rules (see: <a href="https://counterexamples.org/intro.html" rel="nofollow noreferrer">Counterexamples in Type Systems</a>)</li>
<li>Functions which might never terminate</li>
</ul>
<p>These are serious exceptions in most languages like C/C++ and TypeScript. Even if you ignore exceptions, functions like <code>exit</code>, and explicit casts, these languages have unsound holes in the type system (trivial example: in non-strict TypeScript, you implicitly cast a union <code>A | B | C</code> to any one of its variants e.g. <code>B</code>). Most of all, they lack termination checking, and functions which don't trivially terminate are extremely common; even &quot;functional languages&quot; like OCaml and Haskell don't warn you if you define non-terminating functions.</p>
<pre class="lang-cpp prettyprint-override"><code>// You can also model logic in more traditional languages like C++
struct True {};
enum class False {};
template&lt;typename A, typename B&gt; struct And { A a; B b; };
// Although some of these are much more verbose
template&lt;typename A, typename B&gt; class Or {
    using Data = union { A a; B b; };
    bool tag;
    Data data;
    Or(bool tag, Data data) : tag(tag), data(data) {}

  public:
    static Or left(A a) { return Or(false, { .a = a }) }
    static Or right(B b) { return Or(true, { .b = b }) }

    template&lt;typename T&gt; T visit(std::function&lt;T(A)&gt; ifLeft, std::function&lt;T(B)&gt; ifRight) {
        return tag ? ifRight(data.b) : ifLeft(data.a);
    }
}

// True -&gt; (A \/ A) -&gt; A
template&lt;typename A&gt; std::function&lt;A(Or&lt;A, A&gt;)&gt; trueImpliesAOrAImpliesA(true: True) {
    return [](Or&lt;A, A&gt; aOrA){ return aOrA.visit([](A a){ return a; }, [](A a){ return a; }) });
}

// Of course, many C++ features let you break this
False aFalse = (False)42;
template&lt;typename A&gt; False aImpliesFalse(A a) {
    std::abort(&quot;not true&quot;);
}
</code></pre>
<p>But <strong>there are special <a href="https://en.wikipedia.org/wiki/Proof_assistant#System_comparison" rel="nofollow noreferrer">&quot;theorem-proving languages&quot;</a> where there are no erroring functions, no unsound type casts, and and all functions must be inferred or explicitly proven to terminate; thus, when code in these languages typechecks, it defines theorems which are guaranteed (up to some &quot;obvious&quot; fundamental axioms) to be true</strong>. The &quot;theorems&quot; in these languages are types, and the &quot;proofs&quot; which guarantee their correctness are instances.</p>
<pre><code>(* This is 100% valid coq code *)
Theorem n_plus_n_is_n_times_2 : forall n : nat, n + n = n * 2.
Proof.
(* This &quot;proof&quot; is more or less unreadable, you must use the IDE like CoqIDE
   or proof general to step through it. But it proves the above is true *)
  intros n.
  induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite &lt;- plus_n_Sm. rewrite &lt;- IHn'. reflexivity.
(* The IDE will not let you step past this and coq won't compile this if the
   above doesn't prove that the theorem holds *)
Qed.

(* This is the actual &quot;proof&quot; value, which is even uglier *)
Print n_plus_n_is_n_times_2.
n_plus_n_is_n_times_2 =
fun n : nat =&gt;
nat_ind (fun n0 : nat =&gt; n0 + n0 = n0 * 2) (eq_refl : 0 + 0 = 0 * 2)
  (fun (n' : nat) (IHn' : n' + n' = n' * 2) =&gt;
   eq_ind (S (n' + n')) (fun n0 : nat =&gt; S n0 = S (S (n' * 2)))
     (eq_ind (n' + n') (fun n0 : nat =&gt; S (S (n' + n')) = S (S n0)) eq_refl (n' * 2) IHn')
     (n' + S n') (plus_n_Sm n' n')
   :
   S n' + S n' = S n' * 2) n
     : forall n : nat, n + n = n * 2

</code></pre>
<p>Often the proofs/instances are very complicated and unreadable, so the developer constructs them with the aid of an IDE, and <a href="https://dependenttyp.es/classes/598sp2022.html" rel="nofollow noreferrer">proof automation</a> in the form of <a href="https://coq.inria.fr/refman/proof-engine/tactics.html" rel="nofollow noreferrer">tactics</a>) which partially or fully infer and construct an instance for a given type. You also have <a href="https://stackoverflow.com/questions/9338709/what-is-dependent-typing">dependent types</a>, which are types that include values and value expressions, like <code>forall n, Eq (collatz n) 1</code>, as well as functions which take one type and return another (like <code>UpTo : (P : Nat -&gt; Type) -&gt; (n : Nat) -&gt; forall n', n' &lt; n -&gt; P n'</code>). As you can start to see, the types get really complicated, and they can represent really complicated proofs; this is the power of the Curry-Howard correspondence. Incredible projects like <a href="https://compcert.org/" rel="nofollow noreferrer">CompCert</a> (a C compiler <em>proven</em> to have equivalent semantics to a C AST interpreter), <a href="https://sel4.systems/" rel="nofollow noreferrer">sel4</a> (a microkernel <em>proven</em> to not crash, barring hardware issues), and the <a href="https://en.wikipedia.org/wiki/Four_color_theorem#Proof_by_computer" rel="nofollow noreferrer">first known <em>proof</em> of the Four-Color Theorem</a> were created using Coq, all <em>proven</em> using the Curry-Howard correspondance, some fundamental axioms, and very advanced type-checking.</p>
<hr />
<p>Lastly, I want to go back to &quot;traditional&quot; non-theorem proving languages, just to note that while it's not feasible to use them to write advanced proofs or code guaranteed to be correct with high confidence, their type systems can still be used to verify properties of your program. For example, if you define a type which can only be created from an operation (e.g. <code>AuthorizedUser</code> which can only be created by a call to <code>Option&lt;AuthorizedUser&gt; login(String name, String password)</code> with the correct arguments), you can create functions which can only be used in a type-safe way if they have that value (e.g. <code>String getSecretData(AuthorizedUser user)</code>, which can't be called unless we create an authorized user, which we can't do unless we enter the correct name and password). This is especially important when designing an API, though it veers away from &quot;how to use type systems for theorem proving&quot; and towards &quot;how to effectively use type systems in general&quot;.</p>

CC BY-SA 4.0
2023-08-15T00:44:53.143Z
2023-08-15T00:44:53.143Z
tarzh
CC BY-SA 4.0
2023-08-15T01:14:08.960Z
I’m not sure that this *really* answers the question, though I don’t think it’s totally unrelated, either. The question is about using the metatheoretical framework of type systems to model things that are not conventionally considered type systems, but the Curry–Howard correspondence is about embedding propositions into a type system satisfying certain properties. This is not really the same thing.
Alexis King
<p>Formally speaking, type systems are defined as <a href="https://en.wikipedia.org/wiki/Judgment_(mathematical_logic)" rel="noreferrer">logical judgments</a>. As described in <a href="https://langdev.stackexchange.com/a/2693">my answer explaining the notation</a>, inference rules are really just a fancy way of writing logical implication. This is an exceedingly general framework, and in fact it’s possible to specify <em>any</em> syntactic rule system using the notation of <a href="https://en.wikipedia.org/wiki/Natural_deduction" rel="noreferrer">natural deduction</a> (and plenty of PL researchers often do).</p>
<p>Within that extremely general logical framework, the judgments a PL researcher might call a “type system” are qualitatively identified by five things:</p>
<ol>
<li><p>The judgment defines a relation between <em>terms</em> and <em>types</em>, the latter of which classify terms.</p>
<p>Note that these syntactic classes do not even need to be distinct—in dependent type systems, terms and types are syntactically the same. However, in all cases, the types somehow “approximate” terms, which is to say multiple terms are assigned the same type.</p>
</li>
<li><p>The judgment is context-sensitive. This is represented in the iconic <span class="math-container">$\Gamma \vdash$</span> notation.</p>
</li>
<li><p>The judgment is at least <em>mostly</em> syntax-directed, which is to say there is a typing rule corresponding to each production in the grammar of terms, and the nested structure of proof trees induced by the judgment mirrors the nested structure of terms.</p>
</li>
<li><p>The judgment does not depend on Turing-complete evaluation.</p>
<p>Generally, the typing judgment does not depend on term evaluation at all, as type systems are supposed to represent <em>static</em> analysis. However, excluding it completely would once again fail to account for dependent type systems, where terms can appear inside types, and those terms must be normalized, which is a form of evaluation. However, terms in those languages are usually quite restricted, so evaluation of all terms is guaranteed to terminate.</p>
</li>
<li><p>The defined relation admits a <a href="https://en.wikipedia.org/wiki/Type_safety" rel="noreferrer">type soundness</a> theorem.</p>
<p>How exactly this theorem is stated can vary considerably, but broadly speaking, the intent is to demonstrate that the defined typing rules usefully approximate some aspect of evaluation. One aphorism often stated here is that “well-typed programs can’t go wrong.” A common approach to formally stating type soundness is known as “progress and preservation”.</p>
</li>
</ol>
<p>You’ll note that this definition is still rather vague on the matter of what exactly terms and types <em>are</em> and what the typing relation represents. This is what makes the framework so astonishingly useful! Many programmers would consider a “type” to be, essentially, a description of the structure of the value an expression will evaluate to. However, a PL researcher might consider types that are substantially more abstract:</p>
<ul>
<li><p>A resource-aware type system might keep track of which resources a term consumes and produces, such as in <a href="https://dl.acm.org/doi/10.1145/3209108.3209146" rel="noreferrer">Work Analysis with Resource-Aware Session Types</a> (<a href="http://www.scs.cmu.edu/afs/cs.cmu.edu/Web/People/fp/papers/lics18.pdf" rel="noreferrer">pdf</a>)</p>
</li>
<li><p>An effect system might keep track of which side effects a term performs, such as in <a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v3.pdf" rel="noreferrer">Algebraic effects for Functional Programming</a>.</p>
</li>
<li><p>A macro system might keep track of which subforms of the macro are binders and which are uses, as in <a href="https://dl.acm.org/doi/abs/10.1145/3110288" rel="noreferrer">Inferring scope through syntactic sugar</a>.</p>
</li>
<li><p>For some languages, the typing judgment performs double-duty as both the definition of the typing rules and the definition of the <em>elaboration</em> rules, which is a type-directed translation of the terms into another (often simpler) language and often involves <a href="https://en.wikipedia.org/wiki/Type_erasure" rel="noreferrer">type erasure</a>.</p>
</li>
</ul>
<p>There are numerous other examples, but those are just ones that immediately come to mind.</p>

CC BY-SA 4.0
2023-08-14T23:33:22.243Z
2023-08-14T23:33:22.243Z
Alexis King
# How can type systems be a useful formal framework for modeling things other than type-checking?
Posted by: username_0 on 2023-08-14
Quoting one of [Alexis King's answers](https://langdev.stackexchange.com/a/2709/89):

> Many programming language researchers would call many things “type systems” that programmers probably don’t think of as type systems. Many forms of static analysis can be usefully viewed in the framework of type systems, but they may not have all that much to do with programmers’ notion of types.

It’s not clear to me why this would be true. Why is the framework of formal type systems useful for modeling other things (particularly, other static analyses besides the standard notion of type-checking)? What are some examples of things modeled in that way?

To make clear: the "standard notion" of types are things which are associated with each variable, expression or other language construct which can have, receive or produce a value, and which describe (usually lossily) or constrain the possible values those language constructs can have, receive or produce.
**Tags:** types static-analysis type-systems
> **Comments:**
> **username_1**: In C/C++, `const` allows verifying that data is not modified inside a function call, even if that call delegates to other functions. This is done through the type system, by pretending that non-`const` to `const` is a one-way type conversion.  
> **username_2**: So, what _is_ a type? (In programming languages.) A formal definition of _type system_ is in the answers. What about the programmer's notion?  
---
## 4 answers
### Answer by username_3 on 2023-08-14. Score: 12 | Accepted answer
Formally speaking, type systems are defined as [logical judgments](https://en.wikipedia.org/wiki/Judgment_(mathematical_logic)). As described in [my answer explaining the notation](https://langdev.stackexchange.com/a/2693), inference rules are really just a fancy way of writing logical implication. This is an exceedingly general framework, and in fact it’s possible to specify *any* syntactic rule system using the notation of [natural deduction](https://en.wikipedia.org/wiki/Natural_deduction) (and plenty of PL researchers often do).

Within that extremely general logical framework, the judgments a PL researcher might call a “type system” are qualitatively identified by five things:

1. The judgment defines a relation between *terms* and *types*, the latter of which classify terms.

   Note that these syntactic classes do not even need to be distinct—in dependent type systems, terms and types are syntactically the same. However, in all cases, the types somehow “approximate” terms, which is to say multiple terms are assigned the same type.
2. The judgment is context-sensitive. This is represented in the iconic $\Gamma \vdash$ notation.
3. The judgment is at least *mostly* syntax-directed, which is to say there is a typing rule corresponding to each production in the grammar of terms, and the nested structure of proof trees induced by the judgment mirrors the nested structure of terms.
4. The judgment does not depend on Turing-complete evaluation.

   Generally, the typing judgment does not depend on term evaluation at all, as type systems are supposed to represent *static* analysis. However, excluding it completely would once again fail to account for dependent type systems, where terms can appear inside types, and those terms must be normalized, which is a form of evaluation. However, terms in those languages are usually quite restricted, so evaluation of all terms is guaranteed to terminate.
5. The defined relation admits a [type soundness](https://en.wikipedia.org/wiki/Type_safety) theorem.

   How exactly this theorem is stated can vary considerably, but broadly speaking, the intent is to demonstrate that the defined typing rules usefully approximate some aspect of evaluation. One aphorism often stated here is that “well-typed programs can’t go wrong.” A common approach to formally stating type soundness is known as “progress and preservation”.

You’ll note that this definition is still rather vague on the matter of what exactly terms and types *are* and what the typing relation represents. This is what makes the framework so astonishingly useful! Many programmers would consider a “type” to be, essentially, a description of the structure of the value an expression will evaluate to. However, a PL researcher might consider types that are substantially more abstract:

* A resource-aware type system might keep track of which resources a term consumes and produces, such as in [Work Analysis with Resource-Aware Session Types](https://dl.acm.org/doi/10.1145/3209108.3209146) ([pdf](http://www.scs.cmu.edu/afs/cs.cmu.edu/Web/People/fp/papers/lics18.pdf))
* An effect system might keep track of which side effects a term performs, such as in [Algebraic effects for Functional Programming](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/08/algeff-tr-2016-v3.pdf).
* A macro system might keep track of which subforms of the macro are binders and which are uses, as in [Inferring scope through syntactic sugar](https://dl.acm.org/doi/abs/10.1145/3110288).
* For some languages, the typing judgment performs double-duty as both the definition of the typing rules and the definition of the *elaboration* rules, which is a type-directed translation of the terms into another (often simpler) language and often involves [type erasure](https://en.wikipedia.org/wiki/Type_erasure).

There are numerous other examples, but those are just ones that immediately come to mind.
---
### Answer by username_0 on 2023-08-14. Score: 6
## Control-flow effects

Consider a simple imperative language with statements as defined below; $e$, $s$ and $i$ are for expressions, statements and identifiers respectively:

$$
\begin{array}{lcl}
s & ::= & \mathsf{Expr}(e) \\
&|& \mathsf{Break} \\
&|& \mathsf{Return}(e) \\
&|& \mathsf{Sequence}(s, s) \\
&|& \mathsf{If}(e, s) \\
&|& \mathsf{Loop}(s) \\
&|& \mathsf{Function}(i, s) \\
\end{array}
$$

For simplicity, the "Loop" statement here is like a "while true" loop, and functions have no parameters and aren't void. (We won't concern ourselves with function return types, because we're not doing standard type-checking here.)

There are some requirements which we want to statically enforce:

1. A break can't occur outside of a loop;
2. A return can't occur outside of a function;
3. A function must either return, or loop infinitely;
4. A break, return or infinite loop cannot be followed by another statement in sequence.

---

To formalise these requirements, we will assign a "type" to each statement. The "types" in this system are tuples $(n, b, r)$ of booleans, where $n$ indicates whether the statement can complete normally (without breaking or returning), $b$ indicates whether it can break, and $r$ indicates whether it can return.

Now we can write the rules for determining the "type" of each statement:

$$
\begin{array}{l}\hline \vdash \mathsf{Expr}(e) : (\mathrm{true}, \mathrm{false}, \mathrm{false})\end{array}
\qquad
\begin{array}{l}\hline \vdash \mathsf{Break} : (\mathrm{false}, \mathrm{true}, \mathrm{false})\end{array}
\qquad
\begin{array}{l}\hline \vdash \mathsf{Return}(e) : (\mathrm{false}, \mathrm{false}, \mathrm{true})\end{array}
\qquad
\begin{array}{l}\vdash s\_1 : (\mathrm{true}, b\_1, r\_1) \\ \vdash s\_2 : (n, b\_2, r\_2) \\ \hline \vdash \mathsf{Sequence}(s\_1, s\_2) : (n, b\_1 \lor b\_2, r\_1 \lor r\_2)\end{array}
\qquad
\begin{array}{l}\vdash s : (n, b, r) \\ \hline \vdash \mathsf{If}(e, s) : (\mathrm{true}, b, r)\end{array}
\qquad
\begin{array}{l}\vdash s : (n, b, r) \\ \hline \vdash \mathsf{Loop}(s) : (b, \mathrm{false}, r)\end{array}
\qquad
\begin{array}{l}\vdash s : (\mathrm{false}, \mathrm{false}, r) \\ \hline \vdash \mathsf{Function}(i, s) : (\mathrm{true}, \mathrm{false}, \mathrm{false})\end{array}
$$

A few things are worth commenting on:

* For simplicity we're supposing that expressions cannot have control-flow effects. That's reasonable in a simple language which has no exceptions, and we aren't modelling exceptions in this example.
* Break and return statements never complete normally.
* An "if" statement can always complete normally, when the condition is false; and when the condition is true, the statement can throw or return if its body can. This conservatively assumes that the condition can be either true or false.
* A loop can complete normally only if its body can break. Since the loop "consumes" breaks which occur within it, the loop statement itself cannot propagate a break. Hence its type is like $(b, \mathrm{false}, r)$.
* A function body must have type $(\mathrm{false}, \mathrm{false}, r)$ meaning it cannot break (satisfying requirement 1), and it cannot complete normally (i.e. complete without returning), satisfying requirement 3). The function declaration itself completes normally without breaking or returning, because declaring a function doesn't invoke it.
* In a sequence of two statements, the first statement's type must be $(\mathrm{true}, b\_1, r\_1)$ because according to requirement 4, it must be able to complete normally. So the resulting type is like $(n, b\_1 \lor b\_2, r\_1 \lor r\_2)$ because it completes normally only if $s\_2$ does, but it can break or return if either $s\_1$ or $s\_2$ can.

Finally, we require the root statement (i.e. the top-level of the program) to have a type of the form $(n, \mathrm{false}, \mathrm{false})$. This encodes requirement 2, and the rest of requirement 1.

---

So, why model control-flow effects this way? Well, one reason is that it gives a formal specification which we can check our static analysis algorithm against.

Another is that the "type" of each statement becomes data which can be retained for other purposes, rather than existing only transiently during checking. That data might be useful for [program transformations](https://langdev.stackexchange.com/q/2660/89) such as

$$\mathsf{Loop}(\mathsf{Sequence}(s, \mathsf{Break})) \mapsto s$$

which is only valid when $s : (n, \mathrm{false}, r)$, i.e. when $s$ cannot break. It also provides a safety net to sometimes catch incorrect transformations, since we can check that the type of the original statement is equal to the type of the transformed one.
> **Comments:**
> **username_3** (2023-08-14): I’m curious if you know of any existing presentations that model things this way, or if this is novel. It’s a neat example! Some nitpicking: your BNF grammar should have $s$ to the left of the $::=$, not $\mathsf{Statement}$. Also, I wouldn’t use `mathsf` for your booleans since they seem to be terms in the metalanguage rather than terms in the language.  
> **username_3** (2023-08-15): For what it’s worth, I would probably not expect to find this sort of thing represented this way, as booleans do not have very much structure. Instead, I would probably expect to see a set of labels $\overline{\ell}$ contained within a context and locally extended by $\mathbf{loop}$, and I’d expect $\mathbf{break}$ to be indexed by a label in the form $\mathbf{break}\ \ell$ or $\mathbf{break}_\ell$.  
> **username_3** (2023-08-15): I also don’t entirely understand the purpose of the $r$ element of your tuples; it seems to be left unconstrained by every rule.  
> **username_0** (2023-08-15): @AlexisKing Thanks for the nitpicking; I've edited to address it. The example comes from [something similar I'm doing](https://github.com/kaya3/MJr/blob/2864b6cfcefe6d9e2ee417c40a7c4b06a55a5441/src/ir/ir.ts#L88) in the compiler for my language MJr, where I'm using it for inference and transformations rather than checking. Good point about labels, I just tried to keep it simple in this example; the $r$ element is required to check that you can't return from the top-level, but I wasn't sure how to encode that.  
---
### Answer by username_4 on 2023-08-15. Score: 4
Any static analysis that a compiler or programmer might be interested is a potential candidate for turning into a system of strong static programmer-visible guarantees.

Think of the way that some modern languages basically incorporate null reference checking into the type system, which was something that was previously an optimisation. Also consider Rust's static memory management (which was, of course, taken from Cyclone).

In [Mercury](https://mercurylang.org/), a logic language, we used a static analysis system to enforce [static strong modes](https://mercurylang.org/documentation/papers.html#p33-overton) (i.e. dataflow) and [static strong determinism](https://mercurylang.org/documentation/papers.html#acsc96).

Some ideas that have been under-explored:

* Strong static aliasing. (Disclaimer: I tried this once, in the context of Mercury, but it would also be extremely useful in a Fortran-like language.)
* Strong static bounds checking. It's nice for a compiler to eliminate, say, array bounds checks when it can, but wouldn't it be even nicer if the compiler could statically guarantee that array bounds checks are not needed?
* Strong static vectorisation/loop-parallelism.

I feel like this is fertile ground for future research: compilers that *guarantee* that certain optimisations will occur.
> **Comments:**
> **username_0** (2023-08-15): "Any static analysis" sounds like a strong claim ─ in Alexis's answer there are some stipulations about it being a judgement per term in the language (as opposed to e.g. a judgement which applies only to whole programs) and it being "at least mostly syntax-directed", presumably because typing rules are defined by structural recursion on the syntax. How should I square these two answers?  
> **username_0** (2023-08-15): Also, could you clarify what the difference would be between a compiler being able to eliminate array bounds checks where it can, and being able to eliminate them where it can statically guarantee they are not needed? Isn't that what "where it can" means?  
> **username_4** (2023-08-16): @kaya3 There is a difference between an optimisation and a guarantee. An optimisation might happen with certain compiler flags if the compiler can prove that the optimisation is safe, but the programmer can't rely on it always happening. Similarly, in a dynamically typed language, a compiler may be able to infer that some variable is always an integer, and optimise accordingly (e.g. basic computations are "unboxed" and use no heap), but in a statically typed language, that might be guaranteed, so a programmer can rely on that "optimisation" always happening.  
> **username_4** (2023-08-16): Incidentally, the "at least mostly syntax-directed" qualification is likely for diagnostic reasons as much as anything. Programmers like it when errors and warnings are reported with specific reference to the program that they typed in. Nothing is more frustrating than a message which says in effect "your program is not type correct, but I have no idea what specific lines of code might be responsible".  
---
### Answer by username_5 on 2023-08-15. Score: 2
Curry-Howard correspondance
Type systems can be used to model formal logic, and this is the basis of the "Curry Howard correspondence".
Each type represents a logical proposition, and an instance of the type represents a proof of the proposition. Function types represent "if"/"implies" statements (which is why the syntax of function types uses -> in many languages), product types (structures with multiple fields) represent conjunctions (AND), and sum types ("enums" with multiple variants) represent disjunctions (OR). FALSE is represented by a type with no instances (an enumeration with no variants), and TRUE is represented by a type with one instance (the unit type, a struct with no fields).
-- Basic rules
data True = True
data False
data And a b = And a b
data Or a b = OrL a | OrR b

-- We can define (type-safe) functions which are valid propositions
anythingImpliesTrue :: a -> True
anythingImpliesTrue anything = True

falseImpliesAnything :: False -> a
-- How does this typecheck? Here we do "standard" case analysis on `False`,
-- except it has no cases! Since there are no cases, every case returns an
-- instance of `a` (`∀ f, all f [] = true`), thus the entire case expression
-- is an instance of `a`
falseImpliesAnything False = case False of {}

-- We can compose predicates, do everything a regular language supports
trueAndFalseImpliesFalse :: And (True False) -> False
trueAndFalseImpliesFalse (And true false) = falseImpliesAnything false

-- We can also compose types
type Not a = a -> False
trueOrFalseDoesntImplyFalse :: Not (Or (True False) -> False)
trueOrFalseDoesntImplyFalse f = falseImpliesAnything (OrL True)

-- However, we can't define functions which are invalid propositions
-- UNLESS we cheat with a value like `error msg`
trueImpliesFalse :: True -> False
trueImpliesFalse True = error "cheating"

-- OR write a function which never terminates
trueImpliesFalse' :: True -> False
trueImpliesFalse' True = trueImpliesFalse' True

Sticking to this representation, we can only create type-checking values which are valid propositions, we can't create values which type-check and represent invalid propositions. Except for:

Operations which may error (exceptions, undefined behavior)
Failable type-casts or type-casts which may invoke undefined behavior
Unsound typing rules (see: Counterexamples in Type Systems)
Functions which might never terminate

These are serious exceptions in most languages like C/C++ and TypeScript. Even if you ignore exceptions, functions like exit, and explicit casts, these languages have unsound holes in the type system (trivial example: in non-strict TypeScript, you implicitly cast a union A | B | C to any one of its variants e.g. B). Most of all, they lack termination checking, and functions which don't trivially terminate are extremely common; even "functional languages" like OCaml and Haskell don't warn you if you define non-terminating functions.
// You can also model logic in more traditional languages like C++
struct True {};
enum class False {};
template struct And { A a; B b; };
// Although some of these are much more verbose
template class Or {
    using Data = union { A a; B b; };
    bool tag;
    Data data;
    Or(bool tag, Data data) : tag(tag), data(data) {}

  public:
    static Or left(A a) { return Or(false, { .a = a }) }
    static Or right(B b) { return Or(true, { .b = b }) }

    template T visit(std::function ifLeft, std::function ifRight) {
        return tag ? ifRight(data.b) : ifLeft(data.a);
    }
}

// True -> (A \/ A) -> A
template std::function)> trueImpliesAOrAImpliesA(true: True) {
    return [](Or aOrA){ return aOrA.visit([](A a){ return a; }, [](A a){ return a; }) });
}

// Of course, many C++ features let you break this
False aFalse = (False)42;
template False aImpliesFalse(A a) {
    std::abort("not true");
}

But there are special "theorem-proving languages" where there are no erroring functions, no unsound type casts, and and all functions must be inferred or explicitly proven to terminate; thus, when code in these languages typechecks, it defines theorems which are guaranteed (up to some "obvious" fundamental axioms) to be true. The "theorems" in these languages are types, and the "proofs" which guarantee their correctness are instances.
(* This is 100% valid coq code *)
Theorem n_plus_n_is_n_times_2 : forall n : nat, n + n = n * 2.
Proof.
(* This "proof" is more or less unreadable, you must use the IDE like CoqIDE
   or proof general to step through it. But it proves the above is true *)
  intros n.
  induction n as [| n' IHn'].
  - simpl. reflexivity.
  - simpl. rewrite <- plus_n_Sm. rewrite <- IHn'. reflexivity.
(* The IDE will not let you step past this and coq won't compile this if the
   above doesn't prove that the theorem holds *)
Qed.

(* This is the actual "proof" value, which is even uglier *)
Print n_plus_n_is_n_times_2.
n_plus_n_is_n_times_2 =
fun n : nat =>
nat_ind (fun n0 : nat => n0 + n0 = n0 * 2) (eq_refl : 0 + 0 = 0 * 2)
  (fun (n' : nat) (IHn' : n' + n' = n' * 2) =>
   eq_ind (S (n' + n')) (fun n0 : nat => S n0 = S (S (n' * 2)))
     (eq_ind (n' + n') (fun n0 : nat => S (S (n' + n')) = S (S n0)) eq_refl (n' * 2) IHn')
     (n' + S n') (plus_n_Sm n' n')
   :
   S n' + S n' = S n' * 2) n
     : forall n : nat, n + n = n * 2


Often the proofs/instances are very complicated and unreadable, so the developer constructs them with the aid of an IDE, and proof automation in the form of tactics) which partially or fully infer and construct an instance for a given type. You also have dependent types, which are types that include values and value expressions, like forall n, Eq (collatz n) 1, as well as functions which take one type and return another (like UpTo : (P : Nat -> Type) -> (n : Nat) -> forall n', n' < n -> P n'). As you can start to see, the types get really complicated, and they can represent really complicated proofs; this is the power of the Curry-Howard correspondence. Incredible projects like CompCert (a C compiler proven to have equivalent semantics to a C AST interpreter), sel4 (a microkernel proven to not crash, barring hardware issues), and the first known proof of the Four-Color Theorem were created using Coq, all proven using the Curry-Howard correspondance, some fundamental axioms, and very advanced type-checking.

Lastly, I want to go back to "traditional" non-theorem proving languages, just to note that while it's not feasible to use them to write advanced proofs or code guaranteed to be correct with high confidence, their type systems can still be used to verify properties of your program. For example, if you define a type which can only be created from an operation (e.g. AuthorizedUser which can only be created by a call to Option login(String name, String password) with the correct arguments), you can create functions which can only be used in a type-safe way if they have that value (e.g. String getSecretData(AuthorizedUser user), which can't be called unless we create an authorized user, which we can't do unless we enter the correct name and password). This is especially important when designing an API, though it veers away from "how to use type systems for theorem proving" and towards "how to effectively use type systems in general".
> **Comments:**
> **username_3** (2023-08-15): I’m not sure that this *really* answers the question, though I don’t think it’s totally unrelated, either. The question is about using the metatheoretical framework of type systems to model things that are not conventionally considered type systems, but the Curry–Howard correspondence is about embedding propositions into a type system satisfying certain properties. This is not really the same thing.  
---
