百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rdl

> 编程语言
开源

Ruby 的类型、类型检查和合约

600 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Ruby 的类型、类型检查和合约

Table of Contents

  • Introduction
  • Using RDL
    • Supported versions of Ruby
    • Installing RDL
    • Loading RDL
    • Disabling RDL
    • Rails
    • Preconditions and Postconditions
    • Type Annotations
  • RDL Types
    • Nominal Types
    • Nil Type
    • Top Type (%any)
    • Dynamic Type (%dyn)
    • Union Types
    • Intersection Types
    • Optional Argument Types
    • Variable Length Argument Types
    • Named Argument Types
    • Dependent Types
    • Higher-order Types
    • Class/Singleton Method Types
    • Structural Types
    • Singleton Types
    • Self Type
    • Type Aliases
    • Generic Class Types
    • Tuple Types
    • Finite Hash Types
    • Type Casts
    • Bottom Type (%bot)
    • Non-null Type
    • Constructor Type
  • Static Type Checking
    • Types for Variables
    • Tuples, Finite Hashes, and Subtyping
    • Other Features and Limitations
    • Assumptions
  • Type-Level Computations
  • RDL Method Reference
  • Performance
  • Queries
  • Configuration
  • Bibliography
  • Copyright
  • Contributors
  • TODO List

Introduction

RDL is a lightweight system for adding types, type checking, and contracts to Ruby. In RDL, types can be used to decorate methods:

ruby
require 'rdl'
extend RDL::Annotate # add annotation methods to current scope

type '(Integer, Integer) -> String'
def m(x,y) ... end

This indicates that m returns a String if given two Integer arguments. When written as above, RDL enforces this type as a contract checked at run time: When m is called, RDL checks that m is given exactly two arguments and both are Integers, and that m returns an instance of String.

RDL can also statically type check method bodies against their signatures. For example:

ruby
file.rb:
  require 'rdl'
  extend RDL::Annotate

  type '(Integer) -> Integer', typecheck: :label
  def id(x)
    "forty-two"
  end

  RDL.do_typecheck :label
$ ruby file.rb
.../lib/rdl/typecheck.rb:158:in `error':  (RDL::Typecheck::StaticTypeError)
.../file.rb:6:3: error: got type `String' where return type `Integer' expected
.../file.rb:6:   "forty-two"
.../file.rb:6:   ^~~~~~~~~~~

Passing typecheck: sym for some other symbol statically type checks the method body when RDL.do_typecheck sym is called. Passing typecheck: :call to type statically type checks the method body whenever it is called.

Note that RDL only type checks the bodies of methods with type signatures. Methods without type signatues, or code that is not in method bodies, is not checked.

The type method can also be called with the class and method to be annotated, and it can also be invoked as RDL.type in case extend RDL::Annotate would cause namespace issues:

  type :A, :id, '(Integer) -> Integer', typecheck: :label # Add a type annotation for A#id.
  RDL.type :A, :id, '(Integer) -> Integer', typecheck: :label # Note class and method name required when calling like this

RDL tries to follow the philosophy that you get what you pay for. Methods with type annotations can be checked dynamically or statically; methods without type annotations are unaffected by RDL. See the performance discussion for more detail.

RDL supports many more complex type annotations; see below for a complete discussion and examples.

RDL types are stored in memory at run time, so it's also possible for programs to query them. RDL includes lots of contracts and types for the core and standard libraries. Since those methods are generally trustworthy, RDL doesn't actually enforce the contracts (since that would add overhead), but they are available to search, query, and use during type checking. RDL includes a small script rdl_query to look up type information from the command line. Note you might need to put the argument in quotes depending on your shell.

bash
$ rdl_query String#include?            # print type for instance method of another class
$ rdl_query Pathname.glob              # print type for singleton method of a class
$ rdl_query Array                      # print types for all methods of a class
$ rdl_query "(Integer) -> Integer"     # print all methods that take an Integer and return an Integer
$ rdl_query "(.) -> Integer"           # print all methods that take a single arg of any type
$ rdl_query "(..., Integer, ...) -> ." # print all methods that take an Integer as some argument

See below for more details of the query format. The RDL.query method performs the same function as long as the gem is loaded, so you can use this in irb.

ruby
$ irb
> require 'rdl'
 => true
> require 'types/core'
 => true

> RDL.query '...' # as above

RDL also supports more general contracts, though these can only be enforced at run time and are not statically checked. These more general contracts take the form of preconditions, describing what a method assumes about its inputs, and postconditions, describing what a method guarantees about its outputs. For example:

ruby
require 'rdl'
extend RDL::Annotate

pre { |x| x > 0 }
post { |r,x| r > 0 }
def sqrt(x)
  # return the square root of x
end

Given this program, RDL intercepts the call to sqrt and passes its argument to the pre block, which checks that the argument is positive. Then when sqrt returns, RDL passes the return value (as r) and the initial argument (as x) to the post block, which checks that the return is positive. (Let's ignore complex numbers to keep things simple...) RDL contracts are enforced at method entry and exit. For example, if we call sqrt(49), RDL first checks that 49 > 0; then it passes 49 to sqrt, which (presumably) returns 7; then RDL checks that 7 > 0; and finally it returns 7. The pre and post methods can also be called as RDL.pre and RDL.post, as long as they are also given class and method arguments, similarly to type. Note that pre- and postconditions can't be searched for using RDL.query.

Note: RDL is a research project from the Tufts University Computer Science Department and the University of Maryland, College Park Computer Science Department. If you are looking for an industrial strength Ruby type system, check out Stripe’s Sorbet system.

Using RDL

Supported versions of Ruby

RDL currently supports Ruby 2.x except 2.1.1-2.1.6. RDL may or may not work with other versions.

Installing RDL

gem install rdl should do it.

Loading RDL

Use require 'rdl' to load the RDL library. If you want to access the annotation language, add extend RDL::Annotate as appropriate. If you want to use the core and standard library type signatures that come with RDL, follow it with require 'types/core'. Currently RDL has types for the following versions of Ruby:

  • 2.x

Disabling RDL

For performance reasons you probably don't want to use RDL in production code. To disable RDL, replace require 'rdl' with require 'rdl_disable'. This will cause all invocations of RDL methods to either be no-ops or to do the minimum necessary to preserve the program's semantics (e.g., if the RDL method returns self, then so does the rdl_disable method.)

Rails

To add types to a Ruby on Rails application, add

ruby
gem 'rdl'

to your Gemfile to get the latest stable version, or

ruby
gem 'rdl', git: 'https://github.com/plum-umd/rdl'

to get the head version from github.

In development and test mode, you will now have access to rdl, types/core from RDL, and extra type annotations for Rails and some related gems. In production mode, RDL will be disabled (by loading rdl_disable).

Warning: Rails support is currently extremely limited, not well tested, and generally needs more work...please send bug reports/pull requests/etc and we will try to fix things.

Preconditions and Postconditions

The pre method takes a block and adds that block as a precondition to a method. When it's time to check the precondition, the block will be called with the method's arguments. If the block returns false or nil the precondition is considered to have failed, and RDL will raise a ContractError. Otherwise, if the block returns a true value, then the method executes as usual. The block can also raise its own error if the contract fails.

The pre method can be called in several ways:

  • pre { block } - Apply precondition to the next method to be defined
  • pre(mth) { block } - Apply precondition to method mth of the current class, where mth is a Symbol or String
  • pre(cls, mth) { block } - Apply precondition to method mth of class cls, where cls is a Class, Symbol, or String, and mth is a Symbol or String

The post method is similar, except its block is called with the return value of the method (in the first position) followed by all the method's arguments. For example, you probably noticed that for sqrt above the post block took the return value r and the method argument x.

(Note: RDL does not clone or dup the arguments at method entry. So, for example, if the method body has mutated fields stored inside those argument objects, the post block or any other check evaluated afterwards will see the mutated field values rather than the original values.)

The post method can be called in the same ways as pre.

Methods can have no contracts, pre by itself, post by itself, both, or multiple instances of either. If there are multiple contracts, RDL checks that all contracts are satisfied, in the order that the contracts were bound to the method.

Both pre and post accept an optional named argument version that takes a rubygems version requirement string or array of version requirement students. If the current Ruby version does not match the requirement, then the call to pre and post is ignored.

Type Annotations

The type method adds a type contract to a method. It supports the same calling patterns as pre and post, except rather than a block, it takes a string argument describing the type. More specifically, type can be called as:

  • type 'typ'
  • type m, 'typ'
  • type cls, mth, 'typ'

A type string generally has the form (typ1, ..., typn) -> typ indicating a method that takes n arguments of types typ1 through typn and returns type typ. Below, to illustrate the various types RDL supports, we'll use examples from the core library type annotations.

The type method can be called with wrap: false so the type information is stored but the type is not enforced. For example, due to the way RDL is implemented, the method String#=~ can't have a type or contract on it because then it won't set the correct $1 etc variables:

ruby
type :=~, '(Object) -> Integer or nil', wrap: false # Wrapping this messes up $1 etc

For consistency, pre and post can also be called with wrap: false, but this is generally not as useful.

The type method also accepts an optional version named argument.

RDL Types

Nom

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言