<?xml-model href='http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng' schematypens='http://relaxng.org/ns/structure/1.0'?><TEI xmlns="http://www.tei-c.org/ns/1.0">
	<teiHeader>
		<fileDesc>
			<titleStmt><title level='a'>FlexType: A Plug-and-Play Framework for Type Inference Models</title></titleStmt>
			<publicationStmt>
				<publisher></publisher>
				<date>10/10/2022</date>
			</publicationStmt>
			<sourceDesc>
				<bibl> 
					<idno type="par_id">10464536</idno>
					<idno type="doi">10.1145/3551349.3559527</idno>
					<title level='j'>Automated Software Engineering Conference</title>
<idno></idno>
<biblScope unit="volume"></biblScope>
<biblScope unit="issue"></biblScope>					

					<author>Sivani Voruganti</author><author>Kevin Jesse</author><author>Premkumar Devanbu</author>
				</bibl>
			</sourceDesc>
		</fileDesc>
		<profileDesc>
			<abstract><ab><![CDATA[Types in TypeScript play an important role in the correct usage of variables and APIs. Type errors such as variable or function misuse can be avoided with explicit type annotations. In this work, we introduce FlexType, an IDE extension that can be used on both JavaScript and TypeScript to infer types in an interactive or automatic fashion. We perform experiments with FlexType in JavaScript to determine how many types FlexType could resolve if it were to be used to migrate top JavaScript projects to TypeScript. FlexType is able to annotate 56.69% of all types with high precision and confidence including native and imported types from modules. In addition to the automatic inference, we believe the interactive Visual Studio Code extension is inherently useful in both TypeScript and JavaScript especially when resolving types is taxing for the developer.The source code is available at GitHub 1 and a video demonstration at https://youtu.be/4dPV05BWA8A.
CCS CONCEPTS• Computing methodologies → Machine learning; • Theory of computation → Type structures; • Software and its engineering → Integrated and visual development environments; Source code generation.]]></ab></abstract>
		</profileDesc>
	</teiHeader>
	<text><body xmlns="http://www.tei-c.org/ns/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink">
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="1">INTRODUCTION</head><p>Type inference for dynamically typed programming languages, like Python and TypeScript, can help developers improve code quality. By foregoing type annotations, developers coding in dynamically typed languages gain additional flexibility. This flexibility helps developers and designers avoid committing to particular design decisions regarding types. On the other hand, static typing helps detect bugs before execution, and supports both compilation performance and program understanding <ref type="bibr">[7,</ref><ref type="bibr">30]</ref>. Developers have viewed the benefits of static typing as the most desired feature in languages like Python <ref type="bibr">[19]</ref>. Leading technology companies have developed their own type systems for various languages; Microsoft's Type-Script, Facebook's Flow, and Google's Closure with TypeScript and Flow being syntactic supersets of JavaScript and Python respectively. TypeScript has exploded in popularity over the last few years jumping to the fourth most used language according to GitHub's Octoverse <ref type="bibr">[12]</ref> in 2020 and 2021. While JavaScript remains the top language, it is a reasonable expectation for TypeScript to further increase in popularity since it can be applied to any JavaScript project with few modifications. TypeScript inherits JavaScript's long standing popularity and widespread adoption so tools built for TypeScript often benefit the JavaScript community as well.</p><p>Unlike JavaScript, TypeScript calls for a set of types (either explicitly annotated or inferred) that type the program consistently. Defining a set of types and annotating with said types is not a trivial task for developers; this is called the type annotation tax. Type declaration files (.d.ts) and repositories like DefinitelyTyped<ref type="foot">foot_0</ref> help alleviate the typing cost by defining general, high quality types which are included automatically by the compiler. The convenience of importing existing types does not supplant the action of annotating the code elements. Moreover, the compiler cannot synthesize types where static constraints or dependencies are not satisfied in the type dependency graph. Frequently, existing tools like TypeScript's type checker are unable to infer types more specific than the generic "any" because it fails to find type hints from static type constraints or package dependencies. Type ambiguity often exists in dynamic typing, because the compiler has too few type constraints to resolve <ref type="bibr">[8]</ref>. Type ambiguity is more prevalent in languages like JavaScript, than in explicitly typed languages like TypeScript, where developers have no explicit annotations and must rely on interpretation, documentation, and surrounding expressions to determine the likely types. Thus, developers could benefit from tools that recommend likely types and insert types with little to no effort.</p><p>For these reasons, the type inference task has been well studied, in the software engineering research community <ref type="bibr">[3,</ref><ref type="bibr">14,</ref><ref type="bibr">18,</ref><ref type="bibr">26,</ref><ref type="bibr">27,</ref><ref type="bibr">29,</ref><ref type="bibr">31,</ref><ref type="bibr">33,</ref><ref type="bibr">37]</ref>. Most of these works in type inference are a result of the abundance of code and the success of deep learning for software engineering. The abundance of patterns in code warrants probabilistic models to exploit the regularity of code; in type inference it is the regularity of how types are used. The newest advances in machine learning <ref type="bibr">[10,</ref><ref type="bibr">[22]</ref><ref type="bibr">[23]</ref><ref type="bibr">[24]</ref><ref type="bibr">32]</ref> often come with downstream improvements to software engineering models <ref type="bibr">[1,</ref><ref type="bibr">4,</ref><ref type="bibr">11,</ref><ref type="bibr">13,</ref><ref type="bibr">21,</ref><ref type="bibr">36]</ref>, but in practice, these improvements have not been tangible to developers as most published models stop short of publishing IDE tools. We argue that the gap between model development and model deployment in integrated development environments is worthwhile, but challenging.</p><p>To address this gap, in this paper, we present our tool FlexType, a plug-and-play framework for any new state-of-the-art type inference model in a VSCode environment for TypeScript and JavaScript. JetBrains found that 60% of JavaScript and TypeScript developers use Visual Studio or Visual Studio Code as their preferred IDE <ref type="bibr">[20]</ref>. The core idea behind FlexType is the integration of such models in an interactive and automatic way that complements existing static type checking capabilities, even in dynamically typed languages like JavaScript. To evaluate our idea, we have implemented an extension for Visual Studio Code, a popular IDE from Microsoft, using one of the of several type inference models from ManyTypes4TypeScript <ref type="bibr">[17]</ref>. Our contributions are as follows,</p><p>&#8226; An interactive, model-agnostic framework for type inference in Visual Studio Code. &#8226; A tool that uses the AST to correctly insert type elements from sequence-based or graph-based models. &#8226; A use-case experiment evaluating the effectiveness of Flex-Type in migrating JavaScript projects to TypeScript.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="2">RELATED WORK</head><p>The landscape of type completion tools ranges significantly in capability from static checking <ref type="bibr">[6]</ref>, neural type inference <ref type="bibr">[3,</ref><ref type="bibr">14,</ref><ref type="bibr">17,</ref><ref type="bibr">18,</ref><ref type="bibr">26,</ref><ref type="bibr">31,</ref><ref type="bibr">37]</ref>, and code completion-like type generation <ref type="bibr">[1,</ref><ref type="bibr">5,</ref><ref type="bibr">9,</ref><ref type="bibr">35,</ref><ref type="bibr">36,</ref><ref type="bibr">38]</ref>. Static type checking from the TypeScript compiler occurs when the TypeScript compiler transpiles TypeScript to JavaScript. The TypeScript type checker can be accessed through a shipped version of TypeScript installed with the IDE. The IntelliSense feature in Visual Studio and Visual Studio Code can provide underlying types by relying on the internal type checker for TypeScript. The type checker is capable of performing type inference from the variable's value as long as the type constraints exist. For example, the variable i in var i = 0 can be inferred as a number from the value in the assignment expression. Any high-level interpretation of i, such as the use of i as an iterator, cannot be inferred by the type checker without a higher order type indicating such functionality. In JavaScript, the IntelliSense method signature information shows the uninformative "any" type for the method parameters because JavaScript is dynamic and does not enforce types [25]; this is not particularly helpful for a developer wishing to pass the correct type to the function.</p><p>Neural type inference and code completion aim to model attributes of source code probabilistically by exploiting the regularity of software <ref type="bibr">[2,</ref><ref type="bibr">16]</ref> and an abundance of existing typed code on open source repositories. In contrast to static type inference, neural type models rely on large code corpora and can suggest richer, more contextualized type annotations overcoming the lack of existing type constraints realized when the compiler predicts "any"; in our experiments this occurs 63.46% of all typeable identifiers. Our goal here is to build a flexible way to integrate neural type inference models into an IDE, to make these models more accessible. Some published neural type inference models Typilus <ref type="bibr">[3]</ref>, Hi-Typer <ref type="bibr">[29]</ref>, and LambdaNet <ref type="bibr">[37]</ref> expose inference methods where the model can be called on a set of source code files and the appropriate annotations are logged in an output file; this is impractical for the typical developer and such models often require computing not found on a laptop. One model cites the need of a "high-end Nvidia GPU with at least 8GB of RAM" and "a CPU with 16 threads or higher" <ref type="bibr">[26]</ref>. The requirements for running massive code generation models like Codex <ref type="bibr">[9]</ref> (Copilot), Google's 137B parameter model <ref type="bibr">[5]</ref>, and PolyCoder <ref type="bibr">[38]</ref> is further beyond any consumer PC, thus access to such models must be by remote API. Remote API access is viable for many developers, but communicating large token windows of proprietary software introduces valid security and privacy concerns <ref type="bibr">[9,</ref><ref type="bibr">28,</ref><ref type="bibr">34]</ref>; a local type inference model is ideal. In contrast, FlexType uses local models that can run efficiently on a laptop CPU. The user can simply hover over the variable, parameter, function or method to get a drop down list of types including the compiler inferred type, if any, and see the type properly inserted. In the following sections, we present our approach, implementation, and evaluation of FlexType.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="3">APPROACH</head><p>Figure <ref type="figure">1</ref> shows how FlexType interactively works with the developer to recommend types. When the developer toggles the VSCode extension, FlexType activates the mouse hover action which pops up a list of types. By default, VSCode provides existing prototype information with type annotations that are written in the code such as const sequelize: any in Figure <ref type="figure">2</ref>. FlexType presents an informative list to the developer integrating compiler inferred types (often useful for native types and user-defined types) with the neural type suggestions. The neural type suggestions can be quite useful to the developer, because the type recommendations derive from large corpora training, and elucidate types that local constraints often cannot resolve.</p><p>Figure <ref type="figure">2</ref> illustrates a key situation where the type assistant shines. With the current type constraints, the compiler cannot resolve what type sequelize is. The term "sequelize" in itself is a natural language hint, one that hints at it connecting to a SQL database often pronounced "see-kwl". While these natural language hints are not always readily available, the syntax and usage of function calls are, which deep learning models capture. The resulting list of contextually derived types, as seen in Figure <ref type="figure">2</ref>, is helpful in understanding the likely functionality of such APIs. The developer has the liberty to choose which type annotations are useful with the model's perceived probabilities. This feature is available for TypeScript and JavaScript files as TypeScript data transpiles into JavaScript code and thus captures otherwise implicit type information in JavaScript. JavaScript syntax does not permit types, so types are not "insertable" when interacting with JavaScript. We believe FlexType can help both TypeScript and JavaScript developers, as type information improves code readability, comprehension, and proper usage of code elements. In the following text, we discuss the details of the approach within the framework's pipeline.</p><p>FlexType starts with an incremental compilation 3 of the program, targeting just the current editor file for AST parsing. Then the framework digests the developers current word token index 4  and finds the character offset of the token which aligns best with the pos (position) field in the parsed AST. FlexType uses an AST 3 An incremental compilation saves compute resources when previous changes are minimal across a set of files and project dependencies. 4 The term position is usually synonymous for token indexes in sequences across NLP literature, but is confusing in the context of the AST, thus we only use it when referring to the AST. linter to traverse the AST in preorder, filtering only valid typeable locations. For each leaf node (indicating a code token) the corresponding code token is appended to a list of tokens which will serve as the tokenized input to the machine learning model; tokenizing from the AST has the benefit of filtering out non-code related tokens such as comment blocks. In the traversal, the framework keeps a cache of the parent type because the parent node is where the type annotation is located, specifically, in a variable, parameter, function, or method declaration syntax node. Finally, when the identifier syntax node corresponding to the identifier of interest is visited, which is a child to the typed parent, this token is aligned to the cached AST type and to the current token index. The cached type node is fed to the type checker which returns the result of any the static type constraints, if any, for that identifier. Finally, the token sequence, inferred type, and token index is returned. If the developer's cursor location is not at a typeable variable, parameter, function, or method declaration, the AST linter is immediately returned with null values.</p><p>The token sequence and token index is passed through a localhost port to a WSGI Flask<ref type="foot">foot_1</ref> server started as a background task when the extension is enabled. This server encapsulates the neural inference model. The token sequence is subtokenized using the neural model's tokenizer and the new subtoken index is calculated. The framework then determines an optimal context window around the identifier of interest; this is necessary for long files as a model's sequence-based input is limited. The type inference model in our demo, is a Huggingface type inference model based on the popular GraphCodeBert <ref type="bibr">[13]</ref>. Here, we emphasize the "plug-and-play" dynamic where neural type inference models, such as our from_pretrained('microsoft/graphcodebert-base'), is amenable with alternative choices. With respect to future proofing our design, our GraphCodeBert <ref type="bibr">[13]</ref> type inference model improves upon CodeBert, namely, where data flow awareness is principle to performance. For type inference, GraphCodeBert increases performance, likely due to the role data flow plays in types. Finally, these neural suggestions are serialized and returned to the VSCode portion of the framework where the types are displayed to the developer.</p><p>For a TypeScript (.ts) file, the framework presents the recommended types with keystrokes to embed the types as formal type annotations. For a JavaScript (.js) file, the framework shows the developer the type recommendations only. If the developer chooses a type, the framework performs a postorder AST traversal to return to the identifier's parent node, generate a type node from the type, and assign the type node to the parent's type field. The traversal is immediately returned, returning the root node of the sourcefile which is then used to synthesize the file with the type annotation in the correct location; this insertion technique is guaranteed by the compiler's printer to work for any valid type node. Since the type node's synthesis is independent of the actual type value, FlexType can always guarantee correct type placement. Finally, the VSCode editor is updated with the new type embedded sequence. In the next section, we discuss the high level implementation design. FlexType recall uses only the static type checker (TC) and FlexType using both the type checker and neural type inference model (TC+NN). </p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head>Compiler</head></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="4">IMPLEMENTATION</head><p>We implemented our approach as an extension to Microsoft's Visual Studio Code, Figure <ref type="figure">2</ref>, which is the most adopted TypeScript/-JavaScript IDE according to a JetBrains survey <ref type="bibr">[20]</ref>. We implement the client in TypeScript where VSCode can pass actions such as hover, click and drag, and keyboard strokes to the client. Upon a hover over a type permissive location (variable, parameter, function, method), FlexType performs static and neural type inference and recommends types. The modularity of the static type checker and the neural type model permits the interchange of a variety of models with minimal changes. While sequence-based methods (RNN, Transformer, Pretrained Language Models) are very popular, there is an increasing demand for models that capture code structure (GNN <ref type="bibr">[4]</ref>, Hybrid <ref type="bibr">[15]</ref>). In addition to the "plug-and-play" neural type architecture, FlexType re-synthesizes the snippet of code with the TypeScript Compiler API <ref type="foot">6</ref> . By altering the AST, rather than the code sequence itself, the framework is compatible with graph-based methods. Finally, for best results, we apply graph optimization and quantization to the neural type inference model, which results in blazing quick inference times under .4 seconds on a Intel 8th generation Coffee Lake and even faster on Apple M1. In the next section, we perform an experiment to simulate the impact of our tool for developers migrating from JavaScript to TypeScript and equivalently coding only in JavaScript.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="5">EVALUATION</head><p>FlexType uses both type checker and neural type inference models. To evaluate FlexType's effectiveness migrating JavaScript to Type-Script, we checkout over 150 most-starred Javascript repositories and let FlexType annotate them as best as it can. For brevity, we have only included 5 of these projects in Table <ref type="table">1</ref> with the full results available at our GitHub.</p><p>The 150 JS projects have no human annotated types, so performance must be evaluated with an oracle. The neural type model per se can serve as an oracle if it's confidence threshold is set such that precision remains very high; only if a type prediction is above this threshold can it be labeled as correct. To calibrate, we measure the precision-recall curve of GraphCodeBERT on the ManyTypes4TypeScript <ref type="bibr">[17]</ref> test set. This is a dataset of manuallyannotated Typescript projects allowing direct performance evaluation. GraphCodeBERT achieves a precision of 89.10% and recall of 53.83% across 224,415 types with a 90% confidence threshold. Thus, we can use GraphCodeBERT's confidence threshold with a precision of 89.10% as a proxy to the number of types that can be resolved. In other words, 89.10% of JavaScript types with a confidence of 90% or greater is a reasonable metric for evaluation. While this method is effective, it is important for us to calculate how much we are potentially underestimating our model's performance.</p><p>The recall of 53.83% means that 46.17% of types fall below the confidence threshold. We can calculate the precision across the 46.17% set of types to determine how many types were missed. This precision is 31.51% and so the model's recall is underestimated at most by 15% (31.51% of 46.17%).</p><p>We emphasize that this performance is for the top-1 (the model's best guess), and ignores selecting the 2 nd or 3 rd best choice in the interactive dialog seen in Figure <ref type="figure">2</ref>. In the interactive setting with 5 choices, the recall is naturally higher than in the top-1 setting. We use top-1 in our automatic evaluation of FlexType to estimate a lower bound of performance in a common use case, migrating JavaScript to TypeScript. RQ1: What is the recall of types for FlexType across the top 150 starred JavaScript projects? Across the set of 150 projects, 56.69% of types are resolved by FlexType. The recall of the compiler is 36.54% and the neural type inference model provides the additional 20.15% recall. On a per project evaluation, the mean project recall is 51.44% with the compiler providing 29.49% of the types and the neural type inference model providing an additional 21.95% recall. The per project recall distribution of each component can be seen in Figure <ref type="figure">3</ref>.</p><p>This evaluation suggests that FlexType helps annotate a good fraction of type locations (56.69%) in JavaScript; this reduces the annotation burden in JavaScript to TypeScript migration. Moreover, we argue that developers will use the tool in an interactive fashion using the drop down menu in Figure <ref type="figure">2</ref>. This should further increase the recall which represents the number of type constraints the developer could reasonably add with minimal effort.</p></div>
<div xmlns="http://www.tei-c.org/ns/1.0"><head n="6">CONCLUSION</head><p>As a development tool, FlexType can help increase the volume of type annotations. We also see an opportunity to use FlexType in an automated setting to improve type annotation coverage in existing and new projects. We hope the adoption of this framework can reduce the burden of adding type annotations in TypeScript and the reduce the misuse of variables and APIs in both TypeScript and JavaScript, thus improving software development and maintenance.</p></div><note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="2" xml:id="foot_0"><p>https://github.com/DefinitelyTyped/DefinitelyTyped</p></note>
			<note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="5" xml:id="foot_1"><p>https://flask.palletsprojects.com/en/2.1.x/</p></note>
			<note xmlns="http://www.tei-c.org/ns/1.0" place="foot" n="6" xml:id="foot_2"><p>https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API</p></note>
		</body>
		</text>
</TEI>
