一句话:将神经网络类型预测与搜索式验证结合,为动态语言自动补全正确类型注解。
针对动态类型语言因缺少类型注解而导致的兼容性错误、IDE 支持受限与 API 难理解等问题,本文提出 TypeWriter,首次将概率类型预测与基于搜索的类型精化相结合。其预测器从部分标注的代码库中学习推断函数的返回类型与参数类型,融合代码的自然语言属性与编程语言层面信息。为验证预测类型,TypeWriter 调用渐进类型检查器,以反馈导向方式在类型组合空间中导航,搜索能够通过检查的组合。作者在 Python 上实现该技术,并在 Facebook 数百万行代码库与 1137 个流行开源项目上评估:返回类型 top-1(top-5)F1 为 0.64(0.79),参数类型为 0.57(0.80),明显优于先前类型预测模型;结合搜索验证后可完整标注随机语料中 14% 至 44% 的文件,并保证类型正确性。与静态类型推断工具相比,TypeWriter 能补充更多非平凡类型,且已在 Facebook 中向开发者推荐类型,数千个类型已被接受。
Maintaining large code bases written in dynamically typed languages, such as JavaScript or Python, can be challenging due to the absence of type annotations: simple data compatibility errors proliferate, IDE support is limited, and APIs are hard to comprehend. Recent work attempts to address those issues through either static type inference or probabilistic type prediction. Unfortunately, static type inference for dynamic languages is inherently limited, while probabilistic approaches suffer from imprecision. This paper presents TypeWriter, the first combination of probabilistic type prediction with search-based refinement of predicted types. TypeWriter’s predictor learns to infer the return and argument types for functions from partially annotated code bases by combining the natural language properties of code with programming language-level information. To validate predicted types, TypeWriter invokes a gradual type checker with different combinations of the predicted types, while navigating the space of possible type combinations in a feedback-directed manner. We implement the TypeWriter approach for Python and evaluate it on two code corpora: a multi-million line code base at Facebook and a collection of 1,137 popular open-source projects. We show that TypeWriter’s type predictor achieves an F1 score of 0.64 (0.79) in the top-1 (top-5) predictions for return types, and 0.57 (0.80) for argument types, which clearly outperforms prior type prediction models. By combining predictions with search-based validation, TypeWriter can fully annotate between 14% to 44% of the files in a randomly selected corpus, while ensuring type correctness. A comparison with a static type inference tool shows that TypeWriter adds many more non-trivial types. TypeWriter currently suggests types to developers at Facebook and several thousands of types have already been accepted with minimal changes.