Ruby 的类型、类型检查和合约
RDL is a lightweight system for adding types, type checking, and contracts to Ruby. In RDL, types can be used to decorate methods:
require 'rdl'
extend RDL::Annotate # add annotation methods to current scope
type '(Integer, Integer) -> String'
def m(x,y) ... endThis 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:
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 thisRDL 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.
$ 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.
$ irb
> require 'rdl'
=> true
> require 'types/core'
=> true
> RDL.query '...' # as aboveRDL 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:
require 'rdl'
extend RDL::Annotate
pre { |x| x > 0 }
post { |r,x| r > 0 }
def sqrt(x)
# return the square root of x
endGiven 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.
RDL currently supports Ruby 2.x except 2.1.1-2.1.6. RDL may or may not work with other versions.
gem install rdl should do it.
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:
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.)
To add types to a Ruby on Rails application, add
gem 'rdl'to your Gemfile to get the latest stable version, or
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.
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 definedpre(mth) { block } - Apply precondition to method mth of the current class, where mth is a Symbol or Stringpre(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 StringThe 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.
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:
type :=~, '(Object) -> Integer or nil', wrap: false # Wrapping this messes up $1 etcFor 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.
暂无开放 Issues,或尚未同步最近议题。