From 2c8880e75ded1be31e5435f2be1064e6ea55f641 Mon Sep 17 00:00:00 2001 From: Jakub Jankiewicz Date: Sun, 26 Apr 2020 12:20:55 +0200 Subject: [PATCH] Working ellipsis in syntax-rules #43 --- README.md | 6 +- dist/lips.js | 615 ++++++++++++++++++++++++++++++++------ dist/lips.min.js | 4 +- spec/lips.spec.js | 2 +- src/lips.js | 483 +++++++++++++++++++++++++----- test.js | 1 - tests/helpers/helpers.scm | 20 +- tests/syntax.scm | 138 ++++++++- 8 files changed, 1097 insertions(+), 172 deletions(-) diff --git a/README.md b/README.md index a4cddd2a6..7336bee36 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # [LIPS is Pretty Simple](https://jcubic.github.io/lips/) - Scheme based Powerful LISP [![npm](https://img.shields.io/badge/npm-DEV-blue.svg)](https://www.npmjs.com/package/@jcubic/lips) -[![travis](https://travis-ci.org/jcubic/lips.svg?branch=devel&3ce935ba06e3818e9fd8ba76cfa0b9ffbbe385f4)](https://travis-ci.org/jcubic/lips) -[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=devel&e16c39d35b2647b16bfa848e48a6c3bb)](https://coveralls.io/github/jcubic/lips?branch=devel) +[![travis](https://travis-ci.org/jcubic/lips.svg?branch=devel&67a3fe44274ce072a662263b51feb32af399d0ac)](https://travis-ci.org/jcubic/lips) +[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=devel&cc91fde7195a8236554da603afbfdd15)](https://coveralls.io/github/jcubic/lips?branch=devel) LISP is Powerful LISP based on Scheme dialect and R5RS specification. @@ -109,7 +109,7 @@ $ lips | | |___||_||_| <___/ | | \_\ /_/ -LIPS Scheme Interpreter DEV (2020-04-18) +LIPS Scheme Interpreter DEV (2020-04-26) Copyright (c) 2018-2020 Jakub T. Jankiewicz Type (env) to see environment with functions macros and variables. diff --git a/dist/lips.js b/dist/lips.js index 321f4acda..cdfe4ab34 100644 --- a/dist/lips.js +++ b/dist/lips.js @@ -24,7 +24,7 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Sat, 18 Apr 2020 08:38:56 +0000 + * build: Sun, 26 Apr 2020 10:18:59 +0000 */ (function () { 'use strict'; @@ -1139,8 +1139,13 @@ } var banner = function () { + // Rollup tree-shaking is removing the variable if it's normal string because + // obviously 'Sun, 26 Apr 2020 10:18:59 +0000' == '{{' + 'DATE}}'; can be removed + // but disablig Tree-shaking is adding lot of not used code so we use this + // hack instead + var date = LString('Sun, 26 Apr 2020 10:18:59 +0000'); - var _date = new Date() ; + var _date = date.valueOf() === '{{' + 'DATE}}' ? new Date() : new Date(date); var _format = function _format(x) { return x.toString().padStart(2, '0'); @@ -2340,7 +2345,7 @@ function Nil() {} - Nil.prototype.toString = function () { + Nil.prototype.toString = Nil.prototype.toJSON = function () { return '()'; }; @@ -2348,6 +2353,10 @@ return undefined$1; }; + Nil.prototype.append = function (x) { + return new Pair(x, nil); + }; + var nil = new Nil(); // ---------------------------------------------------------------------- // :: Pair constructor // ---------------------------------------------------------------------- @@ -2443,6 +2452,19 @@ }; // ---------------------------------------------------------------------- + Pair.prototype.lastPair = function () { + var node = this; + + while (true) { + if (node.cdr === nil) { + return node; + } + + node = node.cdr; + } + }; // ---------------------------------------------------------------------- + + Pair.prototype.toArray = function () { var result = []; @@ -3010,7 +3032,7 @@ switch (_context.prev = _context.next) { case 0: if (!(node instanceof Pair && node.car instanceof LSymbol)) { - _context.next = 17; + _context.next = 18; break; } @@ -3027,7 +3049,7 @@ }); if (!(value instanceof Macro && value.defmacro)) { - _context.next = 17; + _context.next = 18; break; } @@ -3047,7 +3069,7 @@ case 11: if (!(result instanceof Pair)) { - _context.next = 17; + _context.next = 18; break; } @@ -3067,42 +3089,45 @@ n = n - 1; case 16: + console.log({ + result: result.toString() + }); return _context.abrupt("return", traverse(result, n)); - case 17: + case 18: // CYCLE DETECT car = node.car; if (!(car instanceof Pair)) { - _context.next = 22; + _context.next = 23; break; } - _context.next = 21; + _context.next = 22; return traverse(car); - case 21: + case 22: car = _context.sent; - case 22: + case 23: cdr = node.cdr; if (!(cdr instanceof Pair)) { - _context.next = 27; + _context.next = 28; break; } - _context.next = 26; + _context.next = 27; return traverse(cdr); - case 26: + case 27: cdr = _context.sent; - case 27: + case 28: pair = new Pair(car, cdr); return _context.abrupt("return", pair); - case 29: + case 30: case "end": return _context.stop(); } @@ -3187,54 +3212,153 @@ return '<#syntax>'; }; - Syntax.className = 'syntax'; - /* - // ---------------------------------------------------------------------- - // :: list of symbols, with at least one - // ---------------------------------------------------------------------- - function is_symbol_list(list) { - return (list instanceof Pair && - list.car instanceof LSymbol && - !list.haveCycles('cdr') && - (list.cdr === nil || is_symbol_list(list.cdr))); - } - // ---------------------------------------------------------------------- - // :: test if value is '((name) ...) or (name ...) it throw exception - // :: when list don't have symbols or if list is empty - // ---------------------------------------------------------------------- - function is_ellipsis(node) { - if (node instanceof Pair && - node.cdr instanceof Pair && - LSymbol.is(node.cdr.car, '...')) { - if (node.car instanceof Pair && is_symbol_list(node.car)) { - return true; - } else if (node.car instanceof LSymbol) { - return true; - } else { - throw new Error('Invalid Syntax'); - } - } - return false; - } - */ - // ---------------------------------------------------------------------- + Syntax.className = 'syntax'; // ---------------------------------------------------------------------- // :: for usage in syntax-rule when pattern match it will return // :: list of bindings from code that match the pattern // :: TODO detect cycles // ---------------------------------------------------------------------- function extract_patterns(pattern, code) { - var bindings = {}; + var bindings = { + '...': { + symbols: {}, + // symbols ellipsis (x ...) + lists: [] + } + }; // pattern_names parameter is used to distinguish + // multiple matches of ((x ...) ...) agains ((1 2 3) (1 2 3)) + // in loop we add x to the list so we know that this is not + // duplicated ellipsis symbol + + function log(x) { + if (user_env.get('DEBUG', { + throwError: false + })) { + console.log(x); + } + } + /* eslint-disable complexity */ + function traverse(pattern, code) { - if (pattern instanceof Pair && LSymbol.is(pattern.car, '...')) { - if (code instanceof Pair) { - bindings['...'] = code; + var pattern_names = arguments.length > 2 && arguments[2] !== undefined$1 ? arguments[2] : []; + var ellipsis = arguments.length > 3 && arguments[3] !== undefined$1 ? arguments[3] : false; + log({ + code: code.toString(), + pattern: pattern.toString() + }); // pattern (a b (x ...)) and (x ...) match nil + + if (pattern instanceof Pair && pattern.car instanceof Pair && pattern.car.cdr instanceof Pair && LSymbol.is(pattern.car.cdr.car, '...')) { + log('>> 0'); + + if (code === nil) { + log({ + pattern: pattern.toString() + }); + + if (pattern.car.car instanceof LSymbol) { + if (pattern.car.cdr instanceof Pair && LSymbol.is(pattern.car.cdr.car, '...')) { + var _name = pattern.car.car.valueOf(); + + var last = pattern.lastPair(); + + if (LSymbol.is(last.car, '...')) { + bindings['...'].symbols[_name] = null; + return true; + } else { + return false; + } + } + + var name = pattern.car.car.valueOf(); + + if (bindings['...'].symbols[name]) { + throw new Error('syntax: named ellipsis can only ' + 'appear onces'); + } + + bindings['...'].symbols[name] = code; + } + return true; } + } + + if (pattern instanceof Pair && pattern.cdr instanceof Pair && LSymbol.is(pattern.cdr.car, '...')) { + // pattern (... ???) + if (pattern.cdr.cdr !== nil) { + throw new Error('syntax: invalid usage of ellipsis'); + } + + if (pattern.car instanceof LSymbol) { + var _name2 = pattern.car.valueOf(); + + if (bindings['...'].symbols[_name2] && !pattern_names.includes(_name2)) { + throw new Error('syntax: named ellipsis can only appear onces'); + } + + log('>> 1'); + + if (code === nil) { + log('>> 2'); + + if (ellipsis) { + bindings['...'].symbols[_name2] = nil; + } else { + return false; + } + } else if (code instanceof Pair && (code.car instanceof Pair || code.car === nil)) { + log('>> 3 ' + ellipsis); + + if (ellipsis) { + bindings['...'].symbols[_name2] = code.car; + } else { + log('>> 4'); + bindings['...'].symbols[_name2] = new Pair(code, nil); + } + } else { + log('>> 6'); + + if (code instanceof Pair) { + log('>> 7 ' + ellipsis); + pattern_names.push(_name2); + + if (!bindings['...'].symbols[_name2]) { + bindings['...'].symbols[_name2] = new Pair(code, nil); + } else { + var node = bindings['...'].symbols[_name2]; + bindings['...'].symbols[_name2] = node.append(new Pair(code, nil)); + } + + log({ + IIIIII: bindings['...'].symbols[_name2].toString() + }); + } else { + log('>> 8'); + return false; //bindings['...'].symbols[name] = code; + } + } + + return true; + } else if (pattern.car instanceof Pair) { + var names = toConsumableArray(pattern_names); + + if (code === nil) { + log('>> 9'); + bindings['...'].lists.push(nil); + return true; + } + + log('>> 10'); + var _node = code; + + while (_node instanceof Pair) { + if (!traverse(pattern.car, _node.car, names, true)) { + return false; + } + + _node = _node.cdr; + } - if (code === nil) { - bindings['...'] = nil; return true; } @@ -3242,24 +3366,74 @@ } if (pattern instanceof LSymbol) { - var name = pattern.valueOf(); - bindings[name] = code; + if (LSymbol.is(pattern, '...')) { + throw new Error('syntax: invalid usage of ellipsis'); + } + + log('>> 11'); + + var _name3 = pattern.valueOf(); + + log({ + name: _name3 + }); //console.log(code.toString()); + + if (ellipsis) { + bindings['...'].symbols[_name3] = bindings['...'].symbols[_name3] || []; + + bindings['...'].symbols[_name3].push(code); + } + + if (!bindings[_name3]) { + bindings[_name3] = code; + } + return true; } if (pattern instanceof Pair && code instanceof Pair) { - if (traverse(pattern.car, code.car) && traverse(pattern.cdr, code.cdr)) { + log('>> 12'); + log(code.toString()); + + if (code.cdr === nil) { + // last item in in call using in recursive calls on + // last element of the list + // case of pattern (p . rest) and code (0) + var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol; + + if (rest_pattern) { + log('>> 12 | 1'); + + var _name4 = pattern.cdr.valueOf(); + + if (!bindings[_name4]) { + bindings[_name4] = nil; + } + + _name4 = pattern.car.valueOf(); + + if (!bindings[_name4]) { + bindings[_name4] = code.car; + } + + return true; + } + } + + if (traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr, code.cdr, pattern_names, ellipsis)) { return true; } } else if (pattern === nil && code === nil) { return true; - } else if (pattern.car instanceof Pair && LSymbol.is(pattern.car.car, '...') && code === nil) { - bindings['...'] = nil; - return true; + } else if (pattern.car instanceof Pair && LSymbol.is(pattern.car.car, '...')) { + // pattern (...) + throw new Error('syntax: invalid usage of ellipsis'); } else { return false; } } + /* eslint-enable complexity */ + if (traverse(pattern, code)) { return bindings; @@ -3354,14 +3528,23 @@ } return traverse(node); - } + } // ---------------------------------------------------------------------- + function transform_syntax(bindings, expr, scope, lex_scope, names) { var gensyms = {}; function transform(symbol) { + if (!(symbol instanceof LSymbol || typeof symbol === 'string')) { + throw new Error('syntax: internal error, rename neeed to be symbol'); + } + var name = symbol.valueOf(); + if (name === '...') { + throw new Error('syntax: internal error, ellipis not transformed'); + } + if (typeof name === 'string' && name in bindings) { return bindings[name]; } @@ -3369,6 +3552,14 @@ return rename(name); } + function log(x) { + if (user_env.get('DEBUG', { + throwError: false + })) { + console.log(x); + } + } + function rename(name) { if (!gensyms[name]) { var value = scope.get(name, { @@ -3393,39 +3584,272 @@ return gensyms[name]; } - function traverse(expr) { - if (expr instanceof Pair) { - if (expr.car instanceof LSymbol) { - var value = transform(expr.car); + function get_binding(list, nested) { + if (!list) { + return; + } + + if (list instanceof Pair) { + return list.car; + } + + if (list instanceof Array) { + var _list = slicedToArray(list, 1), + item = _list[0]; - if (typeof value !== 'undefined') { - expr.car = value; + if (item instanceof Array) { + if (nested) { + return Pair.fromArray(item); } - } else { - traverse(expr.car); + + return item; } - if (expr.cdr instanceof Pair && LSymbol.is(expr.cdr.car, '...') && bindings['...']) { - expr.cdr = bindings['...']; - } else if (expr.cdr instanceof LSymbol) { - var _value = transform(expr.cdr); + return item; + } + } + + function transform_ellipsis_expr(expr, bindings, nested) { + var next = arguments.length > 3 && arguments[3] !== undefined$1 ? arguments[3] : function () {}; + log(' ==> ' + expr.toString()); - if (typeof _value !== 'undefined') { - expr.cdr = _value; + if (expr instanceof LSymbol) { + var name = expr.valueOf(); + log('[t 1'); + var value = get_binding(bindings[name]); + + if (bindings[name]) { + if (bindings[name] instanceof Pair) { + var _bindings$name = bindings[name], + car = _bindings$name.car, + cdr = _bindings$name.cdr; + + if (nested) { + var caar = car.car, + cadr = car.cdr; + + if (cadr !== nil) { + next(name, new Pair(cadr, nil)); + } + + return caar; + } + + if (cdr !== nil) { + next(name, cdr); + } + + return car; + } else if (bindings[name] instanceof Array) { + next(name, bindings[name].slice(1)); + return bindings[name][0]; } - } else { - traverse(expr.cdr); } + + return transform(name); + } + + if (expr instanceof Pair) { + if (expr.car instanceof LSymbol && expr.cdr instanceof Pair && LSymbol.is(expr.cdr.car, '...')) { + log('[t 2'); + + var _name5 = expr.car.valueOf(); + + var item = bindings[_name5]; + + if (item) { + log({ + b: bindings[_name5] + }); + + if (item instanceof Pair) { + log('[t 2 Pair ' + nested); + log({ + ______: item.toString() + }); + var _car = item.car, + _cdr = item.cdr; + + if (nested) { + if (_cdr !== nil) { + next(_name5, _cdr); + } + + return _car; + } else { + if (_car.cdr !== nil) { + next(_name5, new Pair(_car.cdr, _cdr)); + } + + return _car.car; + } + } else if (item instanceof Array) { + log('[t 2 Array ' + nested); + + if (nested) { + next(_name5, item.slice(1)); + return Pair.fromArray(item); + } else { + var rest = item.slice(1); + + if (rest.length) { + next(_name5, rest); + } + + return item[0]; + } + } else { + return item; + } + } + } + + log('[t 3 recur ' + expr.toString()); + return new Pair(transform_ellipsis_expr(expr.car, bindings, nested, next), transform_ellipsis_expr(expr.cdr, bindings, nested, next)); } } - if (expr instanceof Pair) { - expr = expr.clone(); - traverse(expr); + function have_binding(biding) { + var values = Object.values(biding); + return values.length && values.every(function (x) { + return x instanceof Pair || x === nil || x instanceof Array && x.length; + }); + } + + function traverse(expr) { + if (expr instanceof Pair) { + if (expr.cdr instanceof Pair && LSymbol.is(expr.cdr.car, '...')) { + log('>> 1'); + var symbols = bindings['...'].symbols; + var keys = Object.keys(symbols); // case of list as first argument ((x . y) ...) + // we need to recursively process the list + // if we have pattern (_ (x y z ...) ...) and code (foo (1 2) (1 2)) + // x an y will be arrays of [1 1] and [2 2] and z will be array + // of rest, x will also have it's own mapping to 1 and y to 2 + // in case of usage outside of ellipsis list e.g.: (x y) + + if (expr.car instanceof Pair) { + // lists is free ellipsis on pairs ((???) ...) + // TODO: will this work in every case? Do we need to handle + // nesting here? + if (bindings['...'].lists[0] === nil) { + return nil; + } + + log('>> 2'); + var result; + + if (keys.length) { + log('>> 2 (a)'); + + var _bind = _objectSpread({}, symbols); + + result = nil; + + var _loop = function _loop() { + if (!have_binding(_bind)) { + return "break"; + } + + var new_bind = {}; + + var next = function next(key, value) { + // ellipsis decide it what should be the next value + // there are two cases ((a . b) ...) and (a ...) + new_bind[key] = value; + }; + + result = new Pair(transform_ellipsis_expr(expr.car, _bind, true, next), result); + _bind = new_bind; + }; + + while (true) { + var _ret = _loop(); + + if (_ret === "break") break; + } + + if (result !== nil) { + result = result.reverse(); + } + + return result; + } else { + log('>> 3'); + var car = transform_ellipsis_expr(expr.car, symbols, true); + + if (car) { + return new Pair(car, nil); + } + + return nil; + } + } else if (expr.car instanceof LSymbol) { + log('>> 4'); // case: (x ...) + + var name = expr.car.valueOf(); + + var _bind2 = defineProperty({}, name, symbols[name]); + + var _result = nil; + + var _loop2 = function _loop2() { + if (!have_binding(_bind2)) { + log({ + bind: _bind2 + }); + return "break"; + } + + var new_bind = {}; + + var next = function next(key, value) { + new_bind[key] = value; + }; + + log({ + EXPR: expr.toString() + }); + var value = transform_ellipsis_expr(expr, _bind2, false, next); + _result = new Pair(value, _result); + _bind2 = new_bind; + }; + + while (true) { + var _ret2 = _loop2(); + + if (_ret2 === "break") break; + } + + if (_result !== nil) { + _result = _result.reverse(); + } // case if (x ... y ...) second spread is not processed + // by ellipsis transformation + + + if (expr.cdr instanceof Pair && expr.cdr.cdr instanceof Pair) { + _result.append(traverse(expr.cdr.cdr)); + } + + return _result; + } + } + + return new Pair(traverse(expr.car), traverse(expr.cdr)); + } + + if (expr instanceof LSymbol) { + var value = transform(expr); + + if (typeof value !== 'undefined') { + return value; + } + } + return expr; - } else if (expr instanceof LSymbol) { - return transform(expr); } + + return traverse(expr); } // ---------------------------------------------------------------------- // :: check for nullish values // ---------------------------------------------------------------------- @@ -4727,7 +5151,11 @@ LNumber.prototype.toString = LNumber.prototype.toJSON = function (radix) { - return this.value.toString(radix); + if (radix > 2 && radix < 36) { + return this.value.toString(radix); + } + + return this.value.toString(); }; // ------------------------------------------------------------------------- @@ -6086,7 +6514,13 @@ throw new Error(msg); } - unbind(obj)[key] = value.valueOf(); + obj = unbind(obj); + + if (typeof value === 'undefined') { + delete obj[key]; + } else { + obj[key] = value.valueOf(); + } }, "(set-obj! obj key value)\n\n Function set property of JavaScript object"), // ------------------------------------------------------------------ 'null-environment': doc(function () { @@ -6378,7 +6812,13 @@ var bindings = extract_patterns(rule, code); if (bindings) { - // name is modified in transform_syntax + if (user_env.get('DEBUG', { + throwError: false + })) { + console.log(JSON.stringify(bindings, true, 2)); + } // name is modified in transform_syntax + + var names = []; var new_expr = transform_syntax(bindings, expr, scope, var_scope, names); @@ -6401,8 +6841,9 @@ } rules = rules.cdr; - } //throw new Error(`Invalid Syntax ${code}`); + } + throw new Error("Invalid Syntax ".concat(code)); }, env); }, "(syntax-rules () (pattern expression) ...)\n\n Base of Hygienic macro, it will return new syntax expander\n that works like lisp macros."), // ------------------------------------------------------------------ @@ -8277,7 +8718,7 @@ var lips = { version: 'DEV', banner: banner, - date: 'Sat, 18 Apr 2020 08:38:56 +0000', + date: 'Sun, 26 Apr 2020 10:18:59 +0000', exec: exec, parse: parse, tokenize: tokenize, @@ -8300,6 +8741,8 @@ Formatter: Formatter, specials: specials, nil: nil, + extract_patterns: extract_patterns, + transform_syntax: transform_syntax, resolvePromises: resolvePromises, LSymbol: LSymbol, LNumber: LNumber, diff --git a/dist/lips.min.js b/dist/lips.min.js index dd4160233..6bda57200 100644 --- a/dist/lips.min.js +++ b/dist/lips.min.js @@ -24,6 +24,6 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Sat, 18 Apr 2020 08:38:56 +0000 + * build: Sun, 26 Apr 2020 10:18:59 +0000 */ -(function(){"use strict";function e(e,n){return n={exports:{}},e(n,n.exports),n.exports}var u=e(function(t){function r(e,n){t.exports=r=Object.setPrototypeOf||function e(n,t){n.__proto__=t;return n};return r(e,n)}t.exports=r});var Wn=e(function(r){function i(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true}catch(e){return false}}function a(e,n,t){if(i()){r.exports=a=Reflect.construct}else{r.exports=a=function e(n,t,r){var i=[null];i.push.apply(i,t);var a=Function.bind.apply(n,i);var o=new a;if(r)u(o,r.prototype);return o}}return a.apply(null,arguments)}r.exports=a});var n=e(function(e){var n=function(a){var e=Object.prototype;var s=e.hasOwnProperty;var c;var n=typeof Symbol==="function"?Symbol:{};var i=n.iterator||"@@iterator";var t=n.asyncIterator||"@@asyncIterator";var r=n.toStringTag||"@@toStringTag";function o(e,n,t,r){var i=n&&n.prototype instanceof u?n:u;var a=Object.create(i.prototype);var o=new F(r||[]);a._invoke=O(e,t,o);return a}a.wrap=o;function f(e,n,t){try{return{type:"normal",arg:e.call(n,t)}}catch(e){return{type:"throw",arg:e}}}var l="suspendedStart";var p="suspendedYield";var h="executing";var v="completed";var d={};function u(){}function m(){}function y(){}var g={};g[i]=function(){return this};var b=Object.getPrototypeOf;var w=b&&b(b(A([])));if(w&&w!==e&&s.call(w,i)){g=w}var _=y.prototype=u.prototype=Object.create(g);m.prototype=_.constructor=y;y.constructor=m;y[r]=m.displayName="GeneratorFunction";function x(e){["next","throw","return"].forEach(function(n){e[n]=function(e){return this._invoke(n,e)}})}a.isGeneratorFunction=function(e){var n=typeof e==="function"&&e.constructor;return n?n===m||(n.displayName||n.name)==="GeneratorFunction":false};a.mark=function(e){if(Object.setPrototypeOf){Object.setPrototypeOf(e,y)}else{e.__proto__=y;if(!(r in e)){e[r]="GeneratorFunction"}}e.prototype=Object.create(_);return e};a.awrap=function(e){return{__await:e}};function k(u){function c(e,n,t,r){var i=f(u[e],u,n);if(i.type==="throw"){r(i.arg)}else{var a=i.arg;var o=a.value;if(o&&typeof o==="object"&&s.call(o,"__await")){return Promise.resolve(o.__await).then(function(e){c("next",e,t,r)},function(e){c("throw",e,t,r)})}return Promise.resolve(o).then(function(e){a.value=e;t(a)},function(e){return c("throw",e,t,r)})}}var n;function e(t,r){function e(){return new Promise(function(e,n){c(t,r,e,n)})}return n=n?n.then(e,e):e()}this._invoke=e}x(k.prototype);k.prototype[t]=function(){return this};a.AsyncIterator=k;a.async=function(e,n,t,r){var i=new k(o(e,n,t,r));return a.isGeneratorFunction(n)?i:i.next().then(function(e){return e.done?e.value:i.next()})};function O(o,u,c){var s=l;return function e(n,t){if(s===h){throw new Error("Generator is already running")}if(s===v){if(n==="throw"){throw t}return I()}c.method=n;c.arg=t;while(true){var r=c.delegate;if(r){var i=j(r,c);if(i){if(i===d)continue;return i}}if(c.method==="next"){c.sent=c._sent=c.arg}else if(c.method==="throw"){if(s===l){s=v;throw c.arg}c.dispatchException(c.arg)}else if(c.method==="return"){c.abrupt("return",c.arg)}s=h;var a=f(o,u,c);if(a.type==="normal"){s=c.done?v:p;if(a.arg===d){continue}return{value:a.arg,done:c.done}}else if(a.type==="throw"){s=v;c.method="throw";c.arg=a.arg}}}}function j(e,n){var t=e.iterator[n.method];if(t===c){n.delegate=null;if(n.method==="throw"){if(e.iterator["return"]){n.method="return";n.arg=c;j(e,n);if(n.method==="throw"){return d}}n.method="throw";n.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var r=f(t,e.iterator,n.arg);if(r.type==="throw"){n.method="throw";n.arg=r.arg;n.delegate=null;return d}var i=r.arg;if(!i){n.method="throw";n.arg=new TypeError("iterator result is not an object");n.delegate=null;return d}if(i.done){n[e.resultName]=i.value;n.next=e.nextLoc;if(n.method!=="return"){n.method="next";n.arg=c}}else{return i}n.delegate=null;return d}x(_);_[r]="Generator";_[i]=function(){return this};_.toString=function(){return"[object Generator]"};function S(e){var n={tryLoc:e[0]};if(1 in e){n.catchLoc=e[1]}if(2 in e){n.finallyLoc=e[2];n.afterLoc=e[3]}this.tryEntries.push(n)}function E(e){var n=e.completion||{};n.type="normal";delete n.arg;e.completion=n}function F(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(S,this);this.reset(true)}a.keys=function(t){var r=[];for(var e in t){r.push(e)}r.reverse();return function e(){while(r.length){var n=r.pop();if(n in t){e.value=n;e.done=false;return e}}e.done=true;return e}};function A(n){if(n){var e=n[i];if(e){return e.call(n)}if(typeof n.next==="function"){return n}if(!isNaN(n.length)){var t=-1,r=function e(){while(++t=0;--n){var i=this.tryEntries[n];var a=i.completion;if(i.tryLoc==="root"){return e("end")}if(i.tryLoc<=this.prev){var o=s.call(i,"catchLoc");var u=s.call(i,"finallyLoc");if(o&&u){if(this.prev=0;--t){var r=this.tryEntries[t];if(r.tryLoc<=this.prev&&s.call(r,"finallyLoc")&&this.prev=0;--n){var t=this.tryEntries[n];if(t.finallyLoc===e){this.complete(t.completion,t.afterLoc);E(t);return d}}},catch:function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var t=this.tryEntries[n];if(t.tryLoc===e){var r=t.completion;if(r.type==="throw"){var i=r.arg;E(t)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,t){this.delegate={iterator:A(e),resultName:n,nextLoc:t};if(this.method==="next"){this.arg=c}return d}};return a}(e.exports);try{regeneratorRuntime=n}catch(e){Function("r","regeneratorRuntime = r")(n)}});var Zn=n;function c(e,n,t,r,i,a,o){try{var u=e[a](o);var c=u.value}catch(e){t(e);return}if(u.done){n(c)}else{Promise.resolve(c).then(r,i)}}function t(u){return function(){var e=this,o=arguments;return new Promise(function(n,t){var r=u.apply(e,o);function i(e){c(r,n,t,i,a,"next",e)}function a(e){c(r,n,t,i,a,"throw",e)}i(undefined)})}}var et=t;function r(e){if(Array.isArray(e))return e}var i=r;function a(e){if(Symbol.iterator in Object(e)||Object.prototype.toString.call(e)==="[object Arguments]")return Array.from(e)}var o=a;function s(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var f=s;function l(e){return i(e)||o(e)||f()}var nt=l;function p(e){if(Array.isArray(e)){for(var n=0,t=new Array(e.length);n=0)continue;t[i]=e[i]}return t}var k=x;function O(e,n){if(e==null)return{};var t=k(e,n);var r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;t[r]=e[r]}}return t}var it=O;var at=e(function(n){function t(e){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){t=function e(n){return typeof n}}else{t=function e(n){return n&&typeof Symbol==="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n}}return t(e)}function r(e){if(typeof Symbol==="function"&&t(Symbol.iterator)==="symbol"){n.exports=r=function e(n){return t(n)}}else{n.exports=r=function e(n){return n&&typeof Symbol==="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":t(n)}}return r(e)}n.exports=r});function j(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);if(e)r=r.filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable});t.push.apply(t,r)}return t}function ot(n){for(var e=1;e\n\nType (env) to see environment with functions macros and variables.\nYou can also use (help name) to display help for specic function or macro.\n").replace(/^.*\n/,"");return i}();var t=/^\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimy]*)$/;var r=/^(?:#x[-+]?[0-9a-f]+|#o[-+]?[0-7]+|#b[-+]?[01]+|[-+]?[0-9]+)$/i;var i=/^([-+]?([0-9]+([eE][-+]?[0-9]+)|(\.[0-9]+|[0-9]+\.[0-9]+)([eE][-+]?[0-9]+)?)|[0-9]+\.)$/;var a=["alarm","backspace","delete","escape","newline","null","return","space","tab"].join("|");var o=new RegExp("^#\\\\(?:".concat(a,"|[\\s\\S])$"),"i");var u=/^((?:(?:[-+]?[0-9]+(?:[eE][-+]?[0-9]+)?)|(?:[-+]?(?:(?:\.[0-9]+|[0-9]+\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\.))(?=[+-]|i))?((?:[-+]?[0-9]+(?:[eE][-+]?[0-9]+)?)|(?:[-+]?(?:(?:\.[0-9]+|[0-9]+\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\.))i|-i$/;var c=/^[-+]?[0-9]+\/[0-9]+$/;function s(e){var n=e.split("/");return fn({num:parseInt(n[0],10),denom:parseInt(n[1],10)})}function p(e){var n=e.match(/^(?:#([xbo]))?([+-]?[0-9a-f]+)$/i);var t;if(n&&n[1]){switch(n[1]){case"x":t=16;break;case"o":t=8;break;case"b":t=2;break}}else{t=10}return tn([n[2],t])}function h(e){var n=e.match(/#\\(.*)$/);if(n){return Ye(n[1])}}function v(e){if(e==="-i"){return{im:-1,re:0}}var n=e.match(u);var t,r;if(n.length===2){t=an(0);r=an(parseFloat(n[1]))}else{t=an(n[1]?parseFloat(n[1]):0);r=an(parseFloat(n[2]))}return rn({im:r,re:t})}function d(e){var n=/([^\\\n])(\\(?:\\{2})*)(?!u[0-9AF]{1,4})(.)/gi;e=e.replace(n,function(e,n,t,r){if(!['"',"/","b","f","n","r","t"].includes(r)){t=t.substring(1).replace(/\\\\/,"\\");return n+t+r}return e}).replace(/\n/g,"\\n");try{return Ge(JSON.parse(e))}catch(e){throw new Error("Invalid string literal")}}function x(e){var n=e.match(t);if(n){return new RegExp(n[1],n[2])}else if(e.match(/^"/)){return d(e)}else if(e.match(o)){return h(e)}else if(e.match(c)){return s(e)}else if(e.match(u)){return v(e)}else if(e.match(r)){return p(e)}else if(e.match(i)){return an(parseFloat(e))}else if(e==="nil"){return ne}else if(e==="true"){return true}else if(e==="false"){return false}else{return new Z(e)}}function m(e){return!(["(",")"].includes(e)||e.match(t)||e.match(/['"]/)||e.match(r)||e.match(i)||["nil","true","false"].includes(e))}var y=/("(?:\\[\S\s]|[^"])*"|\/(?! )[^\n\/\\]*(?:\\[\S\s][^\n\/\\]*)*\/[gimy]*(?=\s|\[|\]|\(|\)|$)|;.*)/g;var b=/"(?:\\[\S\s]|[^"])*"/g;function w(){var e=E.names().sort(function(e,n){return n.length-e.length||e.localeCompare(n)}).map(k).join("|");return new RegExp("(#\\\\(?:".concat(a,"|[\\s\\S])|#f|#t|#[xbo][0-9a-f]+(?=[\\s()]|$)|[0-9]+/[0-9]+|\\[|\\]|\\(|\\)|;.*|(?:(?:[-+]?(?:(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)[0-9]i)|\\n|\\.{2,}|(?!#:)(?:").concat(e,")|[^(\\s)[\\]]+)"),"gim")}function _(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:1;return e[e.length-n]}function k(e){if(typeof e==="string"){var n=/([-\\^$[\]()+{}?*.|])/g;return e.replace(n,"\\$1")}}function O(e){var a=w();e=e.replace(/\n\r|\r/g,"\n");var o=0;var u=0;var c=[];var s=[];var f=0;e.split(y).filter(Boolean).forEach(function(e){if(e.match(y)){f=0;if(s.length){var n=_(s);if(n.token.match(/\n/)){var t=n.token.split("\n").pop();f+=t.length}else{f+=n.token.length}f+=n.col}var r={col:f,line:u,token:e,offset:o};c.push(r);s.push(r);o+=e.length;f+=e.length;u+=(e.match("\n")||[]).length;return}var i=e.split(a).filter(Boolean);i.forEach(function(e){var n={col:f,line:u,token:e,offset:o};f+=e.length;o+=e.length;c.push(n);s.push(n);if(e==="\n"){++u;s=[];f=0}})});return c}function j(e){var n=e.token,t=it(e,["token"]);if(n.match(/^"[\s\S]+"$/)&&n.match(/\n/)){var r=new RegExp("^ {1,"+(e.col+1)+"}","mg");n=n.replace(r,"")}return ot({token:n},t)}function S(e,n){var t=arguments.length>2&&arguments[2]!==g?arguments[2]:j;if(n){return O(e).map(t)}else{return O(e).map(function(e){var n=t(e);if(!n||typeof n.token!=="string"){throw new Error("[tokenize] Invalid formatter wrong return object")}if(n.token==="#\\ "){return n.token}return n.token.trim()}).filter(function(e){return e&&!e.match(/^;/)})}}var E={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),names:function e(){return Object.keys(this._specials)},type:function e(n){return this.get(n).type},get:function e(n){return this._specials[n]},append:function e(n,t,r){this._specials[n]={seq:n,symbol:t,type:r}},_specials:{}};function F(e){return E.type(e)===E.LITERAL}var A=[["'",new Z("quote"),E.LITERAL],["`",new Z("quasiquote"),E.LITERAL],[",@",new Z("unquote-splicing"),E.LITERAL],[",",new Z("unquote"),E.LITERAL]];A.forEach(function(e){var n=rt(e,3),t=n[0],r=n[1],i=n[2];E.append(t,r,i)});function I(e){if(typeof e==="string"){e=S(e)}var c=[];var s=[];var f=null;var l=E.names();var p=l.map(function(e){return E.get(e).symbol.name});var h=0;var v=false;var d=[];var m=[];var y=0;var g=Z(Symbol["for"]("__splice__"));function b(e){return e==="("||e==="["}function w(e){return e===")"||e==="]"}function _(){var e=c[c.length-1];if(e instanceof Array&&e[0]instanceof Z&&p.includes(e[0].name)&&c.length>1&&!e[0].literal){c.pop();if(c[c.length-1].length===1&&c[c.length-1][0]instanceof Z){c[c.length-1].push(e)}else if(c[c.length-1]instanceof te){if(c[c.length-1].cdr instanceof te){c[c.length-1]=new te(c[c.length-1],te.fromArray(e))}else{c[c.length-1].cdr=te.fromArray(e)}}else{c[c.length-1].push(e)}}}e.forEach(function(e){var n=c[c.length-1];if(l.indexOf(e)!==-1){y++;f=e;c.push([E.get(f).symbol]);if(!f){m=[]}m.push(f)}else{if(f){d.push(m);m=[]}if(b(e)){v=true;h++;var t=[];if(f&&!F(f)){t.push(g)}c.push(t);f=null;y=0}else if(e==="."&&!v){c[c.length-1]=te.fromArray(n)}else if(w(e)){h--;if(!c.length){throw new Error("Unbalanced parenthesis")}if(c.length===1){var r=c.pop();if(r instanceof Array&&r.length===0){r=ne}s.push(r)}else if(c.length>1){var i=c.pop();n=c[c.length-1];if(n instanceof Array){if(i.length===0){n.push(ne)}else if(i instanceof Array&&i[0]===g){var a;(a=n).push.apply(a,tt(i.slice(1)))}else{n.push(i)}}else if(n instanceof te){if(i.length===0){n.append(ne)}else{n.append(te.fromArray(i))}}if(d.length){m=d.pop();while(m.length){_();m.pop()}}else{_()}}if(h===0&&c.length){s.push(c.pop())}}else{v=false;var o=x(e);if(f){while(y--){c[c.length-1].push(o);o=c.pop()}d.pop();y=0;f=false}else if(o instanceof Z&&p.includes(o.name)){o.literal=true}n=c[c.length-1];if(n instanceof te){var u=n;while(true){if(u.cdr===ne){if(o instanceof Array){u.cdr=te.fromArray(o)}else{u.cdr=o}break}else{u=u.cdr}}}else if(!c.length){s.push(o)}else{n.push(o)}}}});if(!e.filter(function(e){return e.match(/^[[\]()]$/)}).length&&c.length){s=s.concat(c);c=[]}if(c.length){throw new Error("Unbalanced parenthesis 2")}return s.map(function(e){if(e instanceof Array){return te.fromArray(e)}return e})}function L(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:function(e){return e};var t=arguments.length>2&&arguments[2]!==g?arguments[2]:null;if(e instanceof Array){var r=e.filter(ge);if(r.length){return L(Promise.all(r),n,t)}return n(e)}if(ge(e)){var i=e.then(n);if(t===null){return i}else{return i["catch"](t)}}return n(e)}function q(e,n){if(n instanceof RegExp){return function(e){return String(e).match(n)}}else if(typeof n!=="function"){throw new Error("".concat(e," argument need to be a function or RegExp"))}else{return n}}function N(e,n,t){if(n){if(t){e.__doc__=n}else{e.__doc__=P(n)}}return e}function P(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function C(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:1;var t=e.length;if(n<=0){throw Error("previousSexp: Invlaid argument sexp = ".concat(n))}e:while(n--&&t>=0){var r=1;while(r>0){var i=e[--t];if(!i){break e}if(i==="("||i.token==="("){r--}else if(i===")"||i.token===")"){r++}}t--}return e.slice(t+1)}function R(e){if(!e||!e.length){return 0}var n=e.length;if(e[n-1].token==="\n"){return 0}while(--n){if(e[n].token==="\n"){var t=(e[n+1]||{}).token;if(t){return t.length}}}return 0}function M(e,n){return s(e,n)===n.length;function s(e,n){function t(){return i>0&&o>0&&e[i-1]===n[o-1]&&e[i+1]===n[o]}function r(){return e[i]===Symbol["for"]("symbol")&&!m(n[o])}var i=0;var a={};for(var o=0;o0){continue}}else if(r()){return-1}}else if(e[i]instanceof Array){var c=s(e[i],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;i++;continue}else{return-1}i++}if(e.length!==i){return-1}return n.length}}function T(e){this._code=e.replace(/\r/g,"")}T.defaults={offset:0,indent:2,exceptions:{specials:[/^define/,"lambda","let*",/^(let|letrec)(-syntax)?$/,"let-env","syntax-rules","try","catch"],shift:{1:["&","#"]}}};T.match=M;T.prototype._options=function e(n){var t=T.defaults;if(typeof n==="undefined"){return Object.assign({},t)}var r=n&&n.exceptions||{};var i=r.specials||[];var a=r.shift||{1:[]};return ot({},t,{},n,{exceptions:{specials:[].concat(tt(t.exceptions.specials),tt(i)),shift:ot({},a,{1:[].concat(tt(t.exceptions.shift[1]),tt(a[1]))})}})};T.prototype.indent=function e(n){var t=S(this._code,true);return this._indent(t,n)};T.exception_shift=function(c,e){function n(e){if(!e.length){return false}if(e.indexOf(c)!==-1){return true}else{var n=e.filter(function(e){return e instanceof RegExp});if(!n.length){return false}var t=true;var r=false;var i=g;try{for(var a=n[Symbol.iterator](),o;!(t=(o=a.next()).done);t=true){var u=o.value;if(c.match(u)){return true}}}catch(e){r=true;i=e}finally{try{if(!t&&a["return"]!=null){a["return"]()}}finally{if(r){throw i}}}}return false}if(n(e.exceptions.specials)){return e.indent}var t=e.exceptions.shift;for(var r=0,i=Object.entries(t);r0){r.offset=0}if(a.toString()===n.toString()&&Vn(a)){return r.offset+a[0].col}else if(a.length===1){return r.offset+a[0].col+1}else{var u=-1;if(o){var c=T.exception_shift(o.token,r);if(c!==-1){u=c}}if(u===-1){u=T.exception_shift(a[1].token,r)}if(u!==-1){return r.offset+a[0].col+u}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return r.offset+a[1].col}return r.offset+a[3].col}else if(a[0].line===a[1].line){return r.offset+r.indent+a[0].col}else{var s=a.slice(2);for(var f=0;f1&&arguments[1]!==g?arguments[1]:true;if(e instanceof te){return e}if(n===false){var t=ne;for(var r=e.length;r--;){t=new te(e[r],t)}return t}if(e.length&&!(e instanceof Array)){e=tt(e)}if(e.length===0){return ne}else{var i;if(e[0]instanceof Array){i=te.fromArray(e[0])}else{i=e[0]}if(typeof i==="string"){i=Ge(i)}if(e.length===1){return new te(i,ne)}else{return new te(i,te.fromArray(e.slice(1)))}}};te.prototype.toObject=function(){var e=this;var n={};while(true){if(e instanceof te&&e.car instanceof te){var t=e.car;var r=t.car;if(r instanceof Z){r=r.name}if(r instanceof String){r=r.valueOf()}var i=t.cdr;if(i instanceof te){i=i.toObject()}if(i instanceof tn||i instanceof Ge){i=i.valueOf()}n[r]=i;e=e.cdr}else{break}}return n};te.fromPairs=function(e){return e.reduce(function(e,n){return new te(new te(new Z(n[0]),n[1]),e)},ne)};te.fromObject=function(n){var e=Object.keys(n).map(function(e){return[e,n[e]]});return te.fromPairs(e)};te.prototype.reduce=function(e){var n=this;var t=ne;while(true){if(n!==ne){t=e(t,n.car);n=n.cdr}else{break}}return t};te.prototype.reverse=function(){if(this.haveCycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var n=ne;while(e!==ne){var t=e.cdr;e.cdr=n;n=e;e=t}return n};te.prototype.transform=function(r){function i(e){if(e instanceof te){if(e.replace){delete e.replace;return e}var n=r(e.car);if(n instanceof te){n=i(n)}var t=r(e.cdr);if(t instanceof te){t=i(t)}return new te(n,t)}return e}return i(this)};te.prototype.map=function(e){if(typeof this.car!=="undefined"){return new te(e(this.car),this.cdr===ne?ne:this.cdr.map(e))}else{return ne}};function ie(n,t){if(typeof jQuery!=="undefined"&&n instanceof jQuery.fn.init){return"<#jQuery("+n.length+")>"}if(n===true){return"#t"}if(n===false){return"#f"}if(typeof n==="undefined"){return"<#undefined>"}if(n instanceof te){return n.toString(t)}var e=[RegExp,ee,Z,tn,Ye,On];for(var r=0,i=e;r"}return"<#procedure>"}if(n instanceof Array){return"#("+n.map(function(e){return ie(e,true)}).join(" ")+")"}if(n instanceof Ge){n=n.toString()}if(n===null||typeof n==="string"&&t){return JSON.stringify(n).replace(/\\n/g,"\n")}if(f.HTMLElement&&n instanceof f.HTMLElement){return"<#HTMLElement(".concat(n.tagName.toLowerCase(),")>")}if(at(n)==="object"){if(typeof n.toString==="function"&&n.toString.__lambda__){return n.toString().valueOf()}var o=n.constructor;var u=at(n)==="object"&&o===Object;if(u){return"&("+Object.keys(n).map(function(e){return":".concat(e," ").concat(ie(n[e],t))}).join(" ")+")"}var c;if(typeof o.__className==="string"){c=o.__className}else if(Tn(n)==="instance"){c="instance"}else{c=o.name}if(c!==""){return"<#"+c+">"}return"<#Object>"}if(typeof n!=="string"){return n.toString()}return n}te.prototype.markCycles=function(){ae(this);return this};te.prototype.haveCycles=function(){var e=arguments.length>0&&arguments[0]!==g?arguments[0]:null;if(!e){return this.haveCycles("car")||this.haveCycles("cdr")}return!!(this.cycles&&this.cycles[e])};function ae(e){var i=[];var n=[];function a(e){if(e instanceof te){if(i.includes(e)){if(!n.includes(e)){n.push(e)}return"#".concat(n.length-1,"#")}}}function o(e){if(e instanceof te){i.push(e);var n={};var t=a(e.car);var r=a(e.cdr);if(t){n["car"]=t}else{o(e.car)}if(r){n["cdr"]=r}else{o(e.cdr)}if(t||r){e.cycles=n}else if(e.cycles){delete e.cycles}}}o(e)}te.prototype.toString=function(e){var n=["("];if(this.car!==g){var t;if(this.cycles&&this.cycles.car){t=this.cycles.car}else{t=ie(this.car,e)}if(t!==g){n.push(t)}if(this.cdr instanceof te){if(this.cycles&&this.cycles.cdr){n.push(" . ");n.push(this.cycles.cdr)}else{var r=this.cdr.toString(e).replace(/^\(|\)$/g,"");n.push(" ");n.push(r)}}else if(typeof this.cdr!=="undefined"&&this.cdr!==ne){n=n.concat([" . ",ie(this.cdr,e)])}}n.push(")");return n.join("")};te.prototype.set=function(e,n){this[e]=n;if(n instanceof te){this.markCycles()}};te.prototype.append=function(e){if(e instanceof Array){return this.append(te.fromArray(e))}var n=this;if(n.car===g){if(e instanceof te){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(e!==ne){while(true){if(n instanceof te&&n.cdr!==ne){n=n.cdr}else{break}}n.cdr=e}return this};function oe(e){return e<0?-e:e}function ue(e,n){var t=nt(n),r=t[0],i=t.slice(1);while(i.length>0){var a=i,o=rt(a,1),u=o[0];if(!e(r,u)){return false}var c=i;var s=nt(c);r=s[0];i=s.slice(1)}return true}function ce(e,n){if(typeof e==="function"&&typeof n==="function"){return xe(e)===xe(n)}else if(e instanceof tn&&n instanceof tn){return e.type===n.type&&e.cmp(n)===0}else if(typeof e==="number"||typeof n==="number"){e=tn(e);n=tn(n);return e.type===n.type&&e.cmp(n)===0}else if(e instanceof Ye&&n instanceof Ye){return e["char"]===n["char"]}else if(e instanceof Z&&n instanceof Z){return e.name===n.name}else{return e===n}}var se=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function fe(e,n,t,r){if(typeof this!=="undefined"&&this.constructor!==fe||typeof this==="undefined"){return new fe(e,n)}Rn("Macro",e,"string",1);Rn("Macro",n,"function",2);if(t){if(r){this.__doc__=t}else{this.__doc__=P(t)}}this.name=e;this.fn=n}fe.defmacro=function(e,n,t,r){var i=new fe(e,n,t,r);i.defmacro=true;return i};fe.prototype.invoke=function(e,n,t){var r=n.env,i=n.dynamic_scope,a=n.error;var o={dynamic_scope:i,error:a,macro_expand:t};var u=this.fn.call(r,e,o,this.name);return u};fe.prototype.toString=function(){return"#"};var le="define-macro";function pe(i){return function(){var t=et(Zn.mark(function e(t,f){var l,p,r;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:r=function e(){r=et(Zn.mark(function e(t,r){var i,a,o,u,c,s;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:if(!(t instanceof te&&t.car instanceof Z)){n.next=17;break}if(!t.data){n.next=3;break}return n.abrupt("return",t);case 3:i=l.get(t.car,{throwError:false});if(!(i instanceof fe&&i.defmacro)){n.next=17;break}a=i instanceof he?t:t.cdr;n.next=8;return i.invoke(a,f,true);case 8:o=n.sent;if(!(o instanceof Z)){n.next=11;break}return n.abrupt("return",jn(o));case 11:if(!(o instanceof te)){n.next=17;break}if(!(typeof r==="number")){n.next=16;break}if(!(r<=1)){n.next=15;break}return n.abrupt("return",o);case 15:r=r-1;case 16:return n.abrupt("return",p(o,r));case 17:u=t.car;if(!(u instanceof te)){n.next=22;break}n.next=21;return p(u);case 21:u=n.sent;case 22:c=t.cdr;if(!(c instanceof te)){n.next=27;break}n.next=26;return p(c);case 26:c=n.sent;case 27:s=new te(u,c);return n.abrupt("return",s);case 29:case"end":return n.stop()}}},e)}));return r.apply(this,arguments)};p=function e(n,t){return r.apply(this,arguments)};l=f["env"]=this;if(!i){n.next=11;break}n.t0=jn;n.next=7;return p(t,1);case 7:n.t1=n.sent.car;return n.abrupt("return",(0,n.t0)(n.t1));case 11:n.t2=jn;n.next=14;return p(t,-1);case 14:n.t3=n.sent.car;return n.abrupt("return",(0,n.t2)(n.t3));case 16:case"end":return n.stop()}}},e,this)}));return function(e,n){return t.apply(this,arguments)}}()}function he(e,n){this.name="syntax";this.env=n;this.fn=e;this.defmacro=true}he.prototype=Object.create(fe.prototype);he.prototype.invoke=function(e,n,t){var r=n.error,i=n.env;var a={error:r,env:i,dynamic_scope:this.env,macro_expand:t};return this.fn.call(i,e,a,this.name)};he.prototype.constructor=he;he.prototype.toString=function(){return"<#syntax>"};he.className="syntax";function ve(e,n){var r={};function i(e,n){if(e instanceof te&&Z.is(e.car,"...")){if(n instanceof te){r["..."]=n;return true}if(n===ne){r["..."]=ne;return true}return false}if(e instanceof Z){var t=e.valueOf();r[t]=n;return true}if(e instanceof te&&n instanceof te){if(i(e.car,n.car)&&i(e.cdr,n.cdr)){return true}}else if(e===ne&&n===ne){return true}else if(e.car instanceof te&&Z.is(e.car.car,"...")&&n===ne){r["..."]=ne;return true}else{return false}}if(i(e,n)){return r}}function de(e,i){function a(n){if(n instanceof te){if(!i.length){return n}var e=a(n.car);var t=a(n.cdr);return new te(e,t)}else if(n instanceof Z){var r=i.find(function(e){return e.gensym===n});if(r){return Z(r.name)}return n}else{return n}}return a(e)}function me(r,e,i,n,a){var o={};function u(e){var n=e.valueOf();if(typeof n==="string"&&n in r){return r[n]}return t(n)}function t(e){if(!o[e]){var n=i.get(e,{throwError:false});var t=Sn(e);a.push({name:e,gensym:t});if(typeof n!=="undefined"){i.set(t,n)}o[e]=t}return o[e]}function c(e){if(e instanceof te){if(e.car instanceof Z){var n=u(e.car);if(typeof n!=="undefined"){e.car=n}}else{c(e.car)}if(e.cdr instanceof te&&Z.is(e.cdr.car,"...")&&r["..."]){e.cdr=r["..."]}else if(e.cdr instanceof Z){var t=u(e.cdr);if(typeof t!=="undefined"){e.cdr=t}}else{c(e.cdr)}}}if(e instanceof te){e=e.clone();c(e);return e}else if(e instanceof Z){return u(e)}}function ye(e){return typeof e==="undefined"||e===ne||e===null}function ge(e){return e instanceof Promise||e&&typeof e!=="undefined"&&typeof e.then==="function"}function be(e){switch(at(e)){case"string":return Ge(e);case"number":return tn(e)}return e}function we(e){return e.valueOf()}function _e(e,n){if(e instanceof te){e.markCycles();return jn(e)}if(typeof e==="function"){if(n){return ke(e,n)}}return be(e)}function xe(e){if(Oe(e)){return e[je]}return e}function ke(n,e){if(n[Symbol["for"]("__bound__")]){return n}var t=n.bind(e);var r=Object.getOwnPropertyNames(n).filter(Ee);r.forEach(function(e){try{t[e]=n[e]}catch(e){}});Fe(t,"__fn__",n);Fe(t,"__bound__",true);if(Ie(n)){Fe(t,"__native__",true)}t.valueOf=function(){return n};return t}function Oe(e){return typeof e==="function"&&e[je]}var je=Symbol["for"]("__fn__");var Se=["name","length","caller","callee","arguments","prototype"];function Ee(e){return!Se.includes(e)}function Fe(e,n,t){Object.defineProperty(e,Symbol["for"](n),{get:function e(){return t},set:function e(){},configurable:false,enumerable:false})}function Ae(n,t){try{Object.defineProperty(n,"length",{get:function e(){return t}});return n}catch(e){var r=new Array(t).fill(0).map(function(e,n){return"a"+n}).join(",");var i=new Function("f","return function(".concat(r,") {\n return f.apply(this, arguments);\n };"));return i(n)}}function Ie(e){var n=Symbol["for"]("__native__");return typeof e==="function"&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[n]===true||!e.name.match(/^bound /)&&!e[n])}function Le(e){var h;switch(e){case Symbol["for"]("letrec"):h="letrec";break;case Symbol["for"]("let"):h="let";break;case Symbol["for"]("let*"):h="let*";break;default:throw new Error("Invalid let_macro value")}return fe.defmacro(h,function(a,e){var o=e.dynamic_scope,u=e.error,n=e.macro_expand;var c;if(a.car instanceof Z){if(!(a.cdr.car instanceof te)){throw new Error("let require list of pairs")}var t=a.cdr.car.map(function(e){return e.car});c=a.cdr.car.map(function(e){return e.cdr.car});return te.fromArray([Z("letrec"),[[a.car,te(Z("lambda"),te(t,a.cdr.cdr))]],te(a.car,c)])}else if(n){return}var s=this;c=this.get("list->array")(a.car);var f=s.inherit(h);var l;if(h==="let*"){l=f}var p=0;return function e(){var n=c[p++];function t(e){if(ge(e)){return e.then(t)}else if(typeof e==="undefined"){f.set(n.car,ne)}else{f.set(n.car,e)}}if(o){o=h==="let*"?f:s}if(!n){var r=new te(new Z("begin"),a.cdr);return Jn(r,{env:f,dynamic_scope:o,error:u})}else{if(h==="let"){l=s}else if(h==="letrec"){l=f}var i=Jn(n.cdr.car,{env:l,dynamic_scope:o,error:u});if(h==="let*"){l=f=l.inherit("let*["+p+"]")}return L(t(i),e)}}()})}function qe(e,c){return new fe(e,function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:{},t=n.dynamic_scope,r=n.error;var i=this;if(t){t=this}var a=e;var o=[];while(a instanceof te){o.push(Jn(a.car,{env:i,dynamic_scope:t,error:r}));a=a.cdr}var u=o.filter(ge).length;if(u){return Promise.all(o).then(c.bind(this))}else{return c.call(this,o)}})}function Ne(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r2?r-2:0),a=2;a1&&arguments[1]!==g?arguments[1]:null;return function(){for(var e=arguments.length,n=new Array(e),t=0;t1?e-1:0),t=1;t=o){return a.apply(this,r)}else{return i}}return i.apply(this,arguments)}}function He(r,i){Rn("limit",i,"function",2);return function(){for(var e=arguments.length,n=new Array(e),t=0;t1?r-1:0),a=1;a0){t.push(this._string.substring(0,e))}t.push(n);if(e0&&arguments[0]!==g?arguments[0]:null;if(e===null){return on(this.value.valueOf())}return un(e.valueOf())(this.value.valueOf())};var on=un(1e-10);function un(r){return function(e){var n=function e(r,n,t){var i=function e(n,t){return t0){i=sn(r,t)}else if(r.cmp(t)<=0){i=t}else if(t.cmp(0)>0){i=sn(t,r)}else if(n.cmp(0)<0){i=tn(sn(r.sub(),t.sub())).sub()}else{i=tn(0)}if(tn.isFloat(n)||tn.isFloat(e)){return an(i)}return i}function sn(e,n){var t=tn(e).floor();var r=tn(n).floor();if(e.cmp(t)<1){return t}else if(t.cmp(r)===0){var i=tn(1).div(n.sub(r));var a=tn(1).div(e.sub(t));return t.add(tn(1).div(sn(i,a)))}else{return t.add(tn(1))}}function fn(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof fn)||typeof this==="undefined"){return new fn(e,n)}if(!tn.isRational(e)){throw new Error("Invalid constructor call for LBigInteger")}if(e.num%e.denom===0&&!n){return tn(e.num/e.denom)}this.num=tn(e.num);this.denom=tn(e.denom);this.type="rational"}fn.prototype=Object.create(tn.prototype);fn.prototype.constructor=fn;fn.prototype.pow=function(e){var n=e.cmp(0);if(n===0){return tn(1)}if(n===-1){e=e.sub();var t=this.denom.pow(e);var r=this.num.pow(e);return fn({num:t,denom:r})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};fn.prototype.abs=function(){var e=this.num;var n=this.denom;if(e.cmp(0)===-1){e=e.sub()}if(n.cmp(0)!==1){n=n.sub()}return fn({num:e,denom:n})};fn.prototype.cmp=function(e){return tn(this.valueOf()).cmp(e)};fn.prototype.toString=function(){var e=En.get("gdc")(this.num,this.denom);if(e!==1){e=tn(e);return this.num.div(e)+"/"+this.denom.div(e)}return this.num+"/"+this.denom};fn.prototype.valueOf=function(){return an(this.num.valueOf()).div(this.denom.valueOf())};fn.prototype.mul=function(e){if(tn.isRational(e)){var n=this.num.mul(e.num);var t=this.denom.mul(e.denom);return fn({num:n,denom:t})}return tn(this.valueOf()).mul(e)};fn.prototype.div=function(e){if(tn.isRational(e)){var n=this.num.mul(e.denom);var t=this.denom.mul(e.num);return fn({num:n,denom:t})}return tn(this.valueOf()).div(e)};fn.prototype.op=function(e,n){return this[hn[e]](n)};fn.prototype.sub=function(e){if(tn.isRational(e)){var n=e.num.sub();var t=e.denom;return this.add(fn({num:n,denom:t}))}if(!(e instanceof tn)){e=tn(e).sub()}else{e=e.sub()}if(tn.isFloat(e)){return an(this.valueOf()).add(e)}return this.add(e)};fn.prototype.add=function(e){if(tn.isRational(e)){var n=this.denom;var t=e.denom;var r=this.num;var i=e.num;var a,o;if(n!==t){o=t.mul(r).add(i.mul(n));a=n.mul(t)}else{o=r.add(i);a=n}return fn({num:o,denom:a})}if(tn.isFloat(e)){return an(this.valueOf()).add(e)}return tn(this.valueOf()).add(e)};function ln(e,n){if(typeof this!=="undefined"&&!(this instanceof ln)||typeof this==="undefined"){return new ln(e,n)}if(e instanceof ln){return ln(e.value,e._native)}if(!tn.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.value=e;this._native=n;this.type="bigint"}ln.prototype=Object.create(tn.prototype);ln.prototype.constructor=ln;ln.prototype.op=function(e,n){if(tn.isBN(this.value)&&tn.isBN(n.value)){var t={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};e=t[e];return ln(this.value.clone()[e](n),false)}if(n instanceof fn){return fn({num:this,denom:1},true)[hn[e]](n)}if(e==="/"){return fn({num:this,denom:n})}return ln(tn._ops[e](this.value,n&&n.value),true)};ln.prototype.sqrt=function(){var e;var n=this.cmp(0)<0;if(tn.isNative(this.value)){e=Math.sqrt(n?-this.valueOf():this.valueOf())}else if(tn.isBN(this.value)){e=n?this.value.neg().sqrt():this.value.sqrt()}if(n){return rn({re:0,im:e})}return e};tn.isFloat=function e(n){return n instanceof an||Number(n)===n&&n%1!==0};tn.isNumber=function(e){return e instanceof tn||!Number.isNaN(e)&&tn.isNative(e)||tn.isBN(e)};tn.isComplex=function(e){return e instanceof rn||tn.isNumber(e.im)&&tn.isNumber(e.re)};tn.isRational=function(e){return e instanceof fn||tn.isNumber(e.num)&&tn.isNumber(e.denom)};tn.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};tn.isBigInteger=function(e){return e instanceof ln||typeof e==="bigint"||tn.isBN(e)};tn.isBN=function(e){return typeof l!=="undefined"&&e instanceof l};tn.getArgsType=function(e,n){if(e instanceof an||n instanceof an){return an}if(e instanceof ln||n instanceof ln){return ln}return tn};tn.prototype.toString=tn.prototype.toJSON=function(e){return this.value.toString(e)};tn.prototype.isBigNumber=function(){return typeof this.value==="bigint"||typeof l!=="undefined"&&!(this.value instanceof l)};["floor","ceil","round"].forEach(function(e){tn.prototype[e]=function(){if(this["float"]||tn.isFloat(this.value)){return tn(Math[e](this.value))}else{return tn(Math[e](this.valueOf()))}}});tn.prototype.valueOf=function(){if(tn.isNative(this.value)){return Number(this.value)}else if(tn.isBN(this.value)){return this.value.toNumber()}};tn.prototype.coerce=function(e){if(e===null){e=0}var n;if(e instanceof tn){n=e.value}else{n=e}if(this instanceof an){return an(e.valueOf())}if(this instanceof rn){return rn({re:n,im:0})}if(this instanceof fn&&!tn.isRational(e)){return tn(n)}if(tn.isComplex(e)){return rn(e)}else if(tn.isRational(e)){return fn(e)}else if(tn.isFloat(n)||this instanceof an){return an(n)}else if(typeof this.value==="bigint"&&typeof n!=="bigint"){return ln(BigInt(n))}else if(typeof l!=="undefined"&&this.value instanceof l&&!n instanceof l){return ln(new l(n))}return tn(n)};tn.getType=function(e){if(e instanceof tn){return e.type}if(tn.isFloat(e)){return"float"}if(tn.isComplex(e)){return"complex"}if(tn.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof l!=="undefined"&&!(e instanceof l)){return"bigint"}};tn.prototype.isFloat=function(){return!!(tn.isFloat(this.value)||this["float"])};tn.prototype.add=function(e){return tn(this.valueOf()+e.valueOf())};tn.prototype.sub=function(){var e=arguments.length>0&&arguments[0]!==g?arguments[0]:null;if(e===null){return tn(-this.valueOf())}return tn(this.valueOf()-e.valueOf())};tn.prototype.mul=function(e){if(e instanceof rn){return rn(this).mul(e)}return tn(this.valueOf()*e.valueOf())};tn.prototype.div=function(e){if(e instanceof rn){return rn(this).mul(e)}return tn(this.valueOf()/e.valueOf())};tn.prototype.rem=function(e){return tn(this.valueOf()%e.valueOf())};tn.prototype.mod=function(e){return tn(this.valueOf()%e.valueOf())};tn.prototype.or=function(e){return tn(this.ValueOf()|e.valueOf())};tn.prototype.and=function(e){return tn(this.valueOf()&e.valueOf())};tn.prototype.neg=function(){return tn(~this.valueOf())};tn.prototype.shl=function(e){return tn(this.valueOf()>>e.valueOf())};tn.prototype.shr=function(e){return this.op(e)};var pn={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var hn={};Object.keys(pn).forEach(function(n){hn[pn[n]]=n;tn.prototype[n]=function(e){return this.op(pn[n],e)}});tn._ops={"*":function e(n,t){return n*t},"+":function e(n,t){return n+t},"-":function e(n,t){if(typeof t==="undefined"){return-n}return n-t},"/":function e(n,t){return n/t},"%":function e(n,t){return n%t},"|":function e(n,t){return n|t},"&":function e(n,t){return n&t},"~":function e(n){return~n},">>":function e(n,t){return n>>t},"<<":function e(n,t){return n<"};function mn(n){var t=this;if(typeof this!=="undefined"&&!(this instanceof mn)||typeof this==="undefined"){return new mn(n)}Rn("OutputStringPort",n,"function");this._buffer=[];this.write=function(e){if(!Ge.isString(e)){e=n(e)}else{e=e.valueOf()}t._buffer.push(e)}}mn.prototype=Object.create(dn.prototype);mn.prototype.getString=function(){return this._buffer.map(function(e){return e.valueOf()}).join("")};mn.prototype.constructor=mn;function yn(e){var n=this;if(typeof this!=="undefined"&&!(this instanceof yn)||typeof this==="undefined"){return new yn(e)}Rn("InputStringPort",e,"string");this._tokens=S(e);this._index=0;this._in_char=0;this.read=function(){return n.getNextTokens()}}yn.prototype=Object.create(vn.prototype);yn.prototype.constructor=yn;yn.prototype.getNextTokens=function(){if(this.peekChar()===gn){return gn}var e=0;var n=[];var t=["(",")"];if(!t.includes(this._tokens[this._index])){return this._tokens[this._index++]}do{var r=this._tokens[this._index];n.push(this._tokens[this._index]);if(r===")"){e--}else if(r==="("){e++}this._index++}while(e!==0);return n};yn.prototype.peekChar=function(){if(this._index>this._tokens.length-1){return gn}if(this._index===this._tokens.length-1&&this.in_char>this._tokens[this._index].length){return gn}return this._tokens[this._index][this.in_char]};var gn=new bn;function bn(){}bn.prototype.toString=function(){return"<#eof>"};function wn(e){this.message=e}wn.prototype=Object.create(Error.prototype);function _n(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:{};if(typeof this!=="undefined"&&!(this instanceof _n)||typeof this==="undefined"){return new _n(e,n)}if(typeof e==="undefined"){e="anonymous"}this.env=Fn.inherit(e,n)}_n.prototype.exec=function(){var n=et(Zn.mark(function e(t){var r,i=arguments;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:r=i.length>1&&i[1]!==g?i[1]:false;Rn("Intepreter::exec",t,"string",1);Rn("Intepreter::exec",r,"boolean",2);En.set("**interaction-environment**",this.env);return n.abrupt("return",Un(t,this.env,r?this.env:false));case 5:case"end":return n.stop()}}},e,this)}));return function(e){return n.apply(this,arguments)}}();_n.prototype.get=function(e){return this.env.get(e).bind(this.env)};_n.prototype.set=function(e,n){return this.env.set(e,n)};function xn(e,n,t){if(arguments.length===1){if(at(arguments[0])==="object"){e=arguments[0];this.parent=null}else if(typeof arguments[0]==="string"){e={};n={};t=arguments[0]}}this.env=e;this.parent=n;this.name=t||"anonymous"}xn.prototype.inherit=function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:{};if(at(e)==="object"){n=e}if(!e||at(e)==="object"){e="child of "+(this.name||"unknown")}return new xn(n||{},this,e)};xn.prototype.newFrame=function(e,n){var r=this.inherit("__frame__");r.set("parent.frame",N(function(){var e=arguments.length>0&&arguments[0]!==g?arguments[0]:1;var n=r.parent;if(!(n instanceof xn)){return ne}if(e<=0){return n}var t=n.get("parent.frame");return t(e-1)},En.env["parent.frame"].__doc__));n.callee=e;r.set("arguments",n);return r};xn.prototype._lookup=function(e){if(e instanceof Z){e=e.name}if(e instanceof Ge){e=e.valueOf()}if(e in this.env){return kn(this.env[e])}if(this.parent){return this.parent._lookup(e)}};xn.prototype.toString=function(){return"<#env:"+this.name+">"};xn.prototype.clone=function(){var n=this;var t={};Object.keys(this.env).forEach(function(e){t[e]=n.env[e]});return new xn(t,this.parent,this.name)};xn.prototype.merge=function(e){Rn("Environment::merge",e,"environment");return this.inherit("merge",e.env)};function kn(e){if(typeof this!=="undefined"&&!(this instanceof kn)||typeof this==="undefined"){return new kn(e)}this.value=e}kn.isUndefined=function(e){return e instanceof kn&&typeof e.value==="undefined"};kn.prototype.valueOf=function(){return this.value};function On(e){if(e.length){if(e.length===1){return e[0]}}if(typeof this!=="undefined"&&!(this instanceof On)||typeof this==="undefined"){return new On(e)}this.values=e}On.prototype.toString=function(){return this.values.map(function(e){return ie(e)}).join("\n")};On.prototype.valueOf=function(){return this.values};xn.prototype.get=function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:{};var t=n.throwError,r=t===void 0?true:t;var i=e;if(i instanceof Z||i instanceof Ge){i=i.valueOf()}var a=this._lookup(i);if(a instanceof kn){if(kn.isUndefined(a)){return g}return _e(a.valueOf())}if(typeof i==="string"){var o=i.split(".").filter(Boolean);if(o.length>0){var u=nt(o),c=u[0],s=u.slice(1);a=this._lookup(c);if(s.length){try{if(a instanceof kn){a=a.valueOf();return Ue.apply(void 0,[a].concat(tt(s)))}else{return Ue.apply(void 0,[f].concat(tt(o)))}}catch(e){}}else if(a instanceof kn){return _e(a.valueOf())}}a=Ue(f,i)}if(typeof a!=="undefined"){return a}if(r){throw new Error("Unbound variable `"+i.toString()+"'")}};xn.prototype.set=function(e,n){if(tn.isNumber(n)){n=tn(n)}if(e instanceof Z){e=e.name}else if(e instanceof Ge){e=e.valueOf()}this.env[e]=n};xn.prototype.has=function(e){return typeof this.env[e]!=="undefined"};xn.prototype.ref=function(e){var n=this;while(true){if(!n){break}if(n.has(e)){return n}n=n.parent}};xn.prototype.parents=function(){var e=this;var n=[];while(e){n.unshift(e);e=e.parent}return n};function jn(e){if(ge(e)){return e.then(jn)}if(e instanceof te||e instanceof Z){e.data=true}return e}var Sn=function(){var n=0;return function(){var e=arguments.length>0&&arguments[0]!==g?arguments[0]:null;if(e instanceof Z){e=e.valueOf()}if(e!==null){return new Z(Symbol("#:".concat(e)))}n++;return new Z(Symbol("#:g".concat(n)))}}();var En=new xn({nil:ne,undefined:g,true:true,false:false,NaN:NaN,stdout:new dn(function(){var e;(e=console).log.apply(e,arguments)}),stdin:vn(function(){return new Promise(function(e){e(prompt(""))})}),"open-input-string":N(function(e){Rn("open-input-string",e,"string");return yn(e)},"(open-input-string string)\n\n Function create new string port as input that can be used to\n read S-exressions from this port using `read` function."),"output-port?":N(function(e){return e instanceof dn},"(output-port? arg)\n\n Function return true if argument is output port."),"input-port?":N(function(e){return e instanceof vn},"(input-port? arg)\n\n Function return true if argument is input port."),"open-output-string":N(function(){return mn(this.get("repr"))},"(open-output-string)\n\n Function create new output port that can used to write string into\n and after finish get the whole string using `get-output-string`"),"get-output-string":N(function(e){Rn("get-output-string",e,"output-string-port");return e.getString()},"(get-output-string port)\n\n Function get full string from string port. If nothing was wrote\n to given port it will return empty string."),"eof-object?":N(function(e){return e===gn},"(eof-object? arg)\n\n Function check if value is eof object, returned from input string\n port when there are no more data to read."),"peek-char":N(function(e){Rn("peek-char",e,["input-port","input-string-port"]);return e.peekChar()},"(peek-char port)\n\n Function get character from string port or EOF object if no more\n data in string port."),read:N(function n(e){var t=this;if(typeof e==="string"){return I(S(e))[0]}if(e instanceof yn){var r=e.read();if(r===gn){return gn}return I(r)[0]}var i;if(e instanceof vn){i=e}else{i=this.get("stdin")}return i.read().then(function(e){return n.call(t,e)})},"(read [string])\n\n Function if used with string will parse the string and return\n list structure of LIPS code. If called without an argument it\n will read string from standard input (using browser prompt or\n user defined way) and call itself with that string (parse is)\n function can be used together with eval to evaluate code from\n string"),pprint:N(function(e){if(e instanceof te){e=new Kn.Formatter(e.toString(true))["break"]().format();this.get("stdout").write.call(this,e)}else{this.get("display").call(this,e)}},"(pprint expression)\n\n Pretty print list expression, if called with non-pair it just call\n print function with passed argument."),print:N(function(){var n=this;for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),i=1;ir.length){throw new Error("Not enough arguments")}var u=0;var c=this.get("repr");n=n.replace(a,function(e){var n=e[1];if(n==="~"){return"~"}else if(n==="%"){return"\n"}else{var t=r[u++];if(n==="a"){return c(t)}else{return c(t,true)}}});o=n.match(/~([\S])/);if(o){throw new Error("format: Unrecognized escape seqence ".concat(o[1]))}return n},"(format string n1 n2 ...)\n\n Function accepts string template and replacing any escape sequences\n by arguments:\n\n * ~a value as if printed with display\n * ~s value as if printed with write\n * ~% newline character\n * ~~ literal tilde '~' is inserted\n\n if there missing arguments or other escape character it throw exception."),display:N(function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:null;if(n===null){n=this.get("stdout")}n.write.call(this,this.get("repr")(e))},"(display arg [port])\n\n Function send string to standard output or provied port."),error:N(function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&arguments[1]!==g?arguments[1]:{},t=e.dynamic_scope,r=e.error;if(t){t=this}var i=Jn(n.cdr.car,{env:this,dynamic_scope:t,error:r});i=Bn(i);var a;function o(n,t){if(ge(n)){return n.then(function(e){return o(e,t)})}if(ge(t)){return t.then(function(e){return o(n,e)})}s[n]=t;return t}if(n.car instanceof te&&Z.is(n.car.car,".")){var u=n.car.cdr.car;var c=n.car.cdr.cdr.car;var s=Jn(u,{env:this,dynamic_scope:t,error:r});var f=Jn(c,{env:this,dynamic_scope:t,error:r});return o(f,i)}if(!(n.car instanceof Z)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}a=this.ref(n.car.name);if(!a){a=this}return L(i,function(e){a.set(n.car,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable (mutate)\n it search the scope chain until it finds first non emtpy slot and set it."),"set-car!":N(function(e,n){Rn("set-car!",e,"pair");e.car=n},"(set-car! obj value)\n\n Function that set car (head) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"set-cdr!":N(function(e,n){Rn("set-cdr!",e,"pair");e.cdr=n},"(set-cdr! obj value)\n\n Function that set cdr (tail) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"empty?":N(function(e){return typeof e==="undefined"||e===ne},"(empty? object)\n\n Function return true if value is undfined empty list."),assoc:N(function(e,n){if(e instanceof te&&!(n instanceof te)){throw new Error("First argument to assoc ned to be a key")}Rn("assoc",n,"pair");var t=n;while(true){if(!(t instanceof te)||this.get("empty?")(t)){break}var r=t.car.car;if(ce(r,e)){return t.car}else if(!t.haveCycles("cdr")){t=t.cdr}}return ne},"(assoc key alist)\n\n Function search Alist (list of pairs) until it find the one that\n have head set equal to key, and return found pair."),gensym:N(Sn,"(gensym)\n\n Function generate unique symbol, to use with macros as meta name."),load:N(function(e){Rn("load",e,"string");var n=this;if(n.name==="__frame__"){n=n.parent}var i;if(n===En){i=n}else{i=this.get("**interaction-environment**")}if(typeof this.get("global",{throwError:false})!=="undefined"){return new Promise(function(t,r){require("fs").readFile(e.valueOf(),function(e,n){if(e){r(e)}else{Un(n.toString(),i).then(function(){t()})}})})}return f.fetch(e).then(function(e){return e.text()}).then(function(e){return Un(e,i)}).then(function(){})},"(load filename)\n\n Function fetch the file and evaluate its content as LIPS code."),while:N(new fe("while",function(r,e){var i=e.dynamic_scope,a=e.error;var o=this;var u=new te(new Z("begin"),r.cdr);var c;if(i){i=o}return function n(){var e=Jn(r.car,{env:o,dynamic_scope:i,error:a});function t(e){if(e&&!ye(e)){c=Jn(u,{env:o,dynamic_scope:i,error:a});if(ge(c)){return c.then(function(e){c=e;return n()})}else{return n()}}else{return c}}return L(e,t)}()}),"(while cond . body)\n\n Macro that create a loop, it exectue body untill cond expression is false"),if:N(new fe("if",function(t,e){var r=e.dynamic_scope,i=e.error;if(r){r=this}var a=this;var n=function e(n){if(n){return Jn(t.cdr.car,{env:a,dynamic_scope:r,error:i})}else{return Jn(t.cdr.cdr.car,{env:a,dynamic_scope:r,error:i})}};var o=Jn(t.car,{env:a,dynamic_scope:r,error:i});return L(o,n)}),"(if cond true-expr false-expr)\n\n Macro evaluate condition expression and if the value is true, it\n evaluate and return true expression if not it evaluate and return\n false expression"),"let-env":new fe("let-env",function(n){var e=arguments.length>1&&arguments[1]!==g?arguments[1]:{};var t=e.dynamic_scope,r=e.error;Rn("let-env",n,"pair");var i=Jn(n.car,{env:this,dynamic_scope:t,error:r});return L(i,function(e){if(!(e instanceof xn)){throw new Error("let-env: First argument need to be "+"environment")}return Jn(te(Z("begin"),n.cdr),{env:e,dynamic_scope:t,error:r})})},"(let-env env . body)\n\n Special macro that evaluate body in context of given environment\n object."),letrec:N(Le(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy and next value can access to\n previous values/names."),"let*":N(Le(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b)) body)\n\n Macro similar to `let` but next argument get environment\n from previous let variable, so they you can define one variable,\n and use in next argument."),let:N(Le(Symbol["for"]("let")),"(let ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy but you can't access\n previous values/names when next are evaluated. You can only get them\n from body of let expression."),"begin*":N(qe("begin*",function(e){return e.pop()}),"(begin* . expr)\n\n This macro is parallel version of begin. It evaluate each expression and\n if it's a promise it will evaluate it in parallel and return value\n of last expression."),begin:N(new fe("begin",function(e,n){var r=Object.assign({},n);var i=this.get("list->array")(e);if(r.dynamic_scope){r.dynamic_scope=this}r.env=this;var a;return function n(){if(i.length){var e=i.shift();var t=Jn(e,r);return L(t,function(e){a=e;return n()})}else{return a}}()}),"(begin . args)\n\n Macro runs list of expression and return valuate of the list one.\n It can be used in place where you can only have single exression,\n like if expression."),ignore:new fe("ignore",function(e,n){var t=n.dynamic_scope,r=n.error;var i={env:this,error:r};if(t){i.dynamic_scope=this}Jn(new te(new Z("begin"),e),i)},"(ignore expression)\n\n Macro that will evaluate expression and swallow any promises that may\n be created. It wil run and ignore any value that may be returned by\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),define:N(fe.defmacro("define",function(n,e){var t=this;if(n.car instanceof te&&n.car.car instanceof Z){var r=new te(new Z("define"),new te(n.car.car,new te(new te(new Z("lambda"),new te(n.car.cdr,n.cdr)))));return r}else if(e.macro_expand){return}if(e.dynamic_scope){e.dynamic_scope=this}e.env=t;var i=n.cdr.car;if(i instanceof te){i=Jn(i,e)}else if(i instanceof Z){i=t.get(i)}Rn("define",n.car,"symbol");L(i,function(e){t.set(n.car,e)})}),"(define name expression)\n (define (function-name . args) body)\n\n Macro for defining values. It can be used to define variables,\n or function. If first argument is list it will create function\n with name beeing first element of the list. The macro evalute\n code `(define function (lambda args body))`"),"set-obj!":N(function(e,n,t){var r=at(e);if(ye(e)||r!=="object"&&r!=="function"){var i=Cn("set-obj!",Tn(e),["object","function"]);throw new Error(i)}xe(e)[n]=t.valueOf()},"(set-obj! obj key value)\n\n Function set property of JavaScript object"),"null-environment":N(function(){return En.inherit("null")},"(null-environment)\n\n Function return new base environment with std lib."),values:N(function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&arguments[1]!==g?arguments[1]:{},p=e.dynamic_scope,h=e.error;var v=this;var d;if(l.cdr instanceof te&&Ge.isString(l.cdr.car)&&l.cdr.cdr!==ne){d=l.cdr.car.valueOf()}function m(){var e;if(p){if(!(this instanceof xn)){e=v}else{e=this}}else{e=v}e=e.inherit("lambda");var n=l.car;var t=0;var r;if(typeof this!=="undefined"){e.set("this",this)}for(var i=arguments.length,a=new Array(i),o=0;o2&&arguments[2]!==g?arguments[2]:u;if(e instanceof te){var r=e.car;var i=e.cdr;if(t(r)){r=n(r)}if(t(i)){i=n(i)}if(ge(r)||ge(i)){return Promise.all([r,i]).then(function(e){var n=rt(e,2),t=n[0],r=n[1];return new te(t,r)})}else{return new te(r,i)}}return e}function s(e,n){if(e instanceof te){if(n!==ne){e.append(n)}}else{e=new te(e,n)}return e}function f(r,e,n){if(er){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(t.cdr instanceof te){if(t.cdr.cdr!==ne){if(t.cdr.car instanceof te){return L(p(t.cdr.cdr,n,r),function(e){var n=Jn(t.cdr.car,{env:o,dynamic_scope:i,error:a});return new te(n,e)})}else{return t.cdr}}else{return Jn(t.cdr.car,{env:o,dynamic_scope:i,error:a})}}else{return t.cdr}}return c(t,function(e){return p(e,n,r)})}return t}function t(e){if(e instanceof te){delete e.data;if(!e.haveCycles("car")){t(e.car)}if(!e.haveCycles("cdr")){t(e.cdr)}}}var r=p(e.car,0,1);return L(r,function(e){t(e);return jn(e)})},"(quasiquote list ,value ,@value)\n\n Similar macro to `quote` but inside it you can use special\n expressions unquote abbreviated to , that will evaluate expresion inside\n and return its value or unquote-splicing abbreviated to ,@ that will\n evaluate expression but return value without parenthesis (it will join)\n the list with its value. Best used with macros but it can be used outside"),clone:N(function(e){Rn("clone",e,"pair");return e.clone()},"(clone list)\n\n Function return clone of the list."),append:N(function(e,n){Rn("append",e,["nil","pair"]);if(e instanceof te){e=e.clone()}return this.get("append!").call(this,e,n)},"(append list item)\n\n Function will create new list with value appended to the end. It return\n New list."),"append!":N(function(e,n){Rn("append!",e,["pair","nil"]);if(!this.get("list?")(e)){throw new Error("append!: Invalid argument, value is not a list")}if(ye(n)){return e}if(e===ne){if(n===ne){return ne}return n}return e.append(n)},"(append! name expression)\n\n Destructive version of append, it modify the list in place. It return\n original list."),reverse:N(function(e){Rn("reverse",e,["array","pair"]);if(e instanceof te){var n=this.get("list->array")(e).reverse();return this.get("array->list")(n)}else if(!(e instanceof Array)){throw new Error(Cn("reverse",Tn(e),"array or pair"))}else{return e.reverse()}},"(reverse list)\n\n Function will reverse the list or array. If value is not a list\n or array it will throw exception."),nth:N(function(e,n){Rn("nth",e,"number");Rn("nth",n,["array","pair"]);if(n instanceof te){var t=n;var r=0;while(rarray")(n).join(e)},"(join separator list)\n\n Function return string by joining elements of the list"),split:N(function(e,n){Rn("split",e,["regex","string"]);Rn("split",n,"string");return this.get("array->list")(n.split(e))},"(split separator string)\n\n Function create list by splitting string by separatar that can\n be a string or regular expression."),replace:N(function(e,n,t){Rn("replace",e,["regex","string"]);Rn("replace",n,["string","function"]);Rn("replace",t,"string");return t.replace(e,n)},"(replace pattern replacement string)\n\n Function change pattern to replacement inside string. Pattern can be string\n or regex and replacement can be function or string."),match:N(function(e,n){Rn("match",e,["regex","string"]);Rn("match",n,"string");var t=n.match(e);return t?this.get("array->list")(t):ne},"(match pattern string)\n\n function return match object from JavaScript as list."),search:N(function(e,n){Rn("search",e,["regex","string"]);Rn("search",n,"string");return n.search(e)},"(search pattern string)\n\n Function return first found index of the pattern inside a string"),repr:N(function e(n,t){return ie(n,t)},"(repr obj)\n\n Function return string LIPS representation of an object as string."),env:N(function(e){e=e||this;var n=Object.keys(e.env);var t;if(n.length){t=te.fromArray(n)}else{t=ne}if(e.parent!==g){return this.get("env").call(this,e.parent).append(t)}return t},"(env obj)\n\n Function return list values (functions and variables) inside environment."),new:N(function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r2&&arguments[2]!==g?arguments[2]:E.LITERAL;Rn("remove-special!",e,"string",1);Rn("remove-special!",n,"symbol",2);Kn.specials.append(e,n,t)},"(add-special! symbol name)\n\n Add special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! '#)` will allow to use `#(1 2 3)` and it will be\n transformed into (# (1 2 3)) so you can write # macro that will process\n the list. It's main purpose to to allow to use `define-symbol-macro`"),get:Ue,".":Ue,unbind:N(xe,"(unbind fn)\n\n Function remove bidning from function so you can get props from it."),type:N(Tn,"(type object)\n\n Function return type of an object as string."),debugger:N(function(){debugger},"(debugger)\n\n Function stop JavaScript code in debugger."),instanceof:N(function(e,n){return n instanceof xe(e)},"(instanceof type obj)\n\n Function check of object is instance of object."),"macro?":N(function(e){return e instanceof fe},"(macro? expression)\n\n Function check if value is a macro."),"function?":N(function(e){return typeof e==="function"},"(function? expression)\n\n Function check if value is a function."),"real?":N(function(e){if(Tn(e)!=="number"){return false}if(e instanceof tn){return e.isFloat()}return tn.isFloat(e)},"(real? number)\n\n Function check if value is real number."),"number?":N(tn.isNumber,"(number? expression)\n\n Function check if value is a number"),"string?":N(function(e){return Ge.isString(e)},"(string? expression)\n\n Function check if value is a string."),"pair?":N(function(e){return e instanceof te},"(pair? expression)\n\n Function check if value is a pair or list structure."),"regex?":N(function(e){return e instanceof RegExp},"(regex? expression)\n\n Function check if value is regular expression."),"null?":N(function(e){return ye(e)},"(null? expression)\n\n Function check if value is nulish."),"boolean?":N(function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Function check if value is boolean."),"symbol?":N(function(e){return e instanceof Z},"(symbol? expression)\n\n Function check if value is LIPS symbol"),"array?":N(function(e){return e instanceof Array},"(array? expression)\n\n Function check if value is an arrray."),"object?":N(function(e){return e!==ne&&e!==null&&!(e instanceof tn)&&at(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Function check if value is an object."),flatten:N(function(e){Rn("flatten",e,"pair");return e.flatten()},"(flatten list)\n\n Return shallow list from tree structure (pairs)."),"array->list":N(function(e){Rn("array->list",e,"array");return te.fromArray(e)},"(array->list array)\n\n Function convert JavaScript array to LIPS list."),"tree->array":N(re("tree->array",true),"(tree->array list)\n\n Function convert LIPS list structure into JavaScript array."),"list->array":N(re("list->array"),"(list->array list)\n\n Function convert LIPS list into JavaScript array."),apply:N(function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;rarray")(i));return e.apply(void 0,tt(t))},"(apply fn list)\n\n Function that call function with list of arguments."),length:N(function(e){if(!e){return tn(0)}if(e instanceof te){return tn(e.length())}if("length"in e){return tn(e.length)}},"(length expression)\n\n Function return length of the object, the object can be list\n or any object that have length property."),"string->number":N(function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:10;Rn("string->number",e,"string",1);Rn("string->number",n,"number",2);if(e.match(r)){return tn([e,n])}else if(e.match(i)){return tn(parseFloat(e))}return tn([e,n])},"(string->number number [radix])\n\n Function convert string to number."),try:N(new fe("try",function(a,e){var o=this;var u=e.dynamic_scope,c=e.error;return new Promise(function(i){var e={env:o,error:function e(n){if(n instanceof wn){throw new wn(n.message)}var t=o.inherit("try");t.set(a.cdr.car.cdr.car.car,n);var r={env:t,error:c};if(u){r.dynamic_scope=o}L(Jn(new te(new Z("begin"),a.cdr.car.cdr.cdr),r),function(e){i(e)});throw new wn(n.message)}};if(u){e.dynamic_scope=o}var n=Jn(a.car,e);if(ge(n)){n["catch"](e.error).then(i)}else{i(n)}})}),"(try expr (catch (e) code)"),throw:N(function(e){throw new Error(e)},"(throw string)\n\n Throw new expection."),find:N(function n(t,r){Rn("find",t,["regex","function"]);Rn("find",r,"pair");if(ye(r)){return ne}var e=q("find",t);return L(e(r.car),function(e){if(e&&e!==ne){return r.car}return n(t,r.cdr)})},"(find fn list)\n (find regex list)\n\n Higher order Function find first value for which function return true.\n If called with regex it will create matcher function."),"for-each":N(function(e){var n;Rn("for-each",e,"function");for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i1?n-1:0),a=1;a3?r-3:0),a=3;a3?i-3:0),o=3;oarray")(n);var a=[];var o=q("filter",e);return function n(t){function e(e){if(e&&e!==ne){a.push(r)}return n(++t)}if(t===i.length){return te.fromArray(a)}var r=i[t];return L(o(r,t),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher order function that call `fn` for each element of the list\n and return list for only those elements for which funtion return\n true value. If called with regex it will create matcher function."),range:N(function(e){Rn("range",e,"number");if(e instanceof tn){e=e.valueOf()}return te.fromArray(new Array(e).fill(0).map(function(e,n){return tn(n)}))},"(range n)\n\n Function return list of n numbers from 0 to n - 1"),compose:N(Ce,"(compose . fns)\n\n Higher order function and create new function that apply all functions\n From right to left and return it's value. Reverse of compose.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 3)\n 11\n "),pipe:N(Pe,"(pipe . fns)\n\n Higher order function and create new function that apply all functions\n From left to right and return it's value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 3)\n 15"),curry:N($e,"(curry fn . args)\n\n Higher order function that create curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning functions until all arguments are added\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"),gdc:N(function e(){for(var n=arguments.length,t=new Array(n),r=0;ra?u%=a:a%=u}u+=a}return tn(u)},"(gdc n1 n2 ...)\n\n Function return the greatest common divisor of their arguments."),lcm:N(function(){var e=arguments.length,n=oe(arguments.length<=0?g:arguments[0]);for(var t=1;tr?n%=r:r%=n}n=oe(i*(t<0||arguments.length<=t?g:arguments[t]))/(n+r)}return tn(n)},"(lcm n1 n2 ...)\n\n Function return the least common multiple of their arguments."),"odd?":N(Te(function(e){return tn(e).isOdd()}),"(odd? number)\n\n Function check if number os odd."),"even?":N(Te(function(e){return tn(e).isEven()}),"(even? number)\n\n Function check if number is even."),"*":N(De(function(e,n){return tn(e).mul(n)},tn(1)),"(* . numbers)\n\n Multiplicate all numbers passed as arguments. If single value is passed\n it will return that value."),"+":N(De(function(e,n){return tn(e).add(n)},tn(0)),"(+ . numbers)\n\n Sum all numbers passed as arguments. If single value is passed it will\n return that value."),"-":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t x1 x2 x3 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically increasing"),"<":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t=":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t= x1 x2 x3 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically nondecreasing"),"eq?":N(ce,"(eq? a b)\n\n Function compare two values if they are identical."),or:N(new fe("or",function(e,n){var i=n.dynamic_scope,a=n.error;var o=this.get("list->array")(e);var u=this;if(i){i=u}var c;return function n(){function e(e){c=e;if(c){return c}else{return n()}}var t=o.shift();if(typeof t==="undefined"){if(c){return c}else{return false}}else{var r=Jn(t,{env:u,dynamic_scope:i,error:a});return L(r,e)}}()}),"(or . expressions)\n\n Macro execute the values one by one and return the one that is truthy value.\n If there are no expression that evaluate to true it return false."),and:N(new fe("and",function(e){var n=arguments.length>1&&arguments[1]!==g?arguments[1]:{},i=n.dynamic_scope,a=n.error;var o=this.get("list->array")(e);var u=this;if(i){i=u}if(!o.length){return true}var c;return function n(){function e(e){c=e;if(!c){return false}else{return n()}}var t=o.shift();if(typeof t==="undefined"){if(c){return c}else{return false}}else{var r=Jn(t,{env:u,dynamic_scope:i,error:a});return L(r,e)}}()}),"(and . expressions)\n\n Macro evalute each expression in sequence if any value return false it will\n return false. If each value return true it will return the last value.\n If it's called without arguments it will return true."),"|":N(function(e,n){return tn(e).or(n)},"(& a b)\n\n Function calculate or bit operation."),"&":N(function(e,n){return tn(e).and(n)},"(& a b)\n\n Function calculate and bit operation."),"~":N(function(e){return tn(e).neg()},"(~ number)\n\n Function negate the value."),">>":N(function(e,n){return tn(e).shr(n)},"(>> a b)\n\n Function right shit the value a by value b."),"<<":N(function(e,n){return tn(e).shl(n)},"(<< a b)\n\n Function left shit the value a by value b."),not:N(function(e){if(ye(e)){return true}return!e},"(not object)\n\n Function return negation of the argument."),"->":N(function(e,n){for(var t=arguments.length,r=new Array(t>2?t-2:0),i=2;i obj name . args)\n\n Function get function from object and call it with arguments.")},g,"global");var Fn=En.inherit("user-env");En.set("**interaction-environment**",Fn);(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(n){var t=e[n]?e[n]:n;En.set(t,N(function(e){Rn(t,e,"number");if(e instanceof tn){return e[n]()}},"(".concat(t," number)\n\n Function calculate ").concat(t," of a number.")))})})();function An(e){if(e.length===1){return e[0]}else{var n=[];var t=An(e.slice(1));for(var r=0;r3&&arguments[3]!==g?arguments[3]:null;var i=e?" in function `".concat(e,"`"):"";if(r!==null){i+=" argument ".concat(r)}if(t instanceof Array){var a=t[t.length-1];t=t.slice(0,-1).join(", ")+" or "+a}return"Expecting ".concat(t," got ").concat(n).concat(i)}function Rn(e,n,t){var r=arguments.length>3&&arguments[3]!==g?arguments[3]:null;var i=Tn(n).toLowerCase();var a=false;if(t instanceof Array){t=t.map(function(e){return e.valueOf().toLowerCase()});if(t.includes(i)){a=true}}else{t=t.valueOf().toLowerCase()}if(!a&&i!==t){throw new Error(Cn(e,i,t,r))}}function Mn(e){var n=at(e);return["string","function"].includes(n)||e instanceof Z||e instanceof tn||e instanceof RegExp}function Tn(e){var n={pair:te,symbol:Z,character:Ye,values:On,macro:fe,string:Ge,array:Array,"native-symbol":Symbol};if(e===ne){return"nil"}if(e===null){return"null"}if(e instanceof he){return"syntax"}for(var t=0,r=Object.entries(n);t1&&arguments[1]!==g?arguments[1]:{},i=e.env,a=e.dynamic_scope,t=e.error,o=t===void 0?function(){}:t;try{if(a===true){i=a=i||En}else if(i===true){i=a=En}else{i=i||En}var r={env:i,dynamic_scope:a,error:o};var u;if(ye(n)){return n}if(n instanceof Z){return i.get(n)}var c=n.car;var s=n.cdr;if(c instanceof te){u=Bn(Jn(c,r));if(ge(u)){return u.then(function(e){return Jn(new te(e,n.cdr),r)})}else if(typeof u!=="function"){throw new Error(Tn(u)+" "+i.get("repr")(u)+" is not a function while evaluating "+n.toString())}}if(c instanceof Z){u=i.get(c);if(u instanceof he){return $n(u,n,r)}else if(u instanceof fe){return Hn(u,s,r)}else if(typeof u!=="function"){if(u){var f="".concat(Tn(u)," `").concat(u,"' is not a function");throw new Error(f)}throw new Error("Unknown function `".concat(c.name,"'"))}}else if(typeof c==="function"){u=c}if(typeof u==="function"){var l=Dn(s,r);return L(l,function(e){if(Oe(u)){e=e.map(we)}if(u.__lambda__){u=xe(u)}var n=e.slice();var t=(a||i).newFrame(u,n);var r=Bn(u.apply(t,e));return L(r,function(e){if(e instanceof te){e.markCycles();return jn(e)}if(typeof e==="number"){return tn(e)}if(typeof e==="string"){return Ge(e)}return e},o)})}else if(n instanceof Z){u=i.get(n);if(u==="undefined"){throw new Error("Unbound variable `"+n.name+"'")}return u}else if(n instanceof te){u=c&&c.toString();throw new Error("".concat(Tn(c)," ").concat(u," is not a function"))}else{return n}}catch(e){o&&o.call(i,e,n)}}function Un(e,n,t){return Yn.apply(this,arguments)}function Yn(){Yn=et(Zn.mark(function e(t,r,i){var a,o,u,c;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:if(i===true){r=i=r||Fn}else if(r===true){r=i=Fn}else{r=r||Fn}a=I(t);o=[];case 3:u=a.shift();if(u){n.next=9;break}return n.abrupt("return",o);case 9:n.next=11;return Jn(u,{env:r,dynamic_scope:i,error:function e(n,t){if(t){if(!(n.code instanceof Array)){n.code=[]}n.code.push(t.toString(true))}throw n}});case 11:c=n.sent;o.push(c);case 13:n.next=3;break;case 15:case"end":return n.stop()}}},e)}));return Yn.apply(this,arguments)}function Gn(n){if(n instanceof RegExp){return function(e){if(!e){return false}return(typeof e==="string"?e:e.token).match(n)}}else{return function(e){if(!e){return false}return(typeof e==="string"?e:e.token)===n}}}var zn=Gn(/[[\]()]/);function Vn(e){var n=typeof e==="string"?S(e):e;var t=n.filter(zn);var r=t.filter(Gn("("));var i=t.filter(Gn(")"));var a=t.filter(Gn("["));var o=t.filter(Gn("]"));return r.length===i.length&&a.length===o.length}te.unDry=function(e){return new te(e.car,e.cdr)};te.prototype.toDry=function(){return{value:{car:this.car,cdr:this.cdr}}};ee.prototype.toDry=function(){return{value:null}};ee.unDry=function(){return ne};Z.prototype.toDry=function(){return{value:{name:this.name}}};Z.unDry=function(e){return new Z(e.name)};function Qn(e){console.error(e.message||e);if(e.code){console.error(e.code.map(function(e,n){return"[".concat(n+1,"]: ").concat(e)}))}}function Xn(){var o=["text/x-lips","text/x-scheme"];if(!window.document){return Promise.resolve()}else{return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function n(){var e=a.shift();if(!e){i()}else{var t=e.getAttribute("type");if(o.includes(t)){var r=e.getAttribute("src");if(r){return f.fetch(r).then(function(e){return e.text()}).then(Un).then(n)["catch"](function(e){Qn(e);n()})}else{return Un(e.innerHTML).then(n)["catch"](function(e){Qn(e);n()})}}else if(t&&t.match(/lips|lisp/)){console.warn("Expecting "+o.join(" or ")+" found "+t)}return n()}}()})}}if(typeof window!=="undefined"){e(window,Xn)}B.__className="ahead";D.__className="pattern";T.__className="formatter";fe.__className="macro";he.__className="syntax";xn.__className="environment";vn.__className="input-port";dn.__className="output-port";mn.__className="output-string-port";yn.__className="input-string-port";var Kn={version:"DEV",banner:n,date:"Sat, 18 Apr 2020 08:38:56 +0000",exec:Un,parse:I,tokenize:S,evaluate:Jn,Environment:xn,global_environment:En,globalEnvironment:En,env:Fn,Interpreter:_n,balanced_parenthesis:Vn,balancedParenthesis:Vn,Macro:fe,Syntax:he,Pair:te,quote:jn,InputPort:vn,OutputPort:dn,InputStringPort:yn,OutputStringPort:mn,Formatter:T,specials:E,nil:ne,resolvePromises:Bn,LSymbol:Z,LNumber:tn,LFloat:an,LComplex:rn,LRational:fn,LBigInteger:ln,LCharacter:Ye,LString:Ge,rationalize:cn};En.set("lips",Kn);return Kn})})(); \ No newline at end of file +(function(){"use strict";function e(e,n){return n={exports:{}},e(n,n.exports),n.exports}var u=e(function(t){function r(e,n){t.exports=r=Object.setPrototypeOf||function e(n,t){n.__proto__=t;return n};return r(e,n)}t.exports=r});var Wn=e(function(r){function i(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true}catch(e){return false}}function a(e,n,t){if(i()){r.exports=a=Reflect.construct}else{r.exports=a=function e(n,t,r){var i=[null];i.push.apply(i,t);var a=Function.bind.apply(n,i);var o=new a;if(r)u(o,r.prototype);return o}}return a.apply(null,arguments)}r.exports=a});var n=e(function(e){var n=function(a){var e=Object.prototype;var s=e.hasOwnProperty;var c;var n=typeof Symbol==="function"?Symbol:{};var i=n.iterator||"@@iterator";var t=n.asyncIterator||"@@asyncIterator";var r=n.toStringTag||"@@toStringTag";function o(e,n,t,r){var i=n&&n.prototype instanceof u?n:u;var a=Object.create(i.prototype);var o=new F(r||[]);a._invoke=O(e,t,o);return a}a.wrap=o;function f(e,n,t){try{return{type:"normal",arg:e.call(n,t)}}catch(e){return{type:"throw",arg:e}}}var l="suspendedStart";var p="suspendedYield";var h="executing";var v="completed";var d={};function u(){}function m(){}function y(){}var g={};g[i]=function(){return this};var b=Object.getPrototypeOf;var w=b&&b(b(A([])));if(w&&w!==e&&s.call(w,i)){g=w}var _=y.prototype=u.prototype=Object.create(g);m.prototype=_.constructor=y;y.constructor=m;y[r]=m.displayName="GeneratorFunction";function x(e){["next","throw","return"].forEach(function(n){e[n]=function(e){return this._invoke(n,e)}})}a.isGeneratorFunction=function(e){var n=typeof e==="function"&&e.constructor;return n?n===m||(n.displayName||n.name)==="GeneratorFunction":false};a.mark=function(e){if(Object.setPrototypeOf){Object.setPrototypeOf(e,y)}else{e.__proto__=y;if(!(r in e)){e[r]="GeneratorFunction"}}e.prototype=Object.create(_);return e};a.awrap=function(e){return{__await:e}};function k(u){function c(e,n,t,r){var i=f(u[e],u,n);if(i.type==="throw"){r(i.arg)}else{var a=i.arg;var o=a.value;if(o&&typeof o==="object"&&s.call(o,"__await")){return Promise.resolve(o.__await).then(function(e){c("next",e,t,r)},function(e){c("throw",e,t,r)})}return Promise.resolve(o).then(function(e){a.value=e;t(a)},function(e){return c("throw",e,t,r)})}}var n;function e(t,r){function e(){return new Promise(function(e,n){c(t,r,e,n)})}return n=n?n.then(e,e):e()}this._invoke=e}x(k.prototype);k.prototype[t]=function(){return this};a.AsyncIterator=k;a.async=function(e,n,t,r){var i=new k(o(e,n,t,r));return a.isGeneratorFunction(n)?i:i.next().then(function(e){return e.done?e.value:i.next()})};function O(o,u,c){var s=l;return function e(n,t){if(s===h){throw new Error("Generator is already running")}if(s===v){if(n==="throw"){throw t}return I()}c.method=n;c.arg=t;while(true){var r=c.delegate;if(r){var i=S(r,c);if(i){if(i===d)continue;return i}}if(c.method==="next"){c.sent=c._sent=c.arg}else if(c.method==="throw"){if(s===l){s=v;throw c.arg}c.dispatchException(c.arg)}else if(c.method==="return"){c.abrupt("return",c.arg)}s=h;var a=f(o,u,c);if(a.type==="normal"){s=c.done?v:p;if(a.arg===d){continue}return{value:a.arg,done:c.done}}else if(a.type==="throw"){s=v;c.method="throw";c.arg=a.arg}}}}function S(e,n){var t=e.iterator[n.method];if(t===c){n.delegate=null;if(n.method==="throw"){if(e.iterator["return"]){n.method="return";n.arg=c;S(e,n);if(n.method==="throw"){return d}}n.method="throw";n.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var r=f(t,e.iterator,n.arg);if(r.type==="throw"){n.method="throw";n.arg=r.arg;n.delegate=null;return d}var i=r.arg;if(!i){n.method="throw";n.arg=new TypeError("iterator result is not an object");n.delegate=null;return d}if(i.done){n[e.resultName]=i.value;n.next=e.nextLoc;if(n.method!=="return"){n.method="next";n.arg=c}}else{return i}n.delegate=null;return d}x(_);_[r]="Generator";_[i]=function(){return this};_.toString=function(){return"[object Generator]"};function j(e){var n={tryLoc:e[0]};if(1 in e){n.catchLoc=e[1]}if(2 in e){n.finallyLoc=e[2];n.afterLoc=e[3]}this.tryEntries.push(n)}function E(e){var n=e.completion||{};n.type="normal";delete n.arg;e.completion=n}function F(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(j,this);this.reset(true)}a.keys=function(t){var r=[];for(var e in t){r.push(e)}r.reverse();return function e(){while(r.length){var n=r.pop();if(n in t){e.value=n;e.done=false;return e}}e.done=true;return e}};function A(n){if(n){var e=n[i];if(e){return e.call(n)}if(typeof n.next==="function"){return n}if(!isNaN(n.length)){var t=-1,r=function e(){while(++t=0;--n){var i=this.tryEntries[n];var a=i.completion;if(i.tryLoc==="root"){return e("end")}if(i.tryLoc<=this.prev){var o=s.call(i,"catchLoc");var u=s.call(i,"finallyLoc");if(o&&u){if(this.prev=0;--t){var r=this.tryEntries[t];if(r.tryLoc<=this.prev&&s.call(r,"finallyLoc")&&this.prev=0;--n){var t=this.tryEntries[n];if(t.finallyLoc===e){this.complete(t.completion,t.afterLoc);E(t);return d}}},catch:function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var t=this.tryEntries[n];if(t.tryLoc===e){var r=t.completion;if(r.type==="throw"){var i=r.arg;E(t)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,t){this.delegate={iterator:A(e),resultName:n,nextLoc:t};if(this.method==="next"){this.arg=c}return d}};return a}(e.exports);try{regeneratorRuntime=n}catch(e){Function("r","regeneratorRuntime = r")(n)}});var Zn=n;function c(e,n,t,r,i,a,o){try{var u=e[a](o);var c=u.value}catch(e){t(e);return}if(u.done){n(c)}else{Promise.resolve(c).then(r,i)}}function t(u){return function(){var e=this,o=arguments;return new Promise(function(n,t){var r=u.apply(e,o);function i(e){c(r,n,t,i,a,"next",e)}function a(e){c(r,n,t,i,a,"throw",e)}i(undefined)})}}var et=t;function r(e){if(Array.isArray(e))return e}var i=r;function a(e){if(Symbol.iterator in Object(e)||Object.prototype.toString.call(e)==="[object Arguments]")return Array.from(e)}var o=a;function s(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}var f=s;function l(e){return i(e)||o(e)||f()}var nt=l;function p(e){if(Array.isArray(e)){for(var n=0,t=new Array(e.length);n=0)continue;t[i]=e[i]}return t}var x=_;function k(e,n){if(e==null)return{};var t=x(e,n);var r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;t[r]=e[r]}}return t}var at=k;var ot=e(function(n){function t(e){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){t=function e(n){return typeof n}}else{t=function e(n){return n&&typeof Symbol==="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n}}return t(e)}function r(e){if(typeof Symbol==="function"&&t(Symbol.iterator)==="symbol"){n.exports=r=function e(n){return t(n)}}else{n.exports=r=function e(n){return n&&typeof Symbol==="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":t(n)}}return r(e)}n.exports=r});function O(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);if(e)r=r.filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable});t.push.apply(t,r)}return t}function ut(n){for(var e=1;e\n\nType (env) to see environment with functions macros and variables.\nYou can also use (help name) to display help for specic function or macro.\n").replace(/^.*\n/,"");return a}();var t=/^\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimy]*)$/;var r=/^(?:#x[-+]?[0-9a-f]+|#o[-+]?[0-7]+|#b[-+]?[01]+|[-+]?[0-9]+)$/i;var i=/^([-+]?([0-9]+([eE][-+]?[0-9]+)|(\.[0-9]+|[0-9]+\.[0-9]+)([eE][-+]?[0-9]+)?)|[0-9]+\.)$/;var a=["alarm","backspace","delete","escape","newline","null","return","space","tab"].join("|");var o=new RegExp("^#\\\\(?:".concat(a,"|[\\s\\S])$"),"i");var u=/^((?:(?:[-+]?[0-9]+(?:[eE][-+]?[0-9]+)?)|(?:[-+]?(?:(?:\.[0-9]+|[0-9]+\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\.))(?=[+-]|i))?((?:[-+]?[0-9]+(?:[eE][-+]?[0-9]+)?)|(?:[-+]?(?:(?:\.[0-9]+|[0-9]+\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\.))i|-i$/;var c=/^[-+]?[0-9]+\/[0-9]+$/;function s(e){var n=e.split("/");return fn({num:parseInt(n[0],10),denom:parseInt(n[1],10)})}function p(e){var n=e.match(/^(?:#([xbo]))?([+-]?[0-9a-f]+)$/i);var t;if(n&&n[1]){switch(n[1]){case"x":t=16;break;case"o":t=8;break;case"b":t=2;break}}else{t=10}return tn([n[2],t])}function h(e){var n=e.match(/#\\(.*)$/);if(n){return Ye(n[1])}}function v(e){if(e==="-i"){return{im:-1,re:0}}var n=e.match(u);var t,r;if(n.length===2){t=an(0);r=an(parseFloat(n[1]))}else{t=an(n[1]?parseFloat(n[1]):0);r=an(parseFloat(n[2]))}return rn({im:r,re:t})}function d(e){var n=/([^\\\n])(\\(?:\\{2})*)(?!u[0-9AF]{1,4})(.)/gi;e=e.replace(n,function(e,n,t,r){if(!['"',"/","b","f","n","r","t"].includes(r)){t=t.substring(1).replace(/\\\\/,"\\");return n+t+r}return e}).replace(/\n/g,"\\n");try{return Ge(JSON.parse(e))}catch(e){throw new Error("Invalid string literal")}}function x(e){var n=e.match(t);if(n){return new RegExp(n[1],n[2])}else if(e.match(/^"/)){return d(e)}else if(e.match(o)){return h(e)}else if(e.match(c)){return s(e)}else if(e.match(u)){return v(e)}else if(e.match(r)){return p(e)}else if(e.match(i)){return an(parseFloat(e))}else if(e==="nil"){return ne}else if(e==="true"){return true}else if(e==="false"){return false}else{return new Z(e)}}function m(e){return!(["(",")"].includes(e)||e.match(t)||e.match(/['"]/)||e.match(r)||e.match(i)||["nil","true","false"].includes(e))}var y=/("(?:\\[\S\s]|[^"])*"|\/(?! )[^\n\/\\]*(?:\\[\S\s][^\n\/\\]*)*\/[gimy]*(?=\s|\[|\]|\(|\)|$)|;.*)/g;var g=/"(?:\\[\S\s]|[^"])*"/g;function b(){var e=E.names().sort(function(e,n){return n.length-e.length||e.localeCompare(n)}).map(k).join("|");return new RegExp("(#\\\\(?:".concat(a,"|[\\s\\S])|#f|#t|#[xbo][0-9a-f]+(?=[\\s()]|$)|[0-9]+/[0-9]+|\\[|\\]|\\(|\\)|;.*|(?:(?:[-+]?(?:(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)[0-9]i)|\\n|\\.{2,}|(?!#:)(?:").concat(e,")|[^(\\s)[\\]]+)"),"gim")}function w(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:1;return e[e.length-n]}function k(e){if(typeof e==="string"){var n=/([-\\^$[\]()+{}?*.|])/g;return e.replace(n,"\\$1")}}function O(e){var a=b();e=e.replace(/\n\r|\r/g,"\n");var o=0;var u=0;var c=[];var s=[];var f=0;e.split(y).filter(Boolean).forEach(function(e){if(e.match(y)){f=0;if(s.length){var n=w(s);if(n.token.match(/\n/)){var t=n.token.split("\n").pop();f+=t.length}else{f+=n.token.length}f+=n.col}var r={col:f,line:u,token:e,offset:o};c.push(r);s.push(r);o+=e.length;f+=e.length;u+=(e.match("\n")||[]).length;return}var i=e.split(a).filter(Boolean);i.forEach(function(e){var n={col:f,line:u,token:e,offset:o};f+=e.length;o+=e.length;c.push(n);s.push(n);if(e==="\n"){++u;s=[];f=0}})});return c}function S(e){var n=e.token,t=at(e,["token"]);if(n.match(/^"[\s\S]+"$/)&&n.match(/\n/)){var r=new RegExp("^ {1,"+(e.col+1)+"}","mg");n=n.replace(r,"")}return ut({token:n},t)}function j(e,n){var t=arguments.length>2&&arguments[2]!==_?arguments[2]:S;if(n){return O(e).map(t)}else{return O(e).map(function(e){var n=t(e);if(!n||typeof n.token!=="string"){throw new Error("[tokenize] Invalid formatter wrong return object")}if(n.token==="#\\ "){return n.token}return n.token.trim()}).filter(function(e){return e&&!e.match(/^;/)})}}var E={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),names:function e(){return Object.keys(this._specials)},type:function e(n){return this.get(n).type},get:function e(n){return this._specials[n]},append:function e(n,t,r){this._specials[n]={seq:n,symbol:t,type:r}},_specials:{}};function F(e){return E.type(e)===E.LITERAL}var A=[["'",new Z("quote"),E.LITERAL],["`",new Z("quasiquote"),E.LITERAL],[",@",new Z("unquote-splicing"),E.LITERAL],[",",new Z("unquote"),E.LITERAL]];A.forEach(function(e){var n=rt(e,3),t=n[0],r=n[1],i=n[2];E.append(t,r,i)});function I(e){if(typeof e==="string"){e=j(e)}var c=[];var s=[];var f=null;var l=E.names();var p=l.map(function(e){return E.get(e).symbol.name});var h=0;var v=false;var d=[];var m=[];var y=0;var g=Z(Symbol["for"]("__splice__"));function b(e){return e==="("||e==="["}function w(e){return e===")"||e==="]"}function _(){var e=c[c.length-1];if(e instanceof Array&&e[0]instanceof Z&&p.includes(e[0].name)&&c.length>1&&!e[0].literal){c.pop();if(c[c.length-1].length===1&&c[c.length-1][0]instanceof Z){c[c.length-1].push(e)}else if(c[c.length-1]instanceof te){if(c[c.length-1].cdr instanceof te){c[c.length-1]=new te(c[c.length-1],te.fromArray(e))}else{c[c.length-1].cdr=te.fromArray(e)}}else{c[c.length-1].push(e)}}}e.forEach(function(e){var n=c[c.length-1];if(l.indexOf(e)!==-1){y++;f=e;c.push([E.get(f).symbol]);if(!f){m=[]}m.push(f)}else{if(f){d.push(m);m=[]}if(b(e)){v=true;h++;var t=[];if(f&&!F(f)){t.push(g)}c.push(t);f=null;y=0}else if(e==="."&&!v){c[c.length-1]=te.fromArray(n)}else if(w(e)){h--;if(!c.length){throw new Error("Unbalanced parenthesis")}if(c.length===1){var r=c.pop();if(r instanceof Array&&r.length===0){r=ne}s.push(r)}else if(c.length>1){var i=c.pop();n=c[c.length-1];if(n instanceof Array){if(i.length===0){n.push(ne)}else if(i instanceof Array&&i[0]===g){var a;(a=n).push.apply(a,tt(i.slice(1)))}else{n.push(i)}}else if(n instanceof te){if(i.length===0){n.append(ne)}else{n.append(te.fromArray(i))}}if(d.length){m=d.pop();while(m.length){_();m.pop()}}else{_()}}if(h===0&&c.length){s.push(c.pop())}}else{v=false;var o=x(e);if(f){while(y--){c[c.length-1].push(o);o=c.pop()}d.pop();y=0;f=false}else if(o instanceof Z&&p.includes(o.name)){o.literal=true}n=c[c.length-1];if(n instanceof te){var u=n;while(true){if(u.cdr===ne){if(o instanceof Array){u.cdr=te.fromArray(o)}else{u.cdr=o}break}else{u=u.cdr}}}else if(!c.length){s.push(o)}else{n.push(o)}}}});if(!e.filter(function(e){return e.match(/^[[\]()]$/)}).length&&c.length){s=s.concat(c);c=[]}if(c.length){throw new Error("Unbalanced parenthesis 2")}return s.map(function(e){if(e instanceof Array){return te.fromArray(e)}return e})}function L(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:function(e){return e};var t=arguments.length>2&&arguments[2]!==_?arguments[2]:null;if(e instanceof Array){var r=e.filter(ge);if(r.length){return L(Promise.all(r),n,t)}return n(e)}if(ge(e)){var i=e.then(n);if(t===null){return i}else{return i["catch"](t)}}return n(e)}function q(e,n){if(n instanceof RegExp){return function(e){return String(e).match(n)}}else if(typeof n!=="function"){throw new Error("".concat(e," argument need to be a function or RegExp"))}else{return n}}function N(e,n,t){if(n){if(t){e.__doc__=n}else{e.__doc__=P(n)}}return e}function P(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function C(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:1;var t=e.length;if(n<=0){throw Error("previousSexp: Invlaid argument sexp = ".concat(n))}e:while(n--&&t>=0){var r=1;while(r>0){var i=e[--t];if(!i){break e}if(i==="("||i.token==="("){r--}else if(i===")"||i.token===")"){r++}}t--}return e.slice(t+1)}function R(e){if(!e||!e.length){return 0}var n=e.length;if(e[n-1].token==="\n"){return 0}while(--n){if(e[n].token==="\n"){var t=(e[n+1]||{}).token;if(t){return t.length}}}return 0}function M(e,n){return s(e,n)===n.length;function s(e,n){function t(){return i>0&&o>0&&e[i-1]===n[o-1]&&e[i+1]===n[o]}function r(){return e[i]===Symbol["for"]("symbol")&&!m(n[o])}var i=0;var a={};for(var o=0;o0){continue}}else if(r()){return-1}}else if(e[i]instanceof Array){var c=s(e[i],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;i++;continue}else{return-1}i++}if(e.length!==i){return-1}return n.length}}function B(e){this._code=e.replace(/\r/g,"")}B.defaults={offset:0,indent:2,exceptions:{specials:[/^define/,"lambda","let*",/^(let|letrec)(-syntax)?$/,"let-env","syntax-rules","try","catch"],shift:{1:["&","#"]}}};B.match=M;B.prototype._options=function e(n){var t=B.defaults;if(typeof n==="undefined"){return Object.assign({},t)}var r=n&&n.exceptions||{};var i=r.specials||[];var a=r.shift||{1:[]};return ut({},t,{},n,{exceptions:{specials:[].concat(tt(t.exceptions.specials),tt(i)),shift:ut({},a,{1:[].concat(tt(t.exceptions.shift[1]),tt(a[1]))})}})};B.prototype.indent=function e(n){var t=j(this._code,true);return this._indent(t,n)};B.exception_shift=function(c,e){function n(e){if(!e.length){return false}if(e.indexOf(c)!==-1){return true}else{var n=e.filter(function(e){return e instanceof RegExp});if(!n.length){return false}var t=true;var r=false;var i=_;try{for(var a=n[Symbol.iterator](),o;!(t=(o=a.next()).done);t=true){var u=o.value;if(c.match(u)){return true}}}catch(e){r=true;i=e}finally{try{if(!t&&a["return"]!=null){a["return"]()}}finally{if(r){throw i}}}}return false}if(n(e.exceptions.specials)){return e.indent}var t=e.exceptions.shift;for(var r=0,i=Object.entries(t);r0){r.offset=0}if(a.toString()===n.toString()&&Vn(a)){return r.offset+a[0].col}else if(a.length===1){return r.offset+a[0].col+1}else{var u=-1;if(o){var c=B.exception_shift(o.token,r);if(c!==-1){u=c}}if(u===-1){u=B.exception_shift(a[1].token,r)}if(u!==-1){return r.offset+a[0].col+u}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return r.offset+a[1].col}return r.offset+a[3].col}else if(a[0].line===a[1].line){return r.offset+r.indent+a[0].col}else{var s=a.slice(2);for(var f=0;f1&&arguments[1]!==_?arguments[1]:true;if(e instanceof te){return e}if(n===false){var t=ne;for(var r=e.length;r--;){t=new te(e[r],t)}return t}if(e.length&&!(e instanceof Array)){e=tt(e)}if(e.length===0){return ne}else{var i;if(e[0]instanceof Array){i=te.fromArray(e[0])}else{i=e[0]}if(typeof i==="string"){i=Ge(i)}if(e.length===1){return new te(i,ne)}else{return new te(i,te.fromArray(e.slice(1)))}}};te.prototype.toObject=function(){var e=this;var n={};while(true){if(e instanceof te&&e.car instanceof te){var t=e.car;var r=t.car;if(r instanceof Z){r=r.name}if(r instanceof String){r=r.valueOf()}var i=t.cdr;if(i instanceof te){i=i.toObject()}if(i instanceof tn||i instanceof Ge){i=i.valueOf()}n[r]=i;e=e.cdr}else{break}}return n};te.fromPairs=function(e){return e.reduce(function(e,n){return new te(new te(new Z(n[0]),n[1]),e)},ne)};te.fromObject=function(n){var e=Object.keys(n).map(function(e){return[e,n[e]]});return te.fromPairs(e)};te.prototype.reduce=function(e){var n=this;var t=ne;while(true){if(n!==ne){t=e(t,n.car);n=n.cdr}else{break}}return t};te.prototype.reverse=function(){if(this.haveCycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var n=ne;while(e!==ne){var t=e.cdr;e.cdr=n;n=e;e=t}return n};te.prototype.transform=function(r){function i(e){if(e instanceof te){if(e.replace){delete e.replace;return e}var n=r(e.car);if(n instanceof te){n=i(n)}var t=r(e.cdr);if(t instanceof te){t=i(t)}return new te(n,t)}return e}return i(this)};te.prototype.map=function(e){if(typeof this.car!=="undefined"){return new te(e(this.car),this.cdr===ne?ne:this.cdr.map(e))}else{return ne}};function ie(n,t){if(typeof jQuery!=="undefined"&&n instanceof jQuery.fn.init){return"<#jQuery("+n.length+")>"}if(n===true){return"#t"}if(n===false){return"#f"}if(typeof n==="undefined"){return"<#undefined>"}if(n instanceof te){return n.toString(t)}var e=[RegExp,ee,Z,tn,Ye,On];for(var r=0,i=e;r"}return"<#procedure>"}if(n instanceof Array){return"#("+n.map(function(e){return ie(e,true)}).join(" ")+")"}if(n instanceof Ge){n=n.toString()}if(n===null||typeof n==="string"&&t){return JSON.stringify(n).replace(/\\n/g,"\n")}if(f.HTMLElement&&n instanceof f.HTMLElement){return"<#HTMLElement(".concat(n.tagName.toLowerCase(),")>")}if(ot(n)==="object"){if(typeof n.toString==="function"&&n.toString.__lambda__){return n.toString().valueOf()}var o=n.constructor;var u=ot(n)==="object"&&o===Object;if(u){return"&("+Object.keys(n).map(function(e){return":".concat(e," ").concat(ie(n[e],t))}).join(" ")+")"}var c;if(typeof o.__className==="string"){c=o.__className}else if(Bn(n)==="instance"){c="instance"}else{c=o.name}if(c!==""){return"<#"+c+">"}return"<#Object>"}if(typeof n!=="string"){return n.toString()}return n}te.prototype.markCycles=function(){ae(this);return this};te.prototype.haveCycles=function(){var e=arguments.length>0&&arguments[0]!==_?arguments[0]:null;if(!e){return this.haveCycles("car")||this.haveCycles("cdr")}return!!(this.cycles&&this.cycles[e])};function ae(e){var i=[];var n=[];function a(e){if(e instanceof te){if(i.includes(e)){if(!n.includes(e)){n.push(e)}return"#".concat(n.length-1,"#")}}}function o(e){if(e instanceof te){i.push(e);var n={};var t=a(e.car);var r=a(e.cdr);if(t){n["car"]=t}else{o(e.car)}if(r){n["cdr"]=r}else{o(e.cdr)}if(t||r){e.cycles=n}else if(e.cycles){delete e.cycles}}}o(e)}te.prototype.toString=function(e){var n=["("];if(this.car!==_){var t;if(this.cycles&&this.cycles.car){t=this.cycles.car}else{t=ie(this.car,e)}if(t!==_){n.push(t)}if(this.cdr instanceof te){if(this.cycles&&this.cycles.cdr){n.push(" . ");n.push(this.cycles.cdr)}else{var r=this.cdr.toString(e).replace(/^\(|\)$/g,"");n.push(" ");n.push(r)}}else if(typeof this.cdr!=="undefined"&&this.cdr!==ne){n=n.concat([" . ",ie(this.cdr,e)])}}n.push(")");return n.join("")};te.prototype.set=function(e,n){this[e]=n;if(n instanceof te){this.markCycles()}};te.prototype.append=function(e){if(e instanceof Array){return this.append(te.fromArray(e))}var n=this;if(n.car===_){if(e instanceof te){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(e!==ne){while(true){if(n instanceof te&&n.cdr!==ne){n=n.cdr}else{break}}n.cdr=e}return this};function oe(e){return e<0?-e:e}function ue(e,n){var t=nt(n),r=t[0],i=t.slice(1);while(i.length>0){var a=i,o=rt(a,1),u=o[0];if(!e(r,u)){return false}var c=i;var s=nt(c);r=s[0];i=s.slice(1)}return true}function ce(e,n){if(typeof e==="function"&&typeof n==="function"){return xe(e)===xe(n)}else if(e instanceof tn&&n instanceof tn){return e.type===n.type&&e.cmp(n)===0}else if(typeof e==="number"||typeof n==="number"){e=tn(e);n=tn(n);return e.type===n.type&&e.cmp(n)===0}else if(e instanceof Ye&&n instanceof Ye){return e["char"]===n["char"]}else if(e instanceof Z&&n instanceof Z){return e.name===n.name}else{return e===n}}var se=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function fe(e,n,t,r){if(typeof this!=="undefined"&&this.constructor!==fe||typeof this==="undefined"){return new fe(e,n)}Rn("Macro",e,"string",1);Rn("Macro",n,"function",2);if(t){if(r){this.__doc__=t}else{this.__doc__=P(t)}}this.name=e;this.fn=n}fe.defmacro=function(e,n,t,r){var i=new fe(e,n,t,r);i.defmacro=true;return i};fe.prototype.invoke=function(e,n,t){var r=n.env,i=n.dynamic_scope,a=n.error;var o={dynamic_scope:i,error:a,macro_expand:t};var u=this.fn.call(r,e,o,this.name);return u};fe.prototype.toString=function(){return"#"};var le="define-macro";function pe(i){return function(){var t=et(Zn.mark(function e(t,f){var l,p,r;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:r=function e(){r=et(Zn.mark(function e(t,r){var i,a,o,u,c,s;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:if(!(t instanceof te&&t.car instanceof Z)){n.next=18;break}if(!t.data){n.next=3;break}return n.abrupt("return",t);case 3:i=l.get(t.car,{throwError:false});if(!(i instanceof fe&&i.defmacro)){n.next=18;break}a=i instanceof he?t:t.cdr;n.next=8;return i.invoke(a,f,true);case 8:o=n.sent;if(!(o instanceof Z)){n.next=11;break}return n.abrupt("return",Sn(o));case 11:if(!(o instanceof te)){n.next=18;break}if(!(typeof r==="number")){n.next=16;break}if(!(r<=1)){n.next=15;break}return n.abrupt("return",o);case 15:r=r-1;case 16:console.log({result:o.toString()});return n.abrupt("return",p(o,r));case 18:u=t.car;if(!(u instanceof te)){n.next=23;break}n.next=22;return p(u);case 22:u=n.sent;case 23:c=t.cdr;if(!(c instanceof te)){n.next=28;break}n.next=27;return p(c);case 27:c=n.sent;case 28:s=new te(u,c);return n.abrupt("return",s);case 30:case"end":return n.stop()}}},e)}));return r.apply(this,arguments)};p=function e(n,t){return r.apply(this,arguments)};l=f["env"]=this;if(!i){n.next=11;break}n.t0=Sn;n.next=7;return p(t,1);case 7:n.t1=n.sent.car;return n.abrupt("return",(0,n.t0)(n.t1));case 11:n.t2=Sn;n.next=14;return p(t,-1);case 14:n.t3=n.sent.car;return n.abrupt("return",(0,n.t2)(n.t3));case 16:case"end":return n.stop()}}},e,this)}));return function(e,n){return t.apply(this,arguments)}}()}function he(e,n){this.name="syntax";this.env=n;this.fn=e;this.defmacro=true}he.prototype=Object.create(fe.prototype);he.prototype.invoke=function(e,n,t){var r=n.error,i=n.env;var a={error:r,env:i,dynamic_scope:this.env,macro_expand:t};return this.fn.call(i,e,a,this.name)};he.prototype.constructor=he;he.prototype.toString=function(){return"<#syntax>"};he.className="syntax";function ve(e,n){var v={"...":{symbols:{},lists:[]}};function d(e){if(Fn.get("DEBUG",{throwError:false})){console.log(e)}}function m(e,n){var t=arguments.length>2&&arguments[2]!==_?arguments[2]:[];var r=arguments.length>3&&arguments[3]!==_?arguments[3]:false;d({code:n.toString(),pattern:e.toString()});if(e instanceof te&&e.car instanceof te&&e.car.cdr instanceof te&&Z.is(e.car.cdr.car,"...")){d(">> 0");if(n===ne){d({pattern:e.toString()});if(e.car.car instanceof Z){if(e.car.cdr instanceof te&&Z.is(e.car.cdr.car,"...")){var i=e.car.car.valueOf();var a=e.lastPair();if(Z.is(a.car,"...")){v["..."].symbols[i]=null;return true}else{return false}}var o=e.car.car.valueOf();if(v["..."].symbols[o]){throw new Error("syntax: named ellipsis can only "+"appear onces")}v["..."].symbols[o]=n}return true}}if(e instanceof te&&e.cdr instanceof te&&Z.is(e.cdr.car,"...")){if(e.cdr.cdr!==ne){throw new Error("syntax: invalid usage of ellipsis")}if(e.car instanceof Z){var u=e.car.valueOf();if(v["..."].symbols[u]&&!t.includes(u)){throw new Error("syntax: named ellipsis can only appear onces")}d(">> 1");if(n===ne){d(">> 2");if(r){v["..."].symbols[u]=ne}else{return false}}else if(n instanceof te&&(n.car instanceof te||n.car===ne)){d(">> 3 "+r);if(r){v["..."].symbols[u]=n.car}else{d(">> 4");v["..."].symbols[u]=new te(n,ne)}}else{d(">> 6");if(n instanceof te){d(">> 7 "+r);t.push(u);if(!v["..."].symbols[u]){v["..."].symbols[u]=new te(n,ne)}else{var c=v["..."].symbols[u];v["..."].symbols[u]=c.append(new te(n,ne))}d({IIIIII:v["..."].symbols[u].toString()})}else{d(">> 8");return false}}return true}else if(e.car instanceof te){var s=tt(t);if(n===ne){d(">> 9");v["..."].lists.push(ne);return true}d(">> 10");var f=n;while(f instanceof te){if(!m(e.car,f.car,s,true)){return false}f=f.cdr}return true}return false}if(e instanceof Z){if(Z.is(e,"...")){throw new Error("syntax: invalid usage of ellipsis")}d(">> 11");var l=e.valueOf();d({name:l});if(r){v["..."].symbols[l]=v["..."].symbols[l]||[];v["..."].symbols[l].push(n)}if(!v[l]){v[l]=n}return true}if(e instanceof te&&n instanceof te){d(">> 12");d(n.toString());if(n.cdr===ne){var p=e.car instanceof Z&&e.cdr instanceof Z;if(p){d(">> 12 | 1");var h=e.cdr.valueOf();if(!v[h]){v[h]=ne}h=e.car.valueOf();if(!v[h]){v[h]=n.car}return true}}if(m(e.car,n.car,t,r)&&m(e.cdr,n.cdr,t,r)){return true}}else if(e===ne&&n===ne){return true}else if(e.car instanceof te&&Z.is(e.car.car,"...")){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(m(e,n)){return v}}function de(e,i){function a(n){if(n instanceof te){if(!i.length){return n}var e=a(n.car);var t=a(n.cdr);return new te(e,t)}else if(n instanceof Z){var r=i.find(function(e){return e.gensym===n});if(r){return Z(r.name)}return n}else{return n}}return a(e)}function me(v,e,r,n,i){var a={};function m(e){if(!(e instanceof Z||typeof e==="string")){throw new Error("syntax: internal error, rename neeed to be symbol")}var n=e.valueOf();if(n==="..."){throw new Error("syntax: internal error, ellipis not transformed")}if(typeof n==="string"&&n in v){return v[n]}return t(n)}function y(e){if(Fn.get("DEBUG",{throwError:false})){console.log(e)}}function t(e){if(!a[e]){var n=r.get(e,{throwError:false});var t=jn(e);i.push({name:e,gensym:t});if(typeof n!=="undefined"){r.set(t,n)}a[e]=t}return a[e]}function g(e,n){if(!e){return}if(e instanceof te){return e.car}if(e instanceof Array){var t=rt(e,1),r=t[0];if(r instanceof Array){if(n){return te.fromArray(r)}return r}return r}}function b(e,n,t){var r=arguments.length>3&&arguments[3]!==_?arguments[3]:function(){};y(" ==> "+e.toString());if(e instanceof Z){var i=e.valueOf();y("[t 1");var a=g(n[i]);if(n[i]){if(n[i]instanceof te){var o=n[i],u=o.car,c=o.cdr;if(t){var s=u.car,f=u.cdr;if(f!==ne){r(i,new te(f,ne))}return s}if(c!==ne){r(i,c)}return u}else if(n[i]instanceof Array){r(i,n[i].slice(1));return n[i][0]}}return m(i)}if(e instanceof te){if(e.car instanceof Z&&e.cdr instanceof te&&Z.is(e.cdr.car,"...")){y("[t 2");var l=e.car.valueOf();var p=n[l];if(p){y({b:n[l]});if(p instanceof te){y("[t 2 Pair "+t);y({______:p.toString()});var h=p.car,v=p.cdr;if(t){if(v!==ne){r(l,v)}return h}else{if(h.cdr!==ne){r(l,new te(h.cdr,v))}return h.car}}else if(p instanceof Array){y("[t 2 Array "+t);if(t){r(l,p.slice(1));return te.fromArray(p)}else{var d=p.slice(1);if(d.length){r(l,d)}return p[0]}}else{return p}}}y("[t 3 recur "+e.toString());return new te(b(e.car,n,t,r),b(e.cdr,n,t,r))}}function d(e){var n=Object.values(e);return n.length&&n.every(function(e){return e instanceof te||e===ne||e instanceof Array&&e.length})}function w(i){if(i instanceof te){if(i.cdr instanceof te&&Z.is(i.cdr.car,"...")){y(">> 1");var e=v["..."].symbols;var n=Object.keys(e);if(i.car instanceof te){if(v["..."].lists[0]===ne){return ne}y(">> 2");var t;if(n.length){y(">> 2 (a)");var a=ut({},e);t=ne;var r=function e(){if(!d(a)){return"break"}var r={};var n=function e(n,t){r[n]=t};t=new te(b(i.car,a,true,n),t);a=r};while(true){var o=r();if(o==="break")break}if(t!==ne){t=t.reverse()}return t}else{y(">> 3");var u=b(i.car,e,true);if(u){return new te(u,ne)}return ne}}else if(i.car instanceof Z){y(">> 4");var c=i.car.valueOf();var s=it({},c,e[c]);var f=ne;var l=function e(){if(!d(s)){y({bind:s});return"break"}var r={};var n=function e(n,t){r[n]=t};y({EXPR:i.toString()});var t=b(i,s,false,n);f=new te(t,f);s=r};while(true){var p=l();if(p==="break")break}if(f!==ne){f=f.reverse()}if(i.cdr instanceof te&&i.cdr.cdr instanceof te){f.append(w(i.cdr.cdr))}return f}}return new te(w(i.car),w(i.cdr))}if(i instanceof Z){var h=m(i);if(typeof h!=="undefined"){return h}}return i}return w(e)}function ye(e){return typeof e==="undefined"||e===ne||e===null}function ge(e){return e instanceof Promise||e&&typeof e!=="undefined"&&typeof e.then==="function"}function be(e){switch(ot(e)){case"string":return Ge(e);case"number":return tn(e)}return e}function we(e){return e.valueOf()}function _e(e,n){if(e instanceof te){e.markCycles();return Sn(e)}if(typeof e==="function"){if(n){return ke(e,n)}}return be(e)}function xe(e){if(Oe(e)){return e[Se]}return e}function ke(n,e){if(n[Symbol["for"]("__bound__")]){return n}var t=n.bind(e);var r=Object.getOwnPropertyNames(n).filter(Ee);r.forEach(function(e){try{t[e]=n[e]}catch(e){}});Fe(t,"__fn__",n);Fe(t,"__bound__",true);if(Ie(n)){Fe(t,"__native__",true)}t.valueOf=function(){return n};return t}function Oe(e){return typeof e==="function"&&e[Se]}var Se=Symbol["for"]("__fn__");var je=["name","length","caller","callee","arguments","prototype"];function Ee(e){return!je.includes(e)}function Fe(e,n,t){Object.defineProperty(e,Symbol["for"](n),{get:function e(){return t},set:function e(){},configurable:false,enumerable:false})}function Ae(n,t){try{Object.defineProperty(n,"length",{get:function e(){return t}});return n}catch(e){var r=new Array(t).fill(0).map(function(e,n){return"a"+n}).join(",");var i=new Function("f","return function(".concat(r,") {\n return f.apply(this, arguments);\n };"));return i(n)}}function Ie(e){var n=Symbol["for"]("__native__");return typeof e==="function"&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[n]===true||!e.name.match(/^bound /)&&!e[n])}function Le(e){var h;switch(e){case Symbol["for"]("letrec"):h="letrec";break;case Symbol["for"]("let"):h="let";break;case Symbol["for"]("let*"):h="let*";break;default:throw new Error("Invalid let_macro value")}return fe.defmacro(h,function(a,e){var o=e.dynamic_scope,u=e.error,n=e.macro_expand;var c;if(a.car instanceof Z){if(!(a.cdr.car instanceof te)){throw new Error("let require list of pairs")}var t=a.cdr.car.map(function(e){return e.car});c=a.cdr.car.map(function(e){return e.cdr.car});return te.fromArray([Z("letrec"),[[a.car,te(Z("lambda"),te(t,a.cdr.cdr))]],te(a.car,c)])}else if(n){return}var s=this;c=this.get("list->array")(a.car);var f=s.inherit(h);var l;if(h==="let*"){l=f}var p=0;return function e(){var n=c[p++];function t(e){if(ge(e)){return e.then(t)}else if(typeof e==="undefined"){f.set(n.car,ne)}else{f.set(n.car,e)}}if(o){o=h==="let*"?f:s}if(!n){var r=new te(new Z("begin"),a.cdr);return Jn(r,{env:f,dynamic_scope:o,error:u})}else{if(h==="let"){l=s}else if(h==="letrec"){l=f}var i=Jn(n.cdr.car,{env:l,dynamic_scope:o,error:u});if(h==="let*"){l=f=l.inherit("let*["+p+"]")}return L(t(i),e)}}()})}function qe(e,c){return new fe(e,function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:{},t=n.dynamic_scope,r=n.error;var i=this;if(t){t=this}var a=e;var o=[];while(a instanceof te){o.push(Jn(a.car,{env:i,dynamic_scope:t,error:r}));a=a.cdr}var u=o.filter(ge).length;if(u){return Promise.all(o).then(c.bind(this))}else{return c.call(this,o)}})}function Ne(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r2?r-2:0),a=2;a1&&arguments[1]!==_?arguments[1]:null;return function(){for(var e=arguments.length,n=new Array(e),t=0;t1?e-1:0),t=1;t=o){return a.apply(this,r)}else{return i}}return i.apply(this,arguments)}}function He(r,i){Rn("limit",i,"function",2);return function(){for(var e=arguments.length,n=new Array(e),t=0;t1?r-1:0),a=1;a0){t.push(this._string.substring(0,e))}t.push(n);if(e0&&arguments[0]!==_?arguments[0]:null;if(e===null){return on(this.value.valueOf())}return un(e.valueOf())(this.value.valueOf())};var on=un(1e-10);function un(r){return function(e){var n=function e(r,n,t){var i=function e(n,t){return t0){i=sn(r,t)}else if(r.cmp(t)<=0){i=t}else if(t.cmp(0)>0){i=sn(t,r)}else if(n.cmp(0)<0){i=tn(sn(r.sub(),t.sub())).sub()}else{i=tn(0)}if(tn.isFloat(n)||tn.isFloat(e)){return an(i)}return i}function sn(e,n){var t=tn(e).floor();var r=tn(n).floor();if(e.cmp(t)<1){return t}else if(t.cmp(r)===0){var i=tn(1).div(n.sub(r));var a=tn(1).div(e.sub(t));return t.add(tn(1).div(sn(i,a)))}else{return t.add(tn(1))}}function fn(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof fn)||typeof this==="undefined"){return new fn(e,n)}if(!tn.isRational(e)){throw new Error("Invalid constructor call for LBigInteger")}if(e.num%e.denom===0&&!n){return tn(e.num/e.denom)}this.num=tn(e.num);this.denom=tn(e.denom);this.type="rational"}fn.prototype=Object.create(tn.prototype);fn.prototype.constructor=fn;fn.prototype.pow=function(e){var n=e.cmp(0);if(n===0){return tn(1)}if(n===-1){e=e.sub();var t=this.denom.pow(e);var r=this.num.pow(e);return fn({num:t,denom:r})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};fn.prototype.abs=function(){var e=this.num;var n=this.denom;if(e.cmp(0)===-1){e=e.sub()}if(n.cmp(0)!==1){n=n.sub()}return fn({num:e,denom:n})};fn.prototype.cmp=function(e){return tn(this.valueOf()).cmp(e)};fn.prototype.toString=function(){var e=En.get("gdc")(this.num,this.denom);if(e!==1){e=tn(e);return this.num.div(e)+"/"+this.denom.div(e)}return this.num+"/"+this.denom};fn.prototype.valueOf=function(){return an(this.num.valueOf()).div(this.denom.valueOf())};fn.prototype.mul=function(e){if(tn.isRational(e)){var n=this.num.mul(e.num);var t=this.denom.mul(e.denom);return fn({num:n,denom:t})}return tn(this.valueOf()).mul(e)};fn.prototype.div=function(e){if(tn.isRational(e)){var n=this.num.mul(e.denom);var t=this.denom.mul(e.num);return fn({num:n,denom:t})}return tn(this.valueOf()).div(e)};fn.prototype.op=function(e,n){return this[hn[e]](n)};fn.prototype.sub=function(e){if(tn.isRational(e)){var n=e.num.sub();var t=e.denom;return this.add(fn({num:n,denom:t}))}if(!(e instanceof tn)){e=tn(e).sub()}else{e=e.sub()}if(tn.isFloat(e)){return an(this.valueOf()).add(e)}return this.add(e)};fn.prototype.add=function(e){if(tn.isRational(e)){var n=this.denom;var t=e.denom;var r=this.num;var i=e.num;var a,o;if(n!==t){o=t.mul(r).add(i.mul(n));a=n.mul(t)}else{o=r.add(i);a=n}return fn({num:o,denom:a})}if(tn.isFloat(e)){return an(this.valueOf()).add(e)}return tn(this.valueOf()).add(e)};function ln(e,n){if(typeof this!=="undefined"&&!(this instanceof ln)||typeof this==="undefined"){return new ln(e,n)}if(e instanceof ln){return ln(e.value,e._native)}if(!tn.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.value=e;this._native=n;this.type="bigint"}ln.prototype=Object.create(tn.prototype);ln.prototype.constructor=ln;ln.prototype.op=function(e,n){if(tn.isBN(this.value)&&tn.isBN(n.value)){var t={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};e=t[e];return ln(this.value.clone()[e](n),false)}if(n instanceof fn){return fn({num:this,denom:1},true)[hn[e]](n)}if(e==="/"){return fn({num:this,denom:n})}return ln(tn._ops[e](this.value,n&&n.value),true)};ln.prototype.sqrt=function(){var e;var n=this.cmp(0)<0;if(tn.isNative(this.value)){e=Math.sqrt(n?-this.valueOf():this.valueOf())}else if(tn.isBN(this.value)){e=n?this.value.neg().sqrt():this.value.sqrt()}if(n){return rn({re:0,im:e})}return e};tn.isFloat=function e(n){return n instanceof an||Number(n)===n&&n%1!==0};tn.isNumber=function(e){return e instanceof tn||!Number.isNaN(e)&&tn.isNative(e)||tn.isBN(e)};tn.isComplex=function(e){return e instanceof rn||tn.isNumber(e.im)&&tn.isNumber(e.re)};tn.isRational=function(e){return e instanceof fn||tn.isNumber(e.num)&&tn.isNumber(e.denom)};tn.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};tn.isBigInteger=function(e){return e instanceof ln||typeof e==="bigint"||tn.isBN(e)};tn.isBN=function(e){return typeof l!=="undefined"&&e instanceof l};tn.getArgsType=function(e,n){if(e instanceof an||n instanceof an){return an}if(e instanceof ln||n instanceof ln){return ln}return tn};tn.prototype.toString=tn.prototype.toJSON=function(e){if(e>2&&e<36){return this.value.toString(e)}return this.value.toString()};tn.prototype.isBigNumber=function(){return typeof this.value==="bigint"||typeof l!=="undefined"&&!(this.value instanceof l)};["floor","ceil","round"].forEach(function(e){tn.prototype[e]=function(){if(this["float"]||tn.isFloat(this.value)){return tn(Math[e](this.value))}else{return tn(Math[e](this.valueOf()))}}});tn.prototype.valueOf=function(){if(tn.isNative(this.value)){return Number(this.value)}else if(tn.isBN(this.value)){return this.value.toNumber()}};tn.prototype.coerce=function(e){if(e===null){e=0}var n;if(e instanceof tn){n=e.value}else{n=e}if(this instanceof an){return an(e.valueOf())}if(this instanceof rn){return rn({re:n,im:0})}if(this instanceof fn&&!tn.isRational(e)){return tn(n)}if(tn.isComplex(e)){return rn(e)}else if(tn.isRational(e)){return fn(e)}else if(tn.isFloat(n)||this instanceof an){return an(n)}else if(typeof this.value==="bigint"&&typeof n!=="bigint"){return ln(BigInt(n))}else if(typeof l!=="undefined"&&this.value instanceof l&&!n instanceof l){return ln(new l(n))}return tn(n)};tn.getType=function(e){if(e instanceof tn){return e.type}if(tn.isFloat(e)){return"float"}if(tn.isComplex(e)){return"complex"}if(tn.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof l!=="undefined"&&!(e instanceof l)){return"bigint"}};tn.prototype.isFloat=function(){return!!(tn.isFloat(this.value)||this["float"])};tn.prototype.add=function(e){return tn(this.valueOf()+e.valueOf())};tn.prototype.sub=function(){var e=arguments.length>0&&arguments[0]!==_?arguments[0]:null;if(e===null){return tn(-this.valueOf())}return tn(this.valueOf()-e.valueOf())};tn.prototype.mul=function(e){if(e instanceof rn){return rn(this).mul(e)}return tn(this.valueOf()*e.valueOf())};tn.prototype.div=function(e){if(e instanceof rn){return rn(this).mul(e)}return tn(this.valueOf()/e.valueOf())};tn.prototype.rem=function(e){return tn(this.valueOf()%e.valueOf())};tn.prototype.mod=function(e){return tn(this.valueOf()%e.valueOf())};tn.prototype.or=function(e){return tn(this.ValueOf()|e.valueOf())};tn.prototype.and=function(e){return tn(this.valueOf()&e.valueOf())};tn.prototype.neg=function(){return tn(~this.valueOf())};tn.prototype.shl=function(e){return tn(this.valueOf()>>e.valueOf())};tn.prototype.shr=function(e){return this.op(e)};var pn={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var hn={};Object.keys(pn).forEach(function(n){hn[pn[n]]=n;tn.prototype[n]=function(e){return this.op(pn[n],e)}});tn._ops={"*":function e(n,t){return n*t},"+":function e(n,t){return n+t},"-":function e(n,t){if(typeof t==="undefined"){return-n}return n-t},"/":function e(n,t){return n/t},"%":function e(n,t){return n%t},"|":function e(n,t){return n|t},"&":function e(n,t){return n&t},"~":function e(n){return~n},">>":function e(n,t){return n>>t},"<<":function e(n,t){return n<"};function mn(n){var t=this;if(typeof this!=="undefined"&&!(this instanceof mn)||typeof this==="undefined"){return new mn(n)}Rn("OutputStringPort",n,"function");this._buffer=[];this.write=function(e){if(!Ge.isString(e)){e=n(e)}else{e=e.valueOf()}t._buffer.push(e)}}mn.prototype=Object.create(dn.prototype);mn.prototype.getString=function(){return this._buffer.map(function(e){return e.valueOf()}).join("")};mn.prototype.constructor=mn;function yn(e){var n=this;if(typeof this!=="undefined"&&!(this instanceof yn)||typeof this==="undefined"){return new yn(e)}Rn("InputStringPort",e,"string");this._tokens=j(e);this._index=0;this._in_char=0;this.read=function(){return n.getNextTokens()}}yn.prototype=Object.create(vn.prototype);yn.prototype.constructor=yn;yn.prototype.getNextTokens=function(){if(this.peekChar()===gn){return gn}var e=0;var n=[];var t=["(",")"];if(!t.includes(this._tokens[this._index])){return this._tokens[this._index++]}do{var r=this._tokens[this._index];n.push(this._tokens[this._index]);if(r===")"){e--}else if(r==="("){e++}this._index++}while(e!==0);return n};yn.prototype.peekChar=function(){if(this._index>this._tokens.length-1){return gn}if(this._index===this._tokens.length-1&&this.in_char>this._tokens[this._index].length){return gn}return this._tokens[this._index][this.in_char]};var gn=new bn;function bn(){}bn.prototype.toString=function(){return"<#eof>"};function wn(e){this.message=e}wn.prototype=Object.create(Error.prototype);function _n(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:{};if(typeof this!=="undefined"&&!(this instanceof _n)||typeof this==="undefined"){return new _n(e,n)}if(typeof e==="undefined"){e="anonymous"}this.env=Fn.inherit(e,n)}_n.prototype.exec=function(){var n=et(Zn.mark(function e(t){var r,i=arguments;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:r=i.length>1&&i[1]!==_?i[1]:false;Rn("Intepreter::exec",t,"string",1);Rn("Intepreter::exec",r,"boolean",2);En.set("**interaction-environment**",this.env);return n.abrupt("return",Un(t,this.env,r?this.env:false));case 5:case"end":return n.stop()}}},e,this)}));return function(e){return n.apply(this,arguments)}}();_n.prototype.get=function(e){return this.env.get(e).bind(this.env)};_n.prototype.set=function(e,n){return this.env.set(e,n)};function xn(e,n,t){if(arguments.length===1){if(ot(arguments[0])==="object"){e=arguments[0];this.parent=null}else if(typeof arguments[0]==="string"){e={};n={};t=arguments[0]}}this.env=e;this.parent=n;this.name=t||"anonymous"}xn.prototype.inherit=function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:{};if(ot(e)==="object"){n=e}if(!e||ot(e)==="object"){e="child of "+(this.name||"unknown")}return new xn(n||{},this,e)};xn.prototype.newFrame=function(e,n){var r=this.inherit("__frame__");r.set("parent.frame",N(function(){var e=arguments.length>0&&arguments[0]!==_?arguments[0]:1;var n=r.parent;if(!(n instanceof xn)){return ne}if(e<=0){return n}var t=n.get("parent.frame");return t(e-1)},En.env["parent.frame"].__doc__));n.callee=e;r.set("arguments",n);return r};xn.prototype._lookup=function(e){if(e instanceof Z){e=e.name}if(e instanceof Ge){e=e.valueOf()}if(e in this.env){return kn(this.env[e])}if(this.parent){return this.parent._lookup(e)}};xn.prototype.toString=function(){return"<#env:"+this.name+">"};xn.prototype.clone=function(){var n=this;var t={};Object.keys(this.env).forEach(function(e){t[e]=n.env[e]});return new xn(t,this.parent,this.name)};xn.prototype.merge=function(e){Rn("Environment::merge",e,"environment");return this.inherit("merge",e.env)};function kn(e){if(typeof this!=="undefined"&&!(this instanceof kn)||typeof this==="undefined"){return new kn(e)}this.value=e}kn.isUndefined=function(e){return e instanceof kn&&typeof e.value==="undefined"};kn.prototype.valueOf=function(){return this.value};function On(e){if(e.length){if(e.length===1){return e[0]}}if(typeof this!=="undefined"&&!(this instanceof On)||typeof this==="undefined"){return new On(e)}this.values=e}On.prototype.toString=function(){return this.values.map(function(e){return ie(e)}).join("\n")};On.prototype.valueOf=function(){return this.values};xn.prototype.get=function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:{};var t=n.throwError,r=t===void 0?true:t;var i=e;if(i instanceof Z||i instanceof Ge){i=i.valueOf()}var a=this._lookup(i);if(a instanceof kn){if(kn.isUndefined(a)){return _}return _e(a.valueOf())}if(typeof i==="string"){var o=i.split(".").filter(Boolean);if(o.length>0){var u=nt(o),c=u[0],s=u.slice(1);a=this._lookup(c);if(s.length){try{if(a instanceof kn){a=a.valueOf();return Ue.apply(void 0,[a].concat(tt(s)))}else{return Ue.apply(void 0,[f].concat(tt(o)))}}catch(e){}}else if(a instanceof kn){return _e(a.valueOf())}}a=Ue(f,i)}if(typeof a!=="undefined"){return a}if(r){throw new Error("Unbound variable `"+i.toString()+"'")}};xn.prototype.set=function(e,n){if(tn.isNumber(n)){n=tn(n)}if(e instanceof Z){e=e.name}else if(e instanceof Ge){e=e.valueOf()}this.env[e]=n};xn.prototype.has=function(e){return typeof this.env[e]!=="undefined"};xn.prototype.ref=function(e){var n=this;while(true){if(!n){break}if(n.has(e)){return n}n=n.parent}};xn.prototype.parents=function(){var e=this;var n=[];while(e){n.unshift(e);e=e.parent}return n};function Sn(e){if(ge(e)){return e.then(Sn)}if(e instanceof te||e instanceof Z){e.data=true}return e}var jn=function(){var n=0;return function(){var e=arguments.length>0&&arguments[0]!==_?arguments[0]:null;if(e instanceof Z){e=e.valueOf()}if(e!==null){return new Z(Symbol("#:".concat(e)))}n++;return new Z(Symbol("#:g".concat(n)))}}();var En=new xn({nil:ne,undefined:_,true:true,false:false,NaN:NaN,stdout:new dn(function(){var e;(e=console).log.apply(e,arguments)}),stdin:vn(function(){return new Promise(function(e){e(prompt(""))})}),"open-input-string":N(function(e){Rn("open-input-string",e,"string");return yn(e)},"(open-input-string string)\n\n Function create new string port as input that can be used to\n read S-exressions from this port using `read` function."),"output-port?":N(function(e){return e instanceof dn},"(output-port? arg)\n\n Function return true if argument is output port."),"input-port?":N(function(e){return e instanceof vn},"(input-port? arg)\n\n Function return true if argument is input port."),"open-output-string":N(function(){return mn(this.get("repr"))},"(open-output-string)\n\n Function create new output port that can used to write string into\n and after finish get the whole string using `get-output-string`"),"get-output-string":N(function(e){Rn("get-output-string",e,"output-string-port");return e.getString()},"(get-output-string port)\n\n Function get full string from string port. If nothing was wrote\n to given port it will return empty string."),"eof-object?":N(function(e){return e===gn},"(eof-object? arg)\n\n Function check if value is eof object, returned from input string\n port when there are no more data to read."),"peek-char":N(function(e){Rn("peek-char",e,["input-port","input-string-port"]);return e.peekChar()},"(peek-char port)\n\n Function get character from string port or EOF object if no more\n data in string port."),read:N(function n(e){var t=this;if(typeof e==="string"){return I(j(e))[0]}if(e instanceof yn){var r=e.read();if(r===gn){return gn}return I(r)[0]}var i;if(e instanceof vn){i=e}else{i=this.get("stdin")}return i.read().then(function(e){return n.call(t,e)})},"(read [string])\n\n Function if used with string will parse the string and return\n list structure of LIPS code. If called without an argument it\n will read string from standard input (using browser prompt or\n user defined way) and call itself with that string (parse is)\n function can be used together with eval to evaluate code from\n string"),pprint:N(function(e){if(e instanceof te){e=new Kn.Formatter(e.toString(true))["break"]().format();this.get("stdout").write.call(this,e)}else{this.get("display").call(this,e)}},"(pprint expression)\n\n Pretty print list expression, if called with non-pair it just call\n print function with passed argument."),print:N(function(){var n=this;for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),i=1;ir.length){throw new Error("Not enough arguments")}var u=0;var c=this.get("repr");n=n.replace(a,function(e){var n=e[1];if(n==="~"){return"~"}else if(n==="%"){return"\n"}else{var t=r[u++];if(n==="a"){return c(t)}else{return c(t,true)}}});o=n.match(/~([\S])/);if(o){throw new Error("format: Unrecognized escape seqence ".concat(o[1]))}return n},"(format string n1 n2 ...)\n\n Function accepts string template and replacing any escape sequences\n by arguments:\n\n * ~a value as if printed with display\n * ~s value as if printed with write\n * ~% newline character\n * ~~ literal tilde '~' is inserted\n\n if there missing arguments or other escape character it throw exception."),display:N(function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:null;if(n===null){n=this.get("stdout")}n.write.call(this,this.get("repr")(e))},"(display arg [port])\n\n Function send string to standard output or provied port."),error:N(function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&arguments[1]!==_?arguments[1]:{},t=e.dynamic_scope,r=e.error;if(t){t=this}var i=Jn(n.cdr.car,{env:this,dynamic_scope:t,error:r});i=Tn(i);var a;function o(n,t){if(ge(n)){return n.then(function(e){return o(e,t)})}if(ge(t)){return t.then(function(e){return o(n,e)})}s[n]=t;return t}if(n.car instanceof te&&Z.is(n.car.car,".")){var u=n.car.cdr.car;var c=n.car.cdr.cdr.car;var s=Jn(u,{env:this,dynamic_scope:t,error:r});var f=Jn(c,{env:this,dynamic_scope:t,error:r});return o(f,i)}if(!(n.car instanceof Z)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}a=this.ref(n.car.name);if(!a){a=this}return L(i,function(e){a.set(n.car,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable (mutate)\n it search the scope chain until it finds first non emtpy slot and set it."),"set-car!":N(function(e,n){Rn("set-car!",e,"pair");e.car=n},"(set-car! obj value)\n\n Function that set car (head) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"set-cdr!":N(function(e,n){Rn("set-cdr!",e,"pair");e.cdr=n},"(set-cdr! obj value)\n\n Function that set cdr (tail) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"empty?":N(function(e){return typeof e==="undefined"||e===ne},"(empty? object)\n\n Function return true if value is undfined empty list."),assoc:N(function(e,n){if(e instanceof te&&!(n instanceof te)){throw new Error("First argument to assoc ned to be a key")}Rn("assoc",n,"pair");var t=n;while(true){if(!(t instanceof te)||this.get("empty?")(t)){break}var r=t.car.car;if(ce(r,e)){return t.car}else if(!t.haveCycles("cdr")){t=t.cdr}}return ne},"(assoc key alist)\n\n Function search Alist (list of pairs) until it find the one that\n have head set equal to key, and return found pair."),gensym:N(jn,"(gensym)\n\n Function generate unique symbol, to use with macros as meta name."),load:N(function(e){Rn("load",e,"string");var n=this;if(n.name==="__frame__"){n=n.parent}var i;if(n===En){i=n}else{i=this.get("**interaction-environment**")}if(typeof this.get("global",{throwError:false})!=="undefined"){return new Promise(function(t,r){require("fs").readFile(e.valueOf(),function(e,n){if(e){r(e)}else{Un(n.toString(),i).then(function(){t()})}})})}return f.fetch(e).then(function(e){return e.text()}).then(function(e){return Un(e,i)}).then(function(){})},"(load filename)\n\n Function fetch the file and evaluate its content as LIPS code."),while:N(new fe("while",function(r,e){var i=e.dynamic_scope,a=e.error;var o=this;var u=new te(new Z("begin"),r.cdr);var c;if(i){i=o}return function n(){var e=Jn(r.car,{env:o,dynamic_scope:i,error:a});function t(e){if(e&&!ye(e)){c=Jn(u,{env:o,dynamic_scope:i,error:a});if(ge(c)){return c.then(function(e){c=e;return n()})}else{return n()}}else{return c}}return L(e,t)}()}),"(while cond . body)\n\n Macro that create a loop, it exectue body untill cond expression is false"),if:N(new fe("if",function(t,e){var r=e.dynamic_scope,i=e.error;if(r){r=this}var a=this;var n=function e(n){if(n){return Jn(t.cdr.car,{env:a,dynamic_scope:r,error:i})}else{return Jn(t.cdr.cdr.car,{env:a,dynamic_scope:r,error:i})}};var o=Jn(t.car,{env:a,dynamic_scope:r,error:i});return L(o,n)}),"(if cond true-expr false-expr)\n\n Macro evaluate condition expression and if the value is true, it\n evaluate and return true expression if not it evaluate and return\n false expression"),"let-env":new fe("let-env",function(n){var e=arguments.length>1&&arguments[1]!==_?arguments[1]:{};var t=e.dynamic_scope,r=e.error;Rn("let-env",n,"pair");var i=Jn(n.car,{env:this,dynamic_scope:t,error:r});return L(i,function(e){if(!(e instanceof xn)){throw new Error("let-env: First argument need to be "+"environment")}return Jn(te(Z("begin"),n.cdr),{env:e,dynamic_scope:t,error:r})})},"(let-env env . body)\n\n Special macro that evaluate body in context of given environment\n object."),letrec:N(Le(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy and next value can access to\n previous values/names."),"let*":N(Le(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b)) body)\n\n Macro similar to `let` but next argument get environment\n from previous let variable, so they you can define one variable,\n and use in next argument."),let:N(Le(Symbol["for"]("let")),"(let ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy but you can't access\n previous values/names when next are evaluated. You can only get them\n from body of let expression."),"begin*":N(qe("begin*",function(e){return e.pop()}),"(begin* . expr)\n\n This macro is parallel version of begin. It evaluate each expression and\n if it's a promise it will evaluate it in parallel and return value\n of last expression."),begin:N(new fe("begin",function(e,n){var r=Object.assign({},n);var i=this.get("list->array")(e);if(r.dynamic_scope){r.dynamic_scope=this}r.env=this;var a;return function n(){if(i.length){var e=i.shift();var t=Jn(e,r);return L(t,function(e){a=e;return n()})}else{return a}}()}),"(begin . args)\n\n Macro runs list of expression and return valuate of the list one.\n It can be used in place where you can only have single exression,\n like if expression."),ignore:new fe("ignore",function(e,n){var t=n.dynamic_scope,r=n.error;var i={env:this,error:r};if(t){i.dynamic_scope=this}Jn(new te(new Z("begin"),e),i)},"(ignore expression)\n\n Macro that will evaluate expression and swallow any promises that may\n be created. It wil run and ignore any value that may be returned by\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),define:N(fe.defmacro("define",function(n,e){var t=this;if(n.car instanceof te&&n.car.car instanceof Z){var r=new te(new Z("define"),new te(n.car.car,new te(new te(new Z("lambda"),new te(n.car.cdr,n.cdr)))));return r}else if(e.macro_expand){return}if(e.dynamic_scope){e.dynamic_scope=this}e.env=t;var i=n.cdr.car;if(i instanceof te){i=Jn(i,e)}else if(i instanceof Z){i=t.get(i)}Rn("define",n.car,"symbol");L(i,function(e){t.set(n.car,e)})}),"(define name expression)\n (define (function-name . args) body)\n\n Macro for defining values. It can be used to define variables,\n or function. If first argument is list it will create function\n with name beeing first element of the list. The macro evalute\n code `(define function (lambda args body))`"),"set-obj!":N(function(e,n,t){var r=ot(e);if(ye(e)||r!=="object"&&r!=="function"){var i=Cn("set-obj!",Bn(e),["object","function"]);throw new Error(i)}e=xe(e);if(typeof t==="undefined"){delete e[n]}else{e[n]=t.valueOf()}},"(set-obj! obj key value)\n\n Function set property of JavaScript object"),"null-environment":N(function(){return En.inherit("null")},"(null-environment)\n\n Function return new base environment with std lib."),values:N(function(){for(var e=arguments.length,n=new Array(e),t=0;t1&&arguments[1]!==_?arguments[1]:{},p=e.dynamic_scope,h=e.error;var v=this;var d;if(l.cdr instanceof te&&Ge.isString(l.cdr.car)&&l.cdr.cdr!==ne){d=l.cdr.car.valueOf()}function m(){var e;if(p){if(!(this instanceof xn)){e=v}else{e=this}}else{e=v}e=e.inherit("lambda");var n=l.car;var t=0;var r;if(typeof this!=="undefined"){e.set("this",this)}for(var i=arguments.length,a=new Array(i),o=0;o2&&arguments[2]!==_?arguments[2]:u;if(e instanceof te){var r=e.car;var i=e.cdr;if(t(r)){r=n(r)}if(t(i)){i=n(i)}if(ge(r)||ge(i)){return Promise.all([r,i]).then(function(e){var n=rt(e,2),t=n[0],r=n[1];return new te(t,r)})}else{return new te(r,i)}}return e}function s(e,n){if(e instanceof te){if(n!==ne){e.append(n)}}else{e=new te(e,n)}return e}function f(r,e,n){if(er){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(t.cdr instanceof te){if(t.cdr.cdr!==ne){if(t.cdr.car instanceof te){return L(p(t.cdr.cdr,n,r),function(e){var n=Jn(t.cdr.car,{env:o,dynamic_scope:i,error:a});return new te(n,e)})}else{return t.cdr}}else{return Jn(t.cdr.car,{env:o,dynamic_scope:i,error:a})}}else{return t.cdr}}return c(t,function(e){return p(e,n,r)})}return t}function t(e){if(e instanceof te){delete e.data;if(!e.haveCycles("car")){t(e.car)}if(!e.haveCycles("cdr")){t(e.cdr)}}}var r=p(e.car,0,1);return L(r,function(e){t(e);return Sn(e)})},"(quasiquote list ,value ,@value)\n\n Similar macro to `quote` but inside it you can use special\n expressions unquote abbreviated to , that will evaluate expresion inside\n and return its value or unquote-splicing abbreviated to ,@ that will\n evaluate expression but return value without parenthesis (it will join)\n the list with its value. Best used with macros but it can be used outside"),clone:N(function(e){Rn("clone",e,"pair");return e.clone()},"(clone list)\n\n Function return clone of the list."),append:N(function(e,n){Rn("append",e,["nil","pair"]);if(e instanceof te){e=e.clone()}return this.get("append!").call(this,e,n)},"(append list item)\n\n Function will create new list with value appended to the end. It return\n New list."),"append!":N(function(e,n){Rn("append!",e,["pair","nil"]);if(!this.get("list?")(e)){throw new Error("append!: Invalid argument, value is not a list")}if(ye(n)){return e}if(e===ne){if(n===ne){return ne}return n}return e.append(n)},"(append! name expression)\n\n Destructive version of append, it modify the list in place. It return\n original list."),reverse:N(function(e){Rn("reverse",e,["array","pair"]);if(e instanceof te){var n=this.get("list->array")(e).reverse();return this.get("array->list")(n)}else if(!(e instanceof Array)){throw new Error(Cn("reverse",Bn(e),"array or pair"))}else{return e.reverse()}},"(reverse list)\n\n Function will reverse the list or array. If value is not a list\n or array it will throw exception."),nth:N(function(e,n){Rn("nth",e,"number");Rn("nth",n,["array","pair"]);if(n instanceof te){var t=n;var r=0;while(rarray")(n).join(e)},"(join separator list)\n\n Function return string by joining elements of the list"),split:N(function(e,n){Rn("split",e,["regex","string"]);Rn("split",n,"string");return this.get("array->list")(n.split(e))},"(split separator string)\n\n Function create list by splitting string by separatar that can\n be a string or regular expression."),replace:N(function(e,n,t){Rn("replace",e,["regex","string"]);Rn("replace",n,["string","function"]);Rn("replace",t,"string");return t.replace(e,n)},"(replace pattern replacement string)\n\n Function change pattern to replacement inside string. Pattern can be string\n or regex and replacement can be function or string."),match:N(function(e,n){Rn("match",e,["regex","string"]);Rn("match",n,"string");var t=n.match(e);return t?this.get("array->list")(t):ne},"(match pattern string)\n\n function return match object from JavaScript as list."),search:N(function(e,n){Rn("search",e,["regex","string"]);Rn("search",n,"string");return n.search(e)},"(search pattern string)\n\n Function return first found index of the pattern inside a string"),repr:N(function e(n,t){return ie(n,t)},"(repr obj)\n\n Function return string LIPS representation of an object as string."),env:N(function(e){e=e||this;var n=Object.keys(e.env);var t;if(n.length){t=te.fromArray(n)}else{t=ne}if(e.parent!==_){return this.get("env").call(this,e.parent).append(t)}return t},"(env obj)\n\n Function return list values (functions and variables) inside environment."),new:N(function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r2&&arguments[2]!==_?arguments[2]:E.LITERAL;Rn("remove-special!",e,"string",1);Rn("remove-special!",n,"symbol",2);Kn.specials.append(e,n,t)},"(add-special! symbol name)\n\n Add special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! '#)` will allow to use `#(1 2 3)` and it will be\n transformed into (# (1 2 3)) so you can write # macro that will process\n the list. It's main purpose to to allow to use `define-symbol-macro`"),get:Ue,".":Ue,unbind:N(xe,"(unbind fn)\n\n Function remove bidning from function so you can get props from it."),type:N(Bn,"(type object)\n\n Function return type of an object as string."),debugger:N(function(){debugger},"(debugger)\n\n Function stop JavaScript code in debugger."),instanceof:N(function(e,n){return n instanceof xe(e)},"(instanceof type obj)\n\n Function check of object is instance of object."),"macro?":N(function(e){return e instanceof fe},"(macro? expression)\n\n Function check if value is a macro."),"function?":N(function(e){return typeof e==="function"},"(function? expression)\n\n Function check if value is a function."),"real?":N(function(e){if(Bn(e)!=="number"){return false}if(e instanceof tn){return e.isFloat()}return tn.isFloat(e)},"(real? number)\n\n Function check if value is real number."),"number?":N(tn.isNumber,"(number? expression)\n\n Function check if value is a number"),"string?":N(function(e){return Ge.isString(e)},"(string? expression)\n\n Function check if value is a string."),"pair?":N(function(e){return e instanceof te},"(pair? expression)\n\n Function check if value is a pair or list structure."),"regex?":N(function(e){return e instanceof RegExp},"(regex? expression)\n\n Function check if value is regular expression."),"null?":N(function(e){return ye(e)},"(null? expression)\n\n Function check if value is nulish."),"boolean?":N(function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Function check if value is boolean."),"symbol?":N(function(e){return e instanceof Z},"(symbol? expression)\n\n Function check if value is LIPS symbol"),"array?":N(function(e){return e instanceof Array},"(array? expression)\n\n Function check if value is an arrray."),"object?":N(function(e){return e!==ne&&e!==null&&!(e instanceof tn)&&ot(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Function check if value is an object."),flatten:N(function(e){Rn("flatten",e,"pair");return e.flatten()},"(flatten list)\n\n Return shallow list from tree structure (pairs)."),"array->list":N(function(e){Rn("array->list",e,"array");return te.fromArray(e)},"(array->list array)\n\n Function convert JavaScript array to LIPS list."),"tree->array":N(re("tree->array",true),"(tree->array list)\n\n Function convert LIPS list structure into JavaScript array."),"list->array":N(re("list->array"),"(list->array list)\n\n Function convert LIPS list into JavaScript array."),apply:N(function(e){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;rarray")(i));return e.apply(void 0,tt(t))},"(apply fn list)\n\n Function that call function with list of arguments."),length:N(function(e){if(!e){return tn(0)}if(e instanceof te){return tn(e.length())}if("length"in e){return tn(e.length)}},"(length expression)\n\n Function return length of the object, the object can be list\n or any object that have length property."),"string->number":N(function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:10;Rn("string->number",e,"string",1);Rn("string->number",n,"number",2);if(e.match(r)){return tn([e,n])}else if(e.match(i)){return tn(parseFloat(e))}return tn([e,n])},"(string->number number [radix])\n\n Function convert string to number."),try:N(new fe("try",function(a,e){var o=this;var u=e.dynamic_scope,c=e.error;return new Promise(function(i){var e={env:o,error:function e(n){if(n instanceof wn){throw new wn(n.message)}var t=o.inherit("try");t.set(a.cdr.car.cdr.car.car,n);var r={env:t,error:c};if(u){r.dynamic_scope=o}L(Jn(new te(new Z("begin"),a.cdr.car.cdr.cdr),r),function(e){i(e)});throw new wn(n.message)}};if(u){e.dynamic_scope=o}var n=Jn(a.car,e);if(ge(n)){n["catch"](e.error).then(i)}else{i(n)}})}),"(try expr (catch (e) code)"),throw:N(function(e){throw new Error(e)},"(throw string)\n\n Throw new expection."),find:N(function n(t,r){Rn("find",t,["regex","function"]);Rn("find",r,"pair");if(ye(r)){return ne}var e=q("find",t);return L(e(r.car),function(e){if(e&&e!==ne){return r.car}return n(t,r.cdr)})},"(find fn list)\n (find regex list)\n\n Higher order Function find first value for which function return true.\n If called with regex it will create matcher function."),"for-each":N(function(e){var n;Rn("for-each",e,"function");for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i1?n-1:0),a=1;a3?r-3:0),a=3;a3?i-3:0),o=3;oarray")(n);var a=[];var o=q("filter",e);return function n(t){function e(e){if(e&&e!==ne){a.push(r)}return n(++t)}if(t===i.length){return te.fromArray(a)}var r=i[t];return L(o(r,t),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher order function that call `fn` for each element of the list\n and return list for only those elements for which funtion return\n true value. If called with regex it will create matcher function."),range:N(function(e){Rn("range",e,"number");if(e instanceof tn){e=e.valueOf()}return te.fromArray(new Array(e).fill(0).map(function(e,n){return tn(n)}))},"(range n)\n\n Function return list of n numbers from 0 to n - 1"),compose:N(Ce,"(compose . fns)\n\n Higher order function and create new function that apply all functions\n From right to left and return it's value. Reverse of compose.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 3)\n 11\n "),pipe:N(Pe,"(pipe . fns)\n\n Higher order function and create new function that apply all functions\n From left to right and return it's value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 3)\n 15"),curry:N($e,"(curry fn . args)\n\n Higher order function that create curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning functions until all arguments are added\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"),gdc:N(function e(){for(var n=arguments.length,t=new Array(n),r=0;ra?u%=a:a%=u}u+=a}return tn(u)},"(gdc n1 n2 ...)\n\n Function return the greatest common divisor of their arguments."),lcm:N(function(){var e=arguments.length,n=oe(arguments.length<=0?_:arguments[0]);for(var t=1;tr?n%=r:r%=n}n=oe(i*(t<0||arguments.length<=t?_:arguments[t]))/(n+r)}return tn(n)},"(lcm n1 n2 ...)\n\n Function return the least common multiple of their arguments."),"odd?":N(Be(function(e){return tn(e).isOdd()}),"(odd? number)\n\n Function check if number os odd."),"even?":N(Be(function(e){return tn(e).isEven()}),"(even? number)\n\n Function check if number is even."),"*":N(De(function(e,n){return tn(e).mul(n)},tn(1)),"(* . numbers)\n\n Multiplicate all numbers passed as arguments. If single value is passed\n it will return that value."),"+":N(De(function(e,n){return tn(e).add(n)},tn(0)),"(+ . numbers)\n\n Sum all numbers passed as arguments. If single value is passed it will\n return that value."),"-":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t x1 x2 x3 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically increasing"),"<":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t=":N(function(){for(var e=arguments.length,n=new Array(e),t=0;t= x1 x2 x3 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically nondecreasing"),"eq?":N(ce,"(eq? a b)\n\n Function compare two values if they are identical."),or:N(new fe("or",function(e,n){var i=n.dynamic_scope,a=n.error;var o=this.get("list->array")(e);var u=this;if(i){i=u}var c;return function n(){function e(e){c=e;if(c){return c}else{return n()}}var t=o.shift();if(typeof t==="undefined"){if(c){return c}else{return false}}else{var r=Jn(t,{env:u,dynamic_scope:i,error:a});return L(r,e)}}()}),"(or . expressions)\n\n Macro execute the values one by one and return the one that is truthy value.\n If there are no expression that evaluate to true it return false."),and:N(new fe("and",function(e){var n=arguments.length>1&&arguments[1]!==_?arguments[1]:{},i=n.dynamic_scope,a=n.error;var o=this.get("list->array")(e);var u=this;if(i){i=u}if(!o.length){return true}var c;return function n(){function e(e){c=e;if(!c){return false}else{return n()}}var t=o.shift();if(typeof t==="undefined"){if(c){return c}else{return false}}else{var r=Jn(t,{env:u,dynamic_scope:i,error:a});return L(r,e)}}()}),"(and . expressions)\n\n Macro evalute each expression in sequence if any value return false it will\n return false. If each value return true it will return the last value.\n If it's called without arguments it will return true."),"|":N(function(e,n){return tn(e).or(n)},"(& a b)\n\n Function calculate or bit operation."),"&":N(function(e,n){return tn(e).and(n)},"(& a b)\n\n Function calculate and bit operation."),"~":N(function(e){return tn(e).neg()},"(~ number)\n\n Function negate the value."),">>":N(function(e,n){return tn(e).shr(n)},"(>> a b)\n\n Function right shit the value a by value b."),"<<":N(function(e,n){return tn(e).shl(n)},"(<< a b)\n\n Function left shit the value a by value b."),not:N(function(e){if(ye(e)){return true}return!e},"(not object)\n\n Function return negation of the argument."),"->":N(function(e,n){for(var t=arguments.length,r=new Array(t>2?t-2:0),i=2;i obj name . args)\n\n Function get function from object and call it with arguments.")},_,"global");var Fn=En.inherit("user-env");En.set("**interaction-environment**",Fn);(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(n){var t=e[n]?e[n]:n;En.set(t,N(function(e){Rn(t,e,"number");if(e instanceof tn){return e[n]()}},"(".concat(t," number)\n\n Function calculate ").concat(t," of a number.")))})})();function An(e){if(e.length===1){return e[0]}else{var n=[];var t=An(e.slice(1));for(var r=0;r3&&arguments[3]!==_?arguments[3]:null;var i=e?" in function `".concat(e,"`"):"";if(r!==null){i+=" argument ".concat(r)}if(t instanceof Array){var a=t[t.length-1];t=t.slice(0,-1).join(", ")+" or "+a}return"Expecting ".concat(t," got ").concat(n).concat(i)}function Rn(e,n,t){var r=arguments.length>3&&arguments[3]!==_?arguments[3]:null;var i=Bn(n).toLowerCase();var a=false;if(t instanceof Array){t=t.map(function(e){return e.valueOf().toLowerCase()});if(t.includes(i)){a=true}}else{t=t.valueOf().toLowerCase()}if(!a&&i!==t){throw new Error(Cn(e,i,t,r))}}function Mn(e){var n=ot(e);return["string","function"].includes(n)||e instanceof Z||e instanceof tn||e instanceof RegExp}function Bn(e){var n={pair:te,symbol:Z,character:Ye,values:On,macro:fe,string:Ge,array:Array,"native-symbol":Symbol};if(e===ne){return"nil"}if(e===null){return"null"}if(e instanceof he){return"syntax"}for(var t=0,r=Object.entries(n);t1&&arguments[1]!==_?arguments[1]:{},i=e.env,a=e.dynamic_scope,t=e.error,o=t===void 0?function(){}:t;try{if(a===true){i=a=i||En}else if(i===true){i=a=En}else{i=i||En}var r={env:i,dynamic_scope:a,error:o};var u;if(ye(n)){return n}if(n instanceof Z){return i.get(n)}var c=n.car;var s=n.cdr;if(c instanceof te){u=Tn(Jn(c,r));if(ge(u)){return u.then(function(e){return Jn(new te(e,n.cdr),r)})}else if(typeof u!=="function"){throw new Error(Bn(u)+" "+i.get("repr")(u)+" is not a function while evaluating "+n.toString())}}if(c instanceof Z){u=i.get(c);if(u instanceof he){return $n(u,n,r)}else if(u instanceof fe){return Hn(u,s,r)}else if(typeof u!=="function"){if(u){var f="".concat(Bn(u)," `").concat(u,"' is not a function");throw new Error(f)}throw new Error("Unknown function `".concat(c.name,"'"))}}else if(typeof c==="function"){u=c}if(typeof u==="function"){var l=Dn(s,r);return L(l,function(e){if(Oe(u)){e=e.map(we)}if(u.__lambda__){u=xe(u)}var n=e.slice();var t=(a||i).newFrame(u,n);var r=Tn(u.apply(t,e));return L(r,function(e){if(e instanceof te){e.markCycles();return Sn(e)}if(typeof e==="number"){return tn(e)}if(typeof e==="string"){return Ge(e)}return e},o)})}else if(n instanceof Z){u=i.get(n);if(u==="undefined"){throw new Error("Unbound variable `"+n.name+"'")}return u}else if(n instanceof te){u=c&&c.toString();throw new Error("".concat(Bn(c)," ").concat(u," is not a function"))}else{return n}}catch(e){o&&o.call(i,e,n)}}function Un(e,n,t){return Yn.apply(this,arguments)}function Yn(){Yn=et(Zn.mark(function e(t,r,i){var a,o,u,c;return Zn.wrap(function e(n){while(1){switch(n.prev=n.next){case 0:if(i===true){r=i=r||Fn}else if(r===true){r=i=Fn}else{r=r||Fn}a=I(t);o=[];case 3:u=a.shift();if(u){n.next=9;break}return n.abrupt("return",o);case 9:n.next=11;return Jn(u,{env:r,dynamic_scope:i,error:function e(n,t){if(t){if(!(n.code instanceof Array)){n.code=[]}n.code.push(t.toString(true))}throw n}});case 11:c=n.sent;o.push(c);case 13:n.next=3;break;case 15:case"end":return n.stop()}}},e)}));return Yn.apply(this,arguments)}function Gn(n){if(n instanceof RegExp){return function(e){if(!e){return false}return(typeof e==="string"?e:e.token).match(n)}}else{return function(e){if(!e){return false}return(typeof e==="string"?e:e.token)===n}}}var zn=Gn(/[[\]()]/);function Vn(e){var n=typeof e==="string"?j(e):e;var t=n.filter(zn);var r=t.filter(Gn("("));var i=t.filter(Gn(")"));var a=t.filter(Gn("["));var o=t.filter(Gn("]"));return r.length===i.length&&a.length===o.length}te.unDry=function(e){return new te(e.car,e.cdr)};te.prototype.toDry=function(){return{value:{car:this.car,cdr:this.cdr}}};ee.prototype.toDry=function(){return{value:null}};ee.unDry=function(){return ne};Z.prototype.toDry=function(){return{value:{name:this.name}}};Z.unDry=function(e){return new Z(e.name)};function Qn(e){console.error(e.message||e);if(e.code){console.error(e.code.map(function(e,n){return"[".concat(n+1,"]: ").concat(e)}))}}function Xn(){var o=["text/x-lips","text/x-scheme"];if(!window.document){return Promise.resolve()}else{return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function n(){var e=a.shift();if(!e){i()}else{var t=e.getAttribute("type");if(o.includes(t)){var r=e.getAttribute("src");if(r){return f.fetch(r).then(function(e){return e.text()}).then(Un).then(n)["catch"](function(e){Qn(e);n()})}else{return Un(e.innerHTML).then(n)["catch"](function(e){Qn(e);n()})}}else if(t&&t.match(/lips|lisp/)){console.warn("Expecting "+o.join(" or ")+" found "+t)}return n()}}()})}}if(typeof window!=="undefined"){e(window,Xn)}T.__className="ahead";D.__className="pattern";B.__className="formatter";fe.__className="macro";he.__className="syntax";xn.__className="environment";vn.__className="input-port";dn.__className="output-port";mn.__className="output-string-port";yn.__className="input-string-port";var Kn={version:"DEV",banner:n,date:"Sun, 26 Apr 2020 10:18:59 +0000",exec:Un,parse:I,tokenize:j,evaluate:Jn,Environment:xn,global_environment:En,globalEnvironment:En,env:Fn,Interpreter:_n,balanced_parenthesis:Vn,balancedParenthesis:Vn,Macro:fe,Syntax:he,Pair:te,quote:Sn,InputPort:vn,OutputPort:dn,InputStringPort:yn,OutputStringPort:mn,Formatter:B,specials:E,nil:ne,extract_patterns:ve,transform_syntax:me,resolvePromises:Tn,LSymbol:Z,LNumber:tn,LFloat:an,LComplex:rn,LRational:fn,LBigInteger:ln,LCharacter:Ye,LString:Ge,rationalize:cn};En.set("lips",Kn);return Kn})})(); \ No newline at end of file diff --git a/spec/lips.spec.js b/spec/lips.spec.js index 25964ae07..a2c878bb4 100644 --- a/spec/lips.spec.js +++ b/spec/lips.spec.js @@ -574,7 +574,7 @@ describe('evaluate', function() { (define (trampoline f) (lambda args (let ((result (apply f args))) - (while (eq? (type result) "function") + (while (equal? (type result) "function") (set! result (result))) result))) diff --git a/src/lips.js b/src/lips.js index 010bb32f5..f69143e41 100644 --- a/src/lips.js +++ b/src/lips.js @@ -151,8 +151,12 @@ }; } var banner = (function() { - var date = '{{DATE}}'; - var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date); + // Rollup tree-shaking is removing the variable if it's normal string because + // obviously '{{DATE}}' == '{{' + 'DATE}}'; can be removed + // but disablig Tree-shaking is adding lot of not used code so we use this + // hack instead + var date = LString('{{DATE}}'); + var _date = date.valueOf() === '{{' + 'DATE}}' ? new Date() : new Date(date); var _format = x => x.toString().padStart(2, '0'); var _year = _date.getFullYear(); var _build = `${_year}-${_format(_date.getMonth() + 1)}-${_format(_date.getDate())}`; @@ -1154,12 +1158,15 @@ You can also use (help name) to display help for specic function or macro. // :: Nil constructor with only once instance // ---------------------------------------------------------------------- function Nil() {} - Nil.prototype.toString = function() { + Nil.prototype.toString = Nil.prototype.toJSON = function() { return '()'; }; Nil.prototype.valueOf = function() { return undefined; }; + Nil.prototype.append = function(x) { + return new Pair(x, nil); + }; var nil = new Nil(); // ---------------------------------------------------------------------- // :: Pair constructor @@ -1238,6 +1245,17 @@ You can also use (help name) to display help for specic function or macro. return clone(this); }; + // ---------------------------------------------------------------------- + Pair.prototype.lastPair = function() { + let node = this; + while (true) { + if (node.cdr === nil) { + return node; + } + node = node.cdr; + } + }; + // ---------------------------------------------------------------------- Pair.prototype.toArray = function() { var result = []; @@ -1710,6 +1728,7 @@ You can also use (help name) to display help for specic function or macro. } n = n - 1; } + console.log({ result: result.toString() }); return traverse(result, n); } } @@ -1760,75 +1779,189 @@ You can also use (help name) to display help for specic function or macro. return '<#syntax>'; }; Syntax.className = 'syntax'; - /* - // ---------------------------------------------------------------------- - // :: list of symbols, with at least one - // ---------------------------------------------------------------------- - function is_symbol_list(list) { - return (list instanceof Pair && - list.car instanceof LSymbol && - !list.haveCycles('cdr') && - (list.cdr === nil || is_symbol_list(list.cdr))); - } - // ---------------------------------------------------------------------- - // :: test if value is '((name) ...) or (name ...) it throw exception - // :: when list don't have symbols or if list is empty - // ---------------------------------------------------------------------- - function is_ellipsis(node) { - if (node instanceof Pair && - node.cdr instanceof Pair && - LSymbol.is(node.cdr.car, '...')) { - if (node.car instanceof Pair && is_symbol_list(node.car)) { - return true; - } else if (node.car instanceof LSymbol) { - return true; - } else { - throw new Error('Invalid Syntax'); - } - } - return false; - } - */ // ---------------------------------------------------------------------- // :: for usage in syntax-rule when pattern match it will return // :: list of bindings from code that match the pattern // :: TODO detect cycles // ---------------------------------------------------------------------- function extract_patterns(pattern, code) { - var bindings = {}; - function traverse(pattern, code) { - if (pattern instanceof Pair && LSymbol.is(pattern.car, '...')) { - if (code instanceof Pair) { - bindings['...'] = code; + var bindings = { + '...': { + symbols: { }, // symbols ellipsis (x ...) + lists: [ ] + } + }; + // pattern_names parameter is used to distinguish + // multiple matches of ((x ...) ...) agains ((1 2 3) (1 2 3)) + // in loop we add x to the list so we know that this is not + // duplicated ellipsis symbol + function log(x) { + if (user_env.get('DEBUG', { throwError: false })) { + console.log(x); + } + } + /* eslint-disable complexity */ + function traverse(pattern, code, pattern_names = [], ellipsis = false) { + log({ code: code.toString(), pattern: pattern.toString() }); + // pattern (a b (x ...)) and (x ...) match nil + if (pattern instanceof Pair && + pattern.car instanceof Pair && + pattern.car.cdr instanceof Pair && + LSymbol.is(pattern.car.cdr.car, '...')) { + log('>> 0'); + if (code === nil) { + log({ pattern: pattern.toString() }); + if (pattern.car.car instanceof LSymbol) { + if (pattern.car.cdr instanceof Pair && + LSymbol.is(pattern.car.cdr.car, '...')) { + let name = pattern.car.car.valueOf(); + const last = pattern.lastPair(); + if (LSymbol.is(last.car, '...')) { + bindings['...'].symbols[name] = null; + return true; + } else { + return false; + } + } + let name = pattern.car.car.valueOf(); + if (bindings['...'].symbols[name]) { + throw new Error('syntax: named ellipsis can only ' + + 'appear onces'); + } + bindings['...'].symbols[name] = code; + } return true; } - if (code === nil) { - bindings['...'] = nil; + } + if (pattern instanceof Pair && + pattern.cdr instanceof Pair && + LSymbol.is(pattern.cdr.car, '...')) { + // pattern (... ???) + if (pattern.cdr.cdr !== nil) { + throw new Error('syntax: invalid usage of ellipsis'); + } + if (pattern.car instanceof LSymbol) { + let name = pattern.car.valueOf(); + if (bindings['...'].symbols[name] && !pattern_names.includes(name)) { + throw new Error('syntax: named ellipsis can only appear onces'); + } + log('>> 1'); + if (code === nil) { + log('>> 2'); + if (ellipsis) { + bindings['...'].symbols[name] = nil; + } else { + return false; + } + } else if (code instanceof Pair && + (code.car instanceof Pair || code.car === nil)) { + log('>> 3 ' + ellipsis); + if (ellipsis) { + bindings['...'].symbols[name] = code.car; + } else { + log('>> 4'); + bindings['...'].symbols[name] = new Pair(code, nil); + } + } else { + log('>> 6'); + if (code instanceof Pair) { + log('>> 7 ' + ellipsis); + pattern_names.push(name); + if (!bindings['...'].symbols[name]) { + bindings['...'].symbols[name] = new Pair( + code, + nil + ); + } else { + const node = bindings['...'].symbols[name]; + bindings['...'].symbols[name] = node.append( + new Pair( + code, + nil + ) + ); + } + log({ IIIIII: bindings['...'].symbols[name].toString() }); + } else { + log('>> 8'); + return false; + //bindings['...'].symbols[name] = code; + } + } + return true; + } else if (pattern.car instanceof Pair) { + var names = [...pattern_names]; + if (code === nil) { + log('>> 9'); + bindings['...'].lists.push(nil); + return true; + } + log('>> 10'); + let node = code; + while (node instanceof Pair) { + if (!traverse(pattern.car, node.car, names, true)) { + return false; + } + node = node.cdr; + } return true; } return false; } if (pattern instanceof LSymbol) { + if (LSymbol.is(pattern, '...')) { + throw new Error('syntax: invalid usage of ellipsis'); + } + log('>> 11'); const name = pattern.valueOf(); - bindings[name] = code; + log({ name }); + //console.log(code.toString()); + if (ellipsis) { + bindings['...'].symbols[name] = bindings['...'].symbols[name] || []; + bindings['...'].symbols[name].push(code); + } + if (!bindings[name]) { + bindings[name] = code; + } return true; } if (pattern instanceof Pair && code instanceof Pair) { - if (traverse(pattern.car, code.car) && - traverse(pattern.cdr, code.cdr)) { + log('>> 12'); + log(code.toString()); + if (code.cdr === nil) { + // last item in in call using in recursive calls on + // last element of the list + // case of pattern (p . rest) and code (0) + var rest_pattern = pattern.car instanceof LSymbol && + pattern.cdr instanceof LSymbol; + if (rest_pattern) { + log('>> 12 | 1'); + let name = pattern.cdr.valueOf(); + if (!bindings[name]) { + bindings[name] = nil; + } + name = pattern.car.valueOf(); + if (!bindings[name]) { + bindings[name] = code.car; + } + return true; + } + } + if (traverse(pattern.car, code.car, pattern_names, ellipsis) && + traverse(pattern.cdr, code.cdr, pattern_names, ellipsis)) { return true; } } else if (pattern === nil && code === nil) { return true; } else if (pattern.car instanceof Pair && - LSymbol.is(pattern.car.car, '...') && - code === nil) { - bindings['...'] = nil; - return true; + LSymbol.is(pattern.car.car, '...')) { + // pattern (...) + throw new Error('syntax: invalid usage of ellipsis'); } else { return false; } } + /* eslint-enable complexity */ if (traverse(pattern, code)) { return bindings; } @@ -1917,15 +2050,27 @@ You can also use (help name) to display help for specic function or macro. } return traverse(node); } + // ---------------------------------------------------------------------- function transform_syntax(bindings, expr, scope, lex_scope, names) { var gensyms = {}; function transform(symbol) { + if (!(symbol instanceof LSymbol || typeof symbol === 'string')) { + throw new Error('syntax: internal error, rename neeed to be symbol'); + } const name = symbol.valueOf(); + if (name === '...') { + throw new Error('syntax: internal error, ellipis not transformed'); + } if (typeof name === 'string' && name in bindings) { return bindings[name]; } return rename(name); } + function log(x) { + if (user_env.get('DEBUG', { throwError: false })) { + console.log(x); + } + } function rename(name) { if (!gensyms[name]) { var value = scope.get(name, { throwError: false }); @@ -1943,37 +2088,220 @@ You can also use (help name) to display help for specic function or macro. } return gensyms[name]; } - function traverse(expr) { + function get_binding(list, nested) { + if (!list) { + return; + } + if (list instanceof Pair) { + return list.car; + } + if (list instanceof Array) { + const [item] = list; + if (item instanceof Array) { + if (nested) { + return Pair.fromArray(item); + } + return item; + } + return item; + } + } + function transform_ellipsis_expr(expr, bindings, nested, next = () => {}) { + log(' ==> ' + expr.toString()); + if (expr instanceof LSymbol) { + const name = expr.valueOf(); + log('[t 1'); + const value = get_binding(bindings[name]); + if (value) { + //return value; + } + if (bindings[name]) { + if (bindings[name] instanceof Pair) { + const { car, cdr } = bindings[name]; + if (nested) { + const { car: caar, cdr: cadr } = car; + if (cadr !== nil) { + next(name, new Pair(cadr, nil)); + } + return caar; + } + if (cdr !== nil) { + next(name, cdr); + } + return car; + } else if (bindings[name] instanceof Array) { + next(name, bindings[name].slice(1)); + return bindings[name][0]; + } + } + return transform(name); + } if (expr instanceof Pair) { - if (expr.car instanceof LSymbol) { - const value = transform(expr.car); - if (typeof value !== 'undefined') { - expr.car = value; + if (expr.car instanceof LSymbol && + expr.cdr instanceof Pair && + LSymbol.is(expr.cdr.car, '...')) { + log('[t 2'); + const name = expr.car.valueOf(); + const item = bindings[name]; + if (item) { + log({ b: bindings[name] }); + if (item instanceof Pair) { + log('[t 2 Pair ' + nested); + log({ ______: item.toString() }); + const { car, cdr } = item; + if (nested) { + if (cdr !== nil) { + next(name, cdr); + } + return car; + } else { + if (car.cdr !== nil) { + next(name, new Pair(car.cdr, cdr)); + } + return car.car; + } + } else if (item instanceof Array) { + log('[t 2 Array ' + nested); + if (nested) { + next(name, item.slice(1)); + return Pair.fromArray(item); + } else { + const rest = item.slice(1); + if (rest.length) { + next(name, rest); + } + return item[0]; + } + } else { + return item; + } } - } else { - traverse(expr.car); } + log('[t 3 recur ' + expr.toString()); + return new Pair( + transform_ellipsis_expr(expr.car, bindings, nested, next), + transform_ellipsis_expr(expr.cdr, bindings, nested, next) + ); + } + } + function have_binding(biding) { + const values = Object.values(biding); + return values.length && values.every(x => { + return x instanceof Pair || + x === nil || (x instanceof Array && x.length); + }); + } + function traverse(expr) { + if (expr instanceof Pair) { if (expr.cdr instanceof Pair && - LSymbol.is(expr.cdr.car, '...') && - bindings['...']) { - expr.cdr = bindings['...']; - } else if (expr.cdr instanceof LSymbol) { - const value = transform(expr.cdr); - if (typeof value !== 'undefined') { - expr.cdr = value; + LSymbol.is(expr.cdr.car, '...')) { + log('>> 1'); + const symbols = bindings['...'].symbols; + var keys = Object.keys(symbols); + // case of list as first argument ((x . y) ...) + // we need to recursively process the list + // if we have pattern (_ (x y z ...) ...) and code (foo (1 2) (1 2)) + // x an y will be arrays of [1 1] and [2 2] and z will be array + // of rest, x will also have it's own mapping to 1 and y to 2 + // in case of usage outside of ellipsis list e.g.: (x y) + if (expr.car instanceof Pair) { + // lists is free ellipsis on pairs ((???) ...) + // TODO: will this work in every case? Do we need to handle + // nesting here? + if (bindings['...'].lists[0] === nil) { + return nil; + } + log('>> 2'); + let result; + if (keys.length) { + log('>> 2 (a)'); + let bind = { ...symbols }; + result = nil; + while (true) { + if (!have_binding(bind)) { + break; + } + const new_bind = {}; + const next = (key, value) => { + // ellipsis decide it what should be the next value + // there are two cases ((a . b) ...) and (a ...) + new_bind[key] = value; + }; + result = new Pair( + transform_ellipsis_expr(expr.car, bind, true, next), + result + ); + bind = new_bind; + } + if (result !== nil) { + result = result.reverse(); + } + return result; + } else { + log('>> 3'); + const car = transform_ellipsis_expr(expr.car, symbols, true); + if (car) { + return new Pair( + car, + nil + ); + } + return nil; + } + } else if (expr.car instanceof LSymbol) { + log('>> 4'); + // case: (x ...) + let name = expr.car.valueOf(); + let bind = { [name]: symbols[name] }; + let result = nil; + while (true) { + if (!have_binding(bind)) { + log({ bind }); + break; + } + const new_bind = {}; + const next = (key, value) => { + new_bind[key] = value; + }; + log({ EXPR: expr.toString() }); + const value = transform_ellipsis_expr( + expr, + bind, + false, + next + ); + result = new Pair( + value, + result + ); + bind = new_bind; + } + if (result !== nil) { + result = result.reverse(); + } + // case if (x ... y ...) second spread is not processed + // by ellipsis transformation + if (expr.cdr instanceof Pair && + expr.cdr.cdr instanceof Pair) { + result.append(traverse(expr.cdr.cdr)); + } + return result; } - } else { - traverse(expr.cdr); + } + return new Pair( + traverse(expr.car), + traverse(expr.cdr) + ); + } + if (expr instanceof LSymbol) { + const value = transform(expr); + if (typeof value !== 'undefined') { + return value; } } - } - if (expr instanceof Pair) { - expr = expr.clone(); - traverse(expr); return expr; - } else if (expr instanceof LSymbol) { - return transform(expr); } + return traverse(expr); } // ---------------------------------------------------------------------- // :: check for nullish values @@ -2960,7 +3288,10 @@ You can also use (help name) to display help for specic function or macro. }; // ------------------------------------------------------------------------- LNumber.prototype.toString = LNumber.prototype.toJSON = function(radix) { - return this.value.toString(radix); + if (radix > 2 && radix < 36) { + return this.value.toString(radix); + } + return this.value.toString(); }; // ------------------------------------------------------------------------- LNumber.prototype.isBigNumber = function() { @@ -4170,7 +4501,12 @@ You can also use (help name) to display help for specic function or macro. var msg = typeErrorMessage('set-obj!', type(obj), ['object', 'function']); throw new Error(msg); } - unbind(obj)[key] = value.valueOf(); + obj = unbind(obj); + if (typeof value === 'undefined') { + delete obj[key]; + } else { + obj[key] = value.valueOf(); + } }, `(set-obj! obj key value) Function set property of JavaScript object`), @@ -4425,6 +4761,9 @@ You can also use (help name) to display help for specic function or macro. var expr = rules.car.cdr.car; var bindings = extract_patterns(rule, code); if (bindings) { + if (user_env.get('DEBUG', { throwError: false })) { + console.log(JSON.stringify(bindings, true, 2)); + } // name is modified in transform_syntax var names = []; const new_expr = transform_syntax( @@ -4450,7 +4789,7 @@ You can also use (help name) to display help for specic function or macro. } rules = rules.cdr; } - //throw new Error(`Invalid Syntax ${code}`); + throw new Error(`Invalid Syntax ${code}`); }, env); }, `(syntax-rules () (pattern expression) ...) @@ -6218,6 +6557,8 @@ You can also use (help name) to display help for specic function or macro. specials, nil, + extract_patterns, + transform_syntax, resolvePromises, LSymbol, diff --git a/test.js b/test.js index 59fab55ab..e6db0f0b5 100644 --- a/test.js +++ b/test.js @@ -8,7 +8,6 @@ const readDir = promisify(fs.readdir); const lips = require('./src/lips'); readDir('./tests/').then(function(filenames) { - return Promise.all(filenames.filter(function(file) { return file.match(/.scm$/) && !file.match(/^\.#/); }).map(function(file) { diff --git a/tests/helpers/helpers.scm b/tests/helpers/helpers.scm index 187fd7c17..d3280e091 100644 --- a/tests/helpers/helpers.scm +++ b/tests/helpers/helpers.scm @@ -1,12 +1,18 @@ (define-macro (t.is a b) "(t.is a b) - Helper comparator for ava. It use equal? so it match two lists and strings." - (let ((result (gensym))) - `(let ((,result (--> t (is (equal? ,a ,b) #t)))) - ;;(if (not ,result) - ;; (throw (new Error (concat "failed: " (repr ',a) " is not equal " (repr ',b))))) - ,result))) + Helper comparator for ava. It use equal? so it match two lists and strings. + It use undecumented API that allow to delete StackTrace when assersion fail." + (let ((attempt (gensym))) + `(let ((,attempt (t.try (lambda (e) + (if (equal? ,a ,b) + (--> e (pass)) + (--> e (fail (concat "failed: " (repr ',a) + " is not equal " (repr ',b))))))))) + (if (not (. ,attempt 'passed)) + (--> (. ,attempt 'errors) (forEach (lambda (e) + (set-obj! e 'savedError undefined))))) + (--> ,attempt (commit))))) (define-macro (to.throw . body) "(to.throw code) @@ -16,7 +22,7 @@ (let ((result (gensym))) `(let ((,result (try (begin ,@body #f) (catch (e) #t)))) (if (not ,result) - (throw (new Error (concat "failed: " ',body)))) + (throw (new Error (concat "failed: " ',(repr body true))))) ,result))) (define (test_ . rest) diff --git a/tests/syntax.scm b/tests/syntax.scm index 36ddc2076..b7e277425 100644 --- a/tests/syntax.scm +++ b/tests/syntax.scm @@ -116,19 +116,22 @@ (test "syntax-rules: function and macro" (lambda (t) + (define even? (lambda (x) (or (= x 0) (odd? (- x 1))))) + (define odd? (syntax-rules () ((_ x) (not (even? x))))) + (t.is (even? 10) #t) (t.is (even? 13) #f))) (test "syntax-rules: scope" (lambda (t) (let () - (define-syntax nil! + (define-syntax nil! (syntax-rules () ((_ x) (set! x '())))) @@ -138,4 +141,137 @@ (nil! x) (t.is x nil))))) +(test "syntax-rules: skip second item in list" + (lambda (t) + (define-syntax foo + (syntax-rules () ((_ (a . (b . (c ...))) ...) '(foo (a c ... ) ...)))) + (t.is (foo (1 2 3 4 5) (6 7 8 9 10)) '(foo (1 3 4 5) (6 8 9 10))))) + +(test "syntax-rules: only cddr (list)" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a b c ...) ...) '(foo (c ...) ...)))) + + (t.is (foo) '(foo)) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo (1))) #t) + (t.is (foo (1 2)) '(foo ())) + (t.is (foo (1 2 3 4 5) (6 7 8 9 10)) '(foo (3 4 5) (8 9 10))))) + +(test "syntax-rules: only cddr (cons literals)" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a . (b . (c ...))) ...) '(foo (c ...) ...)))) + + (t.is (foo) '(foo)) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo (1))) #t) + (t.is (foo (1 2)) '(foo ())) + (t.is (foo (1 2 3 4 5) (6 7 8 9 10)) '(foo (3 4 5) (8 9 10))))) + +(test "syntax-rules: map on cddr" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ x ...) (cons 'foo (map cddr '(x ...)))))) + + (t.is (foo (1 2 3 4 5) (6 7 8 9 10)) '(foo (3 4 5) (8 9 10))))) + +(test "syntax-rules: extract 1st and 2nd items from list" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a . (b . (c . nil))) ...) '(foo (a . c) ...)))) + + (t.is (foo) '(foo)) + (t.is (foo (1 2 3)) '(foo (1 . 3))) + (t.is (foo (1 2 3) (4 5 6)) '(foo (1 . 3) (4 . 6))))) + +(test "syntax-rules: extract 2nd elements from lists" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a . (b . (c . nil))) ...) '(foo b ...)))) + + (t.is (foo) '(foo)) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo (1))) #t) + (t.is (to.throw (foo (1 2))) #t) + (t.is (foo (1 2 3)) '(foo 2)) + (t.is (foo (1 2 3) (4 5 6)) '(foo 2 5)) + (t.is (foo (1 2 3) (4 5 6) (7 8 9)) '(foo 2 5 8)))) + +(test "syntax-rules: should spread elements" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a . (b . (c . nil))) ...) '(foo a ... b ... c ...)))) + + (t.is (foo) '(foo)) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo (1))) #t) + (t.is (to.throw (foo (1 2))) #t) + (t.is (foo (1 2 3) (4 5 6) (7 8 9)) '(foo 1 4 7 2 5 8 3 6 9)) + (t.is (foo (1 2 3)) '(foo 1 2 3)) + (t.is (foo (1 2 3) (4 5 6)) '(foo 1 4 2 5 3 6)))) + +(test "syntax-rules: list quine" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (x ...) ...) '(foo (x ...) ...)))) + + (t.is (foo) '(foo)) + (t.is (to.throw (foo 1)) #t) + (t.is (foo ()) '(foo ())) + (t.is (foo (x)) '(foo (x))) + (t.is (foo (x y)) '(foo (x y))) + (t.is (foo (a b) (c d)) '(foo (a b) (c d))))) + +(test "syntax-rules: cons 1st and 2nd in lists" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a b) ...) '((a . b) ...)))) + + (t.is (foo) '()) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo ())) #t) + (t.is (to.throw (foo (1))) #t) + + (t.is (foo (1 2)) '((1 . 2))) + (t.is (foo (1 2) (3 4)) '((1 . 2) (3 . 4))) + (t.is (foo (1 2) (3 4) (5 6)) '((1 . 2) (3 . 4) (5 . 6))))) + +(test "syntax-rules: zip trasformation" + (lambda (t) + + (define-syntax foo + (syntax-rules () ((_ (a ...) (b ...)) '((a . b) ...)))) + + (t.is (to.throw (foo)) #t) + (t.is (to.throw (foo 1)) #t) + (t.is (to.throw (foo 1 1)) #t) + (t.is (to.throw (foo (1))) #t) + (t.is (to.throw (foo () () ())) #t) + (t.is (foo (1) (2)) '((1 . 2))) + (t.is (foo (1 2) (3 4)) '((1 . 3) (2 . 4))) + (t.is (foo (1 2 3) (4 5 6)) '((1 . 4) (2 . 5) (3 . 6))))) + +(test "syntax-rules: merge lists" + (lambda (t) + (define-syntax merge + (syntax-rules () + ((_) '()) + ;; ((_ (foo ...)) (list foo ...)) ;; rest === nil + ((_ (foo ...) . rest) + (append (list foo ...) (merge . rest))))) + (t.is (to.throw (merge 1)) #t) + (t.is (to.throw (merge 1 2)) #t) + (t.is (merge) '()) + (t.is (merge (1 2 3)) '(1 2 3)) + (t.is (merge (1 2 3) (4 5 6)) '(1 2 3 4 5 6)) + (t.is (merge (1 2 3) (4 5 6) (7 8 9)) '(1 2 3 4 5 6 7 8 9))))