goodguide-gibbon 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,87 +1,22 @@
1
1
  var Gibbon = (function(undefined) {
2
- var Parsimmon = (function(undefined) {
3
- var P = (function(prototype, ownProperty, undefined) {
4
- return function P(_superclass /* = Object */, definition) {
5
- // handle the case where no superclass is given
6
- if (definition === undefined) {
7
- definition = _superclass;
8
- _superclass = Object;
9
- }
10
-
11
- // C is the class to be returned.
12
- //
13
- // When called, creates and initializes an instance of C, unless
14
- // `this` is already an instance of C, then just initializes `this`;
15
- // either way, returns the instance of C that was initialized.
16
- //
17
- // TODO: the Chrome inspector shows all created objects as `C`
18
- // rather than `Object`. Setting the .name property seems to
19
- // have no effect. Is there a way to override this behavior?
20
- function C() {
21
- var self = this instanceof C ? this : new Bare;
22
- self.init.apply(self, arguments);
23
- return self;
24
- }
25
-
26
- // C.Bare is a class with a noop constructor. Its prototype will be
27
- // the same as C, so that instances of C.Bare are instances of C.
28
- // `new MyClass.Bare` then creates new instances of C without
29
- // calling .init().
30
- function Bare() {}
31
- C.Bare = Bare;
32
-
33
- // Extend the prototype chain: first use Bare to create an
34
- // uninitialized instance of the superclass, then set up Bare
35
- // to create instances of this class.
36
- var _super = Bare[prototype] = _superclass[prototype];
37
- var proto = Bare[prototype] = C[prototype] = C.p = new Bare;
38
-
39
- // pre-declaring the iteration variable for the loop below to save
40
- // a `var` keyword after minification
41
- var key;
42
-
43
- // set the constructor property on the prototype, for convenience
44
- proto.constructor = C;
45
-
46
- C.extend = function(def) { return P(C, def); }
47
-
48
- return (C.open = function(def) {
49
- if (typeof def === 'function') {
50
- // call the defining function with all the arguments you need
51
- // extensions captures the return value.
52
- def = def.call(C, proto, _super, C, _superclass);
53
- }
54
-
55
- // ...and extend it
56
- if (typeof def === 'object') {
57
- for (key in def) {
58
- if (ownProperty.call(def, key)) {
59
- proto[key] = def[key];
60
- }
61
- }
62
- }
63
-
64
- // if no init, assume we're inheriting from a non-Pjs class, so
65
- // default to using the superclass constructor.
66
- if (!('init' in proto)) proto.init = _superclass;
67
-
68
- return C;
69
- })(definition);
70
- }
71
-
72
- // as a minifier optimization, we've closured in a few helper functions
73
- // and the string 'prototype' (C[p] is much shorter than C.prototype)
74
- })('prototype', ({}).hasOwnProperty);
2
+ // pass
75
3
  var Parsimmon = {};
76
4
 
77
- Parsimmon.Parser = P(function(_, _super, Parser) {
5
+ Parsimmon.Parser = (function() {
78
6
  "use strict";
7
+
79
8
  // The Parser object is a wrapper for a parser function.
80
9
  // Externally, you use one to parse a string by calling
81
10
  // var result = SomeParser.parse('Me Me Me! Parse Me!');
82
11
  // You should never call the constructor, rather you should
83
12
  // construct your Parser from the base parsers and the
84
13
  // parser combinator methods.
14
+ function Parser(action) {
15
+ if (!(this instanceof Parser)) return new Parser(action);
16
+ this._ = action;
17
+ };
18
+
19
+ var _ = Parser.prototype;
85
20
 
86
21
  function makeSuccess(index, value) {
87
22
  return {
@@ -89,7 +24,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
89
24
  index: index,
90
25
  value: value,
91
26
  furthest: -1,
92
- expected: ''
27
+ expected: []
93
28
  };
94
29
  }
95
30
 
@@ -99,20 +34,24 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
99
34
  index: -1,
100
35
  value: null,
101
36
  furthest: index,
102
- expected: expected
37
+ expected: [expected]
103
38
  };
104
39
  }
105
40
 
106
- function furthestBacktrackFor(result, last) {
41
+ function mergeReplies(result, last) {
107
42
  if (!last) return result;
108
- if (result.furthest >= last.furthest) return result;
43
+ if (result.furthest > last.furthest) return result;
44
+
45
+ var expected = (result.furthest === last.furthest)
46
+ ? result.expected.concat(last.expected)
47
+ : last.expected;
109
48
 
110
49
  return {
111
50
  status: result.status,
112
51
  index: result.index,
113
52
  value: result.value,
114
53
  furthest: last.furthest,
115
- expected: last.expected
54
+ expected: expected
116
55
  }
117
56
  }
118
57
 
@@ -120,23 +59,28 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
120
59
  if (!(p instanceof Parser)) throw new Error('not a parser: '+p);
121
60
  }
122
61
 
123
- var formatError = Parsimmon.formatError = function(stream, error) {
124
- var expected = error.expected;
62
+ function formatExpected(expected) {
63
+ if (expected.length === 1) return expected[0];
64
+
65
+ return 'one of ' + expected.join(', ')
66
+ }
67
+
68
+ function formatGot(stream, error) {
125
69
  var i = error.index;
126
70
 
127
- if (i === stream.length) {
128
- return 'expected ' + expected + ', got the end of the string';
129
- }
71
+ if (i === stream.length) return ', got the end of the stream'
72
+
130
73
 
131
74
  var prefix = (i > 0 ? "'..." : "'");
132
75
  var suffix = (stream.length - i > 12 ? "...'" : "'");
133
- return (
134
- 'expected ' + expected + ' at character ' + i + ', got ' +
135
- prefix + stream.slice(i, i+12) + suffix
136
- );
137
- };
138
76
 
139
- _.init = function(body) { this._ = body; };
77
+ return ' at character ' + i + ', got ' + prefix + stream.slice(i, i+12) + suffix
78
+ }
79
+
80
+ var formatError = Parsimmon.formatError = function(stream, error) {
81
+ console.log('formatError', stream, error);
82
+ return 'expected ' + formatExpected(error.expected) + formatGot(stream, error)
83
+ };
140
84
 
141
85
  _.parse = function(stream) {
142
86
  var result = this.skip(eof)._(stream, 0);
@@ -161,13 +105,22 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
161
105
  var accum = new Array(numParsers);
162
106
 
163
107
  for (var j = 0; j < numParsers; j += 1) {
164
- result = furthestBacktrackFor(parsers[j]._(stream, i), result);
108
+ result = mergeReplies(parsers[j]._(stream, i), result);
165
109
  if (!result.status) return result;
166
110
  accum[j] = result.value
167
111
  i = result.index;
168
112
  }
169
113
 
170
- return furthestBacktrackFor(makeSuccess(i, accum), result);
114
+ return mergeReplies(makeSuccess(i, accum), result);
115
+ });
116
+ };
117
+
118
+
119
+ var seqMap = Parsimmon.seqMap = function() {
120
+ var args = [].slice.call(arguments);
121
+ var mapper = args.pop();
122
+ return seq.apply(null, args).map(function(results) {
123
+ return mapper.apply(null, results);
171
124
  });
172
125
  };
173
126
 
@@ -186,7 +139,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
186
139
  return Parser(function(stream, i) {
187
140
  var result;
188
141
  for (var j = 0; j < parsers.length; j += 1) {
189
- result = furthestBacktrackFor(parsers[j]._(stream, i), result);
142
+ result = mergeReplies(parsers[j]._(stream, i), result);
190
143
  if (result.status) return result;
191
144
  }
192
145
  return result;
@@ -200,7 +153,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
200
153
 
201
154
  _.then = function(next) {
202
155
  if (typeof next === 'function') {
203
- throw new Error('chaining features of .then are no longer supported');
156
+ throw new Error('chaining features of .then are no longer supported, use .chain instead');
204
157
  }
205
158
 
206
159
  assertParser(next);
@@ -230,14 +183,14 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
230
183
  var prevResult;
231
184
 
232
185
  for (;;) {
233
- result = furthestBacktrackFor(self._(stream, i), result);
186
+ result = mergeReplies(self._(stream, i), result);
234
187
 
235
188
  if (result.status) {
236
189
  i = result.index;
237
190
  accum.push(result.value);
238
191
  }
239
192
  else {
240
- return furthestBacktrackFor(makeSuccess(i, accum), result);
193
+ return mergeReplies(makeSuccess(i, accum), result);
241
194
  }
242
195
  }
243
196
  });
@@ -275,39 +228,35 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
275
228
 
276
229
  for (var times = 0; times < min; times += 1) {
277
230
  result = self._(stream, i);
278
- prevResult = furthestBacktrackFor(result, prevResult);
231
+ prevResult = mergeReplies(result, prevResult);
279
232
  if (result.status) {
280
233
  i = result.index;
281
234
  accum.push(result.value);
282
235
  }
283
- else {
284
- return prevResult;
285
- }
236
+ else return prevResult;
286
237
  }
287
238
 
288
239
  for (; times < max; times += 1) {
289
240
  result = self._(stream, i);
290
- prevResult = furthestBacktrackFor(result, prevResult);
241
+ prevResult = mergeReplies(result, prevResult);
291
242
  if (result.status) {
292
243
  i = result.index;
293
244
  accum.push(result.value);
294
245
  }
295
- else {
296
- break;
297
- }
246
+ else break;
298
247
  }
299
248
 
300
- return furthestBacktrackFor(makeSuccess(i, accum), prevResult);
249
+ return mergeReplies(makeSuccess(i, accum), prevResult);
301
250
  });
302
251
  };
303
252
 
304
253
  // -*- higher-level combinators -*- //
305
- _.result = function(res) { return this.then(succeed(res)); };
254
+ _.result = function(res) { return this.map(function(_) { return res; }); };
306
255
  _.atMost = function(n) { return this.times(0, n); };
307
256
  _.atLeast = function(n) {
308
257
  var self = this;
309
- return seq(this.times(n), this.many()).map(function(results) {
310
- return results[0].concat(results[1]);
258
+ return seqMap(this.times(n), this.many(), function(init, rest) {
259
+ return init.concat(rest);
311
260
  });
312
261
  };
313
262
 
@@ -316,7 +265,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
316
265
  return Parser(function(stream, i) {
317
266
  var result = self._(stream, i);
318
267
  if (!result.status) return result;
319
- return furthestBacktrackFor(makeSuccess(result.index, fn(result.value)), result);
268
+ return mergeReplies(makeSuccess(result.index, fn(result.value)), result);
320
269
  });
321
270
  };
322
271
 
@@ -325,13 +274,18 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
325
274
  };
326
275
 
327
276
  _.mark = function() {
328
- return seq(index, this, index).map(function(results) {
329
- return { start: results[0], value: results[1], end: results[2] };
277
+ return seqMap(index, this, index, function(start, value, end) {
278
+ return { start: start, value: value, end: end };
330
279
  });
331
280
  };
332
281
 
333
282
  _.desc = function(expected) {
334
- return this.or(fail(expected))
283
+ var self = this;
284
+ return Parser(function(stream, i) {
285
+ var reply = self._(stream, i);
286
+ if (!reply.status) reply.expected = [expected];
287
+ return reply;
288
+ });
335
289
  };
336
290
 
337
291
  // -*- primitive parsers -*- //
@@ -351,19 +305,21 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
351
305
  });
352
306
  };
353
307
 
354
- var regex = Parsimmon.regex = function(re) {
308
+ var regex = Parsimmon.regex = function(re, group) {
355
309
  var anchored = RegExp('^(?:'+re.source+')', (''+re).slice((''+re).lastIndexOf('/')+1));
310
+ var expected = '' + re;
311
+ if (group == null) group = 0;
356
312
 
357
313
  return Parser(function(stream, i) {
358
314
  var match = anchored.exec(stream.slice(i));
359
315
 
360
316
  if (match) {
361
- var result = match[0];
362
- return makeSuccess(i+result.length, result);
363
- }
364
- else {
365
- return makeFailure(i, re);
317
+ var fullMatch = match[0];
318
+ var groupMatch = match[group];
319
+ if (groupMatch != null) return makeSuccess(i+fullMatch.length, groupMatch);
366
320
  }
321
+
322
+ return makeFailure(i, expected);
367
323
  });
368
324
  };
369
325
 
@@ -412,6 +368,14 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
412
368
  });
413
369
  };
414
370
 
371
+ var oneOf = Parsimmon.oneOf = function(str) {
372
+ return test(function(ch) { return str.indexOf(ch) >= 0; });
373
+ };
374
+
375
+ var noneOf = Parsimmon.noneOf = function(str) {
376
+ return test(function(ch) { return str.indexOf(ch) < 0; });
377
+ };
378
+
415
379
  var takeWhile = Parsimmon.takeWhile = function(predicate) {
416
380
  return Parser(function(stream, i) {
417
381
  var j = i;
@@ -450,9 +414,7 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
450
414
  _.of = Parser.of = Parsimmon.of = succeed
451
415
 
452
416
  _.ap = function(other) {
453
- return seq(this, other).map(function(results) {
454
- return results[0](results[1]);
455
- });
417
+ return seqMap(this, other, function(f, x) { return f(x); })
456
418
  };
457
419
 
458
420
  //- Monad
@@ -462,12 +424,13 @@ Parsimmon.Parser = P(function(_, _super, Parser) {
462
424
  var result = self._(stream, i);
463
425
  if (!result.status) return result;
464
426
  var nextParser = f(result.value);
465
- return furthestBacktrackFor(nextParser._(stream, result.index), result);
427
+ return mergeReplies(nextParser._(stream, result.index), result);
466
428
  });
467
429
  };
468
- });
469
- return Parsimmon;
470
- })()
430
+
431
+ return Parser;
432
+ })();
433
+ // pass
471
434
  // Generated by CoffeeScript 1.6.3
472
435
  var AST, CompiledCode, Core, DEBUG, Dependency, Failure, Gibbon, Hash, JS, List, Map, ObjHash, RVal, Result, Ruby, Semantic, Step, Thunk, Trace, Type, TypeAST, TypeExpr, TypeLookup, Value, VarTrace, Variant, analyze, applyOp1, applyOp2, asyncMap, contIter, contMap, equalArrays, eval_, inspectNative, isArray, nameGen, parse, stdlib, uniq, _ref, _ref1, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref16, _ref17, _ref18, _ref19, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9,
473
436
  __slice = [].slice,
@@ -1050,7 +1013,8 @@ Gibbon.AST = AST = (function(_super) {
1050
1013
  flow: ['loc', 'head', 'tail'],
1051
1014
  metadata: ['loc', 'key', 'text'],
1052
1015
  definition: ['loc', 'metadata', 'name', 'frame'],
1053
- frame: ['loc', 'definitions', 'flow']
1016
+ frame: ['loc', 'definitions', 'flow'],
1017
+ program: ['definitions']
1054
1018
  });
1055
1019
 
1056
1020
  inspectDefinitions = function(defs) {
@@ -1169,6 +1133,9 @@ Gibbon.AST = AST = (function(_super) {
1169
1133
  out.push(flow.inspect());
1170
1134
  out.push(")");
1171
1135
  return out.join('');
1136
+ },
1137
+ program: function(definitions) {
1138
+ return inspectDefinitions(definitions);
1172
1139
  }
1173
1140
  });
1174
1141
  };
@@ -1205,17 +1172,10 @@ Gibbon.TypeAST = TypeAST = (function(_super) {
1205
1172
  })(Variant);
1206
1173
 
1207
1174
  parse = Gibbon.parse = (function() {
1208
- var accessor, accessorExpr, arrow, arrowType, assertString, blankLines, blockExpr, blockType, comma, commaSepFlows, comment, component, concrete, decimal, decimalExpr, defaulted, define, definition, expr, fail, flow, fraction, fractionExpr, frame, freeFrame, fullSignature, func, funcPlaceholder, handleResult, identifier, innerFrame, integer, integerExpr, isString, label, labelVal, lazy, lbrace, lbrack, lexeme, lexical, lexicalExpr, lines, listExpr, listType, lparen, lsplat, metadata, multiline, name, nonDefaultedFlow, nonPairedFlow, numericExpr, opt, pair, parenFlow, parenFrame, parenType, percent, percentExpr, program, query, queryArg, queryExpr, rbrace, rbrack, regex, rparen, rsplat, seq, signature, simpleType, singletonFlow, spanLoc, squishListExpr, str, string, stringExpr, substExpr, succeed, tag, tassign, type, typeVar, variable, whitespace, wildType, wildcard, withLoc,
1175
+ var accessor, accessorExpr, arrow, arrowType, assertString, blankLines, blockExpr, blockType, comma, commaSepFlows, comment, component, concrete, decimal, decimalExpr, defaulted, define, definition, expr, fail, flow, fraction, fractionExpr, frame, freeFrame, fullFrame, fullSignature, func, funcPlaceholder, handleResult, identifier, innerFrame, integer, integerExpr, isString, label, labelVal, lazy, lbrace, lbrack, lexeme, lexical, lexicalExpr, lines, listExpr, listType, lparen, lsplat, metadata, multiline, name, nonDefaultedFlow, nonPairedFlow, numericExpr, opt, pair, parenFlow, parenFrame, parenType, percent, percentExpr, program, query, queryArg, queryExpr, rbrace, rbrack, regex, rparen, rsplat, seq, signature, simpleType, singletonFlow, spanLoc, squishListExpr, str, string, stringExpr, substExpr, succeed, tag, tassign, type, typeVar, variable, whitespace, wildType, wildcard, withLoc,
1209
1176
  _this = this;
1210
1177
  tag = function(name, parser) {
1211
- return Parsimmon.Parser(function(stream, i) {
1212
- var result;
1213
- result = parser._(stream, i);
1214
- if (!result.status) {
1215
- result.expected = name;
1216
- }
1217
- return result;
1218
- });
1178
+ return parser.desc(name);
1219
1179
  };
1220
1180
  Parsimmon.Parser.prototype.tryChain = function(f) {
1221
1181
  return this.chain(function(res) {
@@ -1224,10 +1184,10 @@ parse = Gibbon.parse = (function() {
1224
1184
  };
1225
1185
  string = Parsimmon.string, regex = Parsimmon.regex, succeed = Parsimmon.succeed, fail = Parsimmon.fail;
1226
1186
  seq = Parsimmon.seq, lazy = Parsimmon.lazy;
1227
- whitespace = regex(/^[ \t]*/);
1228
- blankLines = regex(/^[\n;\s]+/);
1229
- comment = regex(/^#.*?(\n|$)/);
1230
- lines = (blankLines.or(comment)).many();
1187
+ whitespace = tag('inline whitespace', regex(/^[ \t]*/));
1188
+ blankLines = regex(/[\n;\s]+/).desc('blank lines');
1189
+ comment = regex(/#.*?(\n|$)/).desc('a comment');
1190
+ lines = tag('whitespace', (blankLines.or(comment)).many());
1231
1191
  lexeme = function(p) {
1232
1192
  return p.mark().skip(whitespace);
1233
1193
  };
@@ -1267,9 +1227,9 @@ parse = Gibbon.parse = (function() {
1267
1227
  defaulted = multiline(string('|'));
1268
1228
  lsplat = multiline(string('[*'));
1269
1229
  rsplat = lexeme(string('*]'));
1270
- query = lexeme(string('@:').then(identifier));
1230
+ query = lexeme(string('@:').then(identifier).desc('a query'));
1271
1231
  queryArg = lexeme(regex(/^\w[\w-]*/));
1272
- accessor = lexeme(string('@').then(identifier));
1232
+ accessor = lexeme(string('@').then(identifier).desc('an accessor'));
1273
1233
  lexical = lexeme(string('.').then(identifier));
1274
1234
  name = lexeme(identifier);
1275
1235
  str = lexeme(string("'").then(regex(/^[^']*/)).skip(string("'")));
@@ -1404,7 +1364,7 @@ parse = Gibbon.parse = (function() {
1404
1364
  }
1405
1365
  return els;
1406
1366
  });
1407
- metadata = seq(label, labelVal).map(function(_arg) {
1367
+ metadata = seq(label, labelVal).desc('metadata').map(function(_arg) {
1408
1368
  var key, text;
1409
1369
  key = _arg[0], text = _arg[1];
1410
1370
  return AST.metadata(spanLoc(key, text), key.value, text.value);
@@ -1417,10 +1377,11 @@ parse = Gibbon.parse = (function() {
1417
1377
  return AST.definition(loc, md, n.value, fl);
1418
1378
  });
1419
1379
  });
1420
- frame = seq(definition.many(), flow).map(function(_arg) {
1421
- var defs, flow, loc;
1422
- defs = _arg[0], flow = _arg[1];
1423
- loc = spanLoc((defs[0] || flow).loc, flow.loc);
1380
+ frame = seq(definition, definition.many(), flow).map(function(_arg) {
1381
+ var defs, first, flow, loc, rest;
1382
+ first = _arg[0], rest = _arg[1], flow = _arg[2];
1383
+ defs = [first].concat(rest);
1384
+ loc = spanLoc(first.loc, flow.loc);
1424
1385
  return AST.frame(loc, defs, flow);
1425
1386
  });
1426
1387
  parenFrame = seq(lparen, frame, rparen, lines).map(function(_arg) {
@@ -1433,7 +1394,10 @@ parse = Gibbon.parse = (function() {
1433
1394
  return AST.frame(fl.loc, [], fl);
1434
1395
  });
1435
1396
  innerFrame = parenFrame.or(freeFrame);
1436
- program = lines.then(frame);
1397
+ program = lines.then(definition.many()).map(function(ds) {
1398
+ return AST.program(ds);
1399
+ });
1400
+ fullFrame = lines.then(frame.or(flow));
1437
1401
  tassign = lexeme(string('='));
1438
1402
  concrete = name.map(function(n) {
1439
1403
  return TypeAST.concrete(n.value);
@@ -1493,6 +1457,9 @@ parse = Gibbon.parse = (function() {
1493
1457
  assertString(str);
1494
1458
  return handleResult(str, program.parse(str));
1495
1459
  };
1460
+ parse.frame = function(str) {
1461
+ return handleResult(str, fullFrame.parse(str));
1462
+ };
1496
1463
  parse.type = function(str) {
1497
1464
  assertString(str);
1498
1465
  return handleResult(str, fullSignature.parse(str));
@@ -1732,9 +1699,9 @@ Gibbon.TypeExpr = TypeExpr = (function(_super) {
1732
1699
  variable: ['name', 'uniq'],
1733
1700
  query: ['input', 'scope', 'query'],
1734
1701
  lexical: ['syntax', 'scope'],
1735
- destructure: ['constraint', 'name', 'argnum'],
1736
1702
  "native": ['id'],
1737
1703
  param: ['name', 'constraints'],
1704
+ destructure: ['constraint', 'name', 'argnum'],
1738
1705
  error: ['type', 'args'],
1739
1706
  any: []
1740
1707
  });
@@ -1958,29 +1925,6 @@ Gibbon.TypeExpr = TypeExpr = (function(_super) {
1958
1925
  });
1959
1926
  };
1960
1927
 
1961
- TypeExpr.prototype.mapAsync = function(f, cb) {
1962
- return this.cases({
1963
- param: function(name, params) {
1964
- return asyncMap(params, f, function(ps) {
1965
- return cb(TypeExpr.param(name, ps));
1966
- });
1967
- },
1968
- query: function(input, scope, query) {
1969
- return f(input, function(i) {
1970
- return cb(TypeExpr.query(i, scope, query));
1971
- });
1972
- },
1973
- destructure: function(param, name, argnum) {
1974
- return f(param, function(p) {
1975
- return cb(TypeExpr.destructure(p, name, argnum));
1976
- });
1977
- },
1978
- other: function() {
1979
- return cb(this);
1980
- }
1981
- });
1982
- };
1983
-
1984
1928
  return TypeExpr;
1985
1929
 
1986
1930
  })(Variant);
@@ -2003,19 +1947,18 @@ analyze = Gibbon.analyze = (function() {
2003
1947
  })();
2004
1948
  }
2005
1949
 
2006
- NativeContext.prototype.query = function(id, query, cb) {
2007
- var cacheKey, lookupFn,
2008
- _this = this;
1950
+ NativeContext.prototype.query = function(id, query) {
1951
+ var cacheKey, lookupFn;
2009
1952
  cacheKey = "" + id + "/" + query.type + " " + (query.args.join(' '));
2010
- if (this.queryCache.has(cacheKey)) {
2011
- return Thunk.trampoline(cb(this.queryCache.get(cacheKey)));
2012
- }
2013
1953
  lookupFn = this.externalLookup;
2014
- return lookupFn(id, query, Type, function(err, analysis) {
1954
+ return this.queryCache.cache(cacheKey, function() {
2015
1955
  var result;
2016
- result = err ? TypeLookup.error(err) : TypeLookup.response(query, analysis);
2017
- _this.queryCache.set(cacheKey, result);
2018
- return Thunk.trampoline(cb(result));
1956
+ result = lookupFn(id, query, Type);
1957
+ if (result.success) {
1958
+ return TypeLookup.response(query, result.analysis);
1959
+ } else {
1960
+ return TypeLookup.error(result.error);
1961
+ }
2019
1962
  });
2020
1963
  };
2021
1964
 
@@ -2025,14 +1968,14 @@ analyze = Gibbon.analyze = (function() {
2025
1968
  Scope = (function() {
2026
1969
  var makeKey;
2027
1970
 
2028
- Scope.global = function(context, frame) {
2029
- return new Scope(null, [], frame, context, new Hash);
1971
+ Scope.global = function(context, defs) {
1972
+ return new Scope(null, [], defs, context, new Hash);
2030
1973
  };
2031
1974
 
2032
- function Scope(parent, breadcrumbs, frame, context, metadata) {
1975
+ function Scope(parent, breadcrumbs, definitions, context, metadata) {
2033
1976
  this.parent = parent;
2034
1977
  this.breadcrumbs = breadcrumbs;
2035
- this.frame = frame;
1978
+ this.definitions = definitions;
2036
1979
  this.context = context;
2037
1980
  this.metadata = metadata;
2038
1981
  this.bindings = new Hash;
@@ -2040,20 +1983,20 @@ analyze = Gibbon.analyze = (function() {
2040
1983
  }
2041
1984
 
2042
1985
  Scope.prototype.extend = function(definition) {
2043
- var breadcrumbs, frame, key, metadata, text, _i, _len, _ref10, _ref9;
1986
+ var breadcrumbs, definitions, key, metadata, text, _i, _len, _ref10, _ref9;
2044
1987
  breadcrumbs = this.breadcrumbs.concat(definition.name);
2045
- frame = definition.frame;
1988
+ definitions = definition.frame.definitions;
2046
1989
  metadata = new Hash;
2047
1990
  _ref9 = definition.metadata;
2048
1991
  for (_i = 0, _len = _ref9.length; _i < _len; _i++) {
2049
1992
  _ref10 = _ref9[_i], key = _ref10.key, text = _ref10.text;
2050
1993
  metadata.set(key, text);
2051
1994
  }
2052
- return new Scope(this, breadcrumbs, frame, this.context, metadata);
1995
+ return new Scope(this, breadcrumbs, definitions, this.context, metadata);
2053
1996
  };
2054
1997
 
2055
- Scope.prototype.lookup = function(nativeId, query, cb) {
2056
- return this.context.query(nativeId, query, cb);
1998
+ Scope.prototype.lookup = function(nativeId, query) {
1999
+ return this.context.query(nativeId, query);
2057
2000
  };
2058
2001
 
2059
2002
  Scope.prototype.lexicalLookup = function(name) {
@@ -2079,20 +2022,21 @@ analyze = Gibbon.analyze = (function() {
2079
2022
  };
2080
2023
 
2081
2024
  Scope.prototype.analyze = function(push) {
2082
- var def, frame, frameScope, global, _i, _len, _ref9,
2025
+ var def, framePush, frameScope, global, _i, _len, _ref9, _results,
2083
2026
  _this = this;
2084
- _ref9 = this.frame.definitions;
2027
+ global = TypeExpr["native"](this.context.globalID);
2028
+ _ref9 = this.definitions;
2029
+ _results = [];
2085
2030
  for (_i = 0, _len = _ref9.length; _i < _len; _i++) {
2086
2031
  def = _ref9[_i];
2087
- frameScope = this.extend(def);
2032
+ frameScope = this.bindings.set(def.name, this.extend(def));
2088
2033
  frameScope.analyze(push);
2089
- this.bindings.set(def.name, frameScope);
2034
+ framePush = function(lhs, rhs) {
2035
+ return push(frameScope, def.frame, [lhs, rhs]);
2036
+ };
2037
+ _results.push(frameScope.analyzeFlow(def.frame.flow, global, framePush));
2090
2038
  }
2091
- global = TypeExpr["native"](this.context.globalID);
2092
- frame = this.frame;
2093
- return this.analyzeFlow(this.frame.flow, global, function(lhs, rhs) {
2094
- return push(_this, [lhs, rhs]);
2095
- });
2039
+ return _results;
2096
2040
  };
2097
2041
 
2098
2042
  Scope.prototype.analyzeFlow = function(flow, global, push) {
@@ -2186,13 +2130,14 @@ analyze = Gibbon.analyze = (function() {
2186
2130
  return function(globalID, externalLookup, program) {
2187
2131
  var constraintMap, context, scope;
2188
2132
  context = new NativeContext(globalID, externalLookup);
2189
- scope = Scope.global(context, program);
2133
+ scope = Scope.global(context, program.definitions);
2190
2134
  constraintMap = new Hash;
2191
- scope.analyze(function(scope, constraint) {
2135
+ scope.analyze(function(scope, frame, constraint) {
2192
2136
  var entry;
2193
2137
  entry = constraintMap.cache(scope.key(), function() {
2194
2138
  return {
2195
2139
  scope: scope,
2140
+ frame: frame,
2196
2141
  constraints: []
2197
2142
  };
2198
2143
  });
@@ -2202,7 +2147,8 @@ analyze = Gibbon.analyze = (function() {
2202
2147
  };
2203
2148
  })();
2204
2149
  solve = (function() {
2205
- var TypeError, consume, _ref9;
2150
+ var SolveState, Solver, TypeError, _ref9;
2151
+
2206
2152
  TypeError = (function(_super) {
2207
2153
  __extends(TypeError, _super);
2208
2154
 
@@ -2246,364 +2192,429 @@ analyze = Gibbon.analyze = (function() {
2246
2192
  return TypeError;
2247
2193
 
2248
2194
  })(Variant);
2249
-
2250
- consume = function(array, next, body) {
2251
- var loop_, push;
2252
- push = function(x, y) {
2253
- return array.push([x, y]);
2195
+ SolveState = (function() {
2196
+ function SolveState(constraintMap) {
2197
+ this.constraintMap = constraintMap;
2198
+ this.locks = new Hash;
2199
+ this.crumbs = [];
2200
+ this.errors = [];
2201
+ this.semantics = new Hash;
2202
+ }
2203
+
2204
+ SolveState.prototype.solved = function(key, semantic) {
2205
+ return this.semantics.set(key, semantic);
2206
+ };
2207
+
2208
+ SolveState.prototype.solverFor = function(key) {
2209
+ return new Solver(this, key);
2210
+ };
2211
+
2212
+ SolveState.prototype.solveKey = function(key) {
2213
+ if (this.semantics.has(key)) {
2214
+ return TypeExpr.fromType(this.semantics.get(key).flow.type);
2215
+ }
2216
+ return this.solverFor(key).solve();
2254
2217
  };
2255
- loop_ = function() {
2256
- var lhs, rhs, _ref10;
2257
- if (!(array.length > 0)) {
2258
- return next();
2218
+
2219
+ SolveState.prototype.solveAll = function() {
2220
+ var key, _i, _len, _ref10;
2221
+
2222
+ _ref10 = this.constraintMap.keys();
2223
+ for (_i = 0, _len = _ref10.length; _i < _len; _i++) {
2224
+ key = _ref10[_i];
2225
+ this.solveKey(key);
2259
2226
  }
2260
- _ref10 = array.pop(), lhs = _ref10[0], rhs = _ref10[1];
2261
- return body(lhs, rhs, push, function() {
2262
- return new Thunk(loop_);
2227
+ if (this.errors.length === 0) {
2228
+ return {
2229
+ success: true,
2230
+ semantics: this.semantics
2231
+ };
2232
+ } else {
2233
+ return {
2234
+ success: false,
2235
+ errors: this.errors
2236
+ };
2237
+ }
2238
+ };
2239
+
2240
+ return SolveState;
2241
+
2242
+ })();
2243
+ Solver = (function() {
2244
+ function Solver(state, key) {
2245
+ var entry;
2246
+ this.state = state;
2247
+ this.key = key;
2248
+ entry = this.state.constraintMap.get(this.key);
2249
+ this.scope = entry.scope;
2250
+ this.frame = entry.frame;
2251
+ this.constraints = entry.constraints.reverse();
2252
+ this.dependencies = [];
2253
+ this.solutions = new ObjHash;
2254
+ this.queryResults = new ObjHash;
2255
+ }
2256
+
2257
+ Solver.prototype.error = function() {
2258
+ var args, type;
2259
+ type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
2260
+ this.state.errors.push(TypeError[type].apply(TypeError, args));
2261
+ return TypeExpr.any();
2262
+ };
2263
+
2264
+ Solver.prototype.hasErrors = function() {
2265
+ return this.state.errors.length > 0;
2266
+ };
2267
+
2268
+ Solver.prototype.typeOf = function(expr) {
2269
+ if (this.solutions.has(expr)) {
2270
+ return this.solutions.get(expr).realize();
2271
+ }
2272
+ return expr.cases({
2273
+ expr: function() {
2274
+ throw new Error('unsolved!');
2275
+ },
2276
+ other: function() {
2277
+ return Type.abstract(TypeExpr.expr(expr));
2278
+ }
2263
2279
  });
2264
2280
  };
2265
- return Thunk.trampoline(loop_());
2266
- };
2267
- return function(constraintMap, finish) {
2268
- var errors, frameTypes, initialCrumbs, k, locks, semantics, solutions, solveEntry;
2269
- errors = [];
2270
- solutions = new ObjHash;
2271
- semantics = new Hash;
2272
- frameTypes = new Hash;
2273
- locks = new Hash;
2274
- solveEntry = function(crumbs, solved) {
2275
- var constraints, dependencies, done, error, frame, fullSubstitute, key, nextCrumbs, scope, semanticAccessors, simplify, substitute, _ref10;
2276
- key = crumbs[crumbs.length - 1];
2277
- if (semantics.has(key)) {
2278
- return solved();
2281
+
2282
+ Solver.prototype.makeSemantic = function(expr) {
2283
+ var _this = this;
2284
+ return expr.cases({
2285
+ frame: function(_, __, flow) {
2286
+ return Semantic.definition(_this.dependencies, _this.makeSemantic(flow), _this.scope.metadata);
2287
+ },
2288
+ flow: function(_, head, tail) {
2289
+ return Semantic.flow(_this.typeOf(TypeExpr.expr(expr)), _this.makeSemantic(head), tail && _this.makeSemantic(tail));
2290
+ },
2291
+ query: function(_, type, name) {
2292
+ if (!(_this.hasErrors() || _this.queryResults.has(expr))) {
2293
+ throw "panic: unsolved query with no errors!";
2294
+ }
2295
+ return _this.queryResults.get(expr);
2296
+ },
2297
+ lexical: function(_, name) {
2298
+ return _this.queryResults.get(expr);
2299
+ },
2300
+ func: function(_, name, args) {
2301
+ var a, semArgs, solvedScope, typeScope;
2302
+ typeScope = expr.__scope__;
2303
+ solvedScope = new Hash;
2304
+ typeScope && typeScope.each(function(name, texpr) {
2305
+ return solvedScope.set(name, _this.typeOf(texpr));
2306
+ });
2307
+ semArgs = (function() {
2308
+ var _i, _len, _results;
2309
+ _results = [];
2310
+ for (_i = 0, _len = args.length; _i < _len; _i++) {
2311
+ a = args[_i];
2312
+ _results.push(this.makeSemantic(a));
2313
+ }
2314
+ return _results;
2315
+ }).call(_this);
2316
+ return Semantic.func(name, semArgs, solvedScope);
2317
+ },
2318
+ pair: function(_, first, second) {
2319
+ return Semantic.pair(_this.makeSemantic(first), _this.makeSemantic(second));
2320
+ },
2321
+ block: function(_, flow) {
2322
+ return Semantic.block(_this.makeSemantic(flow));
2323
+ },
2324
+ subst: function(_, subFlow) {
2325
+ return _this.makeSemantic(subFlow);
2326
+ },
2327
+ list: function(_, elements, squish) {
2328
+ var e;
2329
+ return Semantic.list((function() {
2330
+ var _i, _len, _results;
2331
+ _results = [];
2332
+ for (_i = 0, _len = elements.length; _i < _len; _i++) {
2333
+ e = elements[_i];
2334
+ _results.push(this.makeSemantic(e));
2335
+ }
2336
+ return _results;
2337
+ }).call(_this), squish);
2338
+ },
2339
+ defaulted: function(_, body, alt) {
2340
+ return Semantic.defaulted(_this.makeSemantic(body), _this.makeSemantic(alt));
2341
+ },
2342
+ integer: function() {
2343
+ return Semantic.literal(this);
2344
+ },
2345
+ decimal: function() {
2346
+ return Semantic.literal(this);
2347
+ },
2348
+ percent: function() {
2349
+ return Semantic.literal(this);
2350
+ },
2351
+ fraction: function() {
2352
+ return Semantic.literal(this);
2353
+ },
2354
+ string: function() {
2355
+ return Semantic.literal(this);
2356
+ }
2357
+ });
2358
+ };
2359
+
2360
+ Solver.prototype.lookup = function(scope, id, query) {
2361
+ var lookup,
2362
+ _this = this;
2363
+ lookup = scope.lookup(id, query);
2364
+ this.dependencies.push(lookup);
2365
+ return lookup.cases({
2366
+ error: function(e) {
2367
+ return _this.error('lookup', query, id, e);
2368
+ },
2369
+ response: function(_, analysis) {
2370
+ _this.queryResults.set(query, Semantic.query({
2371
+ annotations: analysis.annotations,
2372
+ type: analysis.type.toSexpr()
2373
+ }));
2374
+ return TypeExpr.fromType(analysis.type);
2375
+ }
2376
+ });
2377
+ };
2378
+
2379
+ Solver.prototype.lexicalLookup = function(syntax, scope) {
2380
+ var lookupKey;
2381
+ lookupKey = scope.lexicalLookup(syntax.name);
2382
+ if (!lookupKey) {
2383
+ return this.error('lexical', name, scope);
2279
2384
  }
2280
- nextCrumbs = crumbs.concat([key]);
2281
- _ref10 = constraintMap.get(key), scope = _ref10.scope, constraints = _ref10.constraints;
2282
- frame = scope.frame;
2385
+ this.queryResults.set(syntax, Semantic.localAccessor(lookupKey));
2386
+ this.dependencies.push(TypeLookup.local(lookupKey));
2387
+ return this.state.solveKey(lookupKey);
2388
+ };
2389
+
2390
+ Solver.prototype.resolve = function(expr) {
2391
+ var _this = this;
2392
+ return expr.cases({
2393
+ error: function(type, args) {
2394
+ return _this.error.apply(_this, [type].concat(__slice.call(args)));
2395
+ },
2396
+ destructure: function(constraint, name, argnum) {
2397
+ return _this.resolve(constraint).cases({
2398
+ param: function(paramName, paramArgs) {
2399
+ if (paramName === name) {
2400
+ return paramArgs[argnum];
2401
+ } else {
2402
+ return _this.error('destructure', expr);
2403
+ }
2404
+ },
2405
+ other: function() {
2406
+ return _this.error('destructure', expr);
2407
+ }
2408
+ });
2409
+ },
2410
+ lexical: function(syntax, scope) {
2411
+ return _this.lexicalLookup(syntax, scope);
2412
+ },
2413
+ query: function(input, scope, query) {
2414
+ return _this.resolve(input).cases({
2415
+ "native": function(id) {
2416
+ return _this.lookup(scope, id, query);
2417
+ },
2418
+ other: function() {
2419
+ return expr;
2420
+ }
2421
+ });
2422
+ },
2423
+ other: function() {
2424
+ return expr.map(function(e) {
2425
+ return _this.resolve(e);
2426
+ });
2427
+ }
2428
+ });
2429
+ };
2430
+
2431
+ Solver.prototype.substitute = function(texpr) {
2432
+ var _this = this;
2433
+ return this.solutions.fetch(texpr, function() {
2434
+ return texpr.map(function(e) {
2435
+ return _this.substitute(e);
2436
+ });
2437
+ });
2438
+ };
2439
+
2440
+ Solver.prototype.fullSubstitute = function(texpr) {
2441
+ var resolved, substituted;
2442
+ substituted = this.substitute(texpr);
2443
+ resolved = this.resolve(substituted);
2283
2444
 
2284
- locks.set(key, true);
2285
- semanticAccessors = new ObjHash;
2286
- dependencies = [];
2445
+ return resolved;
2446
+ };
2447
+
2448
+ Solver.prototype.addSolution = function(lhs, rhs) {
2449
+ var _this = this;
2450
+
2451
+ this.solutions.set(lhs, rhs);
2452
+ return this.solutions.each(function(k, texpr) {
2453
+ return _this.solutions.set(k, _this.fullSubstitute(texpr));
2454
+ });
2455
+ };
2456
+
2457
+ Solver.prototype.processPair = function(lhs, rhs) {
2458
+ var log, matchError, push, solveFor, swap,
2459
+ _this = this;
2287
2460
 
2288
- substitute = function(texpr, cb) {
2289
- if (solutions.has(texpr)) {
2290
- return cb(solutions.get(texpr));
2461
+ push = function(newLhs, newRhs) {
2462
+ return _this.constraints.push([newLhs, newRhs]);
2463
+ };
2464
+ solveFor = function() {
2465
+ rhs = _this.fullSubstitute(rhs);
2466
+ if (_this.solutions.has(lhs)) {
2467
+ return push(_this.solutions.get(lhs), rhs);
2291
2468
  } else {
2292
- return texpr.mapAsync(substitute, cb);
2469
+ return _this.addSolution(lhs, rhs);
2293
2470
  }
2294
2471
  };
2295
- fullSubstitute = function(texpr, cb) {
2296
- return substitute(texpr, function(substituted) {
2297
- return simplify(substituted, function(result) {
2298
-
2299
- return cb(result);
2300
- });
2301
- });
2472
+ log = function() {
2473
+ return DEBUG.logConstraint('?> ', lhs, rhs);
2302
2474
  };
2303
- error = function() {
2304
- var args, type;
2305
- type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
2306
- errors.push(TypeError[type].apply(TypeError, args));
2307
- return TypeExpr.any();
2475
+ swap = function() {
2476
+ return push(rhs, lhs);
2308
2477
  };
2309
- simplify = function(expr, cb) {
2310
- return expr.cases({
2311
- error: function(type, args) {
2312
- return cb(error.apply(null, [type].concat(__slice.call(args))));
2313
- },
2314
- destructure: function(constraint, name, argnum) {
2315
- var destructured;
2316
- destructured = this;
2317
- return simplify(constraint, function(x) {
2318
- return cb(x.cases({
2319
- param: function(paramName, paramArgs) {
2320
- if (paramName === name) {
2321
- return paramArgs[argnum];
2322
- } else {
2323
- return error('destructure', this);
2324
- }
2325
- },
2326
- other: function() {
2327
- return error('destructure', this);
2328
- }
2329
- }));
2330
- });
2331
- },
2332
- lexical: function(syntax, scope) {
2333
- var lookupKey;
2334
- lookupKey = scope.lexicalLookup(syntax.name);
2335
- if (!lookupKey) {
2336
- return cb(error('lexical', name, scope));
2337
- }
2338
- semanticAccessors.set(syntax, Semantic.localAccessor(lookupKey));
2339
- dependencies.push(TypeLookup.local(lookupKey));
2340
- nextCrumbs = crumbs.concat([lookupKey]);
2341
- if (locks.get(lookupKey)) {
2342
- return cb(error('circular', nextCrumbs));
2343
- }
2344
- return new Thunk(function() {
2345
- return solveEntry(nextCrumbs, function() {
2346
- return new Thunk(function() {
2347
- return cb(frameTypes.get(lookupKey));
2348
- });
2349
- });
2350
- });
2351
- },
2352
- query: function(input, scope, query) {
2353
- return simplify(input, function(x) {
2354
- return x.cases({
2355
- "native": function(id) {
2356
- return scope.lookup(id, query, function(lookup) {
2357
- dependencies.push(lookup);
2358
- return lookup.cases({
2359
- error: function(e) {
2360
- return cb(error('lookup', query, id, e));
2361
- },
2362
- response: function(_, analysis) {
2363
- semanticAccessors.set(query, Semantic.query({
2364
- annotations: analysis.annotations,
2365
- type: analysis.type.toSexpr()
2366
- }));
2367
- return cb(TypeExpr.fromType(analysis.type));
2368
- }
2369
- });
2370
- });
2371
- },
2372
- other: function() {
2373
- return cb(expr);
2374
- }
2375
- });
2376
- });
2377
- },
2378
- other: function() {
2379
- return this.mapAsync(simplify, cb);
2380
- }
2381
- });
2478
+ matchError = function() {
2479
+
2480
+ return _this.error('match', lhs, rhs);
2382
2481
  };
2383
- done = function() {
2384
- var flowType, toSemanticTree;
2385
- flowType = function(expr) {
2386
- if (!solutions.has(expr)) {
2387
- if (errors.length === 0 && expr._tag === 'expr') {
2388
- throw new Error('unsolved!');
2389
- }
2390
- return Type.abstract(TypeExpr.expr(expr));
2391
- }
2392
- return solutions.get(expr).realize();
2393
- };
2394
- toSemanticTree = function(expr) {
2395
- return expr.cases({
2396
- frame: function(_, __, flow) {
2397
- return Semantic.definition(dependencies, toSemanticTree(flow), scope.metadata);
2398
- },
2399
- flow: function(_, head, tail) {
2400
- return Semantic.flow(flowType(TypeExpr.expr(this)), toSemanticTree(head), tail && toSemanticTree(tail));
2401
- },
2402
- query: function(_, type, name) {
2403
- if (!(errors.length || semanticAccessors.has(this))) {
2404
- throw "unsolved with no errors!";
2482
+ if ('any' === rhs._tag || 'any' === lhs._tag) {
2483
+ return;
2484
+ }
2485
+ if (lhs.equals(rhs)) {
2486
+ return;
2487
+ }
2488
+ return lhs.cases({
2489
+ expr: solveFor,
2490
+ variable: solveFor,
2491
+ query: function() {
2492
+ return rhs.cases({
2493
+ expr: swap,
2494
+ variable: swap,
2495
+ param: swap,
2496
+ other: log
2497
+ });
2498
+ },
2499
+ "native": function(id) {
2500
+ return rhs.cases({
2501
+ variable: swap,
2502
+ expr: swap,
2503
+ "native": function(otherId) {
2504
+ if (id !== otherId) {
2505
+ return matchError();
2405
2506
  }
2406
- return semanticAccessors.get(this);
2407
- },
2408
- lexical: function(_, name) {
2409
- return semanticAccessors.get(this);
2410
- },
2411
- func: function(_, name, args) {
2412
- var a, semArgs, solvedScope, typeScope;
2413
- typeScope = this.__scope__;
2414
- solvedScope = new Hash;
2415
- typeScope && typeScope.each(function(name, texpr) {
2416
- return solvedScope.set(name, flowType(texpr));
2417
- });
2418
- semArgs = (function() {
2419
- var _i, _len, _results;
2420
- _results = [];
2421
- for (_i = 0, _len = args.length; _i < _len; _i++) {
2422
- a = args[_i];
2423
- _results.push(toSemanticTree(a));
2424
- }
2425
- return _results;
2426
- })();
2427
- return Semantic.func(name, semArgs, solvedScope);
2428
2507
  },
2429
- pair: function(_, first, second) {
2430
- return Semantic.pair(toSemanticTree(first), toSemanticTree(second));
2431
- },
2432
- block: function(_, flow) {
2433
- return Semantic.block(toSemanticTree(flow));
2434
- },
2435
- subst: function(_, subFlow) {
2436
- return toSemanticTree(subFlow);
2437
- },
2438
- list: function(_, elements, squish) {
2439
- var e;
2440
- return Semantic.list((function() {
2441
- var _i, _len, _results;
2442
- _results = [];
2443
- for (_i = 0, _len = elements.length; _i < _len; _i++) {
2444
- e = elements[_i];
2445
- _results.push(toSemanticTree(e));
2446
- }
2447
- return _results;
2448
- })(), squish);
2449
- },
2450
- defaulted: function(_, body, alt) {
2451
- return Semantic.defaulted(toSemanticTree(body), toSemanticTree(alt));
2452
- },
2453
- integer: function() {
2454
- return Semantic.literal(this);
2455
- },
2456
- decimal: function() {
2457
- return Semantic.literal(this);
2458
- },
2459
- percent: function() {
2460
- return Semantic.literal(this);
2508
+ query: swap,
2509
+ other: matchError
2510
+ });
2511
+ },
2512
+ param: function() {
2513
+ return rhs.cases({
2514
+ param: function() {
2515
+ var constraint, i, _i, _len, _ref10, _results;
2516
+ if (lhs.name !== rhs.name) {
2517
+ return matchError();
2518
+ }
2519
+ _ref10 = lhs.constraints;
2520
+ _results = [];
2521
+ for (i = _i = 0, _len = _ref10.length; _i < _len; i = ++_i) {
2522
+ constraint = _ref10[i];
2523
+ _results.push(push(constraint, rhs.constraints[i]));
2524
+ }
2525
+ return _results;
2461
2526
  },
2462
- fraction: function() {
2463
- return Semantic.literal(this);
2527
+ query: function() {
2528
+ var c, i, _i, _len, _ref10, _results;
2529
+ _ref10 = lhs.constraints;
2530
+ _results = [];
2531
+ for (i = _i = 0, _len = _ref10.length; _i < _len; i = ++_i) {
2532
+ c = _ref10[i];
2533
+ _results.push(push(c, TypeExpr.destructure(rhs, lhs.type, i)));
2534
+ }
2535
+ return _results;
2464
2536
  },
2465
- string: function() {
2466
- return Semantic.literal(this);
2467
- }
2537
+ expr: swap,
2538
+ variable: swap,
2539
+ other: matchError
2468
2540
  });
2469
- };
2470
-
2541
+ },
2542
+ other: log
2543
+ });
2544
+ };
2545
+
2546
+ Solver.prototype.registeredType = function() {
2547
+ if (!this.state.semantics.has(this.key)) {
2548
+ return null;
2549
+ }
2550
+ return TypeExpr.fromType(this.state.semantics.get(this.key).flow.type);
2551
+ };
2552
+
2553
+ Solver.prototype.register = function() {
2554
+
2555
+ return this.state.semantics.set(this.key, this.makeSemantic(this.frame));
2556
+ };
2557
+
2558
+ Solver.prototype.setLock = function() {
2559
+
2560
+ return this.state.locks.set(this.key, true);
2561
+ };
2562
+
2563
+ Solver.prototype.clearLock = function() {
2564
+
2565
+ return this.state.locks.set(this.key, false);
2566
+ };
2567
+
2568
+ Solver.prototype.isLocked = function() {
2569
+ return this.state.locks.get(this.key);
2570
+ };
2571
+
2572
+ Solver.prototype.withLock = function(fn) {
2573
+ var result;
2574
+ this.state.crumbs.push(this.key);
2575
+ if (this.isLocked()) {
2576
+ result = this.error('circular', this.state.crumbs.slice());
2577
+ } else {
2578
+ this.setLock();
2579
+ result = fn(this);
2580
+ this.clearLock();
2581
+ }
2582
+ this.state.crumbs.pop();
2583
+ return result;
2584
+ };
2585
+
2586
+ Solver.prototype.solve = function() {
2587
+ var _this = this;
2588
+ return this.withLock(function() {
2589
+ var lhs, rhs, _ref10;
2471
2590
 
2472
- if (!errors.length) {
2473
- semantics.set(key, toSemanticTree(frame));
2591
+ while (_this.constraints.length > 0) {
2592
+ _ref10 = _this.constraints.pop(), lhs = _ref10[0], rhs = _ref10[1];
2593
+ _this.processPair(lhs, rhs);
2474
2594
  }
2475
- frameTypes.set(key, solutions.get(TypeExpr.expr(frame.flow)));
2476
-
2477
- locks.set(key, false);
2478
- return solved();
2479
- };
2480
- return consume(constraints.reverse(), done, function(lhs, rhs, push, next) {
2481
- var log, matchError, skip, solveFor, swap;
2482
2595
 
2483
- if (lhs.equals(rhs)) {
2484
- return next();
2596
+ if (!_this.hasErrors()) {
2597
+ _this.register();
2485
2598
  }
2486
- solveFor = function() {
2487
- return fullSubstitute(rhs, function(rhs) {
2488
- var mapper;
2489
- if (solutions.has(lhs)) {
2490
- push(solutions.get(lhs), rhs);
2491
- return next();
2492
- } else {
2493
-
2494
- solutions.set(lhs, rhs);
2495
- mapper = function(k, texpr, cb) {
2496
- return fullSubstitute(texpr, (function(s) {
2497
- solutions.set(k, s);
2498
- return cb();
2499
- }));
2500
- };
2501
- return solutions.eachAsync(mapper, next);
2502
- }
2503
- });
2504
- };
2505
- log = function() {
2506
-
2507
- return next();
2508
- };
2509
- skip = function() {
2510
- return next();
2511
- };
2512
- swap = function() {
2513
- push(rhs, lhs);
2514
- return next();
2515
- };
2516
- matchError = function() {
2517
-
2518
- error('match', lhs, rhs);
2519
- return next();
2520
- };
2521
- if ('any' === rhs._tag || 'any' === lhs._tag) {
2522
- return next();
2523
- }
2524
- return lhs.cases({
2525
- expr: solveFor,
2526
- variable: solveFor,
2527
- query: function() {
2528
- return rhs.cases({
2529
- expr: swap,
2530
- variable: swap,
2531
- param: swap,
2532
- other: log
2533
- });
2534
- },
2535
- "native": function(id) {
2536
- return rhs.cases({
2537
- variable: swap,
2538
- expr: swap,
2539
- "native": function(otherId) {
2540
- if (id === otherId) {
2541
- return skip();
2542
- } else {
2543
- return matchError();
2544
- }
2545
- },
2546
- other: matchError
2547
- });
2548
- },
2549
- param: function() {
2550
- return rhs.cases({
2551
- param: function() {
2552
- var constraint, i, _i, _len, _ref11;
2553
- if (lhs.name !== rhs.name) {
2554
- return matchError();
2555
- }
2556
- _ref11 = lhs.constraints;
2557
- for (i = _i = 0, _len = _ref11.length; _i < _len; i = ++_i) {
2558
- constraint = _ref11[i];
2559
- push(constraint, rhs.constraints[i]);
2560
- }
2561
- return next();
2562
- },
2563
- query: function() {
2564
- var c, i, _i, _len, _ref11;
2565
- _ref11 = lhs.constraints;
2566
- for (i = _i = 0, _len = _ref11.length; _i < _len; i = ++_i) {
2567
- c = _ref11[i];
2568
- push(c, TypeExpr.destructure(rhs, lhs.type, i));
2569
- }
2570
- return next();
2571
- },
2572
- expr: swap,
2573
- variable: swap,
2574
- other: matchError
2575
- });
2576
- },
2577
- other: log
2599
+ return _this.solutions.fetch(TypeExpr.expr(_this.frame.flow), function() {
2600
+ return TypeExpr.any();
2578
2601
  });
2579
2602
  });
2580
2603
  };
2581
- initialCrumbs = (function() {
2582
- var _i, _len, _ref10, _results;
2583
- _ref10 = constraintMap.keys();
2584
- _results = [];
2585
- for (_i = 0, _len = _ref10.length; _i < _len; _i++) {
2586
- k = _ref10[_i];
2587
- _results.push([k]);
2588
- }
2589
- return _results;
2590
- })();
2591
-
2592
- return contMap(initialCrumbs, solveEntry, function() {
2593
- if (errors.length === 0) {
2594
- return finish(null, semantics);
2595
- } else {
2596
- return finish(errors);
2597
- }
2598
- });
2604
+
2605
+ return Solver;
2606
+
2607
+ })();
2608
+ return function(constraintMap) {
2609
+ return new SolveState(constraintMap).solveAll();
2599
2610
  };
2600
2611
  })();
2601
- return function(program, globalID, external, cb) {
2612
+ return function(program, globalID, external) {
2602
2613
  var constraints;
2603
2614
 
2604
2615
 
2605
2616
  constraints = generate(globalID, external.analyzeQuery, program);
2606
- return solve(constraints, cb);
2617
+ return solve(constraints);
2607
2618
  };
2608
2619
  })();
2609
2620
 
@@ -3265,8 +3276,8 @@ Gibbon.Core = Core = (function(_super) {
3265
3276
 
3266
3277
  })(Variant);
3267
3278
 
3268
- Gibbon.translate = (function() {
3269
- var translate;
3279
+ Gibbon.translate = function(semantics) {
3280
+ var translate, translated;
3270
3281
  translate = function(semantic, input, context) {
3271
3282
  if (input == null) {
3272
3283
  input = Core.global();
@@ -3289,7 +3300,15 @@ Gibbon.translate = (function() {
3289
3300
  return input.query(annotations);
3290
3301
  },
3291
3302
  localAccessor: function(key) {
3292
- return Core.localQuery(key);
3303
+ var definition;
3304
+ definition = semantics.get(key) || (function() {
3305
+ throw "panic: invalid reference";
3306
+ })();
3307
+ if (definition.metadata.has('export')) {
3308
+ return translate(definition, Core.global());
3309
+ } else {
3310
+ return Core.localQuery(key);
3311
+ }
3293
3312
  },
3294
3313
  func: function(name, args, tvars) {
3295
3314
  var arg, compArgs;
@@ -3337,10 +3356,12 @@ Gibbon.translate = (function() {
3337
3356
  }
3338
3357
  });
3339
3358
  };
3340
- return function(semantic) {
3341
- return translate(semantic);
3342
- };
3343
- })();
3359
+ translated = new Hash;
3360
+ semantics.each(function(key, semantic) {
3361
+ return translated.set(key, translate(semantic));
3362
+ });
3363
+ return translated;
3364
+ };
3344
3365
 
3345
3366
  Gibbon.optimize = (function() {
3346
3367
  var insertBindings, partialEval, uncachedPartialEval;
@@ -3380,15 +3401,21 @@ Gibbon.optimize = (function() {
3380
3401
  });
3381
3402
  },
3382
3403
  branch: function(cond, ifTrue, ifFalse) {
3383
- var abort;
3404
+ var abort,
3405
+ _this = this;
3384
3406
  cond = recurse(cond);
3385
3407
  abort = function() {
3408
+ var _ref10;
3386
3409
  ifTrue = recurse(ifTrue);
3387
3410
  ifFalse = recurse(ifFalse);
3388
3411
  if (ifTrue.equals(ifFalse)) {
3389
3412
 
3390
3413
  return ifTrue;
3391
3414
  }
3415
+ if (ifTrue._tag === 'constant' && ifFalse._tag === 'constant' && ((_ref10 = ifTrue.value) === true || _ref10 === false)) {
3416
+
3417
+ return (ifTrue.value ? cond : recurse(cond.op1('!')));
3418
+ }
3392
3419
  return cond.branch(ifTrue, ifFalse);
3393
3420
  };
3394
3421
  return cond.cases({
@@ -6003,6 +6030,18 @@ stdlib = Gibbon.stdlib = (function() {
6003
6030
  obj = _arg[0];
6004
6031
  return equals(input, obj, tvars.get('a')).op1('!');
6005
6032
  }
6033
+ },
6034
+ t: {
6035
+ type: parse.type('t = % -> bool'),
6036
+ compile: function() {
6037
+ return TRUE;
6038
+ }
6039
+ },
6040
+ f: {
6041
+ type: parse.type('f = % -> bool'),
6042
+ compile: function() {
6043
+ return FALSE;
6044
+ }
6006
6045
  }
6007
6046
  };
6008
6047
  })();
@@ -6434,9 +6473,6 @@ Gibbon.CompiledCode = CompiledCode = (function() {
6434
6473
 
6435
6474
  CompiledCode.prototype.outputType = function(key) {
6436
6475
  var e, type;
6437
- if (key == null) {
6438
- key = '/';
6439
- }
6440
6476
  try {
6441
6477
  type = this.semantics.get(key).flow.type;
6442
6478
  if (type == null) {
@@ -6457,11 +6493,12 @@ Gibbon.CompiledCode = CompiledCode = (function() {
6457
6493
  })();
6458
6494
 
6459
6495
  Gibbon.compile = function(semantics) {
6460
- var codegen, compiled, optimize, reduce, sequence, translate;
6496
+ var codegen, compiled, optimize, reduce, sequence, translate, translated;
6461
6497
  codegen = Gibbon.codegen, reduce = Gibbon.reduce, sequence = Gibbon.sequence, optimize = Gibbon.optimize, translate = Gibbon.translate;
6462
6498
  compiled = new Hash;
6463
- semantics.each(function(k, v) {
6464
- return compiled.set(k, codegen(reduce(sequence(optimize(translate(v))))).block.toJS());
6499
+ translated = translate(semantics);
6500
+ translated.each(function(k, v) {
6501
+ return compiled.set(k, codegen(reduce(sequence(optimize(v)))).block.toJS());
6465
6502
  });
6466
6503
  return new CompiledCode(semantics, compiled);
6467
6504
  };
@@ -6893,11 +6930,12 @@ Gibbon.compileRuby = (function() {
6893
6930
  });
6894
6931
  };
6895
6932
  return function(semantics) {
6896
- var key, keys, optimize, out, processKey, seen, translate, _i, _len;
6933
+ var key, keys, optimize, out, processKey, seen, translate, translated, _i, _len;
6897
6934
  optimize = Gibbon.optimize, translate = Gibbon.translate;
6898
6935
  keys = semantics.keys();
6899
6936
  seen = new Hash;
6900
6937
  out = [];
6938
+ translated = translate(semantics);
6901
6939
  processKey = function(key) {
6902
6940
  var compiledRuby, dep, _i, _len, _ref20;
6903
6941
  if (seen.has(key)) {
@@ -6911,7 +6949,7 @@ Gibbon.compileRuby = (function() {
6911
6949
  processKey(dep.name);
6912
6950
  }
6913
6951
  }
6914
- compiledRuby = compileCore(optimize(translate(semantics.get(key))), null, key).toRuby();
6952
+ compiledRuby = compileCore(optimize(translated.get(key)), null, key).toRuby();
6915
6953
  return out.push("" + (idForLocal(key)) + " = begin\n {:status=>:success,:value=>(" + compiledRuby + ")}\nrescue E => e\n {:status=>:failure,:error=>e}\nend");
6916
6954
  };
6917
6955
  for (_i = 0, _len = keys.length; _i < _len; _i++) {
@@ -6929,6 +6967,7 @@ Gibbon.compileRuby = (function() {
6929
6967
  return _results;
6930
6968
  })()).join(','));
6931
6969
  out.push('}');
6970
+
6932
6971
  return out.join("\n");
6933
6972
  };
6934
6973
  })();
@@ -6939,19 +6978,28 @@ Gibbon.jsonConsumer = (function() {
6939
6978
  getType = function(id, accessorName, t, callback) {
6940
6979
  var fields;
6941
6980
  if (!tables.hasOwnProperty(id)) {
6942
- return callback(new Error("no such type " + id));
6981
+ return {
6982
+ success: false,
6983
+ error: new Error("no such type " + id)
6984
+ };
6943
6985
  }
6944
6986
  fields = tables[id].fields;
6945
6987
  if (!fields.hasOwnProperty(accessorName)) {
6946
- return callback(new Error("" + id + " has no field " + accessorName));
6988
+ return {
6989
+ success: false,
6990
+ error: new Error("" + id + " has no field " + accessorName)
6991
+ };
6947
6992
  }
6948
- return callback(null, {
6949
- type: fields[accessorName],
6950
- annotations: {
6951
- name: accessorName,
6952
- table: id
6993
+ return {
6994
+ success: true,
6995
+ analysis: {
6996
+ type: fields[accessorName],
6997
+ annotations: {
6998
+ name: accessorName,
6999
+ table: id
7000
+ }
6953
7001
  }
6954
- });
7002
+ };
6955
7003
  };
6956
7004
  getValue = function(id, annotations, callback) {
6957
7005
  var entity, values;
@@ -6972,18 +7020,27 @@ Gibbon.jsonConsumer = (function() {
6972
7020
  analyzeList = function(id, listName, t, callback) {
6973
7021
  var list;
6974
7022
  if (!lists.hasOwnProperty(listName)) {
6975
- callback(new Error("unkown list `" + listName + "'"));
7023
+ ({
7024
+ success: false,
7025
+ error: new Error("unkown list `" + listName + "'")
7026
+ });
6976
7027
  }
6977
7028
  list = lists[listName];
6978
7029
  if (id !== list.type) {
6979
- callback(new Error("wrong type " + id + " for list `" + listName + "'"));
7030
+ ({
7031
+ success: false,
7032
+ error: new Error("wrong type " + id + " for list `" + listName + "'")
7033
+ });
6980
7034
  }
6981
- return callback(null, {
6982
- type: t.bool(),
6983
- annotations: {
6984
- list: listName
7035
+ return {
7036
+ success: true,
7037
+ analysis: {
7038
+ type: t.bool(),
7039
+ annotations: {
7040
+ list: listName
7041
+ }
6985
7042
  }
6986
- });
7043
+ };
6987
7044
  };
6988
7045
  listLookup = function(id, listName, callback) {
6989
7046
  var list;
@@ -6998,11 +7055,14 @@ Gibbon.jsonConsumer = (function() {
6998
7055
  analyzeQuery: function(id, query, t, callback) {
6999
7056
  switch (query.type) {
7000
7057
  case 'access':
7001
- return getType(id, query.args[0], t, callback);
7058
+ return getType(id, query.args[0], t);
7002
7059
  case 'on':
7003
- return analyzeList(id, query.args[0], t, callback);
7060
+ return analyzeList(id, query.args[0], t);
7004
7061
  default:
7005
- return callback(new Error("unknown query `" + query.type + "'"));
7062
+ return {
7063
+ success: false,
7064
+ error: new Error("unknown query `" + query.type + "'")
7065
+ };
7006
7066
  }
7007
7067
  },
7008
7068
  performQuery: function(id, annotations, callback) {