Manuscript Offprint
arXiv:2609.02005Unifying Function- and Argument-First Bidirectional Type Systems
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Bidirectional typing mixes type synthesis and type checking into a single process. Existing bidirectional type systems can be classified into two styles based on whether, given a function application, a bidirectional typing algorithm synthesizes the function's type first and typechecks the argument against the synthesized argument type, or it synthesizes the arguments' types first and typechecks the function against the synthesized arguments' types. We call the former function-first and the latter argument-first. Not only do the two styles significantly differ in how the type systems and typing algorithms are formalized, but also they lead to incompatible typeabilities, forcing a language designer to select one style and to give up the other's typeabilities.
In this paper, we unify the two styles and develop with a new bidirectional type system for higher-rank polymorphism. Key ideas of the unification are twofold. Each function application is annotated with a bit of information to represent whether function- or argument-first typing is used, to allow a language designer (or even a programmer) to switch between the two styles at their discretion. We reformulate the function- and argument-first type systems by using ideas from colored types (Odersky et al., 2001) and boxy types (Vytiniotis et al., 2006), which can specify which part of a type should be synthesized or used for checking in a flexible manner. We also develop a typing algorithm based on the worklist approach by Zhao et al.
*This is a full version of the paper that has been accepted for publication in the Proceedings of Asian Symposium on Programming Languages and Systems (APLAS 2026), Lecture Notes in Computer Science (LNCS), Springer. This version discusses the algorithmic typing in detail with its full definition, a heuristics of guide insertion, and possible extensions of . The definitions omitted from the short version can also be found.
The (declarative) type system of is shown to be sound and to subsume two representative function- and argument-first bidirectional type systems. Our typing algorithm is shown to be sound with respect to the type system of and complete with respect to representative function- and argument-first systems. We mechanically prove the metatheorems using the Abella theorem prover.
1 Introduction
Bidirectional typing [12] mixes type checking, which takes a type as input and determines whether a given program has that type, and type synthesis, which returns the type of a given program, into a single process. For example, given a function application , a bidirectional type system may synthesize the type, say, for the function , then check that the argument has the type . Bidirectional typing has been used for implementing complex typing features, such as dependent types [15, 1], higher-rank polymorphism [11, 5], and total type error localization and recovery [21].
However, each existing bidirectional type system fixes the built-in typing order, making their typeabilities incompatible. Typing function applications is one of the main problems. Many bidirectional type systems [12, 11, 5] prefer to synthesize the type of the function first, then extract the argument type from the synthesized type, and check that the argument has the extracted type. We call this typing style function-first. By contrast, another system [18] prefers to synthesize the type of the argument first, which we call argument-first. The argument-first style checks that the given function has the synthesized type as its argument type. The gap between the function- and argument-first styles makes them incompatible, thereby forcing the language designer to select one and give up the other's typeability. Furthermore, supporting (higher-rank) polymorphism also distinguishes between the two formalizations, in terms of when polymorphic types are instantiated.
We propose a language that subsumes function- and argument-first bidirectional typing, and a typing algorithm for that system.¹ The type system of chooses either of the two styles based on “guides”, statically given at each function application². The language designer can choose the function-first (resp. argument-first) bidirectional typing at their discretion by inserting the guide for the function-first (resp. argument-first) style. For example, our framework allows the argument-first style only if a given argument is a variable and the function-first style otherwise. The existing two styles can be obtained as instances of the type system, by fixing all the guides in a program to the function-first or argument-first. Thanks to the guides, we can separate the problem of determining the typing order from a bidirectional type system and
¹BH stands for “both-handed” because our language flexibly switches between the function- and argument-first styles. ²Contextual typing [19] can also choose between the two styles, but it cannot switch between them for every function application. See Section 5.3 for more details.
leave that decision to the language designer. To show that this separation works well not only in a simple setting, supports higher-rank polymorphism.
A challenge with incorporating function- and argument-first bidirectional typing is to address partially known type information. For example, suppose that, given the expression , a typing process first synthesizes the type of , as in the argument-first style, secondly synthesizes the type of using 's type, and then checks that has the first argument type of . At the point of synthesizing 's type, the known information on is that takes two arguments, and the second argument type is the same as the type of . Therefore, we need a mechanism to use partially known type information, but neither the function-nor argument-first style represents such type information.
Actually, the idea of such partially known type information during type synthesis/checking has been studied in the literature [10, 16]. In Odersky et al. [10], each type constructor in a type expression is assigned one of the two colors, which stand for which part should be synthesized, while, in Vytiniotis et al. [16], boxes in a type expression specify which part of a type should be synthesized. For instance, a colored type and a boxy type mean that the argument type should be synthesized, resulting in unit, and the other parts are given for checking. The notation used in this paper is based on boxy types, because we adopt the restriction on boxy types that no synthesized part of a type occurs within a checking part.³ The distinction between synthesized and checked parts in a type expression is helpful to unify function- and argument-first bidirectional typing. For example, recall the above typing process for the expression . The boxy type indicates that the part outside the boxes consists of the known type information for synthesizing 's type, that is, the second argument 's type is .
The type system of is declarative in that it guesses types for universal quantifiers, and predicative in that the guessed types are only monotypes. Although the bidirectional type system in the simply typed setting [4] immediately leads to its typing algorithm, bidirectional type systems [11, 5, 18] for higher-rank polymorphism usually rely on guessing oracles. Furthermore, those systems restrict the guessed types to monomorphic types, making their typing algorithms simple and decidable. The type system of follows these design decisions⁴.
We provide a typing algorithm for the declarative type system. Our typing algorithm is based on the worklist approach introduced by Zhao et al. [24]. Their typing algorithm is for the function-first style bidirectional type system proposed by Dunfield and Krishnaswami [5]. Still, we show that its core idea is also applicable to the argument-first style, and even to the unified style.
The metatheory of is classified into declarative and algorithmic parts. From the declarative point of view, the type system of is sound with respect to System F extended with type coercions [3], and complete with respect to the
³In colored types, synthesized and checked parts can be arbitrarily nested.
⁴Section 5.2 discusses the choice to follow ML-style type systems supporting first-class polymorphism.
function-first bidirectional type system by Dunfield and Krishnaswami [5] and the argument-first one by Xie and Oliveira [18]. From the algorithmic point of view, our typing algorithm is sound with respect to the type system of . Although it is not quite complete with respect to the type system of , it is complete with respect to weaker systems—the two bidirectional type systems of Dunfield and Krishnaswami [5] and Xie and Oliveira [18].
The contributions of this work are summarized as follows.
-
We provide a unified type system that subsumes both the function- and argument-first bidirectional type systems with higher-rank polymorphism using boxy types. Our language serves as an intermediate language in that a language designer can use their own approach to determine whether to choose function- or argument-first bidirectional typing and reflect the choice in compiling their language to .
-
We provide a sound typing algorithm with respect to the type system of . It is also complete with respect to existing function- and argument-first bidirectional type systems. This algorithm is independent of which of the two styles a language designer chooses.
-
We mechanically formalize both declarative and algorithmic typing and prove the aforementioned soundness and completeness theorems, as well as termination of the algorithm, using the Abella theorem prover [7].
In addition, we have a prototype implementation of our typing algorithm with a heuristic elaboration of an ML-like language to . It is written in OCaml and available on Zenodo at https://doi.org/10.5281/zenodo.22218838, together with the Abella proofs.
The rest of the paper is organized as follows. Section 2 reviews the technical background of our work and overviews our approach. Section 3 presents , its declarative type system, and its metatheory. Section 4 summarizes our typing algorithm for and its metatheory. Section 5 discusses related work and Section 6 concludes.
2.1 Function- and Argument-First Bidirectional Typing
A bidirectional type system has two modes of typing: synthesis and checking modes. A judgment of the synthesis mode takes the form of , where , and are a typing context, an expression, and a type, respectively. This judgment means that, given and , the type is synthesized. By contrast, a judgment of the checking mode takes the form of , meaning that, given , and , it can be checked that has the type under .
Bidirectional typing switches between the two modes, usually based on term constructors. For example, a typing rule [4] for function applications is:
One can read off a recursive algorithm for type synthesis/checking, if the two modes are specified appropriately: this rule means that, given a typing context and a function application , the algorithm first synthesizes the type of , then checks that the argument has the type required by the function , and finally outputs the type as a result of the type synthesis for .
Bidirectional typing rules for function applications are classified into two styles. One style is, given a function application, to first synthesize the type of the function. We call this style function-first. In this sense, the typing rule shown above is in the function-first style. Many bidirectional type systems [12, 11, 5] can be classified as the function-first style. We select the system by Dunfield and Krishnaswami [5], referred to as the DK system for short, as a subject of our research because of its simplicity. Another style is to first synthesize the type of the argument. We call this style argument-first. The argument-first style of bidirectional typing originates from the work by Xie and Oliveira [18]. We refer to their type system (without let polymorphism) as the XO system for short .
The formalization of the argument-first style is very different from that of the function-first style. The XO system has no typechecking rule. Instead, it has an application context in its typing judgment, as , to reuse the known type information. An application context stacks the synthesized types of the arguments. To see the role of an application context, we show the XO typing rules for function applications and lambda abstractions as follows.
The typing rule for function applications in the XO system stacks the type synthesized from the argument . It first synthesizes the type of the argument ; pushes the synthesized type into the application context ; and synthesizes the type of the function using the information about the argument types accumulated in . On the other hand, the typing rule for lambda abstractions uses stacked type information to determine the argument type.
While the function- and argument-first styles are formalized in different ways even in a simple setting, their difference becomes larger when considering (higher-rank) polymorphism. For example, consider the function application id 42 where id has the type . The DK system first synthesizes the type of id and then guesses a monotype to instantiate it for typechecking 42. The XO system, in contrast, first synthesizes the type of 42 and then guesses a monotype to instantiate the type of id, ensuring the argument type is int. In
We leave supporting let polymorphism as future work.
We omit a type generalization from the original typing rule because let polymorphism is out of scope.
short, if a function has a polymorphic type, the function-first (resp. argument-first) style guesses a type to instantiate it in the derivation for the argument (resp. function).
More crucially, the typeabilities of the DK and XO systems are incompatible with higher-rank polymorphism. Consider the following two expressions:
Note that both systems only infer monotypes for parameters of lambda abstractions, following the Hindley–Milner type inference. The former expression is well-typed under the DK system but ill-typed under the XO system. The XO system fails to synthesize the desired type of g, which should be polymorphic for the expression to be well-typed, but it can only assign a monomorphic type to it. The latter expression is well-typed under the XO system but ill-typed under the DK system, because the DK system fails to synthesize the desired type of f, which should be polymorphic. This example shows that their typeabilities are incompatible, as Xie and Oliveira [18] pointed out.
2.2 Our Work: Unifying Function- and Argument-First Styles
We aim to unify the function- and argument-first bidirectional type systems, specifically the DK and XO systems, into a single system that incorporates their different typeabilities. This feature helps augment the typeabilities of existing bidirectional type systems.
We clarify a challenge in mixing function- and argument-first bidirectional typing before showing our approach. As shown in Section 2.1, if a lambda abstraction whose argument has a polymorphic type is supplied as an argument, the function- and argument-first styles differ in typeability, i.e., where we must write type annotations. Therefore, the situation in which two or more arguments are lambda abstractions of this kind is troublesome. For example, suppose that, given the following declarations and the function application , we use the function-first style for the left application and the argument-first style for the right application .
Because both the DK and XO systems guess only monotypes for parameters of lambda abstractions, we must reuse the synthesized type information about to synthesize the type of . However, neither the DK nor the XO system can address the situation where, given a function, we must synthesize its first argument type and typecheck its second argument type. Therefore, we need a more flexible representation for partially known type information.
Our key idea to address this challenge is to adapt boxy types [16], which were originally proposed for the function-first style, to the argument-first style.
A boxy type specifies that partial type information is synthesized and that the other part is typechecked by enclosing type information to be synthesized within a box. For example, the boxy type int intuitively indicates that unit is synthesized, and that the type information outside the box, namely the function arrow and the return type int, is given. We can mix the function-and argument-first bidirectional typing using boxy types. Recall the expression . We can use the following boxy type for to accept the program, where is .
Introducing boxy types enables us to define function- and argument-first typing rules for function applications without an application context. We use the metavariables and to denote an ordinary type, i.e., a type with no box, and a boxy type, respectively. Then, our typing rules are as follows.
The former rule (3) corresponds to the function-first typing. It synthesizes the argument type of the function and checks that has the synthesized type . Algorithmically, denotes a placeholder that should be replaced with a synthesized type, and is the synthesized one. For example, supposing , we have the following typing derivation.
First, the non-boxed type unit in the conclusion means that is typechecked against unit. Then, the polymorphic type of is instantiated with unit because 's return type is required to be unit. Finally, the argument () is typechecked against unit.
The latter typing rule (4), which is for the argument-first style, first synthesizes a type of . It checks that has a function type with the synthesized argument type , as expressed by the boxy type . Recall that a type with no box indicates that it is fully given information. Unlike the XO system, a boxy type, not an application context, stacks the synthesized argument types.
The remaining issue is: given a function application, should we choose the rule (3) or (4)? Here, our central interest is a declarative type system, rather than an algorithmic one that determines how to choose them. Therefore, we assume that every function application has an annotation so that the language designer can choose the rule as they wish.
We introduce application guides to decide whether we use the function- or argument-first typing rule. An application guide is either a function-first guide or an argument-first guide . If a function application takes the form of (resp. ), we choose the function-first (resp. argument-first) rule. These constructs allow a language designer or even a programmer to switch their typing style between the two rules. For example, both programs shown in Section 2.1 are made well-typed by properly inserting application guides like:
Adopting application guides enables to serve as a fundamental intermediate language. Although writing a guide for every function application is cumbersome, a language designer can define their own scheme to choose either the function- or argument-first style along with their language. For example, if a language designer wants to use argument-first typing only when an argument is a variable, they may introduce the following translation.
Our prototype implementation includes a more practical insertion of application guides. It tries to make the best use of known type information in type checking. For example, our insertion algorithm heuristically chooses the function-first style if a variable takes an argument , because the type of is known when typing . Similarly, it uses the argument-first style if an argument type is fully known. Using our heuristics transforms the two expressions (1) and (2) into (5) and (6), respectively. In other words, it enables programmers to enjoy the benefits of the function- and argument-first styles without writing application guides directly. However, evaluating how well our elaboration algorithm works in practice is left for future work. Further details of our heuristics can be found in Appendix C.
3 and Its Type System
This section shows our language and its declarative type system. We discuss only subtyping and typing—interested readers are referred to Appendix E for the omitted definitions, including well-formedness of types.
The type system of is declarative in the sense that it guesses monotypes for instantiating polymorphic types or for parameters of lambda abstractions. We design this type system so that its synthesis result is uniquely determined if the guessing oracle outputs the same monotype.
3.1 Syntax
We show the syntax of in Figure 1. Expressions, ranged over by , consist of the unit term (), variables , lambda abstractions , lambda abstractions with type annotations , and two kinds of function applications and . We use type annotations in lambda abstractions to introduce variables of higher-rank polymorphic types. For example, we can write a function that takes a polymorphic identity function, like . Function applications involve application guides, as explained in Section 2.
Figure 1: Syntax
Types, ranged over by and , consist of the unit type unit, type variables , function types , and universal types . Monotypes, ranged over by and , are the types with no universal type.
The syntax for boxy types, ranged over by and , reflects the intuition explained in Section 2.2. Note that we only allow a type , with no box, inside a universal type. Consider the typing judgment
to see why this restriction is justified. This judgment would mean that we synthesize the type denoted as “?” under the universal type . However, the typing process cannot uniquely determine the synthesis result. For example, both filling the hole with and with are valid, because our subtyping system can derive the following two subtyping judgments.
Therefore, we require all type information within a universal type to be given.
Typing contexts are standard . Note that, following existing systems [10, 16], typing contexts are always assumed to be complete inputs. Thus, the types in a typing context cannot include boxes.
3.2 Subtyping
We have two subtyping judgments, and . The box as a subscript indicates on which side boxes can appear. In the subtyping judgment , the input consists of the typing context , the type , and the part of the boxy type outside boxes, and the output is the part of the boxy type inside boxes. For example, the subtyping judgment means that, given the empty typing context, the subtype , and the information that the supertype should be a
We use rather than to denote a typing context, following Zhao et al. [24].
Figure 2: Subtyping
function type with the return type unit, our subtyping system outputs that the argument type of the supertype is unit. The subtyping judgment is the reversed version of in the sense that the boxy type is a subtype, not a supertype. We show the subtyping rules in Figure 2. We use the names prefixed with “SL” (resp. “SR”) for the rules of the subtyping judgment (resp. ).
The rules SL_BOX and SR_BOX are for cases with no given type information in a boxy type. Thus, they return the type A without changing it. The rules SL_UNIT, SR_UNIT, SL_TVAR, SR_TVAR, SL_FUN, and SR_FUN are straightforward. The outermost type constructor of the boxy type is the same as that of the type.
The rules SL_∨R and SR_∨R generalize a polymorphic variable, similarly to the corresponding rules in the DK and XO systems. Note that these rules never instantiate the type in a box because the type is guessed and should be reused without changing. SR_∨R has the premise condition not□(A□), which means that the outermost constructor is not a box. We need this condition to ensure that the synthesis result, namely the type in a box, is unique if the guessing oracle outputs the same monotype. Without this condition, the subtyping
Figure 3: Typing
judgments and would hold, but they have different synthesis results, unit and . The condition excludes the former judgment, and only the latter is valid via SR_BOX.
The rules SL_∀L and SR_∀L instantiate quantified type variables with guessed monotypes. These rules are also similar to the corresponding rules in the DK and XO systems. In both rules, guessed and substituted types must be monomorphic because our system is predicative. The condition in the rule SL_∀L is required for the same reason as in SR_∀R.
3.3 Typing
Our typing judgment takes the form of . Note that we only have a single judgment form because using boxy types enables us to unify type synthesis and checking, with and corresponding to type synthesis and checking respectively. In the typing judgment , the input consists of , , and the part of the boxy type outside boxes. The output is a part of the boxy type inside boxes. For example, the typing judgment means that, given the typing context , the expression , and the information that must have a function type with the return type unit, our typing system outputs that the argument type is unit.
The rules T_UNIT and T_VAR are standard except that we use and in their respective premises. These premises enable our type system to represent type synthesis and checking in one typing rule. The rule T_∀ is also standard and similar to the corresponding rule in the DK system.
There are three rules T_λBOX, T_λFUN1, and T_λFUN2 for lambda abstractions without type annotations and two rules T_λ:BOX and T_λ:FUN for those with. T_λBOX applies in the case where no type information is given, i.e., the entire type must be synthesized. In this case, a monotype is guessed as the argument type, similarly to the DK, XO, and other bidirectional type systems [11, 16, 24] that support higher-rank polymorphism. T_λFUN1 applies when the argument type is fully given (by ), in which case we need no guess. T_λFUN2 applies when the argument type is partially given (by ). The condition hasBox() means that there is no type such that —in other words, at least one box appears in —to avoid the overlap with T_λFUN1. In this case, we need to guess an argument type and check that the guess matches by using the subtyping judgment . T_λ:BOX is for the case where the type has to be fully synthesized. T_λ:FUN is for the case where a part of the type is given. The second premise means that can be given type , which has to be a subtype of , hence the first premise.
The rule T_APPR is for function applications with the function-first guide. It means that the argument type of the function is first synthesized, and the argument is checked against that type.
The rule T_APPL is for function applications with the argument-first guide. This rule means that the type of the argument is first synthesized, and the function is checked against the type that includes the synthesized argument type.
3.4 Metatheory
Soundness. The type system of is sound with respect to System F [3], an extension of System F with type coercions. We choose System F, not System F, because we require a base calculus to be equipped with a mechanism to encode our subtyping derivations.
We briefly explain the auxiliary functions before stating the soundness theorem. is the type that results from removing the boxes from the boxy type . is the expression in the untyped lambda-calculus that results from eliminating type annotations and application guides from . This translation preserves the reduction of the source language because neither type annotations nor application guides influence the reduction. Given the expression of System F, is the expression in the untyped lambda-calculus that results by eliminating type annotations, type abstractions, and coercions. This translation preserves the original semantics, as proven in Cretin and Rémy [3].
Theorem 3.1 (Soundness w.r.t. System ). If , then there exists some such that and .
Completeness. The type system of is complete with respect to both the DK and XO systems.
We introduce a few notations to state the completeness theorem regarding the DK system. We use the translation from the expression in the DK system to the expression in . This translation simply bridges the syntactic gap between the DK system and . Since the DK system adopts function-first typing, we translate a function application in the DK system to a function application with the function-first guide . Furthermore, because the DK system allows for annotating any expression with a type, we translate a type-annotated expression to a function application . These changes do not affect the reduction of the DK language.
Theorem 3.2 (Completeness w.r.t. the DK System).
-
If , then there exists some such that and .
-
If , then .
A notable point is that we use the subtyping relation , not the equality on types. This choice comes from the limitation of the DK system. The DK system only synthesizes a monotype for a lambda abstraction. For example, it can derive only the former of the following two judgments.
However, the XO system and ours can derive only the latter. Thus, the completeness theorem must state that the type system of may synthesize a more general type than the DK system does.
To state the completeness theorem regarding the XO system, we use the two auxiliary functions and . We translate the expression in the XO system to the expression in by marking every function application with . Because the XO system stacks the synthesized type information about the arguments in an application context as explained in Section 2.1, we embed such information in a boxy type using defined as follows.
Then, the completeness theorem is stated as follows:
Theorem 3.3 (Completeness w.r.t. the XO System). If , then .
4 Algorithmic Typing
This section briefly explains our typing algorithm. Its formal definition can be found in Appendix B.
4.1 Typing Algorithm based on the Worklist Approach
Our typing algorithm is based on the worklist approach. It was originally proposed by Zhao et al. [23] to formalize an algorithm for polymorphic subtyping [9]. Afterward, Zhao et al. [24] extended it to the DK system.
A worklist is a typing context extended with existential variables and subtyping/typing judgments, defined as follows.
An existential variable in is solved to only a monotype that is well-formed under . In other words, a typing algorithm based on the worklist approach propagates the guessed monotype through an existential variable.
A typing algorithm using a worklist is defined as a reduction . It means that a typing algorithm, given a worklist , pops the rightmost judgment in and processes it in one step, resulting in . For example, let us consider the following reduction.
The left-hand side worklist means that the first judgment of a typing algorithm is to check that the type is a subtype of under the empty typing context. This reduction means that we need to check that (resp. ) is a subtype of (resp. ) to check that is a subtype of . In this sense, a worklist can be seen as a “flattened” version of a corresponding derivation tree. After we learn that the two subtyping relations hold, the typing process removes the completed work items and reaches the empty worklist , indicating that the typing process has successfully finished. Generally speaking, a typing process successfully ends if holds, where is defined as the reflexive and transitive closure of .
We introduce polymorphic existential variables to adapt the worklist approach to boxy types. A boxy type may have multiple “output channels”; e.g., means that the output types are unit and . Therefore, our typing algorithm must propagate the (polymorphic) types that fill up boxes from one work item to the remaining work items. We assign a polymorphic existential variable to each box in a boxy type to support this propagation. This idea, assigning a special variable to each box, is also used in the type inference algorithm of the original work on boxy types [16].
We use the following reduction example to explain how polymorphic existential variables work in our typing algorithm.
▷{β} in the former worklist accumulates polymorphic existential variables. After this reduction, our typing algorithm synthesizes an argument type, which can be polymorphic, for , and uses it to typecheck . To propagate the synthesized type, this reduction introduces a new polymorphic existential variable . We use an existential variable and a polymorphic one to guess a monotype and to synthesize a (polymorphic) type in a box, respectively.
4.2 Metatheory
Our major metatheorems about the typing algorithm are: (1) the soundness w.r.t. the declarative type system of , (2) the completeness w.r.t. the DK and XO systems, and (3) its decidability.
To relate our typing algorithm and the type system of , we use a declarative worklist and worklist instantiation , following Zhao et al. [24]. Declarative worklists and their reduction correspond to the declarative type system of . For example, is reduced to only if holds, where is a typing context obtained by eliminating all (sub)typing judgments from . Worklist instantiation substitutes well-formed types for all (polymorphic) existential variables. Namely, if and hold, there exists a solution for (polymorphic) existential variables that makes the corresponding declarative typing hold.
Soundness. Our typing algorithm is sound with respect to the type system of . We denote the well-formedness of by .
Theorem 4.1 (Soundness w.r.t. the Declarative System of ). If and , then there exists some such that and .
As a corollary, we show the soundness for each specific work item.
Corollary 4.2 (Soundness for Each Work Item). 1. If and , then there exist some , and such that and .
-
If and , then there exist some , , and such that and .
-
If and , then there exist some , , and such that and .
Incompleteness with respect to the Declarative System. One may expect that our typing algorithm is complete with respect to the declarative system.
Statement 4.3. If and and , then .
However, the following and show a counterexample.
Our typing algorithm reduces to (): . However, this reduction does not proceed further because the type inside a box must be a polymorphic existential variable in our typing algorithm.
We can still prove a weaker statement by excluding “invalid” inputs of the following two kinds:
-
A type other than a polymorphic existential variable in a box; and
-
Two or more occurrences of a polymorphic existential variable in a box.
We introduce two judgments, and , to exclude them. (See Appendix E to see the full definitions of these judgments.) The former judgment imposes a stricter well-formedness than . It excludes the first kind of invalid inputs. The latter judgment accumulates polymorphic existential variables in boxes into the variable set , resulting in . During this accumulation process, the judgment checks that a previously encountered polymorphic existential variable never occurs in a box. Therefore, excludes the second kind of invalid inputs. Under the restrictions, our typing algorithm is “complete” with respect to the declarative typing of .
Lemma 4.4. If and and and , then .
Completeness with respect to the DK and XO systems. Our typing algorithm is complete with respect to both the DK and XO systems. We show that the restriction posed on the input in Theorem 4.4 is not so strict as to reject the well-typed program in the DK system or the XO system.
Corollary 4.5 (Completeness w.r.t. the DK and XO systems).
• If , then .
• If , then .
• If , then .
This corollary indicates that our typing algorithm successfully types the well-typed program under the DK or the XO system by properly inserting the polymorphic existential variable.
Decidability. Our typing algorithm is decidable.
Theorem 4.6. If and , then or there exists some non-empty such that and .
The proof strategy follows that of the decidability shown by Zhao et al. [24].
5 Related Work
5.1 Predicative Systems
Peyton Jones et al. [11] developed a function-first style bidirectional type system supporting higher-rank polymorphism. They force a synthesized type to have no top-level quantifier by instantiated higher-rank types. However, not only does their system lack the typeability that the argument-first style has, but this requirement introduces a further limitation regarding typeability. For example, their system cannot synthesize the type unit , given the expression and the typing context . Having no restriction on the forms of synthesized types, our system can synthesize this type, as the XO system can.
Dunfield and Krishnaswami [5] proposed an application judgment, which extracts the argument type from a (polymorphic) function type. They added it to a function-first style bidirectional type system to support higher-rank polymorphism. We show that boxy types enable our type system to subsume their type system in Section 3.4.
Xie and Oliveira [18] introduced argument-first bidirectional typing using an application context, as discussed in Section 2. We show that boxy types can subsume the notion of an application context in Section 3.4. However, their system also supports let-polymorphism and is a conservative extension of the Hindley-Milner type system, in contrast to the type system of .
5.2 Impredicative Systems
Work on first-class polymorphism for ML-like languages includes PolyML [8], ML [2], and FPH [17]. These systems are based on the Damas-Milner style, while supporting impredicative polymorphism. Nevertheless, their annotation-free inference does not cover every program accepted by argument-first typing. For example, if has type , the corresponding unannotated program is rejected: these systems do not use the argument type to check the body of an abstraction under the assumption . PolyML and ML require polymorphism to be made explicit when a lambda-bound variable is used polymorphically, while FPH infers monotypes for unannotated lambda-bound variables.
Serrano et al. [14] proposed an algorithm called Quick Look to support impredicativity, combining bidirectional typing and constraint-based type inference. They showed that Quick Look can be easily integrated with the existing type inference algorithms. While their system lacks some typeability that the XO system has, similarly to the system of Peyton Jones et al. [11], Quick Look can be a good guide to extending our system with impredicativity.
Zhao and Oliveira [22] extended the DK system with top and bottom types and impredicative explicit type applications. Incorporating their change to the DK system would be a first step toward extending our system with impredicativity.
5.3 Generalizing Bidirectional Typing
Vytiniotis et al. [16] proposed boxy types, on which our formalization is based. While their type system is impredicative and a conservative extension of the Hindley-Milner type system, it forces a synthesized type to have no top-level quantifier by instantiating higher-rank types, as Peyton Jones et al. [11] do. Since the XO system has no such restriction, we need to develop our language to subsume the XO system. We expect that the way Vytiniotis et al. support impredicative polymorphism could serve as a guide to extending the type system of to impredicative polymorphism.
Odersky et al. [10] refined local type inference [12] and introduced colored types to reduce type annotations. Colored types specify how type information flows and allow type information intended for checking to occur in a synthesized type. Boxy types are similar to their colored types, except that they prevent type information that should be checked from arising in a synthesized type. However, because the declarative type system with colored types is based on , our typing and subtyping rules differ from theirs.
Contextual typing [19] combined function- and argument-first styles of bidirectional typing to some degree. However, contextual typing has no feature to freely switch between function- and argument-first typing, i.e., it cannot synthesize the type for the function application in our syntax. Moreover, it does not support any kind of polymorphism, while it has been shown to scale to subtyping, intersection types, overloading, and records.
Xue et al. [20] proposed Contextual System F based on contextual typing. Contextual System F is a variant of implicit System F and more flexibly switches between function- and argument-first bidirectional typing than Xue and Oliveira [19]. However, it is even more restrictive in how it switches than the type system of . For example, given the function application written in our syntax, the type system of synthesizes the first argument type of using the synthesized type of to proceed with type checking for . Still, Contextual System F disallows this typing flow and applies type synthesis or checking to arguments only in left-to-right order, i.e., the typing procedure of Contextual System F always flows from to in the example. While this restriction in Contextual System F helps realize implicit and impredicative polymorphism both in declarative and algorithmic systems, it prevents Contextual System F from accepting some programs that are well-typed under either the DK or XO system, and the algorithmic typing of Contextual System F sticks to the restriction. Incorporating the typeability of Contextual System F, especially impredicativity, is an interesting future direction of our work.
6 Conclusion and Future Work
In this paper, we propose a unified language and its declarative type system that subsumes function- and argument-first bidirectional type systems and supports higher-rank polymorphism using boxy types. serves as an inter-mediate language and leaves design space to allow a language designer to define their own approach to choosing either function- or argument-first typing. We formalize them and prove that the type system of is complete with respect to both the DK and XO systems and is sound with respect to System .
Moreover, we present a typing algorithm for using the worklist approach. This algorithm is independent of the heuristics that a language designer adopts to determine whether they use function- or argument-first typing. We mechanically prove that our typing algorithm is sound with respect to the type system of . Our typing algorithm is not complete with respect to the type system of , but we show that it is complete with respect to both the DK and XO systems.
Future work on the declarative side includes extending to support product types, let-polymorphism, and impredicativity. Since the type of an argument in a function application is fully synthesized or checked in the type system of , the following derivation with a product type is not supported.
A challenging future direction is to support this kind of typing. Supporting let-polymorphism enables to subsume the original XO system completely. Supporting explicit type applications is another interesting future direction. The works of Xie and Oliveira [18] and Zhao et al. [22] guide us to extend with explicit type applications to allow for impredicative type instantiations. The other existing work [16, 20] could also help support impredicativity.
Future work on the algorithmic side includes combining our typing algorithm with a level-based type-inference method [13, 6] and providing a typeability benchmark. Because a level-based type inference has been used to implement practical programming languages, adopting it for helps bring 's typeability to practical implementations, requiring minimal changes. To evaluate the practical usefulness of our framework, we need to explore how stable our typing is with certain program transformations. For example, studying whether a well-typed program in remains well-typed after removing type annotations, -reduction, and -conversion is an interesting future direction.
References
[1] Thorsten Altenkirch, Nils Anders Danielsson, Andres Löh, and Nicolas Oury. PiSigma: Dependent types without the sugar. In Matthias Blume, Naoki Kobayashi, and Germán Vidal, editors, Functional and Logic Programming, 10th International Symposium, FLOPS 2010, Sendai, Japan, April 19-21, 2010. Proceedings, volume 6009 of Lecture Notes in Computer Science, pages 40-55. Springer, 2010. https://doi.org/10.1007/978-3-642-12251-4_5.
[2] Didier Le Botlan and Didier Rémy. ML: raising ML to the power of system F. In Colin Runciman and Olin Shivers, editors, Proceedings of the Eighth ACM SIGPLAN International Conference on Functional Programming, ICFP 2003, Uppsala, Sweden, August 25-29, 2003, pages 27-38. ACM, 2003. https://doi.org/10.1145/944705.944709.
[3] Julien Cretin and Didier Rémy. On the power of coercion abstraction. In John Field and Michael Hicks, editors, Proceedings of the 39th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL 2012, Philadelphia, Pennsylvania, USA, January 22-28, 2012, pages 361-372. ACM, 2012. https://doi.org/10.1145/2103656.2103699.
[4] Jana Dunfield and Neel Krishnaswami. Bidirectional typing. ACM Comput. Surv., 54(5):98:1-98:38, 2022. https://doi.org/10.1145/3450952.
[5] Jana Dunfield and Neelakantan R. Krishnaswami. Complete and easy bidirectional typechecking for higher-rank polymorphism. In Greg Morrisett and Tarmo Uustalu, editors, ACM SIGPLAN International Conference on Functional Programming, ICFP'13, Boston, MA, USA - September 25-27, 2013, pages 429-442. ACM, 2013. https://doi.org/10.1145/2500365.2500582.
[6] Andong Fan, Han Xu, and Ningning Xie. Practical type inference with levels. Proc. ACM Program. Lang., 9(PLDI):2180-2203, 2025. https://doi.org/10.1145/3729338.
[7] Andrew Gacek. The Abella interactive theorem prover (system description). In Alessandro Armando, Peter Baumgartner, and Gilles Dowek, editors, Automated Reasoning, 4th International Joint Conference, IJCAR 2008, Sydney, Australia, August 12-15, 2008, Proceedings, volume 5195 of Lecture Notes in Computer Science, pages 154-161. Springer, 2008. https://doi.org/10.1007/978-3-540-71070-7_13.
[8] Jacques Garrigue and Didier Rémy. Semi-explicit first-class polymorphism for ML. Inf. Comput., 155(1-2):134-169, 1999. https://doi.org/10.1006/INCO.1999.2830.
[9] Martin Odersky and Konstantin Läufer. Putting type annotations to work. In Hans-Juergen Boehm and Guy L. Steele Jr, editors, Conference Record of POPL'96: The 23rd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, Papers Presented at the Symposium, St. Petersburg Beach, Florida, USA, January 21-24, 1996, pages 54-67. ACM Press, 1996. https://doi.org/10.1145/237721.237729.
[10] Martin Odersky, Christoph Zenger, and Matthias Zenger. Colored local type inference. In Chris Hankin and Dave Schmidt, editors, Conference Record of POPL 2001: The 28th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, London, UK, January 17-19, 2001, pages 41-53. ACM, 2001. https://doi.org/10.1145/360204.360207.
[11] Simon L. Peyton Jones, Dimitrios Vytiniotis, Stephanie Weirich, and Mark Shields. Practical type inference for arbitrary-rank types. J. Funct. Program., 17(1):1–82, 2007. https://doi.org/10.1017/S0956796806006034.
[12] Benjamin C. Pierce and David N. Turner. Local type inference. In David B. MacQueen and Luca Cardelli, editors, POPL '98, Proceedings of the 25th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, San Diego, CA, USA, January 19-21, 1998, pages 252–265. ACM, 1998. https://doi.org/10.1145/268946.268967.
[13] Didier Rémy. Extension of ML type system with a sorted equation theory on types. PhD thesis, INRIA, 1992.
[14] Alejandro Serrano, Jurriaan Hage, Simon Peyton Jones, and Dimitrios Vytiniotis. A quick look at impredicativity. Proc. ACM Program. Lang., 4 (ICFP):89:1–89:29, 2020. https://doi.org/10.1145/3408971.
[15] Vilhelm Sjöberg and Stephanie Weirich. Programming up to congruence. In Sriram K. Rajamani and David Walker, editors, Proceedings of the 42nd Annual ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, POPL 2015, Mumbai, India, January 15-17, 2015, pages 369–382. ACM, 2015. https://doi.org/10.1145/2676726.2676974.
[16] Dimitrios Vytiniotis, Stephanie Weirich, and Simon L. Peyton Jones. Boxy types: inference for higher-rank types and impredicativity. In John H. Reppy and Julia Lawall, editors, Proceedings of the 11th ACM SIGPLAN International Conference on Functional Programming, ICFP 2006, Portland, Oregon, USA, September 16-21, 2006, pages 251–262. ACM, 2006. https://doi.org/10.1145/1159803.1159838.
[17] Dimitrios Vytiniotis, Stephanie Weirich, and Simon L. Peyton Jones. FPH: first-class polymorphism for Haskell. In James Hook and Peter Thiemann, editors, Proceeding of the 13th ACM SIGPLAN international conference on Functional programming, ICFP 2008, Victoria, BC, Canada, September 20-28, 2008, pages 295–306. ACM, 2008. https://doi.org/10.1145/1411204.1411246.
[18] Ningning Xie and Bruno C. d S. Oliveira. Let arguments go first. In Amal Ahmed, editor, Programming Languages and Systems - 27th European Symposium on Programming, ESOP 2018, Held as Part of the European Joint Conferences on Theory and Practice of Software, ETAPS 2018, Thessaloniki, Greece, April 14-20, 2018, Proceedings, volume 10801 of Lecture Notes in Computer Science, pages 272–299. Springer, 2018. https://doi.org/10.1007/978-3-319-89884-1_10.
[19] Xu Xue and Bruno C. d. S. Oliveira. Contextual typing. Proc. ACM Program. Lang., 8(ICFP), August 2024. https://doi.org/10.1145/3674655.
[20] Xu Xue, Chen Cui, Shengyi Jiang, and Bruno C. d S. Oliveira. Local contextual type inference. Proc. ACM Program. Lang., 10(POPL):294–323, 2026. https://doi.org/10.1145/3776653.
[21] Eric Zhao, Raef Maroof, Anand Dukkipati, Andrew Blinn, Zhiyi Pan, and Cyrus Omar. Total type error localization and recovery with holes. Proc. ACM Program. Lang., 8(POPL):2041–2068, 2024. https://doi.org/10.1145/3632910.
[22] Jinxu Zhao and Bruno C. d S. Oliveira. Elementary type inference. In Karim Ali and Jan Vitek, editors, 36th European Conference on Object-Oriented Programming, ECOOP 2022, June 6-10, 2022, Berlin, Germany, volume 222 of LIPIcs, pages 2:1–2:28. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2022. https://doi.org/10.4230/LIPICS.ECOOP.2022.2.
[23] Jinxu Zhao, Bruno C. d S. Oliveira, and Tom Schrijvers. Formalization of a polymorphic subtyping algorithm. In Jeremy Avigad and Asia Mahboubi, editors, Interactive Theorem Proving - 9th International Conference, ITP 2018, Held as Part of the Federated Logic Conference, FloC 2018, Oxford, UK, July 9-12, 2018, Proceedings, volume 10895 of Lecture Notes in Computer Science, pages 604–622. Springer, 2018. https://doi.org/10.1007/978-3-319-94821-8_36.
[24] Jinxu Zhao, Bruno C. d S. Oliveira, and Tom Schrijvers. A mechanical formalization of higher-ranked polymorphic type inference. Proc. ACM Program. Lang., 3(ICFP):112:1–112:29, 2019. https://doi.org/10.1145/3341716.
A Design Direction Towards Algorithmic Typing
This section overviews our typing algorithm for . Our typing algorithm is based on the worklist approach. It was originally proposed by Zhao et al. [23] to mechanically formalize an algorithm for polymorphic subtyping [9] and subsequently extended by Zhao et al. [24] to the DK system. Appendix A.1 reviews the notion of the latter worklist approach and Appendix A.2 discusses key design ideas behind our algorithm to extend the worklist approach to boxy types.
A.1 Review: Worklist Approach
A worklist is a typing context extended with existential variables and subtyping/typing judgments. An existential variable should be solved to a monotype similarly to a unification variable, but its scope is managed in a worklist. This approach enables us to avoid accidentally solving unification variables, which violates the scope condition imposed by the declarative type system.
A worklist is defined as follows.
A worklist can contain an existential variable and a subtyping judgment . An existential variable in is solved to only a type that is well-formed under . Note that an existential variable can occur in a type.
A typing algorithm using a worklist is defined as a reduction , which means that a typing algorithm, given a worklist , pops the rightmost judgment in and processes it in one step, resulting in . For example, let us consider the following reduction.
The left-hand side worklist means that the first judgment of a typing algorithm is to check that the type is a subtype of under the empty typing context. This reduction means that we need to check that (resp. ) is a subtype of (resp. ) to check that is a subtype of . In this sense, a worklist can be seen as a “flattened” version of a corresponding derivation tree. After we learn that the two subtyping relations hold, the typing process removes the completed work items and reaches the empty worklist , indicating that the typing process has successfully finished.
Consider the following worklist to understand why existential variables are not globally declared.
A reduction of this worklist must get stuck because the corresponding declarative typing judgment
is not derivable for any . The worklist is reduced to
by introducing the existential variable to represent the monotype used to instantiate the quantified type variable in the declarative typing. The worklist means that can be solved to only a type that is well-formed under . In a few steps, we reach the following reduction (after removing the successful work item unit<: unit) which introduces the type variable .
Because the existential variable can be solved only to a type well-formed under , unlike globally declared variables, it cannot be solved to . Thus, the typing process fails as required owing to the scope management of existential variables.
We only consider judgments without boxy types for a while.
A.2 Polymorphic Existential Variables and Scope Delimiters
Our typing algorithm differs from that of Zhao et al. [24] mainly in two aspects: using polymorphic existential variables, and introducing scope delimiters. We use the former to support boxy types. To manage their scope, we introduce the latter.
A.2.1 Polymorphic Existential Variables
We introduce polymorphic existential variables to adapt the worklist approach to boxy types. A boxy type may have multiple “output channels”; e.g., unit → unit → unit means that the output types are the argument type unit and the return type unit → unit. Therefore, our typing algorithm must propagate the types that fill up boxes from one work item to the remaining work items. We assign a polymorphic existential variable to each box in a boxy type to support this propagation. This idea is also used in the type inference algorithm of the original work on boxy types [16].
We propagate a solved type in the box of a given boxy type through a polymorphic existential variable , which can be solved to a polymorphic type, in contrast to an existential variable, which propagates guessed monotypes. Roughly speaking, our algorithmic typing rule for function applications with the function-first guide is as follows, where we use a work item for typing.
The aspects that differ from the corresponding declarative typing rule T_APPR are: we introduce a polymorphic existential variable and replace the boxed type in T_APPR with it. The polymorphic existential variable acts as a placeholder for the result of type synthesis. The work item means that our typing algorithm synthesizes the argument type of and substitutes the synthesized type for . The work item means that the expression is typechecked against the synthesized argument type of . Note that we have no rule that solves a polymorphic existential variable outside boxes. A non-boxed polymorphic existential variable, e.g., in , should have been solved when the work item comes to the rightmost position of the worklist.
A.2.2 Scope Delimiters
We introduce scope delimiters to manage scoping of existential variables in a setting with polymorphic existential variables. The notion of scope delimiters is closely related to ranks or levels of type variables [13, 6].
First, we explain why using polymorphic existential variables complicates the scope management of existential variables. Consider the following two declarative typing derivations as examples.
A typing algorithm for must support them because they hold in the declarative type system of . Regarding the derivation (7), the reduction of the corresponding worklist is as follows.
The existential variable is introduced in the second step just after the type variable , because the monotype in (7) is well-formed under . However, introducing existential variables at the rightmost position in a worklist does not always work well with polymorphic existential variables. The reduction of the worklist corresponding to the derivation (8) fails if we introduce an existential variable at the rightmost in a worklist.
Note that the existential variable corresponds to the guessed monotype in the declarative subtyping judgments and . Because the existential variable is after and in this worklist, we cannot solve them to . Therefore, our typing algorithm inserts before the polymorphic existential variables and to solve them.
We introduce scope delimiters to tell our typing algorithm where existential variables should be inserted. A scope delimiter takes the form of , where is a sequence of polymorphic existential variables. Our typing algorithm always introduces a scope delimiter alongside a type variable and inserts an existential variable just before the rightmost scope delimiter. For example, a typing algorithm corresponding to the derivation (7) works as follows.
Because a type variable and a scope delimiter are introduced simultaneously, we can use the type variable to solve existential variables inserted just before the scope delimiter. To see why we insert existential variables before the right-most scope delimiter, consider the following typing process corresponding to the
| Types | A, B | := | unit | a | | A B | .A |
|---|---|---|---|
| Boxy types | := | | unit | a | | | | .A | |
| Work items | := | A <: | <: A | e : | |
| Worklists | := | | | | | | | |
| Mini worklists | := | | | |
Figure 4: Syntax for the algorithmic system
derivation (8), where we suppose that the worklist includes a type variable introduced along with the scope delimiter .
The scope delimiter and its introduction mechanism enable us to insert before .
B Algorithmic Typing
This section proposes the typing algorithm for and shows the metatheorems about it.
B.1 Algorithmic Type System
Here, we explain the updated syntax for the worklist approach and our typing algorithm for .
B.1.1 Syntax
We show the syntax for our typing algorithm in Figure 4. We omit the syntax of expressions, because they are the same as those shown in Figure 1.
We add an existential variable to types and boxy types, and a polymorphic existential variable to boxy types. Note that we allow only a polymorphic type variable to be in a box.
Work items, ranged over by , consist of two kinds of subtyping work items and , and a typing work item . These two subtyping work items and correspond to and , respectively. A typing work item corresponds to . Our typing algorithm removes these work items from a given worklist and processes them.
Worklists, ranged over by , consist of the empty worklist , the type variable binding , the existential variable binding , the scope delimiter binding , and the work item binding . The work item binding intuitively means that a typing algorithm tackles the work item under the worklist , as explained in Appendix A. For example, our typing algorithm solves both and to unit for the worklist .
Figure 5: Binding removal rules
Mini worklists, ranged over by , are worklists without type variable declarations. We only use a mini worklist to specify the rightmost scope delimiter in a worklist by writing .
B.1.2 Algorithmic Typing
Our algorithmic typing is defined as the reduction of worklists. Algorithmic typing rules have the form of . We write to denote multiple reduction steps, i.e., is defined as the reflexive and transitive closure of . Using the multiple-step reduction, represents a successful algorithmic typing. Note that every newly introduced variable is supposed to be fresh.
We break down our algorithmic typing rules into several parts and explain each.
Binding removal We show our binding removal rules in Figure 5. These rules drop variable declarations that are no longer used, as they are out of scope for the remaining work items in .
Algorithmic subtyping We show our algorithmic subtyping rules in Figure 6. Almost all of these subtyping rules are similar to the declarative counterparts. For example, the rule ASL_FUN, which decomposes the two given function (boxy) types and adds two subtyping work items to the given worklist, corresponds to SL_FUN. Note that our typing algorithm introduces the scope delimiter in ASL_ R and ASR_ R as explained in Appendix A.2.2.
Our typing algorithm solves a polymorphic existential variable in the box to a type using the rule ASL_BOX, when it encounters the work item . This rule corresponds to the rule SL_BOX, but has the side condition , meaning that the free type and existential variables of the type are bound in . Using this condition ensures that the polymorphic existential variable is solved to the well-formed type under its scope . We use the condition instead of the well-formedness of the type under to simplify an implementation of our typing algorithm. Because checking the well-formedness of under demands the well-formedness of , checking the condition is easier than checking the well-formedness of under . The rule ASR_BOX is similar.
The rule ASL_∀L differs from the declarative rule SL_∀L in two respects. The first point is that it has the side condition not∨(B□), meaning that the boxy type B□ does not take the form of ∀a.A. This condition enables our typing algorithm to determine the rule to use uniquely. For example, given the
Figure 6: Algorithmic subtyping rules
following worklist, our typing algorithm always uses the rule ASL_VR.
This approach is similar to the work by Zhao et al. [24]. We may impose similar conditions on other rules for the same reason. The second point is that the rule ASL_VL introduces the existential variable and uses it to instantiate a quantified type variable. The introduced existential variable will be solved to the monotype that is well-formed under the worklist . Because the mini worklist has no type nor existential variable binding, and no monotype has polymorphic existential variables, the monotype to which is solved is well-formed under the worklist if it is well-formed under the worklist . This implication keeps the correspondence between our typing algorithm and the declarative type system of .
We show an example corresponding to the declarative judgment
The first step introduces the existential variable using ASL_VL. The second step decomposes the function types using ASL_FUN. After these steps, both polymorphic existential variables and will be solved to . As the final result,
Figure 7: Algorithmic subtyping rules solving existential variables
we reach the empty worklist, indicating that this typing process has successfully ended.
Solving existential variables We show the algorithmic subtyping rules that solve existential variables in Figure 7. We omit the rules for because they are similar to the rules for .
The first six rules instantiate the existential variable with the type on the opposite side. The occurrence order of the existential variable in the worklist is crucial in these rules.
The rules ASL_EXFUN1 and ASL_EXFUN2 “decompose” the given existential variable into and for the argument and return type, respectively. We use the side conditions and for the occurs check as usual.
We show an example corresponding to the declarative judgment unit .
The first two steps are similar to the aforementioned example. The third step solves the existential variable to unit. After that, the polymorphic existential variable is solved to unit as a result.
Algorithmic typing We show our algorithmic typing rules in Figure 8. Many rules straightforwardly correspond to the declarative rules. We mainly explain the difference between them.
The side condition not in AT_UNIT and AT_VAR helps determine the rule to use uniquely.
Γ ⊩ () : A □ ⇝ Γ ⊩ unit <:□ A □ if not∀ (A □) (AT_Unit) Γ ⊩ x : A □ ⇝ Γ ⊩ A <:□ A □ if x : A ∈ Γ and not∀ (A □) (AT_Var) Γ ⊩ e : ∀a.A ⇝ Γ, a, ▷{} ⊩ e : A (AT_∀) Γ1, α, Γ2 ⊩ λx .e : α ⇝ Γ1, α1, α2, [α1 → α2/α](Γ2, x : α1 ⊩ e : α2) (AT_λEx) Γ1, ▷{β⃗ 1 , α, β⃗ 2}, Γ2 ⊩ λx .e : α ⇝ Γ1, α, ▷{β⃗ 1 , β, β⃗ 2}, [α → β/α](Γ2, x : α ⊩ e : β ) (AT_λBox) Γ ⊩ λx .e : A → B □ ⇝ Γ, x : A ⊩ e : B □ (AT_λFun1) Γ, ▷{α⃗ }, ∆ ⊩ λx .e : A □ → B □ ⇝ Γ, α, ▷{α⃗ }, ∆ ⊩ A □ □<: α, x : α ⊩ e : B □ (AT_λFun2) if hasBox (A □) Γ1, α, Γ2 ⊩ λx : A.e : α ⇝ Γ1, α1, α2, [α1 → α2/α](Γ2 ⊩ α1 □<: A, x : A ⊩ e : α2) (AT_λ:Ex) Γ1, ▷{β⃗ 1 , α, β⃗ 2}, Γ2 ⊩ λx : A.e : α ⇝ Γ1, ▷{β⃗ 1 , β, β⃗ 2}, [A → β/α](Γ2, x : A ⊩ e : β ) (AT_λ:Box) if FTV(A) ⊆ dom(Γ1) Γ ⊩ λx : A.e : A □ → B □ ⇝ Γ ⊩ A □ □<: A, x : A ⊩ e : B □ (AT_λ:Fun) Γ, ▷{α⃗ }, ∆ ⊩ e1 ↬ e2 : A □ ⇝ Γ, ▷{α⃗ , α}, ∆ ⊩ e2 : α ⊩ e1 : α → A □ (AT_AppR) if not∀ (A □) Γ, ▷{α⃗ }, ∆ ⊩ e1 ↫ e2 : A □ ⇝ Γ, ▷{α⃗ , α}, ∆ ⊩ e1 : α → A □ ⊩ e2 : α (AT_AppL) if not∀ (A □) Figure 8: Algorithmic typing rules The rule AT_∀ additionally introduces the scope delimiter ▷{} after the type variable a in the given worklist, as explained in Appendix A.2.2. The rules AT_λEx, AT_λBox, AT_λFun1, and AT_λFun2 are for lambda abstractions. AT_λEx decomposes the given existential variable α into α1 and α2 for the argument and return type, respectively, similarly to ASL_ExFun1 and ASL_ExFun2. AT_λBox corresponds to the declarative rule T_λBox. Since T_λBox guesses the argument type τ , AT_λBox introduces the existential variable α. This α must be introduced just after the worklist Γ1 because the given polymorphic existential variable α must be solved to a type wellformed under this worklist. AT_λFun1 is very similar to the declarative rule T_λFun1. AT_λFun2 has two notable points. One is that it introduces the existential variable α, similarly to ASL_∀L or ASR_∀L. The other is that the subtyping work item A□ □<: α occurs just before the binding x : α. This occurrence corresponds to the premise Ψ ⊢ A□ □<: τ in the declarative rule T_λFun2. The rules AT_λ:Ex, AT_λ:Box, and AT_λ:Fun are for lambda abstractions with type annotations. AT_λ:Ex decomposes the given existential variable 30
into and , similarly to AT_λEX. It introduces the subtyping work item just before the binding , similarly to AT_λFUN2. AT_λ:BOX has the side condition FTV() dom() because the given polymorphic existential variable must be solved to a well-formed type under . AT_λ:FUN introduces the subtyping work item just before , similarly to AT_λFUN2.
The rule AT_APPR introduces the polymorphic existential variable in the rightmost scope delimiter. Using the mini worklist keeps the correspondence between the polymorphic existential variable and the type in the declarative typing rule T_APPR. The rule AT_APPL is similar.
We show two examples to illustrate how our typing algorithm works. The first example corresponds to the declarative judgment .
The first step introduces the polymorphic existential variable using AT_APPR. After the second reduction by AT_VAR, this typing process proceeds similarly to the aforementioned example of algorithmic subtyping. The existential variable is introduced via this subtyping process; the unit expression is checked against it, and finally it is solved to unit. The second example corresponds to the declarative judgment .
The first step introduces the polymorphic existential variable using AT_APPL. The two steps using AT_UNIT and ASL_BOX solve to unit, and must have unit as its argument type. After using AT_VAR, this typing process proceeds similarly to the aforementioned example of algorithmic subtyping.
B.2 Metatheory
We show the metatheory of our typing algorithm. Appendix B.2.2 shows that our typing algorithm is sound with respect to the type system of . However, the algorithm is not complete with respect to the type system of . We show a counterexample to the completeness of our typing algorithm in Appendix B.2.3. However, our typing algorithm is expressive enough to subsume both the DK and the XO systems, as shown in Appendix B.2.4.
Declarative worklists
Figure 9: Declarative worklist and its reduction
Figure 10: Worklist instantiation
B.2.1 Preliminaries
We use declarative worklists and worklist instantiation to relate our typing algorithm and the type system of , as Zhao et al. [24] do. Declarative worklists and their reduction can be viewed as the intermediate system between our typing algorithm and the type system of . Every declarative typing rule of the type system of corresponds to the reduction of its declarative worklist counterpart. An algorithmic work item can be instantiated into a declarative worklist by appropriately instantiated the (polymorphic) existential variables in it.
A declarative worklist and its reduction are defined in Figure 9. A declarative worklist is a worklist that does not contain variables or scope delimiters. The subtyping/typing work item on top of the declarative worklist is removed only if it holds under the typing context . The translation just removes work items in the worklist , and is defined as follows.
Worklist instantiation rules are defined in Figure 10. The rule INST_REFL does nothing because a declarative worklist has no (polymorphic) existential variable. The rule INST_ instantiated the existential variable with the monotype well-formed under the typing context . The rule INST_ just removes the scope delimiter . The rule INST_ instantiated the polymorphic existential variable with the type well-formed under the typing context .
B.2.2 Soundness
Our typing algorithm is sound with respect to the type system of . We denote the well-formedness of by . We recall the soundness theorem and its corollary stated in Section 4.2.
Theorem 4.1 (Soundness w.r.t. the Declarative System of ). If and , then there exists some such that and .
Corollary B.1 (Soundness for Each Work Item). 1. If and , then there exist some , and such that and .
-
If and , then there exist some , such that and .
-
If and , then there exist some , and such that and .
B.2.3 A Counterexample to Completeness w.r.t. the Declarative System
One may expect that our typing algorithm is complete with respect to the declarative type system of .
If and and , then .
However, this statement does not hold. A counterexample is:
Since we have
we must have for completeness. However, the reduction from gets stuck as follows.
\begin{array}{r l}{\Gamma}&{\rightsquigarrow\ \vdash\{\alpha,\beta\},a,\vdash\{\}\Vdash(\boxed{\alpha}\to\boxed{\beta})\to\mathrm{u n i t}\Box<:(\forall b.b\to b)\to\mathrm{u n i t}}\\ &{\rightsquigarrow\ \vdash\{\alpha,\beta\},a,\vdash\{\}\Vdash\mathrm{u n i t}\Box<:\mathrm{u n i t}\Vdash\forall b.b\to b<:\Box\boxed{\alpha}\to\boxed{\beta}}\\ &{\rightsquigarrow\ \vdash\{\alpha,\beta\},a,\gamma,\vdash\{\}\Vdash\mathrm{u n i t}\Box<:\mathrm{u n i t}\Vdash\gamma\to\gamma<:\Box\boxed{\alpha}\to\boxed{\beta}}\\ &{\rightsquigarrow\ \vdash\{\alpha,\beta\},a,\gamma,\vdash\{\}\Vdash\mathrm{u n i t}\Box<:\mathrm{u n i t}\Vdash\boxed{\beta}\Box<:\gamma\Vdash\gamma<:\Box\boxed{\alpha}}\quad\not\vdash}\end{array}We cannot use the rule ASL_BOX because the existential variable occurs after the polymorphic existential variables and in the worklist. This problem does not arise in existing approaches similar to boxy types: Odersky et al. [10] do not allow for the subtyping , and Vytiniotis et al. [16] do not have the subtyping corresponding to our judgment .
B.2.4 Completeness with respect to the DK and XO systems
Our typing algorithm is complete with respect to both the DK and XO systems, while the problem presented in Appendix B.2.3 hinders the completeness with respect to the type system of . To prove this completeness, we show that, under a restriction that excludes the aforementioned problem, our typing algorithm is complete with respect to the type system of . Two judgments, and , represent this restriction. The former judgment excludes the problem discussed in Appendix B.2.3 and rejects invalid inputs such as . Because our typing algorithm introduces an existential variable just before a scope delimiter, we need at least one scope delimiter before any work item. The latter judgment ensures that any polymorphic existential variable occurs exactly once in a box and that non-boxed occurrences are always before the boxed occurrence in . See Appendix E for the full definitions of these judgments.
Lemma B.2. If and and and , then .
We show that the restriction posed on the input of our typing algorithm in Theorem 4.4 is not so strict as to reject the well-typed program in the DK system or the XO system.
Corollary B.3 (Completeness w.r.t. the DK and XO systems).
• If , then .
• If , then .
• If , then .
This corollary indicates that our typing algorithm successfully types the well-typed program under the DK or the XO system by properly inserting the polymorphic existential variable.
B.2.5 Decidability
Finally, our typing algorithm is decidable.
Theorem 4.6. If and , then or there exists some non-empty such that and .
The proof strategy follows that of the decidability shown by Zhao et al. [24].
C Application Guide Insertion
This section presents a strategy to decide whether to use the function- or argument-first bidirectional typing. In , the application guides and lead a typing process to apply typing rules T_APPR and T_APPL, respectively.
While writing these guides directly every time a function is applied is cumbersome for programmers, this design aligns with our intention that a language designer define their own way to insert application guides into their surface language. We show a translation to help understand this intention. Our prototype implementation includes this translation.
Our translation aims to conservatively estimate the degree of guessing required to synthesize the type of the given expression, because we prefer to reduce guessing by using known types. Guessing types in type synthesis arises mainly from a lambda abstraction and a function application. For example, type synthesis for includes type guessing. In this case, changing the function-first guide to the argument-first guide removes type guessing. Consider the function application as another example, supposing that has the type . Type synthesis for guesses a monotype to instantiate and propagates the guessed type to the argument (). On the other hand, type synthesis for uses the type unit for such instantiation. This example shows that properly selecting application guides reduces the number of cases in which a typing process uses guessed types. Therefore, a translation of a surface language to needs to consider the degree of guessing required to type the given expression.
We introduce guess values and marks, as shown in Figure 11, to estimate how much guessing is required for typing expressions. A guess value consists of ?, which means that guessing a type may be required, and !, which means that type information is fully known. We assign it to each expression to clarify our estimation result. A mark consists of ! and a function-like form . The guess value in indicates whether the argument type is fully known. The pair is for the body of the lambda abstraction. The guess value indicates whether the body type is fully known or may not be.
We show our marking system in Figure 11. Our marking judgment takes the form , which means that the given expression has the mark and the guess value , and that inserting application guides into results in . The rules M_UNIT and M_VAR assign to the unit value () and the variable , respectively, since we fully know the type information for them if they are well-typed. The rule M_ABS uses ? for the argument because we must guess the argument type. On the other hand, the rule M_AABS uses ! for the argument because we know the argument type from the type annotation. Both rules M_ABS and M_AABS use for the body of the lambda abstraction, similarly to an effect system. The other rules are for function applications. Our marking system prioritizes the argument-first style if we fully know the type of the argument. This decision comes from the fact that we need to instantiate the polymorphic function types, such as , using guessed types with the function-first style. Therefore, the rules M_MAPP1 and M_MAPP3 insert the argument-first guide . In other cases, if we fully know the function type information without guessing, the rules M_MAPP2 and M_MAPP5 insert the function-first guide . Note that our marking system uses M_MAPP5 even when we fully know the argument type, because only expressions of the form have ! , and because we prioritize the type annotation over the
Guess Value ::= ? | ! Mark m ::= ! |
Figure 11: Marking System
synthesized type. The insertion of the function-first guide in the rule M_MAPP4 is arbitrary. This choice depends heavily on the language designer.
We show how our marking system works using the following examples from Section 2.1.
Our marking system assigns the mark and guess value to the function .f. Therefore, it chooses the function-first guide via the rule M_MAPP5. On the other hand, our marking system assigns the mark and guess value to the argument . For simplicity, we assign the guess value ! to the pair without introducing a mark for pairs, since both elements have . Our marking system uses M_MAPP3 to insert the argument-first guide. Through our marking system, we get the following expressions that are well-typed under the type system of .
•
Our marking system also properly inserts application guides to accept the program shown in Section 2.2, which is ill-typed under both the DK and XO systems, resulting in . We leave an empirical evaluation of how our marking system works in practice as future work.
D Extensions
This section discusses possible extensions for .
D.1 Let Polymorphism
Let polymorphism is a practically important extension. It helps achieve backward compatibility with the Hindley–Milner type system. Furthermore, supporting let polymorphism enables to subsume the original XO system.
A challenge in extending with let polymorphism is the generalization of types. Our formulation manages the scope of type variables. This formulation does not fit with the generalization of types in the following traditional typing rule for let expressions.
The generalization Gen quantifies every free type variable in that does not occur in . However, the type , which has a type variable that does not occur in , is not well-formed under , because we manage type variables in a typing context.
To balance the strict management of type variables and the generalization of types, we consider the following declarative typing rule for let expressions.
The metavariable denotes a context containing only type variables. This rule allows us to use fresh type variables when synthesizing the type of . For example, we can have the following derivation using this rule.
This idea of using another context only for let-bound expressions is similar to incrementing a rank [13] or level [6].
D.2 Explicit Type Application
Supporting explicit type application helps realize an impredicative type instantiation, improving typeability. Furthermore, Xie and Oliveira [18] show that argument-first bidirectional typing with explicit type applications encodes a type synonym, which is a new name for an existing type.
We have two major concerns about extending with explicit type applications. First, the XO system with explicit type applications extends an application context, enabling it to stack not only types of arguments but also explicitly applied type arguments. Secondly, combining polymorphic subtyping of Odersky et al. [9], on which the DK, XO, and our type systems are based, with explicit type applications can break important properties [22], as we discuss below.
Xie and Oliveira [18] develop an argument-first bidirectional type system with explicit type application by using the known information about type arguments. Their typing rule for type applications is as follows.
This rule adds the applied type into the application context . Using the information about what types are supplied improves the typeability. For example, the expression is well-typed under the XO system with explicit type applications, while it is ill-typed under the traditional type system for System F. When typing the type abstraction , the XO system knows that int is supplied; consequently, typing succeeds.
This extended formalization inspires us to support explicit type applications in . We add the new boxy type , representing a polymorphic type that yields when supplied with . The typing rules for type abstractions and type applications are as follows.
The former rule (9) substitutes the known type argument into the type variable in . The latter rule (10) uses the known type argument for typing the expression , similarly to how the XO system adds a type argument to an application context. These rules enable the type system of to support the aforementioned expression .
However, straightforwardly combining polymorphic subtyping of Odersky et al. [9] and explicit type applications can break important properties, as Zhao and Oliveira [22] show. An important property is the following lemma.
Lemma D.1 (Subsumption). If and , then .
This lemma ensures that a programmer can annotate a program with a super-type of its type without altering the typing result. An explicit type application can break the subsumption lemma because the result of a type application depends on the order of quantified type variables, while polymorphic subtyping does not. For example, the following type checking and subtyping judgments hold.
However, the type checking judgment
does not hold. In the latter type checking judgment, since we know that the variable has the type , the type application result has the type . However, the expression takes the unit as its second argument, resulting in a type error. We need to address the violation of the subsumption lemma to support explicit type applications, because our subtyping is based on that of Odersky et al. [9].
We have two major directions to support explicit type application while preserving important properties. The first direction is to update subtyping rules for polymorphic types, following Zhao and Oliveira [22]. They forbid changing the order of quantified type variables to add explicit type application to the DK system without violating the subsumption lemma. The subtyping judgment (11) does not hold under this restriction. The second direction is to forbid subtyping over an argument type. The subtyping judgment (11) also does not hold under this restriction. This approach is used in, for example, the XO system with explicit type applications [18] and Quick Look [14].
E Omitted Definitions
E.1 Declarative System
Well-formedness for the declarative system
E.2 Algorithmic System
Subtyping Rules Solving Existential Variables for :
Well-formedness
Limited Well-formedness
Polymorphic existential variable counter
E.3 Declarative Worklist
Syntax
Declarative worklists
Reduction Rules
Worklist Instantiation
\begin{array}{r l}{\xrightarrow[\Omega\stackrel{\mathrm{i n s t}}{\longrightarrow}\Omega]\mathrm{I N S T\_{R} E F L}}&{\frac{|\Omega_{1}|\vdash\tau\quad\Omega_{1},[\tau/\alpha]\Gamma_{2}\stackrel{\mathrm{i n s t}}{\longrightarrow}\Omega}{\Omega_{1},\alpha,\Gamma_{2}\stackrel{\mathrm{i n s t}}{\longrightarrow}\Omega}\mathrm{I N S T\_{\alpha}}}\end{array}E.4 System [3]
Syntax
Typing Rules
Coercion Typing Rules
Translation Rules in Soundness w.r.t. System
E.5 The DK System [5]
Subtyping Rules
Typing Rules
Translation from the DK system to
E.6 The XO System [18]
Subtyping Rules
Typing
Translation from the XO system to