• Stars
    star
    266
  • Rank 154,103 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Design by Contract for JavaScript via a Babel plugin.

Babel Contracts

This is a Babel plugin for design by contract for JavaScript.

Build Status

What?

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, Design by Contract gives them a way to express their assumptions in a convenient syntax, and have those assumptions validated at runtime.

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 or side effects of the function.

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

Although not strictly a contract, assertions are also supported.

Neither invariants, assertions, 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 plugin, 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.

This plugin implements Design by Contract by abusing repurposing 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. The plugin then retrieves these special labeled sections and transpiles them into contracts.

Installation

Install via npm.

npm install --save-dev babel-plugin-contracts

Then, in your babel configuration (usually in your .babelrc file), add "contracts" to your list of plugins:

{
  "plugins": [
    ["contracts", {
      "env": {
        "production": {
          "strip": true
        }
      }
    }]
  ]
}

The above example configuration will remove all contracts when NODE_ENV=production, which is often preferable for performance reasons. You can customize the names of the labels and identifiers by specifying a names option, e.g.

{
  "plugins": [
    ["contracts", {
      "names": {
        "assert": "assert",
        "precondition": "pre",
        "postcondition": "post",
        "invariant": "invariant",
        "return": "it",
        "old": "old"
      }
    }]
  ]
}

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';
  return 'Warning!\n' + message;
}

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

  1. Postcondition Only.

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

Note: Post-conditions introduce a special variable, it which refers to the result of the function.

function items (a, b) {
  let c = [];
  if (a) {
    c.push(a);
  }
  if (b) {
    c.push(b);
  }
  return c;

  post: {
    Array.isArray(it);
    it.length > 0;
  }
}
If we call this function without arguments, the post-condition will fail and an error will be thrown.

Note: preconditions and postconditions can appear in any order directly within the function body.

Postconditions can also refer to the state of the world at the entry point of the function, which is extremely useful when verifying the results of functions with side effects. For this, we use a pseudo-function called old() which takes a single argument - the reference we want to capture, for example:

function applyDiscount (cart, amount) {
  pre: {
    !cart.hasDiscount, "Discounts can only be applied once";
    cart.total >= amount, "Cannot discount to less than zero.";
  }
  post: {
    cart.total === old(cart.total) - amount;
  }
  cart.total -= amount;
  cart.hasDiscount = true;
  // some more complicated stuff goes here...
  return cart;
}
  1. Preconditions and Postconditions.
function withdraw (fromAccount, amount) {
  pre: {
    typeof amount === 'number';
    amount > 0;
    fromAccount.balance - amount > -fromAccount.overdraftLimit;
  }
  post: {
    fromAccount.balance - amount > -fromAccount.overdraftLimit;
  }

  fromAccount.balance -= amount;
}
  1. Invariants

Invariants run at the beginning and end of a block. Using invariants we can simplify the above example.

function withdraw (fromAccount, amount) {
  pre: {
    typeof amount === 'number';
    amount > 0;
  }
  invariant: {
    fromAccount.balance - amount > -fromAccount.overdraftLimit;
  }

  fromAccount.balance -= amount;
}
  1. Assertions

Assertions verify that something is truthy and throw an error if the assertion fails. They run where they are specified:

function add (a, b) {
  const result = a + b;
  assert: typeof result === 'number';
  return result;
}

or, with multiple:

function addAndSquare (a, b) {
  let result = a + b;
  assert: {
    typeof result === 'number';
    !isNaN(result);
  }

  result *= result;

  assert: result < Math.pow(2, 32), "Must be within an acceptable range";

  return result;
}
  1. Error Messages

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

function withdraw (fromAccount, amount) {
  pre: {
    typeof amount === 'number', "Second argument must be a number";
    amount > 0, "Cannot withdraw a zero or negative amount";
    fromAccount.balance - amount > -fromAccount.overdraftLimit, "Must not exceed overdraft limit";
  }
  post: {
    fromAccount.balance - amount > -fromAccount.overdraftLimit, "Must not exceed overdraft limit";
  }

  fromAccount.balance -= amount;
}

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

Migrating from Contractual.

This plugin uses a very similar syntax to our earlier Design by Contract library, contractual. If you're migrating your project there are some differences to be aware of:

  1. There is no longer a main: section. Anything outside of a contract is considered to be part of the normal program code.
  2. Contracts containing more than one assertion must be fully wrapped in a block statement ({ and }), labels no longer act as delimiters.
  3. __result is now called it in postconditions.
  4. Invariants can be specified at the block / scope level, not just at function entry points.
  5. No longer creates custom error types.

License

Published by codemix under a permissive MIT License, see LICENSE.md.

More Repositories

1

fast.js

Faster user-land reimplementations for several common builtin native JavaScript functions.
JavaScript
3,412
star
2

ts-sql

A SQL database implemented purely in TypeScript type annotations.
TypeScript
3,181
star
3

babel-plugin-typecheck

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

deprank

Use PageRank to find the most important files in your codebase.
TypeScript
878
star
5

yii2-localeurls

Automatic locale/language management for URLs
PHP
412
star
6

babel-plugin-closure-elimination

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

babel-plugin-macros

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

oriento

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

htmling

Polymer / HTML5 templating syntax for node.js
JavaScript
177
star
10

yii2-dockerized

A template for docker based Yii 2 applications
PHP
169
star
11

yii2-excelexport

A utility to quickly create Excel files from query results or raw data
PHP
102
star
12

gitignore-parser

A simple .gitignore parser for node.js
JavaScript
97
star
13

contractual

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

babel-plugin-trace

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

yii2-configloader

Build configuration arrays from config files and env vars.
PHP
61
star
16

yii2-streamlog

A Yii 2 log target for streams in URL format
PHP
52
star
17

yii2-dockerbase

Yii 2 base image for dockerized yii2 projects
Shell
39
star
18

YiiElasticSearch

Elastic Search client for Yii
PHP
33
star
19

malloc

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

reign

A persistent, typed objects implementation for node.js and the browser.
JavaScript
23
star
21

binary-protocol

Easy, fast, writers and readers for implementing custom binary protocols in node.js.
JavaScript
20
star
22

oauth2yii

An OAuth2 client / server extension for the Yii framework
PHP
17
star
23

modeling

Fast and flexible data models for node.js and the browser.
JavaScript
15
star
24

restyii

A RESTful extension for Yii.
PHP
15
star
25

babel-plugin-hyperhtml

Babel plugin which compiles JSX into hyperHTML
JavaScript
12
star
26

yii2-excel-message

Translate messages via Excel files
PHP
12
star
27

backing

Provides a virtual address space for large segments of memory via JavaScript ArrayBuffers, and operations for allocating and freeing within the address space, optionally via a simple reference counting garbage collector.
JavaScript
11
star
28

validating

Quick and easy validators for node.js and the browser.
JavaScript
10
star
29

babel-plugin-conditional

Conditionally applies a set of babel plugins based on the result of an expression evaluated at runtime.
JavaScript
10
star
30

yii2-bs3activeform

A Bootstrap 3 enhanced ActiveForm for Yii 2
PHP
9
star
31

url-route

Web component providing URL routing
JavaScript
9
star
32

htmling-demo-app

HTMLing demo running on express
CSS
8
star
33

garbage-collector

A garbage collector for JavaScript built on top of typed arrays.
JavaScript
8
star
34

geonames-importer

Imports geonames data into elasticsearch
JavaScript
7
star
35

orientdb-protobufs

An experiment to see how the orientdb binary protocol could look if it used protocol buffers.
Java
6
star
36

handlebarsphp

Transpiles handlebars templates into native PHP templates
PHP
6
star
37

atomicbuffers

Atomic `readInt32()`, `writeInt32()`, `readUInt32()` and `writeUInt32()` for node.js buffers.
JavaScript
6
star
38

classing

Fluent classes for node.js and the browser.
JavaScript
6
star
39

dispatching

Tiny routing / dispatch library for node and the browser.
JavaScript
5
star
40

casting

Tiny type casting library for node.js and the browser.
JavaScript
5
star
41

php-orientdb

A fast PHP driver for the OrientDB binary protocol.
PHP
5
star
42

obligations

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

AccessRestrictable

A Yii ActiveRecordBehavior that automatically applies conditions for access restriction to every query.
PHP
2
star
44

component-testing-library

A library for testing component driven UIs
TypeScript
2
star
45

bootstrap-css

Twitter Bootstrap CSS / LESS packaged for component.js instead of bower
CSS
2
star
46

miming

Processing and formatting for various mime types.
JavaScript
2
star
47

bs3activeform

A lightweight utility to render Bootstrap 3 forms in Yii
PHP
2
star
48

handlebarsgen

An extendable static code generator for handlebars templates, targetting languages other than JavaScript, e.g. PHP
CoffeeScript
2
star
49

malloc-append

Simple append-only alloc() implementation on top of buffers and array buffers.
JavaScript
1
star
50

jsx-email-nextjs

Reproduce an error with renderToStaticMarkup() in Next.js
TypeScript
1
star
51

bootstrap-tooltip

Twitter Bootstrap Tooltip plugin packaged for component.js instead of bower
JavaScript
1
star
52

bencha

Mocha-esque UI for the excellent benchmarkjs benchmarking library
CoffeeScript
1
star
53

bootstrap-transition

Twitter Bootstrap Transition plugin packaged for component.js instead of bower
JavaScript
1
star
54

urlrouter

Tiny URL routing for the browser
CoffeeScript
1
star
55

bootstrap-affix

Twitter Bootstrap Affix plugin packaged for component.js instead of bower
JavaScript
1
star
56

bootstrap-scrollspy

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