1 |
|
2 | "use strict";
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | var arbitrary = require("./arbitrary.js");
|
24 | var record = require("./record.js");
|
25 | var array = require("./array.js");
|
26 | var fn = require("./fn.js");
|
27 | var typifyParser = require("typify-parser");
|
28 |
|
29 |
|
30 | var compileType;
|
31 | var compileTypeArray;
|
32 |
|
33 | function compileIdent(env, type) {
|
34 | var g = env[type.value];
|
35 | if (!g) {
|
36 | throw new Error("Unknown arbitrary: " + type.value);
|
37 | }
|
38 | return g;
|
39 | }
|
40 |
|
41 | function compileApplication(env, type) {
|
42 | var callee = compileType(env, type.callee);
|
43 | var args = compileTypeArray(env, type.args);
|
44 |
|
45 | return callee.apply(undefined, args);
|
46 | }
|
47 |
|
48 | function compileFunction(env, type) {
|
49 |
|
50 | var result = compileType(env, type.result);
|
51 | return fn.fn(result);
|
52 | }
|
53 |
|
54 | function compileBrackets(env, type) {
|
55 | var arg = compileType(env, type.arg);
|
56 | return array.array(arg);
|
57 | }
|
58 |
|
59 | function compileDisjunction(env, type) {
|
60 | var args = compileTypeArray(env, type.args);
|
61 | return arbitrary.oneof(args);
|
62 | }
|
63 |
|
64 | function compileRecord(env, type) {
|
65 |
|
66 | var spec = {};
|
67 | Object.keys(type.fields).forEach(function (key) {
|
68 | spec[key] = compileType(env, type.fields[key]);
|
69 | });
|
70 | return record.arbitrary(spec);
|
71 | }
|
72 |
|
73 | compileType = function compileTypeFn(env, type) {
|
74 | switch (type.type) {
|
75 | case "ident": return compileIdent(env, type);
|
76 | case "application": return compileApplication(env, type);
|
77 | case "function": return compileFunction(env, type);
|
78 | case "brackets": return compileBrackets(env, type);
|
79 | case "disjunction": return compileDisjunction(env, type);
|
80 | case "record": return compileRecord(env, type);
|
81 | case "number": return type.value;
|
82 | default: throw new Error("Unsupported typify ast type: " + type.type);
|
83 | }
|
84 | };
|
85 |
|
86 | compileTypeArray = function compileTypeArrayFn(env, types) {
|
87 | return types.map(function (type) {
|
88 | return compileType(env, type);
|
89 | });
|
90 | };
|
91 |
|
92 | function parseTypify(env, str) {
|
93 | var type = typifyParser(str);
|
94 | return compileType(env, type);
|
95 | }
|
96 |
|
97 | module.exports = {
|
98 | parseTypify: parseTypify,
|
99 | };
|