contractual 52

Unobtrusive, backwards compatible, syntactic sugar for Design by contract in JavaScript.

codemix/contractual

Written in JavaScript by 2 contributors

Contribute

Need Support?


we offer maintenance, support and development services for all our open source projects.

Contact Us

Contractual

Build Status

Deprecated, use https://github.com/codemix/babel-plugin-contracts instead.

Unobtrusive, backwards compatible syntactic sugar for Design by contract in JavaScript.

Design by contract is a very powerful technique for writing robust software, it can be thought of as a formal but convenient method for specifying assertions. Instead of the developer documenting their assumptions in comments, or worse, not documenting them at all, DbyC gives them a way to express their assumptions in a convenient syntax, and have those assumptions validated at runtime.

In Contractual, contracts come in three flavours:

Each statement in a contract must evaluate to true for the contract to be valid. If a contract fails, an error will be thrown.

Preconditions are usually used to validate the arguments to a function, or the state of the system before the main function body executes.

Postconditions are used to validate the result of the function.

Invariants are used to ensure that an assumption holds true for the duration of the function.

Neither invariants, preconditions or postconditions themselves may have side-effects, e.g. it is not possible to assign a new value to a variable from within a contract.

Purity within contracts is enforced as much as possible by the contractual compiler, but it is still possible for a programmer to circumvent, by calling an impure function from within the precondition or postcondition. This is strongly discouraged.

Contractual implements DbyC by abusing JavaScript labels. Labels are a very rarely used feature of JavaScript, and a nice thing about them is that if a label is specified but not used, it is simply ignored by the JavaScript engine. This allows us to break up our function body into labeled sections, without affecting the result or behavior of the function. Contractual then retrieves these special labeled sections and transpiles them into contracts.

Importantly, since the original source code is both valid JavaScript and semantically identical to the result, it is possible to use source code written for Contractual directly, without compiling it. However, it will of course lack the contractual guarantees.

Examples

  1. Precondition Only.

    The contract for the following function specifies that the first argument must always be a string.

    function warn (message) {
     pre:
       typeof message === 'string';
     main:
       alert('Warning!\n' + message);
    }
    

    If we call this function with a non string argument, a PreconditionError will be thrown.

    See the compiled output.

  1. Postcondition Only.

    The following function specifies that the result of the function must always be an array containing more than one element.

    function items (a, b) {
     main:
       var c = [];
       if (a) {
         c.push(a);
       }
       if (b) {
         c.push(b);
       }
       return c;
     post:
       Array.isArray(__result);
       __result.length > 0;
    }
    

    If we call this function without arguments, the post-condition will fail and a PostconditionError will be thrown.

    See the compiled output.

  2. Preconditions and Postconditions.

    In this example the precondition specifies that both arguments are numbers and that the second argument is not zero. The postcondition specifies that the result of the function is always less than the first argument to the function.

    function divide (a, b) {
     pre:
       typeof a === 'number';
       typeof b === 'number';
       b !== 0;
     main:
       return a / b;
     post:
       __result < a;
    }
    

    See the compiled output.

  3. Invariants

    Invariants run at the beginning and end of a function.

    function spend (amount) {
     invariant:
       typeof amount === 'number', "First argument must be a number";
       this.balance >= 0, 'Cannot go overdrawn';
     main:
       this.balance = this.balance - amount;
       return this.balance;
    }
    

    See the compiled output.

  4. Error Messages

    Often it's nice to provide an error message for the contract that failed, for example:

    function divide (a, b) {
     pre:
       typeof a === 'number', "First argument must be a number";
       typeof b === 'number', "Second argument must be a number";
       b !== 0, "May not divide by zero";
     main:
       return a / b;
     post:
       __result =< a, "Result must always be less than or equal to the first argument";
    }
    

    Now if a contract fails, the error object will have a descriptive message.

    See the compiled output.

Installation

Install via npm.

npm install -g contractual

Contributors please see CONTRIBUTING.md.

Usage

While Contractual can be used programatically, it is mainly used via a command line interface:

> contractual --help
contractual - Syntactic sugar for Design by contract in JavaScript.

Usage: contractual [OPTIONS] [FILES]

Options:
  --output, -o   The directory to write compiled files to.                                             [default: "./out"]
  --libname, -l  The name of the identifier for the obligations library                                [default: "OBLIGATIONS"]
  --global, -g   Whether a global identifier should be used for the obligations lib.                   [default: false]
  --require, -r  The obligations library to require, if `global` is not specified.                     [default: "obligations"]
  --source-map   If true generate source maps, if a string use it as the source filename for the map.
  --source-root  If set, acts as the root for the source files listed in the source map.
  --version, -v  Show the version information.
  --help, -h     Show this help screen.

License

MIT, see LICENSE.md.





44 other JavaScript projects


fast.jsJavaScript 2930

Faster user-land reimplementations for several common builtin native JavaScript functions.

babel-plugin-typecheckJavaScript 823

Static and runtime type checking for JavaScript in the form of a Babel plugin.

babel-plugin-closure-eliminationJavaScript 223

A Babel plugin which eliminates closures from your JavaScript wherever possible.

orientoJavaScript 212

Former official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. Now deprecated.

babel-plugin-macrosJavaScript 184

Hygienic, non-syntactic macros for JavaScript via a Babel plugin.

htmlingJavaScript 167

Polymer / HTML5 templating syntax for node.js

babel-plugin-contractsJavaScript 128

Design by Contract for JavaScript via a Babel plugin.

YiiBlocksJavaScript 70

A set of building blocks that provide common functions for Yii web applications

gitignore-parserJavaScript 34

A simple .gitignore parser for node.js

modelingJavaScript 14

Fast and flexible data models for node.js and the browser.

binary-protocolJavaScript 13

Easy, fast, writers and readers for implementing custom binary protocols in node.js.

YiiJSJavaScript 11

A port of the Yii PHP framework to JavaScript

validatingJavaScript 10

Quick and easy validators for node.js and the browser.

url-routeJavaScript 10

Web component providing URL routing

babel-plugin-traceJavaScript 6

This is a Babel plugin which adds a straightforward, declarative syntax for adding debug logging to JavaScript applications.

mallocJavaScript 6

Simple malloc() & free() implementation for node.js, built on top of array buffers.

geonames-importerJavaScript 6

Imports geonames data into elasticsearch

atomicbuffersJavaScript 5

Atomic `readInt32()`, `writeInt32()`, `readUInt32()` and `writeUInt32()` for node.js buffers.

classingJavaScript 5

Fluent classes for node.js and the browser.

castingJavaScript 5

Tiny type casting library for node.js and the browser.

dispatchingJavaScript 5

Tiny routing / dispatch library for node and the browser.

mimingJavaScript 3

Processing and formatting for various mime types.

bootstrap-transitionJavaScript 1

Twitter Bootstrap Transition plugin packaged for component.js instead of bower

oriento-query-builderJavaScript 1

A standalone query builder for OrientDB, designed for node.js/io.js and the browser.

obligationsJavaScript 1

Tiny JavaScript library for preconditions and postconditions, intended for use with Contractual.

bootstrap-tooltipJavaScript 1

Twitter Bootstrap Tooltip plugin packaged for component.js instead of bower

bootstrap-popoverJavaScript

Twitter Bootstrap Popover plugin packaged for component.js instead of bower

ProductManagerJavaScript

A Sample CRUD application structured by Backbone js and backed by a node restfull api.

bootstrap-modalJavaScript

Twitter Bootstrap Modal plugin packaged for component.js instead of bower

bootstrap-collapseJavaScript

Twitter Bootstrap Collapse plugin packaged for component.js instead of bower

bootstrap-dropdownJavaScript

Twitter Bootstrap Dropdown plugin packaged for component.js instead of bower

bootstrap-carouselJavaScript

Twitter Bootstrap Carousel plugin packaged for component.js instead of bower

cover.jsJavaScript

JQuery plugin for covering/uncovering DOM elements

flex-basicJavaScript

A basic Flex App setup for video broadcasting

bootstrap-tabJavaScript

Twitter Bootstrap Tab plugin packaged for component.js instead of bower

bootstrap-buttonJavaScript

Twitter Bootstrap Button plugin packaged for component.js instead of bower

bootstrap-alertJavaScript

Twitter Bootstrap Alert plugin packaged for component.js instead of bower

bootstrap-affixJavaScript

Twitter Bootstrap Affix plugin packaged for component.js instead of bower

webrtc-playgroundJavaScript

WebRTC sample code. For testing purposes only.

bootstrap-scrollspyJavaScript

Twitter Bootstrap Scrollspy plugin packaged for component.js instead of bower

bootstrap-componentJavaScript

Twitter Bootstrap packaged for component.js instead of bower

bootstrap-typeaheadJavaScript

Twitter Bootstrap Typeahead plugin packaged for component.js instead of bower

elevatorJavaScript

http://samsonradu.github.io/elevator/

tabinetJavaScript

A popular romanian card game