Support type narrowing

未关闭
#1,822 2 条评论 6 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
25/100
Issue 类型
功能
描述清晰度
需要澄清
活跃度
停滞
技术栈
ruby
领域
compilers

调研方向

首先阅读所引用的 Sorbet 和 Steep 实现,然后检查与方法签名和控制流相关的 RBS 语法及类型检查部分。当支持并测试了类型收窄的经过审查的语法和行为(包括 nil? 和 present? 等方法)后,这项工作就完成了。

由索引模型根据 Issue 内容生成。

描述

Ref: https://github.com/soutaro/steep/issues/472

Currently RBS doesn't have any syntax to narrow types in control flow.

So there's no way to achieve the following:

a = [1, nil].sample # a is `Integer | nil`
unless a.nil?
  # a is `Integer` here
  p a + 1
end

But actually, both Sorbet and Steep treat some special methods to narrow types

https://github.com/sorbet/sorbet/blob/718bc64f895abeeff88f56efbc92a3554ffaa4f2/infer/environment.cc#L536-L545

https://github.com/soutaro/steep/blob/a868762c2bd09f0954b05cdd9eab1819e14a51d3/lib/steep/interface/builder.rb#L709-L721

Ideally, I think we need to have a syntax considering Ruby gems which extend Object like ActiveSupport's present?.

I'm not very familiar with type system though, I guess the syntax would be similar with TypeScript's type predicates

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

class Object[T?]
  def nil?: () -> self is nil
end
class Object[T?]
  def present?: () -> self is T
end
主要语言
Ruby
星标
2.2k
派生
263
平均合并
1 天 20 小时
30 天内合并 PR
64

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

ruby/rbs 的其他 Issue

查看 ruby/rbs 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。