diff --git a/.codespellrc b/.codespellrc index 230b89609..bb755833a 100644 --- a/.codespellrc +++ b/.codespellrc @@ -1,2 +1,2 @@ [codespell] -skip = ./node_modules*,./dist/*,./package-lock.json,./lib/srfi/*,./assets/UnicodeData.txt,./assets/CaseFolding.txt,./scripts/numerals.scm +skip = build,coverage,node_modules*,./dist/*,package-lock.json,./lib/srfi/*,./assets/UnicodeData.txt,./assets/CaseFolding.txt,./scripts/numerals.scm diff --git a/.gitattributes b/.gitattributes index 96aed74a3..cdf075204 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,6 +10,7 @@ tests/snapshots/* binary *.xcm binary *.xcb binary dist/** linguist-generated +docs/reference.json linguist-generated binary *config.js linguist-vendored docs/** linguist-documentation **/*.lips linguist-language=scheme diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 415e4f67c..7544416c1 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -39,7 +39,7 @@ jobs: - name: checkout uses: actions/checkout@v4 - name: setup node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: '20' - run: npm ci @@ -48,6 +48,6 @@ jobs: - run: make test - run: make coverage - name: Coveralls - uses: coverallsapp/github-action@master + uses: coverallsapp/github-action@v2 with: github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f28b6332..db80f8cc6 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +## 1.0.0-beta.20 +### Feature +* allow to call `load` with `@lips` prefix [#354](https://github.com/jcubic/lips/issues/354) +* add string interpolation [#321](https://github.com/jcubic/lips/issues/321) +* add default repr for R7RS records +* add parenthesis matching in Node.js REPL +### Bugfix +* fix duplicated identifiers in syntax-rules (case of SRFI-239 example implementation) +* fix `load` of absolute path in Node +* fix require of LIPS package from Node +* fix transforming `syntax-rules` ellipsis that expand into #void +* fix improper lists in `syntax-rules` [#360](https://github.com/LIPS-scheme/lips/issues/360) +* fix handling of REPL in Emacs (`run-scheme`) +* fix `promise?` predicate +* fix handling of `|1|1` and `|a|b|c|` symbols +* fix repr of anonymous classes [#361](https://github.com/LIPS-scheme/lips/issues/361) +* fix handling of escape characters in symbols +* fix processing list with nested unquote-splicing [#362](https://github.com/LIPS-scheme/lips/issues/362) +* fix exception during error from eval [#362](https://github.com/LIPS-scheme/lips/issues/362) +* allow to catch exceptions from eval +* fix else keyword as only expression in cond [#366](https://github.com/LIPS-scheme/lips/issues/366) +* fix clash of variable named `list` in named `let` [#398](https://github.com/LIPS-scheme/lips/issues/398) +* fix Node REPL flickering + ## 1.0.0-beta.19 ### Breaking * change `get-environment-variables` and `get-environment-variable` returns nil and undefined in the browser diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c4bd22a07..a33e988f4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,3 +109,21 @@ run ESLint execute: ```bash make lint ``` + +## Codepell + +LIPS use [Codespell](https://github.com/codespell-project/codespell) to catch +grammar mistakes. It runs as GitHub Action. But you can test locally so you can +fix the type before it will give error from Action. + +You can install Codespell using PIP (you need to have Python installed): + +```bash +pip install codespell +``` + +The run: + +```bash +make codespell +``` diff --git a/Makefile b/Makefile index e692ab114..319f63744 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ COMMIT=`git rev-parse HEAD` URL=`git config --get remote.origin.url` UNICODE_ALL=https://unicode.org/Public/UNIDATA/UnicodeData.txt UNICODE_FOLD=https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt +WORK_TREE=`git worktree list | cut -f1 -d' ' | grep -v "\`pwd\`$$" | xargs -I{} basename {} | tr $$'\n' ',' | sed 's/,$$//'` MAKE=make GIT=git @@ -131,7 +132,7 @@ coverage: $(NPM) run coverage codespell: - $(CODESPELL) -S 'package-lock.json,node_modules,build,coverage' + @$(CODESPELL) -S $(WORK_TREE) lint: - $(ESLINT) src/lips.js lib/js/bookmark.js + $(ESLINT) src/lips.js lib/js/bookmark.js bin/lips.js diff --git a/README.md b/README.md index 7ba347e3b..55cef2930 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@

- LIPS - Scheme Based Powerful Lisp Language

[![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/lips_lang)](https://twitter.com/lips_lang) [![npm](https://img.shields.io/badge/npm-1.0.0%E2%80%93beta.19-blue.svg)](https://www.npmjs.com/package/@jcubic/lips) ![1.0.0 Complete](https://img.shields.io/github/milestones/progress-percent/jcubic/lips/1?label=1.0.0%20Complete) -[![Build and test](https://github.com/jcubic/lips/actions/workflows/build.yaml/badge.svg?branch=master&event=push)](https://github.com/jcubic/lips/actions/workflows/build.yaml) -[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=master&80a731f28ad563e153f52942314ee16b)](https://coveralls.io/github/jcubic/lips?branch=master) +[![Build and test](https://github.com/jcubic/lips/actions/workflows/build.yaml/badge.svg?branch=devel&event=push)](https://github.com/jcubic/lips/actions/workflows/build.yaml) +[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=devel&d99e59bdd4421bb215d5bb781449d63f)](https://coveralls.io/github/jcubic/lips?branch=devel) [![Join Gitter Chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jcubic/lips) ![NPM Download Count](https://img.shields.io/npm/dm/@jcubic/lips) ![JSDelivr Download count](https://img.shields.io/jsdelivr/npm/hm/@jcubic/lips) @@ -162,7 +162,7 @@ npm install -g @jcubic/lips@beta you can run the interpreter from the terminal: -![LIPS: Scheme interactive terminal](https://github.com/jcubic/lips/blob/master/assets/screencast.gif?raw=true) +![LIPS: Scheme interactive terminal](https://github.com/jcubic/lips/blob/devel/assets/screencast.gif?raw=true) You can also run code in a string with: @@ -201,7 +201,7 @@ Executables also return a S-Expression according to SRFI-176 use `lips --version ## FOSDEM'23 Presentation [Video] -[![FOSDEM 2023 - LIPS Scheme: Powerful introspection and extensibility](https://github.com/jcubic/lips/blob/master/assets/fosdem-intro.png?raw=true)](https://fosdem.org/2023/schedule/event/lipsscheme/) +[![FOSDEM 2023 - LIPS Scheme: Powerful introspection and extensibility](https://github.com/jcubic/lips/blob/devel/assets/fosdem-intro.png?raw=true)](https://fosdem.org/2023/schedule/event/lipsscheme/) ## Limitations @@ -210,7 +210,7 @@ Because LIPS is tree walking interpreter, sometimes it may be slow. Especially i process long arrays and use callback function. If the array is quite large each piece of code inside the callback may slow down the processing. For example see: -script [reference.scm](https://github.com/jcubic/lips/blob/master/scripts/reference.scm) +script [reference.scm](https://github.com/jcubic/lips/blob/devel/scripts/reference.scm) That generates reference documentation for all builtin functions and macros. The slow part is `(names.sort name-compare)` (`Array::sort`) that take quite time to calculate, @@ -260,8 +260,16 @@ This can happen with React/Preact and when the component returns a Promise. Some | Custom macro transformers | [SRFI-147](https://srfi.schemers.org/srfi-147/) | | Version flag | [SRFI-176](https://srfi.schemers.org/srfi-176/) | | Command line | [SRFI-193](https://srfi.schemers.org/srfi-193/) | +| Mixing groups of definitions with expressions within bodies | [SRFI-251](https://srfi.schemers.org/srfi-251/) | -### require `(load "./lib/srfi/.scm")` +### require manual loading + +You can load the SRFI with special syntax that start with `@lips` +which points to root LIPS directory: + +```scheme +(load "@lips/lib/srfi/.scm") +``` They should be loaded as R7RS libraries in final 1.0.0 version @@ -278,8 +286,9 @@ They should be loaded as R7RS libraries in final 1.0.0 version | Multiple-value boxes | [SRFI-195](https://srfi.schemers.org/srfi-195) | | Procedures and Syntax for Multiple Values | [SRFI-210](https://srfi.schemers.org/srfi-210/) | | Evaluating expressions in an unspecified order | [SRFI-236](https://srfi.schemers.org/srfi-236) | +| Destructuring Lists | [SRFI 239](https://srfi.schemers.org/srfi-239/) | -in Web (e.g. in Web REPL) you can use URL: +in Web (e.g. in Web REPL) you can also use full URL: ```scheme (load "https://cdn.jsdelivr.net/npm/@jcubic/lips@beta/lib/srfi/.scm") @@ -300,8 +309,7 @@ in Web (e.g. in Web REPL) you can use URL: * [Brian Lovin](https://brianlovin.com/hn/38819212) (HN clone) ## Projects that use LIPS -* [Conzept](https://conze.pt) - Topic exploration system for the 21st century (see also their [Twitter account](https://twitter.com/conzept__) and [Command API Documentation](https://conze.pt/guide/command_api)). -* [Logoi](https://logoi.website/) - a minimalist "superdialect" of the Prolog and Lisp programming languages. +* [Conzept](https://conze.pt) - Topic exploration system for the 21st century (see also their [Twitter account](https://twitter.com/conzept__) and [Command API Documentation](https://conze.pt/guide/command_api)) ## Roadmap ### 1.0 @@ -365,6 +373,8 @@ I would also love to see if you use the library, I may even share the links of p Special thanks to [Lassi Kortela](https://github.com/lassik) for helping with Scheme code. +Thanks for [Algolia DocSearch](https://docsearch.algolia.com/) for providing free search on LIPS website. + ## License Released under [MIT](http://opensource.org/licenses/MIT) license
diff --git a/bin/lips.js b/bin/lips.js index f72f1d070..75f9d740d 100755 --- a/bin/lips.js +++ b/bin/lips.js @@ -67,8 +67,13 @@ function log_error(message) { message = message.split('\n').map(line => { return `${date}: ${line}`; }).join('\n'); - fs.appendFileSync(path.join(os.homedir(), 'lips.error.log'), message + '\n'); + fs.appendFileSync(home_file('lips.error.log'), message + '\n'); } + +function home_file(filename) { + return path.join(os.homedir(), filename); +} + // ----------------------------------------------------------------------------- function debug(message) { console.log(message); @@ -122,7 +127,8 @@ function print(result) { if (last !== undefined) { try { const ret = env.get('repr')(last, true); - console.log('\x1b[K' + ret.toString()); + process.stdout.write('\x1b[K' + ret.toString()); + return true; } catch(e) { print_error(e, options.t || options.trace); } @@ -211,8 +217,9 @@ function log(message) { } // ----------------------------------------------------------------------------- -var strace; -var rl; +let strace; +let rl; +let buffer; var newline; const moduleURL = new URL(import.meta.url); const __dirname = path.dirname(moduleURL.pathname); @@ -416,21 +423,20 @@ if (options.version || options.V) { console.log(banner.replace(/(\n\nLIPS.+)/m, entry)); // ' } var prompt = 'lips> '; - var continuePrompt = '... '; + var continue_prompt = '... '; var terminal = !!process.stdin.isTTY && !(process.env.EMACS || process.env.INSIDE_EMACS); + buffer = make_buffer(process.stdout); rl = readline.createInterface({ input: process.stdin, - output: process.stdout, + output: buffer, prompt: prompt, terminal }); - rl._writeToOutput = function _writeToOutput(string) { - rl.output.write(scheme(string)); - }; - process.stdin.on('keypress', (c, k) => { - setTimeout(function() { - rl._refreshLine(); // force refresh colors - }, 0); + rl.on('close', () => { + setTimeout(() => { + rl.setPrompt(''); + buffer.flush('\n'); + }, 10); }); const historySize = Number(env.LIPS_REPL_HISTORY_SIZE); if (!Number.isNaN(historySize) && historySize > 0) { @@ -441,12 +447,123 @@ if (options.version || options.V) { setupHistory(rl, terminal ? env.LIPS_REPL_HISTORY : '', run_repl); } -function unify_prompt(a, b) { - var result = a; - if (a.length < b.length) { - result += new Array((b.length - a.length) + 1).join(' '); +function is_open(token) { + return ['(', '['].includes(token); +} + +function is_close(token) { + return [')', ']'].includes(token); +} + +function debug_log(filename) { + return (message) => { + const payload = message.replace(/\n/g, '\\n') + '\n'; + fs.appendFile(filename, payload, function (err) { + if (err) throw err; + }); + }; +} + +// buffer Proxy to prevent flicker when Node writes to stdout +function make_buffer(stream) { + const DEBUG = false; + const buffer = []; + const fname = home_file('lips__debug.log'); + if (DEBUG) { + fs.truncate(fname, 0, () => {}); } - return result; + const log = DEBUG ? debug_log(fname) : () => {}; + function flush(data, ...args) { + if (buffer.length) { + const payload = buffer.join('') + data; + buffer.length = 0; + log(`flush ::: ${payload}`); + stream.write(payload, ...args); + } else { + log('write :::'); + stream.write(data, ...args); + } + } + return new Proxy(stream, { + get(target, prop) { + if (prop === 'flush') { + return flush; + } + if (prop === 'write') { + return function(data, ...args) { + log(data); + if (data.match(/\x1b\[(?:1G|0J)|(^(?:lips>|\.\.\.) )/)) { + buffer.push(data); + log('buffer :::'); + } else { + flush(data, ...args); + } + } + } + return target[prop]; + } + }); +} + +// find matching open parentheses. The last token is always +// a closing parenthesis +function matched_token(code) { + try { + let count = 0; + // true to tokenize return tokens with meta data + return tokenize(code, true).reverse().find(token => { + if (is_open(token.token)) { + count--; + } else if (is_close(token.token)) { + count++; + } + return is_open(token.token) && count === 0; + }); + } catch(e) { + if (!(e instanceof Parser.Unterminated)) { + throw e; + } + } +} + +// highlight the open parentheses based on token metadata +function mark_paren(code, token) { + const re = /(\x1b\[[0-9;]*m)/; + let str_len = 0, found; + return code.split(re).reduce((acc, str) => { + let result + if (str.match(re)) { + result = str; + } else if (found) { + result = str; + } else if (str_len + str.length <= token.offset) { + result = str; + str_len += str.length; + } else { + const pos = token.offset - str_len; + const before = str.substring(0, pos); + const after = str.substring(pos + 1); + result = `${before}\x1b[7m(\x1b[m${after}`; + found = true; + } + return acc + result; + }, ''); +} + +// function accept ANSI (syntax highlighted code) and +// return ANSI escapes to overwrite the code +// this is needed to make sure that syntax highlighting +// is always correct +function ansi_rewrite_above(ansi_code) { + const lines = ansi_code.split('\n'); + const stdout = lines.map((line, i) => { + const prefix = i === 0 ? prompt : continue_prompt; + return prefix + line; + }).join('\x1b[E') + '\x1b[E'; + const len = lines.length; + // overwrite all lines to get rid of any artifacts left my stdin + // mostly because of parenthesis matching + return `\x1b[${len}F${stdout}`; } function run_repl(err, rl) { @@ -454,6 +571,7 @@ function run_repl(err, rl) { let cmd = ''; let multiline = false; let resolve; + const brackets_re = /\x1b\[(200|201)~/g; // we use promise loop to fix issue when copy paste list of S-Expression let prev_eval = Promise.resolve(); if (process.stdin.isTTY) { @@ -461,69 +579,134 @@ function run_repl(err, rl) { } let prev_line; const is_emacs = process.env.INSIDE_EMACS; - function continue_multiline() { + function is_brackets_mode() { + return !!cmd.match(brackets_re); + } + function continue_multiline(code) { multiline = true; - if (cmd.match(/\x1b\[200~/) || !supports_paste_brackets) { + // we don't do indentation for paste bracket mode + // indentation will also not work for old Node.js + // because it's too problematice to make it right + if ((is_brackets_mode() || !supports_paste_brackets)) { rl.prompt(); if (is_emacs) { rl.setPrompt(''); } else { - rl.setPrompt(continuePrompt); + rl.setPrompt(continue_prompt); } if (terminal) { - rl.write(' '.repeat(prompt.length - continuePrompt.length)); + rl.write(' '.repeat(prompt.length - continue_prompt.length)); } } else { let ind; try { - ind = indent(code, 2, prompt.length - continuePrompt.length); + ind = indent(code, 2, prompt.length - continue_prompt.length); } catch (e) { ind = 0; } - const spaces = new Array(ind + 1).join(' '); + const spaces = ' '.repeat(ind); if (is_emacs) { rl.setPrompt(''); rl.prompt(); } else { - rl.setPrompt(continuePrompt); + rl.setPrompt(continue_prompt); rl.prompt(); rl.write(spaces); } } } + function char_before_cursor() { + return rl.line[rl.cursor - 1]; + } + function format_input_code(code) { + if (code) { + // we remove trailing newline from code + code = code.substring(0, code.length - 1); + return scheme(code); + } + } + let prev_token; + rl._writeToOutput = function _writeToOutput(string) { + function should_update() { + return (token || prev_token) && code_above && !string.match(/^[\n\r]+$/); + } + let token, code_above, code; + try { + const prefix = multiline ? continue_prompt : prompt; + const current_line = prefix + rl.line; + code = scheme(string); + const bracket_mode = cmd.match(brackets_re); + const full_copy_paste = bracket_mode?.length == 2; + if ((!bracket_mode || full_copy_paste) && !is_emacs) { + // clean bracket mode markers + const clean_cmd = cmd.replace(brackets_re, ''); + code_above = format_input_code(clean_cmd); + if (char_before_cursor() === ')') { + const substring = rl.line.substring(0, rl.cursor); + const input = prefix + substring; + token = matched_token(input); + if (token) { + code = mark_paren(code, token); + } else if (clean_cmd) { + const input = clean_cmd + substring; + // we match paren above the current line + // but we need whole code with rl.line + // so we need to ignore rl.line + token = matched_token(input); + if (token) { + // code_above don't include the current line that + // is added after user press enter + code_above = mark_paren(code_above, token); + } + } + } + if (should_update()) { + // overwrite lines above the cursor this is side effect + process.stdout.write('\x1b7' + ansi_rewrite_above(code_above) + '\x1b8'); + } + prev_token = token; + } + // this always need to be executed inside rl._writeToOutput + // even if nothing changes, this make sure that the input + // stay intact while editing the command line + rl.output.write(code); + } catch(e) { + console.error(e); + } + }; + process.stdin.on('keypress', (c, k) => { + setTimeout(function() { + // we force triggering rl._writeToOutput function + // so we have the change to syntax highlight the command line + // this needs to happen on next tick so the string have time + // to updated with a given key + rl._refreshLine(); + }, 0); + }); bootstrap(interp).then(function() { if (supports_paste_brackets) { + // this make sure that the paste brackets ANSI escape + // is added to cmd so they can be processed in 'line' event process.stdin.on('keypress', (c, k) => { if (k?.name?.match(/^paste-/)) { cmd += k.sequence; } }); + // enable paste bracket mode by the terminal process.stdout.write('\x1b[?2004h'); } - const re = /\x1b\[(200|201)~/g; rl.on('line', function(line) { - cmd += line; - if (cmd.match(/\x1b\[201~$/)) { - cmd = cmd.replace(re, ''); - } - const code = cmd.replace(re, ''); - const lines = code.split('\n'); - if (terminal) { - const stdout = scheme(code).split('\n').map((line, i) => { - let prefix; - if (i === 0) { - prefix = unify_prompt(prompt, continuePrompt); - } else { - prefix = unify_prompt(continuePrompt, prompt); - } - return '\x1b[K' + prefix + line; - }).join('\n'); - let num = lines.length; - const format = `\x1b[${num}F${stdout}\n`; - process.stdout.write(format); - } - cmd += '\n'; try { + cmd += line; + const code = cmd.replace(brackets_re, ''); + if (cmd.match(/\x1b\[201~$/)) { + cmd = code; + } + if (terminal) { + const output = ansi_rewrite_above(scheme(code)); + process.stdout.write(output); + } + cmd += '\n'; if (balanced_parenthesis(code)) { // we need to clear the prompt because resume // is adding the prompt that was present when pause was called @@ -536,11 +719,10 @@ function run_repl(err, rl) { return result; }).then(function(result) { if (process.stdin.isTTY) { - print(result); - if (newline || is_emacs) { + if (print(result) || newline) { // readline doesn't work with not ended lines // it ignore those, so we end them ourselves - process.stdout.write("\n"); + process.stdout.write('\n'); newline = false; } if (multiline) { @@ -559,7 +741,7 @@ function run_repl(err, rl) { rl.resume(); }); } else { - continue_multiline(); + continue_multiline(code); } } catch (e) { console.error(e.message); diff --git a/dist/lips.cjs b/dist/lips.cjs index b8fc51190..e64df1374 100644 --- a/dist/lips.cjs +++ b/dist/lips.cjs @@ -4,7 +4,7 @@ * | | \ \ | | | || . \/ __> | | * | | > \ | |_ | || _/\__ \ | | * | | / ^ \ |___||_||_| <___/ | | - * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19 + * \_\ /_/ \_\ /_/ v. DEV * * LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript * @@ -31,7 +31,7 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Mon, 27 May 2024 11:41:47 +0000 + * build: Fri, 08 Nov 2024 13:26:12 +0000 */ 'use strict'; @@ -105,6 +105,10 @@ function _construct(t, e, r) { return r && _setPrototypeOf(p, r.prototype), p; } +function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} + function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -3502,25 +3506,23 @@ function contentLoaded(win, fn) { } } // ------------------------------------------------------------------------- -/* eslint-disable */ /* c8 ignore next 13 */ function log(x) { - if (is_debug()) { - if (is_plain_object(x)) { - console.log(map_object(x, function (value) { - return toString(value, true); - })); - } else { - var _console; - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { - return toString(item, true); - })))); - } + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (is_plain_object(x) && is_debug(args[0])) { + console.log(map_object(x, function (value) { + return toString(value, true); + })); + } else if (is_debug()) { + var _console; + (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { + return toString(item, true); + })))); } } +/* eslint-enable */ // ---------------------------------------------------------------------- /* c8 ignore next */ function is_debug() { @@ -3909,8 +3911,25 @@ function parse_string(string) { } // ---------------------------------------------------------------------- function parse_symbol(arg) { - if (arg.match(/^\|.*\|$/)) { - arg = arg.replace(/(^\|)|(\|$)/g, ''); + arg.match(/^name/); + var re = /(^|.)\|/g; + if (arg.match(re)) { + // handle escaped bar and escaped slash + arg = arg.split('|').filter(Boolean).reduce(function (acc, str) { + var result = ''; + if (str.match(/^\\+$/)) { + if (str.length > 1) { + var count = Math.floor(str.length / 2); + result = '\\'.repeat(count); + } + if (str.length % 2 !== 0) { + result += '|'; + } + } else { + result = str; + } + return acc + result; + }); var chars = { t: '\t', r: '\r', @@ -3918,8 +3937,8 @@ function parse_symbol(arg) { }; arg = arg.replace(/\\(x[^;]+);/g, function (_, chr) { return String.fromCharCode(parseInt('0' + chr, 16)); - }).replace(/\\(.)/g, function (_, chr) { - return chars[chr] || chr; + }).replace(/\\([trn])/g, function (_, chr) { + return chars[chr]; }); } return new LSymbol(arg); @@ -4220,6 +4239,18 @@ var gensym = function () { return with_props(count, Symbol("#:g".concat(count))); }; }(); +// ---------------------------------------------------------------------- +// :: helper function that make symbols in names array hygienic +// ---------------------------------------------------------------------- +function hygienic_begin(envs, expr) { + var begin = global_env.get('begin'); + var g_begin = gensym('begin'); + envs.forEach(function (env) { + env.set(g_begin, begin); + }); + return new Pair(g_begin, expr); +} + // ---------------------------------------------------------------------- // Class used to escape promises: feature #54 // ---------------------------------------------------------------------- @@ -4517,6 +4548,11 @@ var Lexer = /*#__PURE__*/function () { var found = this.next_token(); if (found) { this._token = this.__input__.substring(this._i, this._next); + if (!this.__token__) { + // handle case when accessing __token__ from the syntax extension + // (e.g. string interpolation) as the first expression in a REPL + read_only(this, '__token__', this.token(true)); + } return this.token(meta); } return eof; @@ -4765,6 +4801,7 @@ Lexer.regex_class = Symbol["for"]('regex_class'); Lexer.character = Symbol["for"]('character'); Lexer.bracket = Symbol["for"]('bracket'); Lexer.b_symbol = Symbol["for"]('b_symbol'); +Lexer.b_symbol_ex = Symbol["for"]('b_symbol_ex'); Lexer.b_comment = Symbol["for"]('b_comment'); Lexer.i_comment = Symbol["for"]('i_comment'); Lexer.l_datum = Symbol["for"]('l_datum'); @@ -4795,7 +4832,7 @@ Lexer._rules = [ // for dot comma `(a .,b) [/\./, Lexer.boundary, /,/, null, null], // block symbols -[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null]]; +[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null]]; // ---------------------------------------------------------------------- Lexer._brackets = [[/[()[\]]/, null, null, null, null]]; // ---------------------------------------------------------------------- @@ -4897,17 +4934,16 @@ var Parser = /*#__PURE__*/function () { _createClass(Parser, [{ key: "_with_syntax_scope", value: function _with_syntax_scope(fn) { - var _this5 = this; // expose parser and change stdin so parser extension can use current-input // to read data from the parser stream #150 var internal = get_internal(this.__env__); var stdin = internal.get('stdin'); - this.__env__.set('lips', _objectSpread(_objectSpread({}, lips), {}, { + global_env.set('lips', _objectSpread(_objectSpread({}, lips), {}, { __parser__: this })); internal.set('stdin', new ParserInputPort(this, this.__env__)); var cleanup = function cleanup() { - _this5.__env__.set('lips', lips); + global_env.set('lips', lips); internal.set('stdin', stdin); }; return unpromise(fn(), function (result) { @@ -5246,7 +5282,7 @@ var Parser = /*#__PURE__*/function () { key: "_resolve_object", value: function () { var _resolve_object2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(object) { - var _this6 = this; + var _this5 = this; var result; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { @@ -5256,7 +5292,7 @@ var Parser = /*#__PURE__*/function () { break; } return _context6.abrupt("return", object.map(function (item) { - return _this6._resolve_object(item); + return _this5._resolve_object(item); })); case 2: if (!is_plain_object(object)) { @@ -5265,7 +5301,7 @@ var Parser = /*#__PURE__*/function () { } result = {}; Object.keys(object).forEach(function (key) { - result[key] = _this6._resolve_object(object[key]); + result[key] = _this5._resolve_object(object[key]); }); return _context6.abrupt("return", result); case 6: @@ -5340,7 +5376,7 @@ var Parser = /*#__PURE__*/function () { key: "_read_object", value: function () { var _read_object3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { - var _this7 = this; + var _this6 = this; var token, special, builtin, expr, extension, is_symbol, was_close_paren, object, args, result, ref, ref_label; return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { @@ -5418,8 +5454,8 @@ var Parser = /*#__PURE__*/function () { } return _context8.abrupt("return", this._with_syntax_scope(function () { return call_function(extension, is_symbol ? [] : args, { - env: _this7.__env__, - dynamic_env: _this7.__env__, + env: _this6.__env__, + dynamic_env: _this6.__env__, use_dynamic: false }); })); @@ -5454,7 +5490,7 @@ var Parser = /*#__PURE__*/function () { } _context8.next = 44; return this._with_syntax_scope(function () { - return _this7.evaluate(expr); + return _this6.evaluate(expr); }); case 44: result = _context8.sent; @@ -6191,7 +6227,7 @@ function keywords_re() { return new RegExp("^(?:#:)?(?:".concat(args.join('|'), ")$")); } // line breaking rules -Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1], [[p_o, let_re, symbol, p_o, let_value, p_e], 1], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; +Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; // ---------------------------------------------------------------------- Formatter.prototype["break"] = function () { var code = this.__code__.replace(/\n[ \t]*/g, '\n ').replace(/^\s+/, ''); @@ -8156,7 +8192,7 @@ function user_repr(obj) { // if key is Object it should only work for plain_object // because otherwise it will match every object // we don't use instanceof so it don't work for subclasses - if (obj instanceof key && (key === Object && plain_object && !iterator || key !== Object)) { + if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) { fn = value; } }); @@ -8363,6 +8399,9 @@ function toString(obj, quote, skip_cycles) { if (type(obj) === 'instance') { if (is_lambda(constructor) && constructor.__name__) { name = constructor.__name__.valueOf(); + if (_typeof$1(name) === 'symbol') { + name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1'); + } } else if (!is_native_function(constructor)) { name = 'instance'; } @@ -9083,8 +9122,13 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { log(symbols); /* eslint-disable complexity */ function traverse(pattern, code) { - var pattern_names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var ellipsis = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var _state$ellipsis = state.ellipsis, + ellipsis = _state$ellipsis === void 0 ? false : _state$ellipsis, + _state$trailing = state.trailing, + trailing = _state$trailing === void 0 ? false : _state$trailing, + _state$pattern_names = state.pattern_names, + pattern_names = _state$pattern_names === void 0 ? [] : _state$pattern_names; log({ code: code, pattern: pattern @@ -9092,13 +9136,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (is_atom(pattern) && !(pattern instanceof LSymbol)) { return same_atom(pattern, code); } - if (pattern instanceof LSymbol && symbols.includes(pattern.literal())) { - // TODO: literal() may be SLOW - if (!LSymbol.is(code, pattern)) { - return false; + if (pattern instanceof LSymbol) { + var literal = pattern.literal(); // TODO: literal() may be SLOW + if (symbols.includes(literal)) { + if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) { + return false; + } + var ref = expansion.ref(literal); + return !ref || ref === define || ref === global_env; } - var ref = expansion.ref(pattern); - return !ref || ref === define || ref === global_env; } if (Array.isArray(pattern) && Array.isArray(code)) { log('<<< a 1'); @@ -9124,25 +9170,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } else if (Array.isArray(pattern[0])) { log('<<< a 3'); var _names = _toConsumableArray(pattern_names); + var new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: _names, + ellipsis: true + }); if (!code.every(function (node) { - return traverse(pattern[0], node, _names, true); + return traverse(pattern[0], node, new_state); })) { return false; } } if (pattern.length > 2) { var pat = pattern.slice(2); - return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis); + return traverse(pat, code.slice(-pat.length), state); } return true; } - var first = traverse(pattern[0], code[0], pattern_names, ellipsis); + var first = traverse(pattern[0], code[0], state); log({ first: first, pattern: pattern[0], code: code[0] }); - var rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis); + var rest = traverse(pattern.slice(1), code.slice(1), state); log({ first: first, rest: rest @@ -9166,23 +9216,30 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } } if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) { + log('>> 1 (a)'); // pattern (... ???) - SRFI-46 if (!is_nil(pattern.cdr.cdr)) { if (is_pair(pattern.cdr.cdr)) { + log('>> 1 (b)'); // if we have (x ... a b) we need to remove two from the end var list_len = pattern.cdr.cdr.length(); + var improper_list = !is_nil(pattern.last_pair().cdr); if (!is_pair(code)) { return false; } var code_len = code.length(); var list = code; - while (code_len - 1 > list_len) { + var _trailing = improper_list ? 1 : 1; + while (code_len - _trailing > list_len) { list = list.cdr; code_len--; } var _rest5 = list.cdr; list.cdr = _nil; - if (!traverse(pattern.cdr.cdr, _rest5, pattern_names, ellipsis)) { + var new_sate = _objectSpread(_objectSpread({}, state), {}, { + trailing: improper_list + }); + if (!traverse(pattern.cdr.cdr, _rest5, new_sate)) { return false; } } @@ -9192,7 +9249,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (bindings['...'].symbols[_name3] && !pattern_names.includes(_name3) && !ellipsis) { throw new Error('syntax: named ellipsis can only appear onces'); } - log('>> 1'); + log('>> 1 (next)'); if (is_nil(code)) { log('>> 2'); if (ellipsis) { @@ -9223,6 +9280,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } else { log('>> 6'); if (is_pair(code)) { + log('>> 7 ' + ellipsis); // cons (a . b) => (var ... . x) if (!is_pair(code.cdr) && !is_nil(code.cdr)) { log('>> 7 (b)'); @@ -9230,28 +9288,34 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { return false; } else if (!bindings['...'].symbols[_name3]) { bindings['...'].symbols[_name3] = new Pair(code.car, _nil); - return traverse(pattern.cdr.cdr, code.cdr); + return traverse(pattern.cdr.cdr, code.cdr, state); } } // code as improper list var last_pair = code.last_pair(); + log({ + last_pair: last_pair + }); if (!is_nil(last_pair.cdr)) { + log('>> 7 (c)'); if (is_nil(pattern.cdr.cdr)) { // case (a ...) for (a b . x) return false; } else { + log('>> 7 (d)'); // case (a ... . b) for (a b . x) var copy = code.clone(); copy.last_pair().cdr = _nil; bindings['...'].symbols[_name3] = copy; - return traverse(pattern.cdr.cdr, last_pair.cdr); + return traverse(pattern.cdr.cdr, last_pair.cdr, state); } } - log('>> 7 ' + ellipsis); pattern_names.push(_name3); if (!bindings['...'].symbols[_name3]) { + log('>> 7 (e)'); bindings['...'].symbols[_name3] = new Pair(code, _nil); } else { + log('>> 7 (f)'); var _node2 = bindings['...'].symbols[_name3]; bindings['...'].symbols[_name3] = _node2.append(new Pair(code, _nil)); } @@ -9262,7 +9326,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { // empty ellipsis with rest (a b ... . d) #290 log('>> 8'); bindings['...'].symbols[_name3] = null; - return traverse(pattern.cdr.cdr, code); + return traverse(pattern.cdr.cdr, code, state); } else { log('>> 9'); return false; @@ -9279,8 +9343,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } log('>> 11'); var _node3 = code; + var _new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node3)) { - if (!traverse(pattern.car, _node3.car, names, true)) { + if (!traverse(pattern.car, _node3.car, _new_state)) { return false; } _node3 = _node3.cdr; @@ -9290,8 +9358,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (Array.isArray(pattern.car)) { var names = _toConsumableArray(pattern_names); var _node4 = code; + var _new_state2 = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node4)) { - if (!traverse(pattern.car, _node4.car, names, true)) { + if (!traverse(pattern.car, _node4.car, _new_state2)) { return false; } _node4 = _node4.cdr; @@ -9326,15 +9398,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { code: code, pattern: pattern }); + var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol; + if (trailing && rest_pattern) { + log('>> 13 (a)'); + // handle (x ... y . z) + if (!is_nil(code.cdr)) { + return false; + } + var _car = pattern.car.valueOf(); + var _cdr = pattern.cdr.valueOf(); + bindings.symbols[_car] = code.car; + bindings.symbols[_cdr] = _nil; + return true; + //return is_pair(code.cdr) && code.cdr.length() > 1; + } if (is_nil(code.cdr)) { + log('>> 13 (b)'); // 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) { // fix for SRFI-26 in recursive call of (b) ==> (<> . x) // where <> is symbol - if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) { + if (!traverse(pattern.car, code.car, state)) { return false; } log('>> 14'); @@ -9354,7 +9440,10 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { code: code }); // case (x y) ===> (var0 var1 ... warn) where var1 match nil - if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) { + // trailing: true start processing of (var ... x . y) + if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, state) && traverse(pattern.cdr.cdr.cdr, code.cdr, _objectSpread(_objectSpread({}, state), {}, { + trailing: true + }))) { var _name6 = pattern.cdr.car.__name__; log({ pattern: pattern, @@ -9372,15 +9461,14 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { pattern: pattern, code: code }); - var car = traverse(pattern.car, code.car, pattern_names, ellipsis); - log({ - car: car, - pattern: pattern.car, - code: code.car - }); - var cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis); + var car = traverse(pattern.car, code.car, state); + var cdr = traverse(pattern.cdr, code.cdr, state); log({ + $car_code: code.car, + $car_pattern: pattern.car, car: car, + $cdr_code: code.cdr, + $cdr_pattern: pattern.cdr, cdr: cdr }); if (car && cdr) { @@ -9573,46 +9661,47 @@ function transform_syntax() { var item = bindings[_name7]; if (item === null) { return; - } else if (item) { + } else if (_name7 in bindings) { log({ name: _name7, binding: bindings[_name7] }); if (is_pair(item)) { log('[t 2 Pair ' + nested); - var _car = item.car, - _cdr = item.cdr; + var _car2 = item.car, + _cdr2 = item.cdr; var _rest_expr = is_array ? expr.slice(2) : expr.cdr.cdr; if (nested) { - if (!is_nil(_cdr)) { + if (!is_nil(_cdr2)) { log('|| next 1'); - next(_name7, _cdr); + next(_name7, _cdr2); } if (is_array && _rest_expr.length || !is_nil(_rest_expr) && !is_array) { var _rest7 = transform_ellipsis_expr(_rest_expr, bindings, state, next); if (is_array) { - return _car.concat(_rest7); - } else if (is_pair(_car)) { - return _car.append(_rest7); + return _car2.concat(_rest7); + } else if (is_pair(_car2)) { + return _car2.append(_rest7); } else { log('UNKNOWN'); } } - return _car; - } else if (is_pair(_car)) { - if (!is_nil(_car.cdr)) { + return _car2; + } else if (is_pair(_car2)) { + if (!is_nil(_car2.cdr)) { log('|| next 2'); - next(_name7, new Pair(_car.cdr, _cdr)); + next(_name7, new Pair(_car2.cdr, _cdr2)); } - return _car.car; - } else if (is_nil(_cdr)) { - return _car; + // wrap with Value to handle undefined + return new Value(_car2.car); + } else if (is_nil(_cdr2)) { + return _car2; } else { var last_pair = expr.last_pair(); if (last_pair.cdr instanceof LSymbol) { log('|| next 3'); next(_name7, item.last_pair()); - return _car; + return _car2; } } } else if (item instanceof Array) { @@ -9675,6 +9764,7 @@ function transform_syntax() { return expr; } if (is_pair(expr) || is_array) { + log('>> 0'); var first = is_array ? expr[0] : expr.car; var second, rest_second; if (is_array) { @@ -9759,6 +9849,9 @@ function transform_syntax() { // undefined can be null caused by null binding // on empty ellipsis if (car !== undefined) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } if (is_spread) { if (is_array) { if (Array.isArray(car)) { @@ -9815,6 +9908,9 @@ function transform_syntax() { nested: true }); if (car) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } return new Pair(car, _nil); } return _nil; @@ -9853,6 +9949,9 @@ function transform_syntax() { value: value }); if (typeof value !== 'undefined') { + if (value instanceof Value) { + value = value.valueOf(); + } if (is_array) { _result3.push(value); } else { @@ -9893,6 +9992,9 @@ function transform_syntax() { } } log('<<<< 2'); + log({ + result: _result3 + }); return _result3; } } @@ -10026,8 +10128,12 @@ function is_undef(value) { return typeof value === 'undefined'; } // ------------------------------------------------------------------------- +function get_proto(obj) { + return Object.getPrototypeOf(obj); +} +// ------------------------------------------------------------------------- function is_iterator(obj, symbol) { - if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) { + if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) { return is_function(obj[symbol]); } } @@ -10322,8 +10428,7 @@ function let_macro(symbol) { return pair.cdr.car; }); } - var args_name = gensym('args'); - return Pair.fromArray([LSymbol('let'), [[args_name, Pair(LSymbol('list'), args)]], [LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], [LSymbol('apply'), code.car, args_name]]]); + return new Pair(Pair.fromArray([LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], code.car]), args); } else if (macro_expand) { // Macro.defmacro are special macros that should return lips code // here we use evaluate, so we need to check special flag set by @@ -10341,7 +10446,7 @@ function let_macro(symbol) { } var i = 0; function exec() { - var output = new Pair(new LSymbol('begin'), code.cdr); + var output = hygienic_begin([env], code.cdr); return _evaluate(output, { env: env, dynamic_env: env, @@ -10461,7 +10566,7 @@ function guard_math_call(fn) { } // ---------------------------------------------------------------------- function pipe() { - var _this8 = this; + var _this7 = this; for (var _len8 = arguments.length, fns = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { fns[_key8] = arguments[_key8]; } @@ -10473,7 +10578,7 @@ function pipe() { args[_key9] = arguments[_key9]; } return fns.reduce(function (args, f) { - return [f.apply(_this8, args)]; + return [f.apply(_this7, args)]; }, args)[0]; }; } @@ -10538,7 +10643,7 @@ function curry(fn) { typecheck('curry', fn, 'function'); var len = fn.length; return function () { - var _this9 = this; + var _this8 = this; var args = init_args.slice(); // HACK: we use IIFE here to get rid of the name of the function. // The JavaScript is smart and add name property to a function @@ -10551,7 +10656,7 @@ function curry(fn) { } args = args.concat(more_args); if (args.length >= len) { - return fn.apply(_this9, args); + return fn.apply(_this8, args); } else { return curried; } @@ -11614,9 +11719,9 @@ LComplex.prototype.mul = function (n) { }; // ------------------------------------------------------------------------- LComplex.prototype.complex_op = function (name, n, fn) { - var _this10 = this; + var _this9 = this; var calc = function calc(re, im) { - var result = fn(_this10.__re__, re, _this10.__im__, im); + var result = fn(_this9.__re__, re, _this9.__im__, im); if ('im' in result && 're' in result) { if (result.im.cmp(0) === 0) { return result.re; @@ -12212,7 +12317,7 @@ LComplex.i = LComplex({ // :: Port abstraction - read should be a function that return next line // ------------------------------------------------------------------------- function InputPort(read) { - var _this11 = this; + var _this10 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputPort) || typeof this === 'undefined') { return new InputPort(read); @@ -12236,12 +12341,12 @@ function InputPort(read) { return _regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) switch (_context14.prev = _context14.next) { case 0: - if (_this11.char_ready()) { + if (_this10.char_ready()) { _context14.next = 6; break; } _context14.next = 3; - return _this11._read(); + return _this10._read(); case 3: line = _context14.sent; parser = new Parser({ @@ -12249,7 +12354,7 @@ function InputPort(read) { }); parser.parse(line); case 6: - return _context14.abrupt("return", _this11.__parser__); + return _context14.abrupt("return", _this10.__parser__); case 7: case "end": return _context14.stop(); @@ -12312,13 +12417,13 @@ InputPort.prototype.is_open = function () { return this._with_parser !== null; }; InputPort.prototype.close = function () { - var _this12 = this; + var _this11 = this; this.__parser__ = null; // make content garbage collected, we assign null, // because the value is in prototype this._with_parser = null; ['read', 'close', 'read_char', 'peek-char', 'read_line'].forEach(function (name) { - _this12[name] = function () { + _this11[name] = function () { throw new Error('input-port: port is closed'); }; }); @@ -12364,20 +12469,20 @@ OutputPort.prototype.toString = function () { var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { _inherits(BufferedOutputPort, _OutputPort); function BufferedOutputPort(fn) { - var _this13; + var _this12; _classCallCheck(this, BufferedOutputPort); - _this13 = _callSuper(this, BufferedOutputPort, [function () { - var _this14; - return (_this14 = _this13)._write.apply(_this14, arguments); + _this12 = _callSuper(this, BufferedOutputPort, [function () { + var _this13; + return (_this13 = _this12)._write.apply(_this13, arguments); }]); typecheck('BufferedOutputPort', fn, 'function'); - read_only(_assertThisInitialized(_this13), '_fn', fn, { + read_only(_assertThisInitialized(_this12), '_fn', fn, { hidden: true }); - read_only(_assertThisInitialized(_this13), '_buffer', [], { + read_only(_assertThisInitialized(_this12), '_buffer', [], { hidden: true }); - return _this13; + return _this12; } _createClass(BufferedOutputPort, [{ key: "flush", @@ -12390,13 +12495,13 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { }, { key: "_write", value: function _write() { - var _this15 = this; + var _this14 = this; for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) { args[_key18] = arguments[_key18]; } if (args.length) { args.forEach(function (arg) { - _this15._buffer.push(arg); + _this14._buffer.push(arg); }); var last_value = this._buffer[this._buffer.length - 1]; if (last_value.match(/\n$/)) { @@ -12409,7 +12514,7 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { return BufferedOutputPort; }(OutputPort); // ------------------------------------------------------------------------- function OutputStringPort(toString) { - var _this16 = this; + var _this15 = this; if (typeof this !== 'undefined' && !(this instanceof OutputStringPort) || typeof this === 'undefined') { return new OutputStringPort(toString); } @@ -12422,7 +12527,7 @@ function OutputStringPort(toString) { } else { x = x.valueOf(); } - _this16.__buffer__.push(x); + _this15.__buffer__.push(x); }; } OutputStringPort.prototype = Object.create(OutputPort.prototype); @@ -12437,7 +12542,7 @@ OutputStringPort.prototype.valueOf = function () { }; // ------------------------------------------------------------------------- function OutputFilePort(filename, fd) { - var _this17 = this; + var _this16 = this; if (typeof this !== 'undefined' && !(this instanceof OutputFilePort) || typeof this === 'undefined') { return new OutputFilePort(filename, fd); } @@ -12453,7 +12558,7 @@ function OutputFilePort(filename, fd) { } else { x = x.valueOf(); } - _this17.fs().write(_this17._fd, x, function (err) { + _this16.fs().write(_this16._fd, x, function (err) { if (err) { throw err; } @@ -12472,16 +12577,16 @@ OutputFilePort.prototype.internal = function (name) { return user_env.get('**internal-env**').get(name); }; OutputFilePort.prototype.close = function () { - var _this18 = this; + var _this17 = this; return new Promise(function (resolve, reject) { - _this18.fs().close(_this18._fd, function (err) { + _this17.fs().close(_this17._fd, function (err) { if (err) { reject(err); } else { - read_only(_this18, '_fd', null, { + read_only(_this17, '_fd', null, { hidden: true }); - OutputPort.prototype.close.call(_this18); + OutputPort.prototype.close.call(_this17); resolve(); } }); @@ -12492,7 +12597,7 @@ OutputFilePort.prototype.toString = function () { }; // ------------------------------------------------------------------------- function InputStringPort(string) { - var _this19 = this; + var _this18 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputStringPort) || typeof this === 'undefined') { return new InputStringPort(string); @@ -12500,13 +12605,13 @@ function InputStringPort(string) { typecheck('InputStringPort', string, 'string'); string = string.valueOf(); this._with_parser = this._with_init_parser.bind(this, function () { - if (!_this19.__parser__) { - _this19.__parser__ = new Parser({ + if (!_this18.__parser__) { + _this18.__parser__ = new Parser({ env: env }); - _this19.__parser__.parse(string); + _this18.__parser__.parse(string); } - return _this19.__parser__; + return _this18.__parser__; }); read_only(this, '__type__', text_port); this._make_defaults(); @@ -12573,13 +12678,13 @@ InputByteVectorPort.prototype.toString = function () { return "#"; }; InputByteVectorPort.prototype.close = function () { - var _this20 = this; + var _this19 = this; read_only(this, '__vector__', _nil); var err = function err() { throw new Error('Input-binary-port: port is closed'); }; ['read_u8', 'close', 'peek_u8', 'read_u8_vector'].forEach(function (name) { - _this20[name] = err; + _this19[name] = err; }); this.u8_ready = this.char_ready = function () { return false; @@ -12697,7 +12802,7 @@ InputBinaryFilePort.prototype.toString = function () { }; // ------------------------------------------------------------------------- function OutputBinaryFilePort(filename, fd) { - var _this21 = this; + var _this20 = this; if (typeof this !== 'undefined' && !(this instanceof OutputBinaryFilePort) || typeof this === 'undefined') { return new OutputBinaryFilePort(filename, fd); } @@ -12712,7 +12817,7 @@ function OutputBinaryFilePort(filename, fd) { typecheck('write', x, ['number', 'uint8array']); var buffer; if (!fs) { - fs = _this21.internal('fs'); + fs = _this20.internal('fs'); } if (LNumber.isNumber(x)) { buffer = new Uint8Array([x.valueOf()]); @@ -12720,7 +12825,7 @@ function OutputBinaryFilePort(filename, fd) { buffer = new Uint8Array(Array.from(x)); } return new Promise(function (resolve, reject) { - fs.write(_this21._fd, buffer, function (err) { + fs.write(_this20._fd, buffer, function (err) { if (err) { reject(err); } else { @@ -12752,7 +12857,7 @@ EOF.prototype.toString = function () { // Simpler way to create interpreter with interaction-environment // ------------------------------------------------------------------------- function Interpreter(name) { - var _this22 = this; + var _this21 = this; var _ref27 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, stderr = _ref27.stderr, stdin = _ref27.stdin, @@ -12776,7 +12881,7 @@ function Interpreter(name) { env: this.__env__ }); this.__env__.set('parent.frame', doc('parent.frame', function () { - return _this22.__env__; + return _this21.__env__; }, global_env.__env__['parent.frame'].__doc__)); var defaults_name = '**interaction-environment-defaults**'; this.set(defaults_name, get_props(obj).concat(defaults_name)); @@ -12796,7 +12901,7 @@ function Interpreter(name) { // ------------------------------------------------------------------------- Interpreter.prototype.exec = /*#__PURE__*/function () { var _ref28 = _asyncToGenerator(function (arg) { - var _this23 = this; + var _this22 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() { var _options$use_dynamic, use_dynamic, dynamic_env, env; @@ -12809,12 +12914,12 @@ Interpreter.prototype.exec = /*#__PURE__*/function () { // simple solution to overwrite this variable in each interpreter // before evaluation of user code if (!env) { - env = _this23.__env__; + env = _this22.__env__; } if (!dynamic_env) { dynamic_env = env; } - global_env.set('**interaction-environment**', _this23.__env__); + global_env.set('**interaction-environment**', _this22.__env__); if (!Array.isArray(arg)) { _context16.next = 10; break; @@ -12825,8 +12930,8 @@ Interpreter.prototype.exec = /*#__PURE__*/function () { use_dynamic: use_dynamic })); case 10: - _this23.__parser__.parse(arg); - return _context16.abrupt("return", exec(_this23.__parser__, { + _this22.__parser__.parse(arg); + return _context16.abrupt("return", exec(_this22.__parser__, { env: env, dynamic_env: dynamic_env, use_dynamic: use_dynamic @@ -13002,12 +13107,12 @@ Environment.prototype.toString = function () { }; // ------------------------------------------------------------------------- Environment.prototype.clone = function () { - var _this24 = this; + var _this23 = this; // duplicate refs var env = {}; // TODO: duplicated Symbols Object.keys(this.__env__).forEach(function (key) { - env[key] = _this24.__env__[key]; + env[key] = _this23.__env__[key]; }); return new Environment(env, this.__parent__, this.__name__); }; @@ -13141,14 +13246,14 @@ Environment.prototype.set = function (name, value) { // For internal use only // ------------------------------------------------------------------------- Environment.prototype.constant = function (name, value) { - var _this25 = this; + var _this24 = this; if (this.__env__.hasOwnProperty(name)) { throw new Error("Environment::constant: ".concat(name, " already exists")); } if (arguments.length === 1 && is_plain_object(arguments[0])) { var obj = arguments[0]; Object.keys(obj).forEach(function (key) { - _this25.constant(name, obj[key]); + _this24.constant(name, obj[key]); }); } else { Object.defineProperty(this.__env__, name, { @@ -13324,14 +13429,14 @@ var global_env = new Environment({ // ------------------------------------------------------------------ read: doc('read', /*#__PURE__*/function () { var _read2 = _asyncToGenerator(function () { - var _this26 = this; + var _this25 = this; var arg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() { var env, port; return _regeneratorRuntime.wrap(function _callee17$(_context17) { while (1) switch (_context17.prev = _context17.next) { case 0: - env = _this26.env; + env = _this25.env; if (arg === null) { port = internal(env, 'stdin'); } else { @@ -13419,6 +13524,19 @@ var global_env = new Environment({ return str; }, "(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."), // ------------------------------------------------------------------ + newline: doc('newline', function newline() { + var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var display = global_env.get('display'); + var use_dynamic = this.use_dynamic; + var env = global_env; + var dynamic_env = global_env; + call_function(display, ['\n', port], { + env: env, + dynamic_env: dynamic_env, + use_dynamic: use_dynamic + }); + }, "(newline [port])\n\n Write newline character to standard output or given port"), + // ------------------------------------------------------------------ display: doc('display', function display(arg) { var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (port === null) { @@ -13441,7 +13559,7 @@ var global_env = new Environment({ } var value = args.map(repr).join(' '); port.write.call(global_env, value); - global_env.get('newline')(port); + global_env.get('newline').call(this, port); }, "(display-error . args)\n\n Display an error message on stderr."), // ------------------------------------------------------------------ '%foldcase-string': doc('%foldcase-string', foldcase_string, "(%foldcase-string string)\n\n Same as string-foldcase but without typechecking"), @@ -13509,7 +13627,7 @@ var global_env = new Environment({ }, "(cdr pair)\n\n This function returns the cdr (all but first) of the list."), // ------------------------------------------------------------------ 'set!': doc(new Macro('set!', function (code) { - var _this27 = this; + var _this26 = this; var _ref30 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, use_dynamic = _ref30.use_dynamic, rest = _objectWithoutProperties(_ref30, _excluded4); @@ -13563,7 +13681,7 @@ var global_env = new Environment({ if (parts.length > 1) { var key = parts.pop(); var name = parts.join('.'); - var obj = _this27.get(name, { + var obj = _this26.get(name, { throwError: false }); if (obj) { @@ -13619,6 +13737,8 @@ var global_env = new Environment({ env = this.get('**interaction-environment**'); } } + var package_name = '@lips'; + var has_package = file.startsWith(package_name); // TODO: move **module-path** to internal env var PATH = '**module-path**'; var module_path = global_env.get(PATH, { @@ -13660,42 +13780,61 @@ var global_env = new Environment({ return code; }); } + function get_root_dir() { + var __dirname = global_env.get('__dirname'); + return __dirname.replace(/[^/]+$/, ''); + } if (is_node()) { return new Promise( /*#__PURE__*/function () { var _ref31 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(resolve, reject) { - var path, cmd, _args20; + var _path, _fs, root_dir, cmd, _args20; return _regeneratorRuntime.wrap(function _callee18$(_context18) { while (1) switch (_context18.prev = _context18.next) { case 0: - path = nodeRequire('path'); + _context18.prev = 0; + _context18.next = 3; + return node_ready; + case 3: + _path = nodeRequire('path'); + _fs = nodeRequire('fs'); + root_dir = get_root_dir(); + if (has_package) { + file = file.replace(package_name, root_dir); + } if (!module_path) { - _context18.next = 6; + _context18.next = 12; break; } module_path = module_path.valueOf(); - file = path.join(module_path, file); - _context18.next = 12; + if (!file.startsWith('/')) { + file = _path.join(module_path, file); + } + _context18.next = 19; break; - case 6: + case 12: + if (file.startsWith('/')) { + _context18.next = 19; + break; + } cmd = g_env.get('command-line', { throwError: false }); if (!cmd) { - _context18.next = 11; + _context18.next = 18; break; } - _context18.next = 10; + _context18.next = 17; return cmd(); - case 10: + case 17: _args20 = _context18.sent; - case 11: + case 18: if (_args20 && !is_nil(_args20)) { process.cwd(); - file = path.join(path.dirname(_args20.car.valueOf()), file); + file = _path.join(_path.dirname(_args20.car.valueOf()), file); } - case 12: - global_env.set(PATH, path.dirname(file)); - nodeRequire('fs').readFile(file, function (err, data) { + case 19: + global_env.set(PATH, _path.dirname(file)); + _fs.readFile(file, function (err, data) { if (err) { reject(err); global_env.set(PATH, module_path); @@ -13710,20 +13849,37 @@ var global_env = new Environment({ } } }); - case 14: + _context18.next = 26; + break; + case 23: + _context18.prev = 23; + _context18.t0 = _context18["catch"](0); + console.error(_context18.t0); + case 26: case "end": return _context18.stop(); } - }, _callee18); + }, _callee18, null, [[0, 23]]); })); return function (_x14, _x15) { return _ref31.apply(this, arguments); }; }()); } + if (has_package) { + var _global_env$get, _path3; + var _path2 = (_global_env$get = global_env.get('__dirname', { + throwError: false + })) !== null && _global_env$get !== void 0 ? _global_env$get : current_script; + (_path3 = _path2) !== null && _path3 !== void 0 ? _path3 : _path2 = current_script; + var _root = _path2.replace(/dist\/?[^\/]*$/, ''); + file = file.replace(package_name, _root); + } if (module_path) { module_path = module_path.valueOf(); - file = module_path + '/' + file.replace(/^\.?\/?/, ''); + if (!file.startsWith('/')) { + file = module_path + '/' + file.replace(/^\.?\/?/, ''); + } } return fetch(file).then(function (code) { global_env.set(PATH, file.replace(/\/[^/]*$/, '')); @@ -13750,7 +13906,7 @@ var global_env = new Environment({ // ------------------------------------------------------------------ 'do': doc(new Macro('do', /*#__PURE__*/function () { var _ref32 = _asyncToGenerator(function (code, _ref33) { - var _this28 = this; + var _this27 = this; var use_dynamic = _ref33.use_dynamic, error = _ref33.error; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() { @@ -13758,7 +13914,7 @@ var global_env = new Environment({ return _regeneratorRuntime.wrap(function _callee19$(_context20) { while (1) switch (_context20.prev = _context20.next) { case 0: - self = _this28; + self = _this27; dynamic_env = self; scope = self.inherit('do'); vars = code.car; @@ -14090,8 +14246,8 @@ var global_env = new Environment({ } env.set(name, parameter); } - var body = new Pair(new LSymbol('begin'), code.cdr); - return _evaluate(body, _objectSpread(_objectSpread({}, eval_args), {}, { + var expr = hygienic_begin([env, eval_args.dynamic_env], code.cdr); + return _evaluate(expr, _objectSpread(_objectSpread({}, eval_args), {}, { env: env })); }), "(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."), @@ -14195,21 +14351,14 @@ var global_env = new Environment({ }, "(parent.frame)\n\n Returns the parent environment if called from inside a function.\n If no parent frame can be found it returns nil."), // ------------------------------------------------------------------ 'eval': doc('eval', function (code, env) { - var _this29 = this; env = env || this.get('interaction-environment').call(this); - return _evaluate(code, { - env: env, - dynamic_env: env, - error: function error(e) { - var error = global_env.get('display-error'); - error.call(_this29, e.message); - if (e.code) { - var stack = e.code.map(function (line, i) { - return "[".concat(i + 1, "]: ").concat(line); - }).join('\n'); - error.call(_this29, stack); - } - } + return new Promise(function (resolve, reject) { + var result = _evaluate(code, { + env: env, + dynamic_env: env, + error: reject + }); + resolve(result); }); }, "(eval expr)\n (eval expr environment)\n\n Function that evaluates LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."), // ------------------------------------------------------------------ @@ -14287,7 +14436,7 @@ var global_env = new Environment({ } } var rest = __doc__ ? code.cdr.cdr : code.cdr; - var output = new Pair(new LSymbol('begin'), rest); + var output = hygienic_begin([env, dynamic_env], rest); var eval_args = { env: env, dynamic_env: dynamic_env, @@ -14620,7 +14769,11 @@ var global_env = new Environment({ // ----------------------------------------------------------------- function unquote_splice(pair, unquote_cnt, max_unq) { if (unquote_cnt < max_unq) { - return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), _nil); + var cdr = _nil; + if (!is_nil(pair.cdr)) { + cdr = recur(pair.cdr, unquote_cnt - 1, max_unq); + } + return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), cdr); } var lists = []; return function next(node) { @@ -14819,7 +14972,7 @@ var global_env = new Environment({ }, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."), // ------------------------------------------------------------------ append: doc('append', function append() { - var _global_env$get; + var _global_env$get2; for (var _len25 = arguments.length, items = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) { items[_key25] = arguments[_key25]; } @@ -14829,7 +14982,7 @@ var global_env = new Environment({ } return item; }); - return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items))); + return (_global_env$get2 = global_env.get('append!')).call.apply(_global_env$get2, [this].concat(_toConsumableArray(items))); }, "(append item ...)\n\n Function that creates a new list with each argument appended end-to-end.\n It will always return a new list and not modify its arguments."), // ------------------------------------------------------------------ 'append!': doc('append!', function () { @@ -15166,7 +15319,7 @@ var global_env = new Environment({ }, "(string->number number [radix])\n\n Function that parses a string into a number."), // ------------------------------------------------------------------ 'try': doc(new Macro('try', function (code, _ref41) { - var _this30 = this; + var _this28 = this; var use_dynamic = _ref41.use_dynamic; _ref41.error; return new Promise(function (resolve, reject) { @@ -15202,15 +15355,15 @@ var global_env = new Environment({ }; } var args = { - env: _this30, + env: _this28, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { if (e instanceof IgnoreException) { throw e; } if (catch_clause) { - var env = _this30.inherit('try'); + var env = _this28.inherit('try'); var name = catch_clause.cdr.car.car; if (!(name instanceof LSymbol)) { throw new Error('try: invalid syntax: catch require variable name'); @@ -15220,7 +15373,7 @@ var global_env = new Environment({ var catch_args = { env: env, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { catch_error = true; reject(e); @@ -15270,7 +15423,7 @@ var global_env = new Environment({ }, "(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."), // ------------------------------------------------------------------ 'for-each': doc('for-each', function (fn) { - var _global_env$get2; + var _global_env$get3; typecheck('for-each', fn, 'function'); for (var _len32 = arguments.length, lists = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) { lists[_key32 - 1] = arguments[_key32]; @@ -15281,14 +15434,14 @@ var global_env = new Environment({ // we need to use call(this because babel transpile this code into: // var ret = map.apply(void 0, [fn].concat(lists)); // it don't work with weakBind - var ret = (_global_env$get2 = global_env.get('map')).call.apply(_global_env$get2, [this, fn].concat(lists)); + var ret = (_global_env$get3 = global_env.get('map')).call.apply(_global_env$get3, [this, fn].concat(lists)); if (is_promise(ret)) { return ret.then(function () {}); } }, "(for-each fn . lists)\n\n Higher-order function that calls function `fn` on each\n value of the argument. If you provide more than one list\n it will take each value from each list and call `fn` function\n with that many arguments as number of list arguments."), // ------------------------------------------------------------------ map: doc('map', function map(fn) { - var _this31 = this; + var _this29 = this; for (var _len33 = arguments.length, lists = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) { lists[_key33 - 1] = arguments[_key33]; } @@ -15297,7 +15450,7 @@ var global_env = new Environment({ lists.forEach(function (arg, i) { typecheck('map', arg, ['pair', 'nil'], i + 1); // detect cycles - if (is_pair(arg) && !is_list.call(_this31, arg)) { + if (is_pair(arg) && !is_list.call(_this29, arg)) { throw new Error("map: argument ".concat(i + 1, " is not a list")); } }); @@ -15319,7 +15472,7 @@ var global_env = new Environment({ use_dynamic: use_dynamic }); return unpromise(result, function (head) { - return unpromise(map.call.apply(map, [_this31, fn].concat(_toConsumableArray(lists.map(function (l) { + return unpromise(map.call.apply(map, [_this29, fn].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))), function (rest) { return new Pair(head, rest); @@ -15343,18 +15496,6 @@ var global_env = new Environment({ } }, "(list? obj)\n\n Predicate that tests if value is a proper linked list structure.\n The car of each pair can be any value. It returns false on cyclic lists.\""), // ------------------------------------------------------------------ - some: doc('some', function some(fn, list) { - typecheck('some', fn, 'function'); - typecheck('some', list, ['pair', 'nil']); - if (is_null(list)) { - return false; - } else { - return unpromise(fn(list.car), function (value) { - return value || some(fn, list.cdr); - }); - } - }, "(some fn list)\n\n Higher-order function that calls fn on each element of the list.\n It stops and returns true when fn returns true for a value.\n If none of the values give true, some will return false.\n Analogous to Python any(map(fn, list))."), - // ------------------------------------------------------------------ fold: doc('fold', fold('fold', function (fold, fn, init) { for (var _len34 = arguments.length, lists = new Array(_len34 > 3 ? _len34 - 3 : 0), _key34 = 3; _key34 < _len34; _key34++) { lists[_key34 - 3] = arguments[_key34]; @@ -15401,7 +15542,7 @@ var global_env = new Environment({ }, "(pluck . strings)\n\n If called with a single string it will return a function that when\n called with an object will return that key from the object.\n If called with more then one string the returned function will\n create a new object by copying all properties from the given object."), // ------------------------------------------------------------------ reduce: doc('reduce', fold('reduce', function (reduce, fn, init) { - var _this32 = this; + var _this30 = this; for (var _len36 = arguments.length, lists = new Array(_len36 > 3 ? _len36 - 3 : 0), _key37 = 3; _key37 < _len36; _key37++) { lists[_key37 - 3] = arguments[_key37]; } @@ -15415,7 +15556,7 @@ var global_env = new Environment({ return unpromise(fn.apply(void 0, _toConsumableArray(lists.map(function (l) { return l.car; })).concat([init])), function (value) { - return reduce.call.apply(reduce, [_this32, fn, value].concat(_toConsumableArray(lists.map(function (l) { + return reduce.call.apply(reduce, [_this30, fn, value].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))); }); @@ -15809,8 +15950,8 @@ combinations(['d', 'a'], 2, 5).forEach(function (spec) { function reversseFind(dir, fn) { var parts = dir.split(path.sep).filter(Boolean); for (var i = parts.length; i--;) { - var _path; - var p = (_path = path).join.apply(_path, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); + var _path4; + var p = (_path4 = path).join.apply(_path4, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); if (fn(p)) { return p; } @@ -15834,7 +15975,7 @@ var noop = function noop() {}; function node_specific() { return _node_specific.apply(this, arguments); } // ------------------------------------------------------------------------- -/* c8 ignore next 11 */ +/* c8 ignore next 15 */ function _node_specific() { _node_specific = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() { var _yield$import, createRequire, moduleURL, __dirname__, __filename__; @@ -15908,16 +16049,20 @@ function _node_specific() { })); return _node_specific.apply(this, arguments); } +var node_ready; // Scheme load function need to wait for node_specific if (is_node()) { - node_specific(); -} else if (typeof window !== 'undefined' && window === root) { - global_env.set('window', window); - global_env.set('global', undefined); - global_env.set('self', window); -} else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { - global_env.set('self', self); - global_env.set('window', undefined); - global_env.set('global', undefined); + node_ready = node_specific(); +} else { + node_ready = Promise.resolve(); + if (typeof window !== 'undefined' && window === root) { + global_env.set('window', window); + global_env.set('global', undefined); + global_env.set('self', window); + } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { + global_env.set('self', self); + global_env.set('window', undefined); + global_env.set('global', undefined); + } } // ------------------------------------------------------------------------- function typeErrorMessage(fn, got, expected) { @@ -16833,6 +16978,7 @@ function bootstrap() { url = "https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version, "/").concat(std); } } + global_env.set('__dirname', url.replace(/[^/]+$/, '')); var load = global_env.get('load'); return load.call(user_env, url, global_env); } @@ -17246,17 +17392,17 @@ if (typeof window !== 'undefined') { // ------------------------------------------------------------------------- var banner = function () { // Rollup tree-shaking is removing the variable if it's normal string because - // obviously 'Mon, 27 May 2024 11:41:47 +0000' == '{{' + 'DATE}}'; can be removed + // obviously 'Fri, 08 Nov 2024 13:26:12 +0000' == '{{' + 'DATE}}'; can be removed // but disabling Tree-shaking is adding lot of not used code so we use this // hack instead - var date = LString('Mon, 27 May 2024 11:41:47 +0000').valueOf(); + var date = LString('Fri, 08 Nov 2024 13:26:12 +0000').valueOf(); var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date); var _format = function _format(x) { return x.toString().padStart(2, '0'); }; var _year = _date.getFullYear(); var _build = [_year, _format(_date.getMonth() + 1), _format(_date.getDate())].join('-'); - var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); + var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); return banner; }(); // ------------------------------------------------------------------------- @@ -17288,8 +17434,8 @@ read_only(LString, '__class__', 'string'); read_only(QuotedPromise, '__class__', 'promise'); read_only(Parameter, '__class__', 'parameter'); // ------------------------------------------------------------------------- -var version = '1.0.0-beta.19'; -var date = 'Mon, 27 May 2024 11:41:47 +0000'; +var version = 'DEV'; +var date = 'Fri, 08 Nov 2024 13:26:12 +0000'; // unwrap async generator into Promise var parse = compose(uniterate_async, _parse); diff --git a/dist/lips.esm.js b/dist/lips.esm.js index b2121145e..60aba343c 100644 --- a/dist/lips.esm.js +++ b/dist/lips.esm.js @@ -4,7 +4,7 @@ * | | \ \ | | | || . \/ __> | | * | | > \ | |_ | || _/\__ \ | | * | | / ^ \ |___||_||_| <___/ | | - * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19 + * \_\ /_/ \_\ /_/ v. DEV * * LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript * @@ -31,7 +31,7 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Mon, 27 May 2024 11:41:47 +0000 + * build: Fri, 08 Nov 2024 13:26:12 +0000 */ function _classApplyDescriptorGet(receiver, descriptor) { @@ -102,6 +102,10 @@ function _construct(t, e, r) { return r && _setPrototypeOf(p, r.prototype), p; } +function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} + function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -3499,25 +3503,23 @@ function contentLoaded(win, fn) { } } // ------------------------------------------------------------------------- -/* eslint-disable */ /* c8 ignore next 13 */ function log(x) { - if (is_debug()) { - if (is_plain_object(x)) { - console.log(map_object(x, function (value) { - return toString(value, true); - })); - } else { - var _console; - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { - return toString(item, true); - })))); - } + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (is_plain_object(x) && is_debug(args[0])) { + console.log(map_object(x, function (value) { + return toString(value, true); + })); + } else if (is_debug()) { + var _console; + (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { + return toString(item, true); + })))); } } +/* eslint-enable */ // ---------------------------------------------------------------------- /* c8 ignore next */ function is_debug() { @@ -3906,8 +3908,25 @@ function parse_string(string) { } // ---------------------------------------------------------------------- function parse_symbol(arg) { - if (arg.match(/^\|.*\|$/)) { - arg = arg.replace(/(^\|)|(\|$)/g, ''); + arg.match(/^name/); + var re = /(^|.)\|/g; + if (arg.match(re)) { + // handle escaped bar and escaped slash + arg = arg.split('|').filter(Boolean).reduce(function (acc, str) { + var result = ''; + if (str.match(/^\\+$/)) { + if (str.length > 1) { + var count = Math.floor(str.length / 2); + result = '\\'.repeat(count); + } + if (str.length % 2 !== 0) { + result += '|'; + } + } else { + result = str; + } + return acc + result; + }); var chars = { t: '\t', r: '\r', @@ -3915,8 +3934,8 @@ function parse_symbol(arg) { }; arg = arg.replace(/\\(x[^;]+);/g, function (_, chr) { return String.fromCharCode(parseInt('0' + chr, 16)); - }).replace(/\\(.)/g, function (_, chr) { - return chars[chr] || chr; + }).replace(/\\([trn])/g, function (_, chr) { + return chars[chr]; }); } return new LSymbol(arg); @@ -4217,6 +4236,18 @@ var gensym = function () { return with_props(count, Symbol("#:g".concat(count))); }; }(); +// ---------------------------------------------------------------------- +// :: helper function that make symbols in names array hygienic +// ---------------------------------------------------------------------- +function hygienic_begin(envs, expr) { + var begin = global_env.get('begin'); + var g_begin = gensym('begin'); + envs.forEach(function (env) { + env.set(g_begin, begin); + }); + return new Pair(g_begin, expr); +} + // ---------------------------------------------------------------------- // Class used to escape promises: feature #54 // ---------------------------------------------------------------------- @@ -4514,6 +4545,11 @@ var Lexer = /*#__PURE__*/function () { var found = this.next_token(); if (found) { this._token = this.__input__.substring(this._i, this._next); + if (!this.__token__) { + // handle case when accessing __token__ from the syntax extension + // (e.g. string interpolation) as the first expression in a REPL + read_only(this, '__token__', this.token(true)); + } return this.token(meta); } return eof; @@ -4762,6 +4798,7 @@ Lexer.regex_class = Symbol["for"]('regex_class'); Lexer.character = Symbol["for"]('character'); Lexer.bracket = Symbol["for"]('bracket'); Lexer.b_symbol = Symbol["for"]('b_symbol'); +Lexer.b_symbol_ex = Symbol["for"]('b_symbol_ex'); Lexer.b_comment = Symbol["for"]('b_comment'); Lexer.i_comment = Symbol["for"]('i_comment'); Lexer.l_datum = Symbol["for"]('l_datum'); @@ -4792,7 +4829,7 @@ Lexer._rules = [ // for dot comma `(a .,b) [/\./, Lexer.boundary, /,/, null, null], // block symbols -[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null]]; +[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null]]; // ---------------------------------------------------------------------- Lexer._brackets = [[/[()[\]]/, null, null, null, null]]; // ---------------------------------------------------------------------- @@ -4894,17 +4931,16 @@ var Parser = /*#__PURE__*/function () { _createClass(Parser, [{ key: "_with_syntax_scope", value: function _with_syntax_scope(fn) { - var _this5 = this; // expose parser and change stdin so parser extension can use current-input // to read data from the parser stream #150 var internal = get_internal(this.__env__); var stdin = internal.get('stdin'); - this.__env__.set('lips', _objectSpread(_objectSpread({}, lips), {}, { + global_env.set('lips', _objectSpread(_objectSpread({}, lips), {}, { __parser__: this })); internal.set('stdin', new ParserInputPort(this, this.__env__)); var cleanup = function cleanup() { - _this5.__env__.set('lips', lips); + global_env.set('lips', lips); internal.set('stdin', stdin); }; return unpromise(fn(), function (result) { @@ -5243,7 +5279,7 @@ var Parser = /*#__PURE__*/function () { key: "_resolve_object", value: function () { var _resolve_object2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(object) { - var _this6 = this; + var _this5 = this; var result; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { @@ -5253,7 +5289,7 @@ var Parser = /*#__PURE__*/function () { break; } return _context6.abrupt("return", object.map(function (item) { - return _this6._resolve_object(item); + return _this5._resolve_object(item); })); case 2: if (!is_plain_object(object)) { @@ -5262,7 +5298,7 @@ var Parser = /*#__PURE__*/function () { } result = {}; Object.keys(object).forEach(function (key) { - result[key] = _this6._resolve_object(object[key]); + result[key] = _this5._resolve_object(object[key]); }); return _context6.abrupt("return", result); case 6: @@ -5337,7 +5373,7 @@ var Parser = /*#__PURE__*/function () { key: "_read_object", value: function () { var _read_object3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { - var _this7 = this; + var _this6 = this; var token, special, builtin, expr, extension, is_symbol, was_close_paren, object, args, result, ref, ref_label; return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { @@ -5415,8 +5451,8 @@ var Parser = /*#__PURE__*/function () { } return _context8.abrupt("return", this._with_syntax_scope(function () { return call_function(extension, is_symbol ? [] : args, { - env: _this7.__env__, - dynamic_env: _this7.__env__, + env: _this6.__env__, + dynamic_env: _this6.__env__, use_dynamic: false }); })); @@ -5451,7 +5487,7 @@ var Parser = /*#__PURE__*/function () { } _context8.next = 44; return this._with_syntax_scope(function () { - return _this7.evaluate(expr); + return _this6.evaluate(expr); }); case 44: result = _context8.sent; @@ -6188,7 +6224,7 @@ function keywords_re() { return new RegExp("^(?:#:)?(?:".concat(args.join('|'), ")$")); } // line breaking rules -Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1], [[p_o, let_re, symbol, p_o, let_value, p_e], 1], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; +Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; // ---------------------------------------------------------------------- Formatter.prototype["break"] = function () { var code = this.__code__.replace(/\n[ \t]*/g, '\n ').replace(/^\s+/, ''); @@ -8153,7 +8189,7 @@ function user_repr(obj) { // if key is Object it should only work for plain_object // because otherwise it will match every object // we don't use instanceof so it don't work for subclasses - if (obj instanceof key && (key === Object && plain_object && !iterator || key !== Object)) { + if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) { fn = value; } }); @@ -8360,6 +8396,9 @@ function toString(obj, quote, skip_cycles) { if (type(obj) === 'instance') { if (is_lambda(constructor) && constructor.__name__) { name = constructor.__name__.valueOf(); + if (_typeof$1(name) === 'symbol') { + name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1'); + } } else if (!is_native_function(constructor)) { name = 'instance'; } @@ -9080,8 +9119,13 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { log(symbols); /* eslint-disable complexity */ function traverse(pattern, code) { - var pattern_names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var ellipsis = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var _state$ellipsis = state.ellipsis, + ellipsis = _state$ellipsis === void 0 ? false : _state$ellipsis, + _state$trailing = state.trailing, + trailing = _state$trailing === void 0 ? false : _state$trailing, + _state$pattern_names = state.pattern_names, + pattern_names = _state$pattern_names === void 0 ? [] : _state$pattern_names; log({ code: code, pattern: pattern @@ -9089,13 +9133,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (is_atom(pattern) && !(pattern instanceof LSymbol)) { return same_atom(pattern, code); } - if (pattern instanceof LSymbol && symbols.includes(pattern.literal())) { - // TODO: literal() may be SLOW - if (!LSymbol.is(code, pattern)) { - return false; + if (pattern instanceof LSymbol) { + var literal = pattern.literal(); // TODO: literal() may be SLOW + if (symbols.includes(literal)) { + if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) { + return false; + } + var ref = expansion.ref(literal); + return !ref || ref === define || ref === global_env; } - var ref = expansion.ref(pattern); - return !ref || ref === define || ref === global_env; } if (Array.isArray(pattern) && Array.isArray(code)) { log('<<< a 1'); @@ -9121,25 +9167,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } else if (Array.isArray(pattern[0])) { log('<<< a 3'); var _names = _toConsumableArray(pattern_names); + var new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: _names, + ellipsis: true + }); if (!code.every(function (node) { - return traverse(pattern[0], node, _names, true); + return traverse(pattern[0], node, new_state); })) { return false; } } if (pattern.length > 2) { var pat = pattern.slice(2); - return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis); + return traverse(pat, code.slice(-pat.length), state); } return true; } - var first = traverse(pattern[0], code[0], pattern_names, ellipsis); + var first = traverse(pattern[0], code[0], state); log({ first: first, pattern: pattern[0], code: code[0] }); - var rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis); + var rest = traverse(pattern.slice(1), code.slice(1), state); log({ first: first, rest: rest @@ -9163,23 +9213,30 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } } if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) { + log('>> 1 (a)'); // pattern (... ???) - SRFI-46 if (!is_nil(pattern.cdr.cdr)) { if (is_pair(pattern.cdr.cdr)) { + log('>> 1 (b)'); // if we have (x ... a b) we need to remove two from the end var list_len = pattern.cdr.cdr.length(); + var improper_list = !is_nil(pattern.last_pair().cdr); if (!is_pair(code)) { return false; } var code_len = code.length(); var list = code; - while (code_len - 1 > list_len) { + var _trailing = improper_list ? 1 : 1; + while (code_len - _trailing > list_len) { list = list.cdr; code_len--; } var _rest5 = list.cdr; list.cdr = _nil; - if (!traverse(pattern.cdr.cdr, _rest5, pattern_names, ellipsis)) { + var new_sate = _objectSpread(_objectSpread({}, state), {}, { + trailing: improper_list + }); + if (!traverse(pattern.cdr.cdr, _rest5, new_sate)) { return false; } } @@ -9189,7 +9246,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (bindings['...'].symbols[_name3] && !pattern_names.includes(_name3) && !ellipsis) { throw new Error('syntax: named ellipsis can only appear onces'); } - log('>> 1'); + log('>> 1 (next)'); if (is_nil(code)) { log('>> 2'); if (ellipsis) { @@ -9220,6 +9277,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } else { log('>> 6'); if (is_pair(code)) { + log('>> 7 ' + ellipsis); // cons (a . b) => (var ... . x) if (!is_pair(code.cdr) && !is_nil(code.cdr)) { log('>> 7 (b)'); @@ -9227,28 +9285,34 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { return false; } else if (!bindings['...'].symbols[_name3]) { bindings['...'].symbols[_name3] = new Pair(code.car, _nil); - return traverse(pattern.cdr.cdr, code.cdr); + return traverse(pattern.cdr.cdr, code.cdr, state); } } // code as improper list var last_pair = code.last_pair(); + log({ + last_pair: last_pair + }); if (!is_nil(last_pair.cdr)) { + log('>> 7 (c)'); if (is_nil(pattern.cdr.cdr)) { // case (a ...) for (a b . x) return false; } else { + log('>> 7 (d)'); // case (a ... . b) for (a b . x) var copy = code.clone(); copy.last_pair().cdr = _nil; bindings['...'].symbols[_name3] = copy; - return traverse(pattern.cdr.cdr, last_pair.cdr); + return traverse(pattern.cdr.cdr, last_pair.cdr, state); } } - log('>> 7 ' + ellipsis); pattern_names.push(_name3); if (!bindings['...'].symbols[_name3]) { + log('>> 7 (e)'); bindings['...'].symbols[_name3] = new Pair(code, _nil); } else { + log('>> 7 (f)'); var _node2 = bindings['...'].symbols[_name3]; bindings['...'].symbols[_name3] = _node2.append(new Pair(code, _nil)); } @@ -9259,7 +9323,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { // empty ellipsis with rest (a b ... . d) #290 log('>> 8'); bindings['...'].symbols[_name3] = null; - return traverse(pattern.cdr.cdr, code); + return traverse(pattern.cdr.cdr, code, state); } else { log('>> 9'); return false; @@ -9276,8 +9340,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { } log('>> 11'); var _node3 = code; + var _new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node3)) { - if (!traverse(pattern.car, _node3.car, names, true)) { + if (!traverse(pattern.car, _node3.car, _new_state)) { return false; } _node3 = _node3.cdr; @@ -9287,8 +9355,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { if (Array.isArray(pattern.car)) { var names = _toConsumableArray(pattern_names); var _node4 = code; + var _new_state2 = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node4)) { - if (!traverse(pattern.car, _node4.car, names, true)) { + if (!traverse(pattern.car, _node4.car, _new_state2)) { return false; } _node4 = _node4.cdr; @@ -9323,15 +9395,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { code: code, pattern: pattern }); + var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol; + if (trailing && rest_pattern) { + log('>> 13 (a)'); + // handle (x ... y . z) + if (!is_nil(code.cdr)) { + return false; + } + var _car = pattern.car.valueOf(); + var _cdr = pattern.cdr.valueOf(); + bindings.symbols[_car] = code.car; + bindings.symbols[_cdr] = _nil; + return true; + //return is_pair(code.cdr) && code.cdr.length() > 1; + } if (is_nil(code.cdr)) { + log('>> 13 (b)'); // 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) { // fix for SRFI-26 in recursive call of (b) ==> (<> . x) // where <> is symbol - if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) { + if (!traverse(pattern.car, code.car, state)) { return false; } log('>> 14'); @@ -9351,7 +9437,10 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { code: code }); // case (x y) ===> (var0 var1 ... warn) where var1 match nil - if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) { + // trailing: true start processing of (var ... x . y) + if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, state) && traverse(pattern.cdr.cdr.cdr, code.cdr, _objectSpread(_objectSpread({}, state), {}, { + trailing: true + }))) { var _name6 = pattern.cdr.car.__name__; log({ pattern: pattern, @@ -9369,15 +9458,14 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) { pattern: pattern, code: code }); - var car = traverse(pattern.car, code.car, pattern_names, ellipsis); - log({ - car: car, - pattern: pattern.car, - code: code.car - }); - var cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis); + var car = traverse(pattern.car, code.car, state); + var cdr = traverse(pattern.cdr, code.cdr, state); log({ + $car_code: code.car, + $car_pattern: pattern.car, car: car, + $cdr_code: code.cdr, + $cdr_pattern: pattern.cdr, cdr: cdr }); if (car && cdr) { @@ -9570,46 +9658,47 @@ function transform_syntax() { var item = bindings[_name7]; if (item === null) { return; - } else if (item) { + } else if (_name7 in bindings) { log({ name: _name7, binding: bindings[_name7] }); if (is_pair(item)) { log('[t 2 Pair ' + nested); - var _car = item.car, - _cdr = item.cdr; + var _car2 = item.car, + _cdr2 = item.cdr; var _rest_expr = is_array ? expr.slice(2) : expr.cdr.cdr; if (nested) { - if (!is_nil(_cdr)) { + if (!is_nil(_cdr2)) { log('|| next 1'); - next(_name7, _cdr); + next(_name7, _cdr2); } if (is_array && _rest_expr.length || !is_nil(_rest_expr) && !is_array) { var _rest7 = transform_ellipsis_expr(_rest_expr, bindings, state, next); if (is_array) { - return _car.concat(_rest7); - } else if (is_pair(_car)) { - return _car.append(_rest7); + return _car2.concat(_rest7); + } else if (is_pair(_car2)) { + return _car2.append(_rest7); } else { log('UNKNOWN'); } } - return _car; - } else if (is_pair(_car)) { - if (!is_nil(_car.cdr)) { + return _car2; + } else if (is_pair(_car2)) { + if (!is_nil(_car2.cdr)) { log('|| next 2'); - next(_name7, new Pair(_car.cdr, _cdr)); + next(_name7, new Pair(_car2.cdr, _cdr2)); } - return _car.car; - } else if (is_nil(_cdr)) { - return _car; + // wrap with Value to handle undefined + return new Value(_car2.car); + } else if (is_nil(_cdr2)) { + return _car2; } else { var last_pair = expr.last_pair(); if (last_pair.cdr instanceof LSymbol) { log('|| next 3'); next(_name7, item.last_pair()); - return _car; + return _car2; } } } else if (item instanceof Array) { @@ -9672,6 +9761,7 @@ function transform_syntax() { return expr; } if (is_pair(expr) || is_array) { + log('>> 0'); var first = is_array ? expr[0] : expr.car; var second, rest_second; if (is_array) { @@ -9756,6 +9846,9 @@ function transform_syntax() { // undefined can be null caused by null binding // on empty ellipsis if (car !== undefined) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } if (is_spread) { if (is_array) { if (Array.isArray(car)) { @@ -9812,6 +9905,9 @@ function transform_syntax() { nested: true }); if (car) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } return new Pair(car, _nil); } return _nil; @@ -9850,6 +9946,9 @@ function transform_syntax() { value: value }); if (typeof value !== 'undefined') { + if (value instanceof Value) { + value = value.valueOf(); + } if (is_array) { _result3.push(value); } else { @@ -9890,6 +9989,9 @@ function transform_syntax() { } } log('<<<< 2'); + log({ + result: _result3 + }); return _result3; } } @@ -10023,8 +10125,12 @@ function is_undef(value) { return typeof value === 'undefined'; } // ------------------------------------------------------------------------- +function get_proto(obj) { + return Object.getPrototypeOf(obj); +} +// ------------------------------------------------------------------------- function is_iterator(obj, symbol) { - if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) { + if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) { return is_function(obj[symbol]); } } @@ -10319,8 +10425,7 @@ function let_macro(symbol) { return pair.cdr.car; }); } - var args_name = gensym('args'); - return Pair.fromArray([LSymbol('let'), [[args_name, Pair(LSymbol('list'), args)]], [LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], [LSymbol('apply'), code.car, args_name]]]); + return new Pair(Pair.fromArray([LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], code.car]), args); } else if (macro_expand) { // Macro.defmacro are special macros that should return lips code // here we use evaluate, so we need to check special flag set by @@ -10338,7 +10443,7 @@ function let_macro(symbol) { } var i = 0; function exec() { - var output = new Pair(new LSymbol('begin'), code.cdr); + var output = hygienic_begin([env], code.cdr); return _evaluate(output, { env: env, dynamic_env: env, @@ -10458,7 +10563,7 @@ function guard_math_call(fn) { } // ---------------------------------------------------------------------- function pipe() { - var _this8 = this; + var _this7 = this; for (var _len8 = arguments.length, fns = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { fns[_key8] = arguments[_key8]; } @@ -10470,7 +10575,7 @@ function pipe() { args[_key9] = arguments[_key9]; } return fns.reduce(function (args, f) { - return [f.apply(_this8, args)]; + return [f.apply(_this7, args)]; }, args)[0]; }; } @@ -10535,7 +10640,7 @@ function curry(fn) { typecheck('curry', fn, 'function'); var len = fn.length; return function () { - var _this9 = this; + var _this8 = this; var args = init_args.slice(); // HACK: we use IIFE here to get rid of the name of the function. // The JavaScript is smart and add name property to a function @@ -10548,7 +10653,7 @@ function curry(fn) { } args = args.concat(more_args); if (args.length >= len) { - return fn.apply(_this9, args); + return fn.apply(_this8, args); } else { return curried; } @@ -11611,9 +11716,9 @@ LComplex.prototype.mul = function (n) { }; // ------------------------------------------------------------------------- LComplex.prototype.complex_op = function (name, n, fn) { - var _this10 = this; + var _this9 = this; var calc = function calc(re, im) { - var result = fn(_this10.__re__, re, _this10.__im__, im); + var result = fn(_this9.__re__, re, _this9.__im__, im); if ('im' in result && 're' in result) { if (result.im.cmp(0) === 0) { return result.re; @@ -12209,7 +12314,7 @@ LComplex.i = LComplex({ // :: Port abstraction - read should be a function that return next line // ------------------------------------------------------------------------- function InputPort(read) { - var _this11 = this; + var _this10 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputPort) || typeof this === 'undefined') { return new InputPort(read); @@ -12233,12 +12338,12 @@ function InputPort(read) { return _regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) switch (_context14.prev = _context14.next) { case 0: - if (_this11.char_ready()) { + if (_this10.char_ready()) { _context14.next = 6; break; } _context14.next = 3; - return _this11._read(); + return _this10._read(); case 3: line = _context14.sent; parser = new Parser({ @@ -12246,7 +12351,7 @@ function InputPort(read) { }); parser.parse(line); case 6: - return _context14.abrupt("return", _this11.__parser__); + return _context14.abrupt("return", _this10.__parser__); case 7: case "end": return _context14.stop(); @@ -12309,13 +12414,13 @@ InputPort.prototype.is_open = function () { return this._with_parser !== null; }; InputPort.prototype.close = function () { - var _this12 = this; + var _this11 = this; this.__parser__ = null; // make content garbage collected, we assign null, // because the value is in prototype this._with_parser = null; ['read', 'close', 'read_char', 'peek-char', 'read_line'].forEach(function (name) { - _this12[name] = function () { + _this11[name] = function () { throw new Error('input-port: port is closed'); }; }); @@ -12361,20 +12466,20 @@ OutputPort.prototype.toString = function () { var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { _inherits(BufferedOutputPort, _OutputPort); function BufferedOutputPort(fn) { - var _this13; + var _this12; _classCallCheck(this, BufferedOutputPort); - _this13 = _callSuper(this, BufferedOutputPort, [function () { - var _this14; - return (_this14 = _this13)._write.apply(_this14, arguments); + _this12 = _callSuper(this, BufferedOutputPort, [function () { + var _this13; + return (_this13 = _this12)._write.apply(_this13, arguments); }]); typecheck('BufferedOutputPort', fn, 'function'); - read_only(_assertThisInitialized(_this13), '_fn', fn, { + read_only(_assertThisInitialized(_this12), '_fn', fn, { hidden: true }); - read_only(_assertThisInitialized(_this13), '_buffer', [], { + read_only(_assertThisInitialized(_this12), '_buffer', [], { hidden: true }); - return _this13; + return _this12; } _createClass(BufferedOutputPort, [{ key: "flush", @@ -12387,13 +12492,13 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { }, { key: "_write", value: function _write() { - var _this15 = this; + var _this14 = this; for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) { args[_key18] = arguments[_key18]; } if (args.length) { args.forEach(function (arg) { - _this15._buffer.push(arg); + _this14._buffer.push(arg); }); var last_value = this._buffer[this._buffer.length - 1]; if (last_value.match(/\n$/)) { @@ -12406,7 +12511,7 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { return BufferedOutputPort; }(OutputPort); // ------------------------------------------------------------------------- function OutputStringPort(toString) { - var _this16 = this; + var _this15 = this; if (typeof this !== 'undefined' && !(this instanceof OutputStringPort) || typeof this === 'undefined') { return new OutputStringPort(toString); } @@ -12419,7 +12524,7 @@ function OutputStringPort(toString) { } else { x = x.valueOf(); } - _this16.__buffer__.push(x); + _this15.__buffer__.push(x); }; } OutputStringPort.prototype = Object.create(OutputPort.prototype); @@ -12434,7 +12539,7 @@ OutputStringPort.prototype.valueOf = function () { }; // ------------------------------------------------------------------------- function OutputFilePort(filename, fd) { - var _this17 = this; + var _this16 = this; if (typeof this !== 'undefined' && !(this instanceof OutputFilePort) || typeof this === 'undefined') { return new OutputFilePort(filename, fd); } @@ -12450,7 +12555,7 @@ function OutputFilePort(filename, fd) { } else { x = x.valueOf(); } - _this17.fs().write(_this17._fd, x, function (err) { + _this16.fs().write(_this16._fd, x, function (err) { if (err) { throw err; } @@ -12469,16 +12574,16 @@ OutputFilePort.prototype.internal = function (name) { return user_env.get('**internal-env**').get(name); }; OutputFilePort.prototype.close = function () { - var _this18 = this; + var _this17 = this; return new Promise(function (resolve, reject) { - _this18.fs().close(_this18._fd, function (err) { + _this17.fs().close(_this17._fd, function (err) { if (err) { reject(err); } else { - read_only(_this18, '_fd', null, { + read_only(_this17, '_fd', null, { hidden: true }); - OutputPort.prototype.close.call(_this18); + OutputPort.prototype.close.call(_this17); resolve(); } }); @@ -12489,7 +12594,7 @@ OutputFilePort.prototype.toString = function () { }; // ------------------------------------------------------------------------- function InputStringPort(string) { - var _this19 = this; + var _this18 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputStringPort) || typeof this === 'undefined') { return new InputStringPort(string); @@ -12497,13 +12602,13 @@ function InputStringPort(string) { typecheck('InputStringPort', string, 'string'); string = string.valueOf(); this._with_parser = this._with_init_parser.bind(this, function () { - if (!_this19.__parser__) { - _this19.__parser__ = new Parser({ + if (!_this18.__parser__) { + _this18.__parser__ = new Parser({ env: env }); - _this19.__parser__.parse(string); + _this18.__parser__.parse(string); } - return _this19.__parser__; + return _this18.__parser__; }); read_only(this, '__type__', text_port); this._make_defaults(); @@ -12570,13 +12675,13 @@ InputByteVectorPort.prototype.toString = function () { return "#"; }; InputByteVectorPort.prototype.close = function () { - var _this20 = this; + var _this19 = this; read_only(this, '__vector__', _nil); var err = function err() { throw new Error('Input-binary-port: port is closed'); }; ['read_u8', 'close', 'peek_u8', 'read_u8_vector'].forEach(function (name) { - _this20[name] = err; + _this19[name] = err; }); this.u8_ready = this.char_ready = function () { return false; @@ -12694,7 +12799,7 @@ InputBinaryFilePort.prototype.toString = function () { }; // ------------------------------------------------------------------------- function OutputBinaryFilePort(filename, fd) { - var _this21 = this; + var _this20 = this; if (typeof this !== 'undefined' && !(this instanceof OutputBinaryFilePort) || typeof this === 'undefined') { return new OutputBinaryFilePort(filename, fd); } @@ -12709,7 +12814,7 @@ function OutputBinaryFilePort(filename, fd) { typecheck('write', x, ['number', 'uint8array']); var buffer; if (!fs) { - fs = _this21.internal('fs'); + fs = _this20.internal('fs'); } if (LNumber.isNumber(x)) { buffer = new Uint8Array([x.valueOf()]); @@ -12717,7 +12822,7 @@ function OutputBinaryFilePort(filename, fd) { buffer = new Uint8Array(Array.from(x)); } return new Promise(function (resolve, reject) { - fs.write(_this21._fd, buffer, function (err) { + fs.write(_this20._fd, buffer, function (err) { if (err) { reject(err); } else { @@ -12749,7 +12854,7 @@ EOF.prototype.toString = function () { // Simpler way to create interpreter with interaction-environment // ------------------------------------------------------------------------- function Interpreter(name) { - var _this22 = this; + var _this21 = this; var _ref27 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, stderr = _ref27.stderr, stdin = _ref27.stdin, @@ -12773,7 +12878,7 @@ function Interpreter(name) { env: this.__env__ }); this.__env__.set('parent.frame', doc('parent.frame', function () { - return _this22.__env__; + return _this21.__env__; }, global_env.__env__['parent.frame'].__doc__)); var defaults_name = '**interaction-environment-defaults**'; this.set(defaults_name, get_props(obj).concat(defaults_name)); @@ -12793,7 +12898,7 @@ function Interpreter(name) { // ------------------------------------------------------------------------- Interpreter.prototype.exec = /*#__PURE__*/function () { var _ref28 = _asyncToGenerator(function (arg) { - var _this23 = this; + var _this22 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() { var _options$use_dynamic, use_dynamic, dynamic_env, env; @@ -12806,12 +12911,12 @@ Interpreter.prototype.exec = /*#__PURE__*/function () { // simple solution to overwrite this variable in each interpreter // before evaluation of user code if (!env) { - env = _this23.__env__; + env = _this22.__env__; } if (!dynamic_env) { dynamic_env = env; } - global_env.set('**interaction-environment**', _this23.__env__); + global_env.set('**interaction-environment**', _this22.__env__); if (!Array.isArray(arg)) { _context16.next = 10; break; @@ -12822,8 +12927,8 @@ Interpreter.prototype.exec = /*#__PURE__*/function () { use_dynamic: use_dynamic })); case 10: - _this23.__parser__.parse(arg); - return _context16.abrupt("return", exec(_this23.__parser__, { + _this22.__parser__.parse(arg); + return _context16.abrupt("return", exec(_this22.__parser__, { env: env, dynamic_env: dynamic_env, use_dynamic: use_dynamic @@ -12999,12 +13104,12 @@ Environment.prototype.toString = function () { }; // ------------------------------------------------------------------------- Environment.prototype.clone = function () { - var _this24 = this; + var _this23 = this; // duplicate refs var env = {}; // TODO: duplicated Symbols Object.keys(this.__env__).forEach(function (key) { - env[key] = _this24.__env__[key]; + env[key] = _this23.__env__[key]; }); return new Environment(env, this.__parent__, this.__name__); }; @@ -13138,14 +13243,14 @@ Environment.prototype.set = function (name, value) { // For internal use only // ------------------------------------------------------------------------- Environment.prototype.constant = function (name, value) { - var _this25 = this; + var _this24 = this; if (this.__env__.hasOwnProperty(name)) { throw new Error("Environment::constant: ".concat(name, " already exists")); } if (arguments.length === 1 && is_plain_object(arguments[0])) { var obj = arguments[0]; Object.keys(obj).forEach(function (key) { - _this25.constant(name, obj[key]); + _this24.constant(name, obj[key]); }); } else { Object.defineProperty(this.__env__, name, { @@ -13321,14 +13426,14 @@ var global_env = new Environment({ // ------------------------------------------------------------------ read: doc('read', /*#__PURE__*/function () { var _read2 = _asyncToGenerator(function () { - var _this26 = this; + var _this25 = this; var arg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() { var env, port; return _regeneratorRuntime.wrap(function _callee17$(_context17) { while (1) switch (_context17.prev = _context17.next) { case 0: - env = _this26.env; + env = _this25.env; if (arg === null) { port = internal(env, 'stdin'); } else { @@ -13416,6 +13521,19 @@ var global_env = new Environment({ return str; }, "(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."), // ------------------------------------------------------------------ + newline: doc('newline', function newline() { + var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var display = global_env.get('display'); + var use_dynamic = this.use_dynamic; + var env = global_env; + var dynamic_env = global_env; + call_function(display, ['\n', port], { + env: env, + dynamic_env: dynamic_env, + use_dynamic: use_dynamic + }); + }, "(newline [port])\n\n Write newline character to standard output or given port"), + // ------------------------------------------------------------------ display: doc('display', function display(arg) { var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (port === null) { @@ -13438,7 +13556,7 @@ var global_env = new Environment({ } var value = args.map(repr).join(' '); port.write.call(global_env, value); - global_env.get('newline')(port); + global_env.get('newline').call(this, port); }, "(display-error . args)\n\n Display an error message on stderr."), // ------------------------------------------------------------------ '%foldcase-string': doc('%foldcase-string', foldcase_string, "(%foldcase-string string)\n\n Same as string-foldcase but without typechecking"), @@ -13506,7 +13624,7 @@ var global_env = new Environment({ }, "(cdr pair)\n\n This function returns the cdr (all but first) of the list."), // ------------------------------------------------------------------ 'set!': doc(new Macro('set!', function (code) { - var _this27 = this; + var _this26 = this; var _ref30 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, use_dynamic = _ref30.use_dynamic, rest = _objectWithoutProperties(_ref30, _excluded4); @@ -13560,7 +13678,7 @@ var global_env = new Environment({ if (parts.length > 1) { var key = parts.pop(); var name = parts.join('.'); - var obj = _this27.get(name, { + var obj = _this26.get(name, { throwError: false }); if (obj) { @@ -13616,6 +13734,8 @@ var global_env = new Environment({ env = this.get('**interaction-environment**'); } } + var package_name = '@lips'; + var has_package = file.startsWith(package_name); // TODO: move **module-path** to internal env var PATH = '**module-path**'; var module_path = global_env.get(PATH, { @@ -13657,42 +13777,61 @@ var global_env = new Environment({ return code; }); } + function get_root_dir() { + var __dirname = global_env.get('__dirname'); + return __dirname.replace(/[^/]+$/, ''); + } if (is_node()) { return new Promise( /*#__PURE__*/function () { var _ref31 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(resolve, reject) { - var path, cmd, _args20; + var _path, _fs, root_dir, cmd, _args20; return _regeneratorRuntime.wrap(function _callee18$(_context18) { while (1) switch (_context18.prev = _context18.next) { case 0: - path = nodeRequire('path'); + _context18.prev = 0; + _context18.next = 3; + return node_ready; + case 3: + _path = nodeRequire('path'); + _fs = nodeRequire('fs'); + root_dir = get_root_dir(); + if (has_package) { + file = file.replace(package_name, root_dir); + } if (!module_path) { - _context18.next = 6; + _context18.next = 12; break; } module_path = module_path.valueOf(); - file = path.join(module_path, file); - _context18.next = 12; + if (!file.startsWith('/')) { + file = _path.join(module_path, file); + } + _context18.next = 19; break; - case 6: + case 12: + if (file.startsWith('/')) { + _context18.next = 19; + break; + } cmd = g_env.get('command-line', { throwError: false }); if (!cmd) { - _context18.next = 11; + _context18.next = 18; break; } - _context18.next = 10; + _context18.next = 17; return cmd(); - case 10: + case 17: _args20 = _context18.sent; - case 11: + case 18: if (_args20 && !is_nil(_args20)) { process.cwd(); - file = path.join(path.dirname(_args20.car.valueOf()), file); + file = _path.join(_path.dirname(_args20.car.valueOf()), file); } - case 12: - global_env.set(PATH, path.dirname(file)); - nodeRequire('fs').readFile(file, function (err, data) { + case 19: + global_env.set(PATH, _path.dirname(file)); + _fs.readFile(file, function (err, data) { if (err) { reject(err); global_env.set(PATH, module_path); @@ -13707,20 +13846,37 @@ var global_env = new Environment({ } } }); - case 14: + _context18.next = 26; + break; + case 23: + _context18.prev = 23; + _context18.t0 = _context18["catch"](0); + console.error(_context18.t0); + case 26: case "end": return _context18.stop(); } - }, _callee18); + }, _callee18, null, [[0, 23]]); })); return function (_x14, _x15) { return _ref31.apply(this, arguments); }; }()); } + if (has_package) { + var _global_env$get, _path3; + var _path2 = (_global_env$get = global_env.get('__dirname', { + throwError: false + })) !== null && _global_env$get !== void 0 ? _global_env$get : current_script; + (_path3 = _path2) !== null && _path3 !== void 0 ? _path3 : _path2 = current_script; + var _root = _path2.replace(/dist\/?[^\/]*$/, ''); + file = file.replace(package_name, _root); + } if (module_path) { module_path = module_path.valueOf(); - file = module_path + '/' + file.replace(/^\.?\/?/, ''); + if (!file.startsWith('/')) { + file = module_path + '/' + file.replace(/^\.?\/?/, ''); + } } return fetch(file).then(function (code) { global_env.set(PATH, file.replace(/\/[^/]*$/, '')); @@ -13747,7 +13903,7 @@ var global_env = new Environment({ // ------------------------------------------------------------------ 'do': doc(new Macro('do', /*#__PURE__*/function () { var _ref32 = _asyncToGenerator(function (code, _ref33) { - var _this28 = this; + var _this27 = this; var use_dynamic = _ref33.use_dynamic, error = _ref33.error; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() { @@ -13755,7 +13911,7 @@ var global_env = new Environment({ return _regeneratorRuntime.wrap(function _callee19$(_context20) { while (1) switch (_context20.prev = _context20.next) { case 0: - self = _this28; + self = _this27; dynamic_env = self; scope = self.inherit('do'); vars = code.car; @@ -14087,8 +14243,8 @@ var global_env = new Environment({ } env.set(name, parameter); } - var body = new Pair(new LSymbol('begin'), code.cdr); - return _evaluate(body, _objectSpread(_objectSpread({}, eval_args), {}, { + var expr = hygienic_begin([env, eval_args.dynamic_env], code.cdr); + return _evaluate(expr, _objectSpread(_objectSpread({}, eval_args), {}, { env: env })); }), "(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."), @@ -14192,21 +14348,14 @@ var global_env = new Environment({ }, "(parent.frame)\n\n Returns the parent environment if called from inside a function.\n If no parent frame can be found it returns nil."), // ------------------------------------------------------------------ 'eval': doc('eval', function (code, env) { - var _this29 = this; env = env || this.get('interaction-environment').call(this); - return _evaluate(code, { - env: env, - dynamic_env: env, - error: function error(e) { - var error = global_env.get('display-error'); - error.call(_this29, e.message); - if (e.code) { - var stack = e.code.map(function (line, i) { - return "[".concat(i + 1, "]: ").concat(line); - }).join('\n'); - error.call(_this29, stack); - } - } + return new Promise(function (resolve, reject) { + var result = _evaluate(code, { + env: env, + dynamic_env: env, + error: reject + }); + resolve(result); }); }, "(eval expr)\n (eval expr environment)\n\n Function that evaluates LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."), // ------------------------------------------------------------------ @@ -14284,7 +14433,7 @@ var global_env = new Environment({ } } var rest = __doc__ ? code.cdr.cdr : code.cdr; - var output = new Pair(new LSymbol('begin'), rest); + var output = hygienic_begin([env, dynamic_env], rest); var eval_args = { env: env, dynamic_env: dynamic_env, @@ -14617,7 +14766,11 @@ var global_env = new Environment({ // ----------------------------------------------------------------- function unquote_splice(pair, unquote_cnt, max_unq) { if (unquote_cnt < max_unq) { - return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), _nil); + var cdr = _nil; + if (!is_nil(pair.cdr)) { + cdr = recur(pair.cdr, unquote_cnt - 1, max_unq); + } + return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), cdr); } var lists = []; return function next(node) { @@ -14816,7 +14969,7 @@ var global_env = new Environment({ }, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."), // ------------------------------------------------------------------ append: doc('append', function append() { - var _global_env$get; + var _global_env$get2; for (var _len25 = arguments.length, items = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) { items[_key25] = arguments[_key25]; } @@ -14826,7 +14979,7 @@ var global_env = new Environment({ } return item; }); - return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items))); + return (_global_env$get2 = global_env.get('append!')).call.apply(_global_env$get2, [this].concat(_toConsumableArray(items))); }, "(append item ...)\n\n Function that creates a new list with each argument appended end-to-end.\n It will always return a new list and not modify its arguments."), // ------------------------------------------------------------------ 'append!': doc('append!', function () { @@ -15163,7 +15316,7 @@ var global_env = new Environment({ }, "(string->number number [radix])\n\n Function that parses a string into a number."), // ------------------------------------------------------------------ 'try': doc(new Macro('try', function (code, _ref41) { - var _this30 = this; + var _this28 = this; var use_dynamic = _ref41.use_dynamic; _ref41.error; return new Promise(function (resolve, reject) { @@ -15199,15 +15352,15 @@ var global_env = new Environment({ }; } var args = { - env: _this30, + env: _this28, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { if (e instanceof IgnoreException) { throw e; } if (catch_clause) { - var env = _this30.inherit('try'); + var env = _this28.inherit('try'); var name = catch_clause.cdr.car.car; if (!(name instanceof LSymbol)) { throw new Error('try: invalid syntax: catch require variable name'); @@ -15217,7 +15370,7 @@ var global_env = new Environment({ var catch_args = { env: env, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { catch_error = true; reject(e); @@ -15267,7 +15420,7 @@ var global_env = new Environment({ }, "(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."), // ------------------------------------------------------------------ 'for-each': doc('for-each', function (fn) { - var _global_env$get2; + var _global_env$get3; typecheck('for-each', fn, 'function'); for (var _len32 = arguments.length, lists = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) { lists[_key32 - 1] = arguments[_key32]; @@ -15278,14 +15431,14 @@ var global_env = new Environment({ // we need to use call(this because babel transpile this code into: // var ret = map.apply(void 0, [fn].concat(lists)); // it don't work with weakBind - var ret = (_global_env$get2 = global_env.get('map')).call.apply(_global_env$get2, [this, fn].concat(lists)); + var ret = (_global_env$get3 = global_env.get('map')).call.apply(_global_env$get3, [this, fn].concat(lists)); if (is_promise(ret)) { return ret.then(function () {}); } }, "(for-each fn . lists)\n\n Higher-order function that calls function `fn` on each\n value of the argument. If you provide more than one list\n it will take each value from each list and call `fn` function\n with that many arguments as number of list arguments."), // ------------------------------------------------------------------ map: doc('map', function map(fn) { - var _this31 = this; + var _this29 = this; for (var _len33 = arguments.length, lists = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) { lists[_key33 - 1] = arguments[_key33]; } @@ -15294,7 +15447,7 @@ var global_env = new Environment({ lists.forEach(function (arg, i) { typecheck('map', arg, ['pair', 'nil'], i + 1); // detect cycles - if (is_pair(arg) && !is_list.call(_this31, arg)) { + if (is_pair(arg) && !is_list.call(_this29, arg)) { throw new Error("map: argument ".concat(i + 1, " is not a list")); } }); @@ -15316,7 +15469,7 @@ var global_env = new Environment({ use_dynamic: use_dynamic }); return unpromise(result, function (head) { - return unpromise(map.call.apply(map, [_this31, fn].concat(_toConsumableArray(lists.map(function (l) { + return unpromise(map.call.apply(map, [_this29, fn].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))), function (rest) { return new Pair(head, rest); @@ -15340,18 +15493,6 @@ var global_env = new Environment({ } }, "(list? obj)\n\n Predicate that tests if value is a proper linked list structure.\n The car of each pair can be any value. It returns false on cyclic lists.\""), // ------------------------------------------------------------------ - some: doc('some', function some(fn, list) { - typecheck('some', fn, 'function'); - typecheck('some', list, ['pair', 'nil']); - if (is_null(list)) { - return false; - } else { - return unpromise(fn(list.car), function (value) { - return value || some(fn, list.cdr); - }); - } - }, "(some fn list)\n\n Higher-order function that calls fn on each element of the list.\n It stops and returns true when fn returns true for a value.\n If none of the values give true, some will return false.\n Analogous to Python any(map(fn, list))."), - // ------------------------------------------------------------------ fold: doc('fold', fold('fold', function (fold, fn, init) { for (var _len34 = arguments.length, lists = new Array(_len34 > 3 ? _len34 - 3 : 0), _key34 = 3; _key34 < _len34; _key34++) { lists[_key34 - 3] = arguments[_key34]; @@ -15398,7 +15539,7 @@ var global_env = new Environment({ }, "(pluck . strings)\n\n If called with a single string it will return a function that when\n called with an object will return that key from the object.\n If called with more then one string the returned function will\n create a new object by copying all properties from the given object."), // ------------------------------------------------------------------ reduce: doc('reduce', fold('reduce', function (reduce, fn, init) { - var _this32 = this; + var _this30 = this; for (var _len36 = arguments.length, lists = new Array(_len36 > 3 ? _len36 - 3 : 0), _key37 = 3; _key37 < _len36; _key37++) { lists[_key37 - 3] = arguments[_key37]; } @@ -15412,7 +15553,7 @@ var global_env = new Environment({ return unpromise(fn.apply(void 0, _toConsumableArray(lists.map(function (l) { return l.car; })).concat([init])), function (value) { - return reduce.call.apply(reduce, [_this32, fn, value].concat(_toConsumableArray(lists.map(function (l) { + return reduce.call.apply(reduce, [_this30, fn, value].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))); }); @@ -15806,8 +15947,8 @@ combinations(['d', 'a'], 2, 5).forEach(function (spec) { function reversseFind(dir, fn) { var parts = dir.split(path.sep).filter(Boolean); for (var i = parts.length; i--;) { - var _path; - var p = (_path = path).join.apply(_path, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); + var _path4; + var p = (_path4 = path).join.apply(_path4, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); if (fn(p)) { return p; } @@ -15831,7 +15972,7 @@ var noop = function noop() {}; function node_specific() { return _node_specific.apply(this, arguments); } // ------------------------------------------------------------------------- -/* c8 ignore next 11 */ +/* c8 ignore next 15 */ function _node_specific() { _node_specific = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() { var _yield$import, createRequire, moduleURL, __dirname__, __filename__; @@ -15905,16 +16046,20 @@ function _node_specific() { })); return _node_specific.apply(this, arguments); } +var node_ready; // Scheme load function need to wait for node_specific if (is_node()) { - node_specific(); -} else if (typeof window !== 'undefined' && window === root) { - global_env.set('window', window); - global_env.set('global', undefined); - global_env.set('self', window); -} else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { - global_env.set('self', self); - global_env.set('window', undefined); - global_env.set('global', undefined); + node_ready = node_specific(); +} else { + node_ready = Promise.resolve(); + if (typeof window !== 'undefined' && window === root) { + global_env.set('window', window); + global_env.set('global', undefined); + global_env.set('self', window); + } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { + global_env.set('self', self); + global_env.set('window', undefined); + global_env.set('global', undefined); + } } // ------------------------------------------------------------------------- function typeErrorMessage(fn, got, expected) { @@ -16830,6 +16975,7 @@ function bootstrap() { url = "https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version, "/").concat(std); } } + global_env.set('__dirname', url.replace(/[^/]+$/, '')); var load = global_env.get('load'); return load.call(user_env, url, global_env); } @@ -17243,17 +17389,17 @@ if (typeof window !== 'undefined') { // ------------------------------------------------------------------------- var banner = function () { // Rollup tree-shaking is removing the variable if it's normal string because - // obviously 'Mon, 27 May 2024 11:41:47 +0000' == '{{' + 'DATE}}'; can be removed + // obviously 'Fri, 08 Nov 2024 13:26:12 +0000' == '{{' + 'DATE}}'; can be removed // but disabling Tree-shaking is adding lot of not used code so we use this // hack instead - var date = LString('Mon, 27 May 2024 11:41:47 +0000').valueOf(); + var date = LString('Fri, 08 Nov 2024 13:26:12 +0000').valueOf(); var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date); var _format = function _format(x) { return x.toString().padStart(2, '0'); }; var _year = _date.getFullYear(); var _build = [_year, _format(_date.getMonth() + 1), _format(_date.getDate())].join('-'); - var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); + var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); return banner; }(); // ------------------------------------------------------------------------- @@ -17285,8 +17431,8 @@ read_only(LString, '__class__', 'string'); read_only(QuotedPromise, '__class__', 'promise'); read_only(Parameter, '__class__', 'parameter'); // ------------------------------------------------------------------------- -var version = '1.0.0-beta.19'; -var date = 'Mon, 27 May 2024 11:41:47 +0000'; +var version = 'DEV'; +var date = 'Fri, 08 Nov 2024 13:26:12 +0000'; // unwrap async generator into Promise var parse = compose(uniterate_async, _parse); diff --git a/dist/lips.esm.min.js b/dist/lips.esm.min.js index 228184631..4a486c70e 100644 --- a/dist/lips.esm.min.js +++ b/dist/lips.esm.min.js @@ -4,7 +4,7 @@ * | | \ \ | | | || . \/ __> | | * | | > \ | |_ | || _/\__ \ | | * | | / ^ \ |___||_||_| <___/ | | - * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19 + * \_\ /_/ \_\ /_/ v. DEV * * LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript * @@ -31,9 +31,9 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Mon, 27 May 2024 11:41:47 +0000 + * build: Fri, 08 Nov 2024 13:26:12 +0000 */ -function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.value}function _classExtractFieldDescriptor(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function _classPrivateFieldGet(e,t){var r=_classExtractFieldDescriptor(e,t,"get");return _classApplyDescriptorGet(e,r)}function _classApplyDescriptorSet(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function _classPrivateFieldSet(e,t,r){var n=_classExtractFieldDescriptor(e,t,"set");_classApplyDescriptorSet(e,n,r);return r}function _assertThisInitialized(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function _setPrototypeOf(e,t){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return _setPrototypeOf(e,t)}function _isNativeReflectConstruct$1(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct$1=function e(){return!!t})()}function _construct(e,t,r){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function _arrayLikeToArray$1(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function _objectWithoutProperties(e,t){if(e==null)return{};var r=_objectWithoutPropertiesLoose(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,o,u=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(o=r["return"](),Object(o)!==o))return}finally{if(c)throw i}}return u}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$1(e,t)||_nonIterableRest()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$1(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$1(e)||_nonIterableSpread()}function _OverloadYield(e,t){this.v=e,this.k=t}function _awaitAsyncGenerator(e){return new _OverloadYield(e,0)}function AsyncGenerator(o){var a,u;function s(r,e){try{var n=o[r](e),i=n.value,a=i instanceof _OverloadYield;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=o[t](e).value}c(n.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):u=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};u?u=u.next=r:(a=u=r,s(n,i))})},"function"!=typeof o["return"]&&(this["return"]=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype["throw"]=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype["return"]=function(e){return this._invoke("return",e)};function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var regeneratorRuntime$1={exports:{}};var _typeof={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(_typeof);var _typeofExports=_typeof.exports;(function(P){var N=_typeofExports["default"];function B(){P.exports=B=function e(){return o},P.exports.__esModule=true,P.exports["default"]=P.exports;var c,o={},e=Object.prototype,l=e.hasOwnProperty,f=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function u(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),o=new C(n||[]);return f(a,"_invoke",{value:S(e,r,o)}),a}function _(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}o.wrap=u;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",y={};function s(){}function v(){}function b(){}var g={};a(g,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(O([])));D&&D!==e&&l.call(D,i)&&(g=D);var x=b.prototype=s.prototype=Object.create(g);function L(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function E(u,s){function c(e,t,r,n){var i=_(u[e],u,t);if("throw"!==i.type){var a=i.arg,o=a.value;return o&&"object"==N(o)&&l.call(o,"__await")?s.resolve(o.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(o).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;f(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function S(a,o,u){var s=p;return function(e,t){if(s===h)throw new Error("Generator is already running");if(s===m){if("throw"===e)throw t;return{value:c,done:!0}}for(u.method=e,u.arg=t;;){var r=u.delegate;if(r){var n=A(r,u);if(n){if(n===y)continue;return n}}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(s===p)throw s=m,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);s=h;var i=_(a,o,u);if("normal"===i.type){if(s=u.done?m:d,i.arg===y)continue;return{value:i.arg,done:u.done}}"throw"===i.type&&(s=m,u.method="throw",u.arg=i.arg)}}}function A(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,A(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=_(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function F(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(F,this),this.reset(!0)}function O(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],o=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var u=l.call(a,"catchLoc"),s=l.call(a,"finallyLoc");if(u&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&l.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),k(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;k(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:O(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},o}P.exports=B,P.exports.__esModule=true,P.exports["default"]=P.exports})(regeneratorRuntime$1);var regeneratorRuntimeExports=regeneratorRuntime$1.exports;var runtime=regeneratorRuntimeExports();var regenerator=runtime;try{regeneratorRuntime=runtime}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=runtime}else{Function("r","regeneratorRuntime = r")(runtime)}}var _regeneratorRuntime=getDefaultExportFromCjs(regenerator);let decoder;try{decoder=new TextDecoder}catch(e){}let src;let srcEnd;let position$1=0;const LEGACY_RECORD_INLINE_ID=105;const RECORD_DEFINITIONS_ID=57342;const RECORD_INLINE_ID=57343;const BUNDLED_STRINGS_ID=57337;const PACKED_REFERENCE_TAG_ID=6;const STOP_CODE={};let currentDecoder={};let currentStructures;let srcString;let srcStringStart=0;let srcStringEnd=0;let bundledStrings$1;let referenceMap;let currentExtensions=[];let currentExtensionRanges=[];let packedValues;let dataView;let restoreMapsAsObject;let defaultOptions={useRecords:false,mapsAsObjects:true};let sequentialMode=false;let inlineObjectReadThreshold=2;try{new Function("")}catch(e){inlineObjectReadThreshold=Infinity}class Decoder{constructor(r){if(r){if((r.keyMap||r._keyMap)&&!r.useRecords){r.useRecords=false;r.mapsAsObjects=true}if(r.useRecords===false&&r.mapsAsObjects===undefined)r.mapsAsObjects=true;if(r.getStructures)r.getShared=r.getStructures;if(r.getShared&&!r.structures)(r.structures=[]).uninitialized=true;if(r.keyMap){this.mapKey=new Map;for(let[e,t]of Object.entries(r.keyMap))this.mapKey.set(t,e)}}Object.assign(this,r)}decodeKey(e){return this.keyMap?this.mapKey.get(e)||e:e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(r){if(!this._keyMap)return r;let n=new Map;for(let[e,t]of Object.entries(r))n.set(this._keyMap.hasOwnProperty(e)?this._keyMap[e]:e,t);return n}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let r={};e.forEach((e,t)=>r[safeKey(this._mapKey.has(t)?this._mapKey.get(t):t)]=e);return r}mapDecode(e,t){let r=this.decode(e);if(this._keyMap){switch(r.constructor.name){case"Array":return r.map(e=>this.decodeKeys(e))}}return r}decode(t,e){if(src){return saveState(()=>{clearSource();return this?this.decode(t,e):Decoder.prototype.decode.call(defaultOptions,t,e)})}srcEnd=e>-1?e:t.length;position$1=0;srcStringEnd=0;srcString=null;bundledStrings$1=null;src=t;try{dataView=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){src=null;if(t instanceof Uint8Array)throw e;throw new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Decoder){currentDecoder=this;packedValues=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues);if(this.structures){currentStructures=this.structures;return checkedRead()}else if(!currentStructures||currentStructures.length>0){currentStructures=[]}}else{currentDecoder=defaultOptions;if(!currentStructures||currentStructures.length>0)currentStructures=[];packedValues=null}return checkedRead()}decodeMultiple(r,n){let i,a=0;try{let e=r.length;sequentialMode=true;let t=this?this.decode(r,e):defaultDecoder.decode(r,e);if(n){if(n(t)===false){return}while(position$1=bundledStrings$1.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}position$1=bundledStrings$1.postBundlePosition;bundledStrings$1=null}if(position$1==srcEnd){currentStructures=null;src=null;if(referenceMap)referenceMap=null}else if(position$1>srcEnd){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!sequentialMode){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){clearSource();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function read(){let n=src[position$1++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=src[position$1++];break;case 25:if(i==7){return getFloat16()}n=dataView.getUint16(position$1);position$1+=2;break;case 26:if(i==7){let t=dataView.getFloat32(position$1);if(currentDecoder.useFloat32>2){let e=mult10[(src[position$1]&127)<<1|src[position$1+1]>>7];position$1+=4;return(e*t+(t>0?.5:-.5)>>0)/e}position$1+=4;return t}n=dataView.getUint32(position$1);position$1+=4;break;case 27:if(i==7){let e=dataView.getFloat64(position$1);position$1+=8;return e}if(i>1){if(dataView.getUint32(position$1)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=dataView.getUint32(position$1+4)}else if(currentDecoder.int64AsNumber){n=dataView.getUint32(position$1)*4294967296;n+=dataView.getUint32(position$1+4)}else n=dataView.getBigUint64(position$1);position$1+=8;break;case 31:switch(i){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e=[];let t,r=0;while((t=read())!=STOP_CODE){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(currentDecoder.mapsAsObjects){let e={};if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e[safeKey(currentDecoder.decodeKey(n))]=read();else while((n=read())!=STOP_CODE)e[safeKey(n)]=read();return e}else{if(restoreMapsAsObject){currentDecoder.mapsAsObjects=true;restoreMapsAsObject=false}let e=new Map;if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e.set(currentDecoder.decodeKey(n),read());else while((n=read())!=STOP_CODE)e.set(n,read());return e}case 7:return STOP_CODE;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+n)}}switch(i){case 0:return n;case 1:return~n;case 2:return readBin(n);case 3:if(srcStringEnd>=position$1){return srcString.slice(position$1-srcStringStart,(position$1+=n)-srcStringStart)}if(srcStringEnd==0&&srcEnd<140&&n<32){let e=n<16?shortStringInJS(n):longStringInJS(n);if(e!=null)return e}return readFixedString(n);case 4:let t=new Array(n);for(let e=0;e=BUNDLED_STRINGS_ID){let e=currentStructures[n&8191];if(e){if(!e.read)e.read=createStructureReader(e);return e.read()}if(n<65536){if(n==RECORD_INLINE_ID){let e=readJustLength();let t=read();let r=read();recordDefinition(t,r);let n={};if(currentDecoder.keyMap)for(let t=2;t23){switch(t){case 24:t=src[position$1++];break;case 25:t=dataView.getUint16(position$1);position$1+=2;break;case 26:t=dataView.getUint32(position$1);position$1+=4;break;default:throw new Error("Expected array header, but got "+src[position$1-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(read);r=r.next}if(this.slowReads++>=inlineObjectReadThreshold){let e=this.length==t?this:this.slice(0,t);r=currentDecoder.keyMap?new Function("r","return {"+e.map(e=>currentDecoder.decodeKey(e)).map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(read)}let n={};if(currentDecoder.keyMap)for(let e=0;e64&&decoder)return decoder.decode(src.subarray(position$1,position$1+=e));const r=position$1+e;const n=[];t="";while(position$165535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=fromCharCode.apply(String,n);n.length=0}}if(n.length>0){t+=fromCharCode.apply(String,n)}return t}let fromCharCode=String.fromCharCode;function longStringInJS(t){let r=position$1;let n=new Array(t);for(let e=0;e0){position$1=r;return}n[e]=i}return fromCharCode.apply(String,n)}function shortStringInJS(h){if(h<4){if(h<2){if(h===0)return"";else{let e=src[position$1++];if((e&128)>1){position$1-=1;return}return fromCharCode(e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=2;return}if(h<3)return fromCharCode(e,t);let r=src[position$1++];if((r&128)>0){position$1-=3;return}return fromCharCode(e,t,r)}}else{let f=src[position$1++];let _=src[position$1++];let p=src[position$1++];let d=src[position$1++];if((f&128)>0||(_&128)>0||(p&128)>0||(d&128)>0){position$1-=4;return}if(h<6){if(h===4)return fromCharCode(f,_,p,d);else{let e=src[position$1++];if((e&128)>0){position$1-=5;return}return fromCharCode(f,_,p,d,e)}}else if(h<8){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=6;return}if(h<7)return fromCharCode(f,_,p,d,e,t);let r=src[position$1++];if((r&128)>0){position$1-=7;return}return fromCharCode(f,_,p,d,e,t,r)}else{let u=src[position$1++];let s=src[position$1++];let c=src[position$1++];let l=src[position$1++];if((u&128)>0||(s&128)>0||(c&128)>0||(l&128)>0){position$1-=8;return}if(h<10){if(h===8)return fromCharCode(f,_,p,d,u,s,c,l);else{let e=src[position$1++];if((e&128)>0){position$1-=9;return}return fromCharCode(f,_,p,d,u,s,c,l,e)}}else if(h<12){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=10;return}if(h<11)return fromCharCode(f,_,p,d,u,s,c,l,e,t);let r=src[position$1++];if((r&128)>0){position$1-=11;return}return fromCharCode(f,_,p,d,u,s,c,l,e,t,r)}else{let n=src[position$1++];let i=src[position$1++];let a=src[position$1++];let o=src[position$1++];if((n&128)>0||(i&128)>0||(a&128)>0||(o&128)>0){position$1-=12;return}if(h<14){if(h===12)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o);else{let e=src[position$1++];if((e&128)>0){position$1-=13;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=14;return}if(h<15)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t);let r=src[position$1++];if((r&128)>0){position$1-=15;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t,r)}}}}}function readBin(e){return currentDecoder.copyBuffers?Uint8Array.prototype.slice.call(src,position$1,position$1+=e):src.subarray(position$1,position$1+=e)}let f32Array=new Float32Array(1);let u8Array=new Uint8Array(f32Array.buffer,0,4);function getFloat16(){let t=src[position$1++];let r=src[position$1++];let e=(t&127)>>2;if(e===31){if(r||t&3)return NaN;return t&128?-Infinity:Infinity}if(e===0){let e=((t&3)<<8|r)/(1<<24);return t&128?-e:e}u8Array[3]=t&128|(e>>1)+56;u8Array[2]=(t&7)<<5|r>>3;u8Array[1]=r<<5;u8Array[0]=0;return f32Array[0]}new Array(4096);class Tag{constructor(e,t){this.value=e;this.tag=t}}currentExtensions[0]=e=>{return new Date(e)};currentExtensions[1]=e=>{return new Date(Math.round(e*1e3))};currentExtensions[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-currentExtensions[2](e)};currentExtensions[4]=e=>{return+(e[1]+"e"+e[0])};currentExtensions[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const recordDefinition=(e,t)=>{e=e-57344;let r=currentStructures[e];if(r&&r.isShared){(currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[e]=r}currentStructures[e]=t;t.read=createStructureReader(t)};currentExtensions[LEGACY_RECORD_INLINE_ID]=r=>{let e=r.length;let n=r[1];recordDefinition(r[0],n);let i={};for(let t=2;t{if(bundledStrings$1)return bundledStrings$1[0].slice(bundledStrings$1.position0,bundledStrings$1.position0+=e);return new Tag(e,14)};currentExtensions[15]=e=>{if(bundledStrings$1)return bundledStrings$1[1].slice(bundledStrings$1.position1,bundledStrings$1.position1+=e);return new Tag(e,15)};let glbl={Error:Error,RegExp:RegExp};currentExtensions[27]=e=>{return(glbl[e[0]]||Error)(e[1],e[2])};const packedTable=e=>{if(src[position$1++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(src.length{if(!packedValues){if(currentDecoder.getShared)loadShared();else return new Tag(e,PACKED_REFERENCE_TAG_ID)}if(typeof e=="number")return packedValues[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};currentExtensions[28]=e=>{if(!referenceMap){referenceMap=new Map;referenceMap.id=0}let t=referenceMap.id++;let r=src[position$1];let n;if(r>>5==4)n=[];else n={};let i={target:n};referenceMap.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};currentExtensions[28].handlesRead=true;currentExtensions[29]=e=>{let t=referenceMap.get(e);t.used=true;return t.target};currentExtensions[258]=e=>new Set(e);(currentExtensions[259]=e=>{if(currentDecoder.mapsAsObjects){currentDecoder.mapsAsObjects=false;restoreMapsAsObject=true}return e()}).handlesRead=true;function combine(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function getPackedValues(){if(!packedValues){if(currentDecoder.getShared)loadShared();else throw new Error("No packed values available")}return packedValues}const SHARED_DATA_TAG_ID=1399353956;currentExtensionRanges.push((e,t)=>{if(e>=225&&e<=255)return combine(getPackedValues().prefixes[e-224],t);if(e>=28704&&e<=32767)return combine(getPackedValues().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return combine(getPackedValues().prefixes[e-1879048192],t);if(e>=216&&e<=223)return combine(t,getPackedValues().suffixes[e-216]);if(e>=27647&&e<=28671)return combine(t,getPackedValues().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return combine(t,getPackedValues().suffixes[e-1811939328]);if(e==SHARED_DATA_TAG_ID){return{packedValues:packedValues,structures:currentStructures.slice(0),version:t}}if(e==55799)return t});const isLittleEndianMachine$1=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;const typedArrays=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array=="undefined"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array=="undefined"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array];const typedArrayTags=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e{if(!u)throw new Error("Could not find typed array for code "+s);if(!currentDecoder.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new u(e.buffer,e.byteOffset,e.byteLength)}return new u(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!u)throw new Error("Could not find typed array for code "+s);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=e.length>>a;let n=new u(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=src[position$1++];break;case 25:e=dataView.getUint16(position$1);position$1+=2;break;case 26:e=dataView.getUint32(position$1);position$1+=4;break}}return e}function loadShared(){if(currentDecoder.getShared){let e=saveState(()=>{src=null;return currentDecoder.getShared()})||{};let t=e.structures||[];currentDecoder.sharedVersion=e.version;packedValues=currentDecoder.sharedValues=e.packedValues;if(currentStructures===true)currentDecoder.structures=currentStructures=t;else currentStructures.splice.apply(currentStructures,[0,t.length].concat(t))}}function saveState(e){let t=srcEnd;let r=position$1;let n=srcStringStart;let i=srcStringEnd;let a=srcString;let o=referenceMap;let u=bundledStrings$1;let s=new Uint8Array(src.slice(0,srcEnd));let c=currentStructures;let l=currentDecoder;let f=sequentialMode;let _=e();srcEnd=t;position$1=r;srcStringStart=n;srcStringEnd=i;srcString=a;referenceMap=o;bundledStrings$1=u;src=s;sequentialMode=f;currentStructures=c;currentDecoder=l;dataView=new DataView(src.buffer,src.byteOffset,src.byteLength);return _}function clearSource(){src=null;referenceMap=null;currentStructures=null}function addExtension$1(e){currentExtensions[e.tag]=e.decode}const mult10=new Array(147);for(let e=0;e<256;e++){mult10[e]=+("1e"+Math.floor(45.15-e*.30103))}let defaultDecoder=new Decoder({useRecords:false});defaultDecoder.decode;defaultDecoder.decodeMultiple;let textEncoder;try{textEncoder=new TextEncoder}catch(e){}let extensions,extensionClasses;const Buffer$1=typeof globalThis==="object"&&globalThis.Buffer;const hasNodeBuffer=typeof Buffer$1!=="undefined";const ByteArrayAllocate=hasNodeBuffer?Buffer$1.allocUnsafeSlow:Uint8Array;const ByteArray=hasNodeBuffer?Buffer$1:Uint8Array;const MAX_STRUCTURES=256;const MAX_BUFFER_SIZE=hasNodeBuffer?4294967296:2144337920;let throwOnIterable;let target;let targetView;let position=0;let safeEnd;let bundledStrings=null;const MAX_BUNDLE_SIZE=61440;const hasNonLatin=/[\u0080-\uFFFF]/;const RECORD_SYMBOL=Symbol("record-id");class Encoder extends Decoder{constructor(r){super(r);this.offset=0;let s;let o;let l;let f;let n;r=r||{};let c=ByteArray.prototype.utf8Write?function(e,t,r){return target.utf8Write(e,t,r)}:textEncoder&&textEncoder.encodeInto?function(e,t){return textEncoder.encodeInto(e,target.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let _=r.maxSharedStructures;if(_==null)_=e?128:0;if(_>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){_=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let p,d,u=r.sharedValues;let h;if(u){h=Object.create(null);for(let e=0,t=u.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!target){target=new ByteArrayAllocate(8192);targetView=new DataView(target.buffer,0,8192);position=0}safeEnd=target.length-10;if(safeEnd-position<2048){target=new ByteArrayAllocate(target.length);targetView=new DataView(target.buffer,0,target.length);safeEnd=target.length-10;position=0}else if(e===REUSE_BUFFER_MODE)position=position+7&2147483640;s=position;if(a.useSelfDescribedHeader){targetView.setUint32(position,3654940416);position+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){bundledStrings=[];bundledStrings.size=Infinity}else bundledStrings=null;o=a.structures;if(o){if(o.uninitialized){let e=a.getShared()||{};a.structures=o=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){h={};for(let e=0,t=r.length;e_&&!i)e=_;if(!o.transitions){o.transitions=Object.create(null);for(let a=0;a0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;b(r);writeArrayHeader(0);writeArrayHeader(0);d=Object.create(h||null);for(let e=0,t=r.length;esafeEnd)w(position);a.offset=position;let e=insertIds(target.subarray(s,position),n.idsToInsert);n=null;return e}if(e&REUSE_BUFFER_MODE){target.start=s;target.end=position;return target}return target.subarray(s,position)}finally{if(o){if(v<10)v++;if(o.length>_)o.length=_;if(y>1e4){o.transitions=null;v=0;y=0;if(m.length>0)m=[]}else if(m.length>0&&!i){for(let e=0,t=m.length;e_){a.structures=a.structures.slice(0,_)}let e=target.subarray(s,position);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&RESET_BUFFER_MODE)position=s}};this.findCommonStringsToPack=()=>{p=new Map;if(!h)h=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!u)u=this.sharedValues=[];for(let[e,t]of p){if(t.count>r){h[e]=n++;u.push(e);l=true}}while(this.saveShared&&this.updateSharedData()===false){}p=null}};const b=o=>{if(position>safeEnd)target=w(position);var e=typeof o;var u;if(e==="string"){if(d){let e=d[o];if(e>=0){if(e<16)target[position++]=e+224;else{target[position++]=198;if(e&1)b(15-e>>1);else b(e-16>>1)}return}else if(p&&!r.pack){let e=p.get(o);if(e)e.count++;else p.set(o,{count:1})}}let i=o.length;if(bundledStrings&&i>=4&&i<1024){if((bundledStrings.size+=i)>MAX_BUNDLE_SIZE){let e;let t=(bundledStrings[0]?bundledStrings[0].length*3+bundledStrings[1].length:0)+10;if(position+t>safeEnd)target=w(position+t);target[position++]=217;target[position++]=223;target[position++]=249;target[position++]=bundledStrings.position?132:130;target[position++]=26;e=position-s;position+=4;if(bundledStrings.position){writeBundles(s,b)}bundledStrings=["",""];bundledStrings.size=0;bundledStrings.position=e}let e=hasNonLatin.test(o);bundledStrings[e?0:1]+=o;target[position++]=e?206:207;b(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(position+e>safeEnd)target=w(position+e);if(i<64||!c){let e,t,r,n=position+a;for(e=0;e>6|192;target[n++]=t&63|128}else if((t&64512)===55296&&((r=o.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;target[n++]=t>>18|240;target[n++]=t>>12&63|128;target[n++]=t>>6&63|128;target[n++]=t&63|128}else{target[n++]=t>>12|224;target[n++]=t>>6&63|128;target[n++]=t&63|128}}u=n-position-a}else{u=c(o,position+a,e)}if(u<24){target[position++]=96|u}else if(u<256){if(a<2){target.copyWithin(position+2,position+1,position+1+u)}target[position++]=120;target[position++]=u}else if(u<65536){if(a<3){target.copyWithin(position+3,position+2,position+2+u)}target[position++]=121;target[position++]=u>>8;target[position++]=u&255}else{if(a<5){target.copyWithin(position+5,position+3,position+3+u)}target[position++]=122;targetView.setUint32(position,u);position+=4}position+=u}else if(e==="number"){if(!this.alwaysUseFloat&&o>>>0===o){if(o<24){target[position++]=o}else if(o<256){target[position++]=24;target[position++]=o}else if(o<65536){target[position++]=25;target[position++]=o>>8;target[position++]=o&255}else{target[position++]=26;targetView.setUint32(position,o);position+=4}}else if(!this.alwaysUseFloat&&o>>0===o){if(o>=-24){target[position++]=31-o}else if(o>=-256){target[position++]=56;target[position++]=~o}else if(o>=-65536){target[position++]=57;targetView.setUint16(position,~o);position+=2}else{target[position++]=58;targetView.setUint32(position,~o);position+=4}}else{let t;if((t=this.useFloat32)>0&&o<4294967296&&o>=-2147483648){target[position++]=250;targetView.setFloat32(position,o);let e;if(t<4||(e=o*mult10[(target[position]&127)<<1|target[position+1]>>7])>>0===e){position+=4;return}else position--}target[position++]=251;targetView.setFloat64(position,o);position+=8}}else if(e==="object"){if(!o)target[position++]=246;else{if(n){let t=n.get(o);if(t){target[position++]=216;target[position++]=29;target[position++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(position-s);position+=2;return}else n.set(o,{offset:position-s})}let e=o.constructor;if(e===Object){g(o,true)}else if(e===Array){u=o.length;if(u<24){target[position++]=128|u}else{writeArrayHeader(u)}for(let e=0;e>8;target[position++]=u&255}else{target[position++]=186;targetView.setUint32(position,u);position+=4}if(a.keyMap){for(let[e,t]of o){b(a.encodeKey(e));b(t)}}else{for(let[e,t]of o){b(e);b(t)}}}else{for(let r=0,e=extensions.length;r>8;target[position++]=t&255}else if(t>-1){target[position++]=218;targetView.setUint32(position,t);position+=4}e.encode.call(this,o,b,w);return}}if(o[Symbol.iterator]){if(throwOnIterable){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}target[position++]=159;for(let e of o){b(e)}target[position++]=255;return}if(o[Symbol.asyncIterator]||isBlob(o)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&o.toJSON){const t=o.toJSON();if(t!==o)return b(t)}g(o,!o.hasOwnProperty)}}}else if(e==="boolean"){target[position++]=o?245:244}else if(e==="bigint"){if(o=0){target[position++]=27;targetView.setBigUint64(position,o)}else if(o>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){target[position++]=160|n}else if(n<256){target[position++]=184;target[position++]=n}else if(n<65536){target[position++]=185;target[position++]=n>>8;target[position++]=n&255}else{target[position++]=186;targetView.setUint32(position,n);position+=4}if(a.keyMap){for(let e=0;e{target[position++]=185;let e=position-s;position+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){b(a.encodeKey(e));b(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){b(e);b(t[e]);n++}}target[e+++s]=n>>8;target[e+s]=n&255}:(t,r)=>{let n,i=f.transitions||(f.transitions=Object.create(null));let a=0;let o=0;let u;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));o=s.length;for(let t=0;t>8|224;target[position++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(u===undefined){c=f.nextId++;if(!c){c=0;f.nextId=1}if(c>=MAX_STRUCTURES){f.nextId=(c=_)+1}}else{c=u}f[c]=s;if(c<_){target[position++]=217;target[position++]=c>>8|224;target[position++]=c&255;i=f.transitions;for(let e=0;e=MAX_STRUCTURES-_)m.shift()[RECORD_SYMBOL]=undefined;m.push(i);writeArrayHeader(o+2);b(57344+c);b(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e]);return}}if(o<24){target[position++]=128|o}else{writeArrayHeader(o)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>MAX_BUFFER_SIZE)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,target.length-1)>>12)+1<<12;let r=new ByteArrayAllocate(t);targetView=new DataView(r.buffer,0,t);if(target.copy)target.copy(r,0,s,e);else r.set(target.slice(s,e));position-=s;s=0;safeEnd=r.length-10;return target=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return A(e,t,L)};this.encodeAsAsyncIterable=function(e,t){return A(e,t,F)};function*L(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)g(n,null);else writeEntityLength(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)b(t);if(e&&typeof e==="object"){if(i[t])yield*L(e,i[t]);else yield*E(e,i,t)}else b(e)}}else if(t===Array){let e=n.length;writeArrayHeader(e);for(let t=0;tD)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}}else if(n[Symbol.iterator]){target[position++]=159;for(let e of n){if(e&&(typeof e==="object"||position-s>D)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}target[position++]=255}else if(isBlob(n)){writeEntityLength(n.size,64);yield target.subarray(s,position);yield n;S()}else if(n[Symbol.asyncIterator]){target[position++]=159;yield target.subarray(s,position);yield n;S();target[position++]=255}else{b(n)}if(e&&position>s)yield target.subarray(s,position);else if(position-s>D){yield target.subarray(s,position);S()}}function*E(t,r,n){let i=position-s;try{b(t);if(position-s>D){yield target.subarray(s,position);S()}}catch(e){if(e.iteratorNotHandled){r[n]={};position=s+i;yield*L.call(this,t,r[n])}else throw e}}function S(){D=x;a.encode(null,THROW_ON_ITERABLE)}function A(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,THROW_ON_ITERABLE);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*F(e,t){for(let r of L(e,t,true)){let e=r.constructor;if(e===ByteArray||e===Uint8Array)yield r;else if(isBlob(r)){let e=r.stream().getReader();let t;while(!(t=await e.read()).done){yield t.value}}else if(r[Symbol.asyncIterator]){for await(let e of r){S();if(e)yield*F(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){target=e;targetView=new DataView(target.buffer,target.byteOffset,target.byteLength);position=0}clearSharedData(){if(this.structures)this.structures=[];if(this.sharedValues)this.sharedValues=undefined}updateSharedData(){let t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new SharedData(e,this.sharedValues,this.sharedVersion);let n=this.saveShared(r,e=>(e&&e.version||0)==t);if(n===false){r=this.getShared()||{};this.structures=r.structures||[];this.sharedValues=r.packedValues;this.sharedVersion=r.version;this.structures.nextId=this.structures.length}else{e.forEach((e,t)=>this.structures[t]=e)}return n}}function writeEntityLength(e,t){if(e<24)target[position++]=t|e;else if(e<256){target[position++]=t|24;target[position++]=e}else if(e<65536){target[position++]=t|25;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=t|26;targetView.setUint32(position,e);position+=4}}class SharedData{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function writeArrayHeader(e){if(e<24)target[position++]=128|e;else if(e<256){target[position++]=152;target[position++]=e}else if(e<65536){target[position++]=153;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=154;targetView.setUint32(position,e);position+=4}}const BlobConstructor=typeof Blob==="undefined"?function(){}:Blob;function isBlob(e){if(e instanceof BlobConstructor)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function findRepetitiveStrings(r,n){switch(typeof r){case"string":if(r.length>3){if(n.objectMap[r]>-1||n.values.length>=n.maxValues)return;let e=n.get(r);if(e){if(++e.count==2){n.values.push(r)}}else{n.set(r,{count:1});if(n.samplingPackedValues){let e=n.samplingPackedValues.get(r);if(e)e.count++;else n.samplingPackedValues.set(r,{count:1})}}}break;case"object":if(r){if(r instanceof Array){for(let e=0,t=r.length;e=0&&r<4294967296){target[position++]=26;targetView.setUint32(position,r);position+=4}else{target[position++]=251;targetView.setFloat64(position,r);position+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,r){writeBuffer(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||hasNodeBuffer&&this.tagUint8Array!==false)return 64}},encode(e,t,r){writeBuffer(e,r)}},typedArrayEncoder(68,1),typedArrayEncoder(69,2),typedArrayEncoder(70,4),typedArrayEncoder(71,8),typedArrayEncoder(72,1),typedArrayEncoder(77,2),typedArrayEncoder(78,4),typedArrayEncoder(79,8),typedArrayEncoder(85,4),typedArrayEncoder(86,8),{encode(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;n(r);writeArrayHeader(0);writeArrayHeader(0);packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let e=0,t=r.length;e1)e-=4;return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let a=t.buffer||t;r(hasNodeBuffer?Buffer$1.from(a,i,n):new Uint8Array(a,i,n))}}}function writeBuffer(e,t){let r=e.byteLength;if(r<24){target[position++]=64+r}else if(r<256){target[position++]=88;target[position++]=r}else if(r<65536){target[position++]=89;target[position++]=r>>8;target[position++]=r&255}else{target[position++]=90;targetView.setUint32(position,r);position+=4}if(position+r>=target.length){t(position+r)}target.set(e.buffer?e:new Uint8Array(e),position);position+=r}function insertIds(n,e){let r;let i=e.length*2;let a=n.length-i;e.sort((e,t)=>e.offset>t.offset?1:-1);for(let r=0;r>8;n[e]=r&255}}while(r=e.pop()){let e=r.offset;n.copyWithin(e+i,e,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function writeBundles(e,t){targetView.setUint32(bundledStrings.position+e,position-bundledStrings.position-e+1);let r=bundledStrings;bundledStrings=null;t(r[0]);t(r[1])}function addExtension(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");extensionClasses.unshift(e.Class);extensions.unshift(e)}addExtension$1(e)}let defaultEncoder=new Encoder({useRecords:false});defaultEncoder.encode;defaultEncoder.encodeAsIterable;defaultEncoder.encodeAsAsyncIterable;const REUSE_BUFFER_MODE=512;const RESET_BUFFER_MODE=1024;const THROW_ON_ITERABLE=2048;var lzjbPack={}; +function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.value}function _classExtractFieldDescriptor(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function _classPrivateFieldGet(e,t){var r=_classExtractFieldDescriptor(e,t,"get");return _classApplyDescriptorGet(e,r)}function _classApplyDescriptorSet(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function _classPrivateFieldSet(e,t,r){var n=_classExtractFieldDescriptor(e,t,"set");_classApplyDescriptorSet(e,n,r);return r}function _assertThisInitialized(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function _setPrototypeOf(e,t){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return _setPrototypeOf(e,t)}function _isNativeReflectConstruct$1(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct$1=function e(){return!!t})()}function _construct(e,t,r){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}function _readOnlyError(e){throw new TypeError('"'+e+'" is read-only')}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function _arrayLikeToArray$1(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function _objectWithoutProperties(e,t){if(e==null)return{};var r=_objectWithoutPropertiesLoose(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,o,u=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(o=r["return"](),Object(o)!==o))return}finally{if(c)throw i}}return u}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$1(e,t)||_nonIterableRest()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$1(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$1(e)||_nonIterableSpread()}function _OverloadYield(e,t){this.v=e,this.k=t}function _awaitAsyncGenerator(e){return new _OverloadYield(e,0)}function AsyncGenerator(o){var a,u;function s(r,e){try{var n=o[r](e),i=n.value,a=i instanceof _OverloadYield;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=o[t](e).value}c(n.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):u=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};u?u=u.next=r:(a=u=r,s(n,i))})},"function"!=typeof o["return"]&&(this["return"]=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype["throw"]=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype["return"]=function(e){return this._invoke("return",e)};function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var regeneratorRuntime$1={exports:{}};var _typeof={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(_typeof);var _typeofExports=_typeof.exports;(function(P){var N=_typeofExports["default"];function B(){P.exports=B=function e(){return o},P.exports.__esModule=true,P.exports["default"]=P.exports;var c,o={},e=Object.prototype,l=e.hasOwnProperty,f=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function u(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),o=new C(n||[]);return f(a,"_invoke",{value:S(e,r,o)}),a}function _(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}o.wrap=u;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",y={};function s(){}function v(){}function b(){}var g={};a(g,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(O([])));D&&D!==e&&l.call(D,i)&&(g=D);var x=b.prototype=s.prototype=Object.create(g);function L(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function E(u,s){function c(e,t,r,n){var i=_(u[e],u,t);if("throw"!==i.type){var a=i.arg,o=a.value;return o&&"object"==N(o)&&l.call(o,"__await")?s.resolve(o.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(o).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;f(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function S(a,o,u){var s=p;return function(e,t){if(s===h)throw new Error("Generator is already running");if(s===m){if("throw"===e)throw t;return{value:c,done:!0}}for(u.method=e,u.arg=t;;){var r=u.delegate;if(r){var n=A(r,u);if(n){if(n===y)continue;return n}}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(s===p)throw s=m,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);s=h;var i=_(a,o,u);if("normal"===i.type){if(s=u.done?m:d,i.arg===y)continue;return{value:i.arg,done:u.done}}"throw"===i.type&&(s=m,u.method="throw",u.arg=i.arg)}}}function A(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,A(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=_(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function F(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(F,this),this.reset(!0)}function O(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],o=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var u=l.call(a,"catchLoc"),s=l.call(a,"finallyLoc");if(u&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&l.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),k(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;k(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:O(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},o}P.exports=B,P.exports.__esModule=true,P.exports["default"]=P.exports})(regeneratorRuntime$1);var regeneratorRuntimeExports=regeneratorRuntime$1.exports;var runtime=regeneratorRuntimeExports();var regenerator=runtime;try{regeneratorRuntime=runtime}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=runtime}else{Function("r","regeneratorRuntime = r")(runtime)}}var _regeneratorRuntime=getDefaultExportFromCjs(regenerator);let decoder;try{decoder=new TextDecoder}catch(e){}let src;let srcEnd;let position$1=0;const LEGACY_RECORD_INLINE_ID=105;const RECORD_DEFINITIONS_ID=57342;const RECORD_INLINE_ID=57343;const BUNDLED_STRINGS_ID=57337;const PACKED_REFERENCE_TAG_ID=6;const STOP_CODE={};let currentDecoder={};let currentStructures;let srcString;let srcStringStart=0;let srcStringEnd=0;let bundledStrings$1;let referenceMap;let currentExtensions=[];let currentExtensionRanges=[];let packedValues;let dataView;let restoreMapsAsObject;let defaultOptions={useRecords:false,mapsAsObjects:true};let sequentialMode=false;let inlineObjectReadThreshold=2;try{new Function("")}catch(e){inlineObjectReadThreshold=Infinity}class Decoder{constructor(r){if(r){if((r.keyMap||r._keyMap)&&!r.useRecords){r.useRecords=false;r.mapsAsObjects=true}if(r.useRecords===false&&r.mapsAsObjects===undefined)r.mapsAsObjects=true;if(r.getStructures)r.getShared=r.getStructures;if(r.getShared&&!r.structures)(r.structures=[]).uninitialized=true;if(r.keyMap){this.mapKey=new Map;for(let[e,t]of Object.entries(r.keyMap))this.mapKey.set(t,e)}}Object.assign(this,r)}decodeKey(e){return this.keyMap?this.mapKey.get(e)||e:e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(r){if(!this._keyMap)return r;let n=new Map;for(let[e,t]of Object.entries(r))n.set(this._keyMap.hasOwnProperty(e)?this._keyMap[e]:e,t);return n}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let r={};e.forEach((e,t)=>r[safeKey(this._mapKey.has(t)?this._mapKey.get(t):t)]=e);return r}mapDecode(e,t){let r=this.decode(e);if(this._keyMap){switch(r.constructor.name){case"Array":return r.map(e=>this.decodeKeys(e))}}return r}decode(t,e){if(src){return saveState(()=>{clearSource();return this?this.decode(t,e):Decoder.prototype.decode.call(defaultOptions,t,e)})}srcEnd=e>-1?e:t.length;position$1=0;srcStringEnd=0;srcString=null;bundledStrings$1=null;src=t;try{dataView=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){src=null;if(t instanceof Uint8Array)throw e;throw new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Decoder){currentDecoder=this;packedValues=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues);if(this.structures){currentStructures=this.structures;return checkedRead()}else if(!currentStructures||currentStructures.length>0){currentStructures=[]}}else{currentDecoder=defaultOptions;if(!currentStructures||currentStructures.length>0)currentStructures=[];packedValues=null}return checkedRead()}decodeMultiple(r,n){let i,a=0;try{let e=r.length;sequentialMode=true;let t=this?this.decode(r,e):defaultDecoder.decode(r,e);if(n){if(n(t)===false){return}while(position$1=bundledStrings$1.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}position$1=bundledStrings$1.postBundlePosition;bundledStrings$1=null}if(position$1==srcEnd){currentStructures=null;src=null;if(referenceMap)referenceMap=null}else if(position$1>srcEnd){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!sequentialMode){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){clearSource();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function read(){let n=src[position$1++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=src[position$1++];break;case 25:if(i==7){return getFloat16()}n=dataView.getUint16(position$1);position$1+=2;break;case 26:if(i==7){let t=dataView.getFloat32(position$1);if(currentDecoder.useFloat32>2){let e=mult10[(src[position$1]&127)<<1|src[position$1+1]>>7];position$1+=4;return(e*t+(t>0?.5:-.5)>>0)/e}position$1+=4;return t}n=dataView.getUint32(position$1);position$1+=4;break;case 27:if(i==7){let e=dataView.getFloat64(position$1);position$1+=8;return e}if(i>1){if(dataView.getUint32(position$1)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=dataView.getUint32(position$1+4)}else if(currentDecoder.int64AsNumber){n=dataView.getUint32(position$1)*4294967296;n+=dataView.getUint32(position$1+4)}else n=dataView.getBigUint64(position$1);position$1+=8;break;case 31:switch(i){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e=[];let t,r=0;while((t=read())!=STOP_CODE){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(currentDecoder.mapsAsObjects){let e={};if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e[safeKey(currentDecoder.decodeKey(n))]=read();else while((n=read())!=STOP_CODE)e[safeKey(n)]=read();return e}else{if(restoreMapsAsObject){currentDecoder.mapsAsObjects=true;restoreMapsAsObject=false}let e=new Map;if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e.set(currentDecoder.decodeKey(n),read());else while((n=read())!=STOP_CODE)e.set(n,read());return e}case 7:return STOP_CODE;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+n)}}switch(i){case 0:return n;case 1:return~n;case 2:return readBin(n);case 3:if(srcStringEnd>=position$1){return srcString.slice(position$1-srcStringStart,(position$1+=n)-srcStringStart)}if(srcStringEnd==0&&srcEnd<140&&n<32){let e=n<16?shortStringInJS(n):longStringInJS(n);if(e!=null)return e}return readFixedString(n);case 4:let t=new Array(n);for(let e=0;e=BUNDLED_STRINGS_ID){let e=currentStructures[n&8191];if(e){if(!e.read)e.read=createStructureReader(e);return e.read()}if(n<65536){if(n==RECORD_INLINE_ID){let e=readJustLength();let t=read();let r=read();recordDefinition(t,r);let n={};if(currentDecoder.keyMap)for(let t=2;t23){switch(t){case 24:t=src[position$1++];break;case 25:t=dataView.getUint16(position$1);position$1+=2;break;case 26:t=dataView.getUint32(position$1);position$1+=4;break;default:throw new Error("Expected array header, but got "+src[position$1-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(read);r=r.next}if(this.slowReads++>=inlineObjectReadThreshold){let e=this.length==t?this:this.slice(0,t);r=currentDecoder.keyMap?new Function("r","return {"+e.map(e=>currentDecoder.decodeKey(e)).map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(read)}let n={};if(currentDecoder.keyMap)for(let e=0;e64&&decoder)return decoder.decode(src.subarray(position$1,position$1+=e));const r=position$1+e;const n=[];t="";while(position$165535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=fromCharCode.apply(String,n);n.length=0}}if(n.length>0){t+=fromCharCode.apply(String,n)}return t}let fromCharCode=String.fromCharCode;function longStringInJS(t){let r=position$1;let n=new Array(t);for(let e=0;e0){position$1=r;return}n[e]=i}return fromCharCode.apply(String,n)}function shortStringInJS(h){if(h<4){if(h<2){if(h===0)return"";else{let e=src[position$1++];if((e&128)>1){position$1-=1;return}return fromCharCode(e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=2;return}if(h<3)return fromCharCode(e,t);let r=src[position$1++];if((r&128)>0){position$1-=3;return}return fromCharCode(e,t,r)}}else{let f=src[position$1++];let _=src[position$1++];let p=src[position$1++];let d=src[position$1++];if((f&128)>0||(_&128)>0||(p&128)>0||(d&128)>0){position$1-=4;return}if(h<6){if(h===4)return fromCharCode(f,_,p,d);else{let e=src[position$1++];if((e&128)>0){position$1-=5;return}return fromCharCode(f,_,p,d,e)}}else if(h<8){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=6;return}if(h<7)return fromCharCode(f,_,p,d,e,t);let r=src[position$1++];if((r&128)>0){position$1-=7;return}return fromCharCode(f,_,p,d,e,t,r)}else{let u=src[position$1++];let s=src[position$1++];let c=src[position$1++];let l=src[position$1++];if((u&128)>0||(s&128)>0||(c&128)>0||(l&128)>0){position$1-=8;return}if(h<10){if(h===8)return fromCharCode(f,_,p,d,u,s,c,l);else{let e=src[position$1++];if((e&128)>0){position$1-=9;return}return fromCharCode(f,_,p,d,u,s,c,l,e)}}else if(h<12){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=10;return}if(h<11)return fromCharCode(f,_,p,d,u,s,c,l,e,t);let r=src[position$1++];if((r&128)>0){position$1-=11;return}return fromCharCode(f,_,p,d,u,s,c,l,e,t,r)}else{let n=src[position$1++];let i=src[position$1++];let a=src[position$1++];let o=src[position$1++];if((n&128)>0||(i&128)>0||(a&128)>0||(o&128)>0){position$1-=12;return}if(h<14){if(h===12)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o);else{let e=src[position$1++];if((e&128)>0){position$1-=13;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=14;return}if(h<15)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t);let r=src[position$1++];if((r&128)>0){position$1-=15;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t,r)}}}}}function readBin(e){return currentDecoder.copyBuffers?Uint8Array.prototype.slice.call(src,position$1,position$1+=e):src.subarray(position$1,position$1+=e)}let f32Array=new Float32Array(1);let u8Array=new Uint8Array(f32Array.buffer,0,4);function getFloat16(){let t=src[position$1++];let r=src[position$1++];let e=(t&127)>>2;if(e===31){if(r||t&3)return NaN;return t&128?-Infinity:Infinity}if(e===0){let e=((t&3)<<8|r)/(1<<24);return t&128?-e:e}u8Array[3]=t&128|(e>>1)+56;u8Array[2]=(t&7)<<5|r>>3;u8Array[1]=r<<5;u8Array[0]=0;return f32Array[0]}new Array(4096);class Tag{constructor(e,t){this.value=e;this.tag=t}}currentExtensions[0]=e=>{return new Date(e)};currentExtensions[1]=e=>{return new Date(Math.round(e*1e3))};currentExtensions[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-currentExtensions[2](e)};currentExtensions[4]=e=>{return+(e[1]+"e"+e[0])};currentExtensions[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const recordDefinition=(e,t)=>{e=e-57344;let r=currentStructures[e];if(r&&r.isShared){(currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[e]=r}currentStructures[e]=t;t.read=createStructureReader(t)};currentExtensions[LEGACY_RECORD_INLINE_ID]=r=>{let e=r.length;let n=r[1];recordDefinition(r[0],n);let i={};for(let t=2;t{if(bundledStrings$1)return bundledStrings$1[0].slice(bundledStrings$1.position0,bundledStrings$1.position0+=e);return new Tag(e,14)};currentExtensions[15]=e=>{if(bundledStrings$1)return bundledStrings$1[1].slice(bundledStrings$1.position1,bundledStrings$1.position1+=e);return new Tag(e,15)};let glbl={Error:Error,RegExp:RegExp};currentExtensions[27]=e=>{return(glbl[e[0]]||Error)(e[1],e[2])};const packedTable=e=>{if(src[position$1++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(src.length{if(!packedValues){if(currentDecoder.getShared)loadShared();else return new Tag(e,PACKED_REFERENCE_TAG_ID)}if(typeof e=="number")return packedValues[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};currentExtensions[28]=e=>{if(!referenceMap){referenceMap=new Map;referenceMap.id=0}let t=referenceMap.id++;let r=src[position$1];let n;if(r>>5==4)n=[];else n={};let i={target:n};referenceMap.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};currentExtensions[28].handlesRead=true;currentExtensions[29]=e=>{let t=referenceMap.get(e);t.used=true;return t.target};currentExtensions[258]=e=>new Set(e);(currentExtensions[259]=e=>{if(currentDecoder.mapsAsObjects){currentDecoder.mapsAsObjects=false;restoreMapsAsObject=true}return e()}).handlesRead=true;function combine(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function getPackedValues(){if(!packedValues){if(currentDecoder.getShared)loadShared();else throw new Error("No packed values available")}return packedValues}const SHARED_DATA_TAG_ID=1399353956;currentExtensionRanges.push((e,t)=>{if(e>=225&&e<=255)return combine(getPackedValues().prefixes[e-224],t);if(e>=28704&&e<=32767)return combine(getPackedValues().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return combine(getPackedValues().prefixes[e-1879048192],t);if(e>=216&&e<=223)return combine(t,getPackedValues().suffixes[e-216]);if(e>=27647&&e<=28671)return combine(t,getPackedValues().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return combine(t,getPackedValues().suffixes[e-1811939328]);if(e==SHARED_DATA_TAG_ID){return{packedValues:packedValues,structures:currentStructures.slice(0),version:t}}if(e==55799)return t});const isLittleEndianMachine$1=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;const typedArrays=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array=="undefined"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array=="undefined"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array];const typedArrayTags=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e{if(!u)throw new Error("Could not find typed array for code "+s);if(!currentDecoder.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new u(e.buffer,e.byteOffset,e.byteLength)}return new u(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!u)throw new Error("Could not find typed array for code "+s);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=e.length>>a;let n=new u(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=src[position$1++];break;case 25:e=dataView.getUint16(position$1);position$1+=2;break;case 26:e=dataView.getUint32(position$1);position$1+=4;break}}return e}function loadShared(){if(currentDecoder.getShared){let e=saveState(()=>{src=null;return currentDecoder.getShared()})||{};let t=e.structures||[];currentDecoder.sharedVersion=e.version;packedValues=currentDecoder.sharedValues=e.packedValues;if(currentStructures===true)currentDecoder.structures=currentStructures=t;else currentStructures.splice.apply(currentStructures,[0,t.length].concat(t))}}function saveState(e){let t=srcEnd;let r=position$1;let n=srcStringStart;let i=srcStringEnd;let a=srcString;let o=referenceMap;let u=bundledStrings$1;let s=new Uint8Array(src.slice(0,srcEnd));let c=currentStructures;let l=currentDecoder;let f=sequentialMode;let _=e();srcEnd=t;position$1=r;srcStringStart=n;srcStringEnd=i;srcString=a;referenceMap=o;bundledStrings$1=u;src=s;sequentialMode=f;currentStructures=c;currentDecoder=l;dataView=new DataView(src.buffer,src.byteOffset,src.byteLength);return _}function clearSource(){src=null;referenceMap=null;currentStructures=null}function addExtension$1(e){currentExtensions[e.tag]=e.decode}const mult10=new Array(147);for(let e=0;e<256;e++){mult10[e]=+("1e"+Math.floor(45.15-e*.30103))}let defaultDecoder=new Decoder({useRecords:false});defaultDecoder.decode;defaultDecoder.decodeMultiple;let textEncoder;try{textEncoder=new TextEncoder}catch(e){}let extensions,extensionClasses;const Buffer$1=typeof globalThis==="object"&&globalThis.Buffer;const hasNodeBuffer=typeof Buffer$1!=="undefined";const ByteArrayAllocate=hasNodeBuffer?Buffer$1.allocUnsafeSlow:Uint8Array;const ByteArray=hasNodeBuffer?Buffer$1:Uint8Array;const MAX_STRUCTURES=256;const MAX_BUFFER_SIZE=hasNodeBuffer?4294967296:2144337920;let throwOnIterable;let target;let targetView;let position=0;let safeEnd;let bundledStrings=null;const MAX_BUNDLE_SIZE=61440;const hasNonLatin=/[\u0080-\uFFFF]/;const RECORD_SYMBOL=Symbol("record-id");class Encoder extends Decoder{constructor(r){super(r);this.offset=0;let s;let o;let l;let f;let n;r=r||{};let c=ByteArray.prototype.utf8Write?function(e,t,r){return target.utf8Write(e,t,r)}:textEncoder&&textEncoder.encodeInto?function(e,t){return textEncoder.encodeInto(e,target.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let _=r.maxSharedStructures;if(_==null)_=e?128:0;if(_>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){_=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let p,d,u=r.sharedValues;let h;if(u){h=Object.create(null);for(let e=0,t=u.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!target){target=new ByteArrayAllocate(8192);targetView=new DataView(target.buffer,0,8192);position=0}safeEnd=target.length-10;if(safeEnd-position<2048){target=new ByteArrayAllocate(target.length);targetView=new DataView(target.buffer,0,target.length);safeEnd=target.length-10;position=0}else if(e===REUSE_BUFFER_MODE)position=position+7&2147483640;s=position;if(a.useSelfDescribedHeader){targetView.setUint32(position,3654940416);position+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){bundledStrings=[];bundledStrings.size=Infinity}else bundledStrings=null;o=a.structures;if(o){if(o.uninitialized){let e=a.getShared()||{};a.structures=o=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){h={};for(let e=0,t=r.length;e_&&!i)e=_;if(!o.transitions){o.transitions=Object.create(null);for(let a=0;a0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;b(r);writeArrayHeader(0);writeArrayHeader(0);d=Object.create(h||null);for(let e=0,t=r.length;esafeEnd)w(position);a.offset=position;let e=insertIds(target.subarray(s,position),n.idsToInsert);n=null;return e}if(e&REUSE_BUFFER_MODE){target.start=s;target.end=position;return target}return target.subarray(s,position)}finally{if(o){if(v<10)v++;if(o.length>_)o.length=_;if(y>1e4){o.transitions=null;v=0;y=0;if(m.length>0)m=[]}else if(m.length>0&&!i){for(let e=0,t=m.length;e_){a.structures=a.structures.slice(0,_)}let e=target.subarray(s,position);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&RESET_BUFFER_MODE)position=s}};this.findCommonStringsToPack=()=>{p=new Map;if(!h)h=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!u)u=this.sharedValues=[];for(let[e,t]of p){if(t.count>r){h[e]=n++;u.push(e);l=true}}while(this.saveShared&&this.updateSharedData()===false){}p=null}};const b=o=>{if(position>safeEnd)target=w(position);var e=typeof o;var u;if(e==="string"){if(d){let e=d[o];if(e>=0){if(e<16)target[position++]=e+224;else{target[position++]=198;if(e&1)b(15-e>>1);else b(e-16>>1)}return}else if(p&&!r.pack){let e=p.get(o);if(e)e.count++;else p.set(o,{count:1})}}let i=o.length;if(bundledStrings&&i>=4&&i<1024){if((bundledStrings.size+=i)>MAX_BUNDLE_SIZE){let e;let t=(bundledStrings[0]?bundledStrings[0].length*3+bundledStrings[1].length:0)+10;if(position+t>safeEnd)target=w(position+t);target[position++]=217;target[position++]=223;target[position++]=249;target[position++]=bundledStrings.position?132:130;target[position++]=26;e=position-s;position+=4;if(bundledStrings.position){writeBundles(s,b)}bundledStrings=["",""];bundledStrings.size=0;bundledStrings.position=e}let e=hasNonLatin.test(o);bundledStrings[e?0:1]+=o;target[position++]=e?206:207;b(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(position+e>safeEnd)target=w(position+e);if(i<64||!c){let e,t,r,n=position+a;for(e=0;e>6|192;target[n++]=t&63|128}else if((t&64512)===55296&&((r=o.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;target[n++]=t>>18|240;target[n++]=t>>12&63|128;target[n++]=t>>6&63|128;target[n++]=t&63|128}else{target[n++]=t>>12|224;target[n++]=t>>6&63|128;target[n++]=t&63|128}}u=n-position-a}else{u=c(o,position+a,e)}if(u<24){target[position++]=96|u}else if(u<256){if(a<2){target.copyWithin(position+2,position+1,position+1+u)}target[position++]=120;target[position++]=u}else if(u<65536){if(a<3){target.copyWithin(position+3,position+2,position+2+u)}target[position++]=121;target[position++]=u>>8;target[position++]=u&255}else{if(a<5){target.copyWithin(position+5,position+3,position+3+u)}target[position++]=122;targetView.setUint32(position,u);position+=4}position+=u}else if(e==="number"){if(!this.alwaysUseFloat&&o>>>0===o){if(o<24){target[position++]=o}else if(o<256){target[position++]=24;target[position++]=o}else if(o<65536){target[position++]=25;target[position++]=o>>8;target[position++]=o&255}else{target[position++]=26;targetView.setUint32(position,o);position+=4}}else if(!this.alwaysUseFloat&&o>>0===o){if(o>=-24){target[position++]=31-o}else if(o>=-256){target[position++]=56;target[position++]=~o}else if(o>=-65536){target[position++]=57;targetView.setUint16(position,~o);position+=2}else{target[position++]=58;targetView.setUint32(position,~o);position+=4}}else{let t;if((t=this.useFloat32)>0&&o<4294967296&&o>=-2147483648){target[position++]=250;targetView.setFloat32(position,o);let e;if(t<4||(e=o*mult10[(target[position]&127)<<1|target[position+1]>>7])>>0===e){position+=4;return}else position--}target[position++]=251;targetView.setFloat64(position,o);position+=8}}else if(e==="object"){if(!o)target[position++]=246;else{if(n){let t=n.get(o);if(t){target[position++]=216;target[position++]=29;target[position++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(position-s);position+=2;return}else n.set(o,{offset:position-s})}let e=o.constructor;if(e===Object){g(o,true)}else if(e===Array){u=o.length;if(u<24){target[position++]=128|u}else{writeArrayHeader(u)}for(let e=0;e>8;target[position++]=u&255}else{target[position++]=186;targetView.setUint32(position,u);position+=4}if(a.keyMap){for(let[e,t]of o){b(a.encodeKey(e));b(t)}}else{for(let[e,t]of o){b(e);b(t)}}}else{for(let r=0,e=extensions.length;r>8;target[position++]=t&255}else if(t>-1){target[position++]=218;targetView.setUint32(position,t);position+=4}e.encode.call(this,o,b,w);return}}if(o[Symbol.iterator]){if(throwOnIterable){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}target[position++]=159;for(let e of o){b(e)}target[position++]=255;return}if(o[Symbol.asyncIterator]||isBlob(o)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&o.toJSON){const t=o.toJSON();if(t!==o)return b(t)}g(o,!o.hasOwnProperty)}}}else if(e==="boolean"){target[position++]=o?245:244}else if(e==="bigint"){if(o=0){target[position++]=27;targetView.setBigUint64(position,o)}else if(o>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){target[position++]=160|n}else if(n<256){target[position++]=184;target[position++]=n}else if(n<65536){target[position++]=185;target[position++]=n>>8;target[position++]=n&255}else{target[position++]=186;targetView.setUint32(position,n);position+=4}if(a.keyMap){for(let e=0;e{target[position++]=185;let e=position-s;position+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){b(a.encodeKey(e));b(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){b(e);b(t[e]);n++}}target[e+++s]=n>>8;target[e+s]=n&255}:(t,r)=>{let n,i=f.transitions||(f.transitions=Object.create(null));let a=0;let o=0;let u;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));o=s.length;for(let t=0;t>8|224;target[position++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(u===undefined){c=f.nextId++;if(!c){c=0;f.nextId=1}if(c>=MAX_STRUCTURES){f.nextId=(c=_)+1}}else{c=u}f[c]=s;if(c<_){target[position++]=217;target[position++]=c>>8|224;target[position++]=c&255;i=f.transitions;for(let e=0;e=MAX_STRUCTURES-_)m.shift()[RECORD_SYMBOL]=undefined;m.push(i);writeArrayHeader(o+2);b(57344+c);b(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e]);return}}if(o<24){target[position++]=128|o}else{writeArrayHeader(o)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>MAX_BUFFER_SIZE)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,target.length-1)>>12)+1<<12;let r=new ByteArrayAllocate(t);targetView=new DataView(r.buffer,0,t);if(target.copy)target.copy(r,0,s,e);else r.set(target.slice(s,e));position-=s;s=0;safeEnd=r.length-10;return target=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return A(e,t,L)};this.encodeAsAsyncIterable=function(e,t){return A(e,t,F)};function*L(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)g(n,null);else writeEntityLength(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)b(t);if(e&&typeof e==="object"){if(i[t])yield*L(e,i[t]);else yield*E(e,i,t)}else b(e)}}else if(t===Array){let e=n.length;writeArrayHeader(e);for(let t=0;tD)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}}else if(n[Symbol.iterator]){target[position++]=159;for(let e of n){if(e&&(typeof e==="object"||position-s>D)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}target[position++]=255}else if(isBlob(n)){writeEntityLength(n.size,64);yield target.subarray(s,position);yield n;S()}else if(n[Symbol.asyncIterator]){target[position++]=159;yield target.subarray(s,position);yield n;S();target[position++]=255}else{b(n)}if(e&&position>s)yield target.subarray(s,position);else if(position-s>D){yield target.subarray(s,position);S()}}function*E(t,r,n){let i=position-s;try{b(t);if(position-s>D){yield target.subarray(s,position);S()}}catch(e){if(e.iteratorNotHandled){r[n]={};position=s+i;yield*L.call(this,t,r[n])}else throw e}}function S(){D=x;a.encode(null,THROW_ON_ITERABLE)}function A(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,THROW_ON_ITERABLE);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*F(e,t){for(let r of L(e,t,true)){let e=r.constructor;if(e===ByteArray||e===Uint8Array)yield r;else if(isBlob(r)){let e=r.stream().getReader();let t;while(!(t=await e.read()).done){yield t.value}}else if(r[Symbol.asyncIterator]){for await(let e of r){S();if(e)yield*F(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){target=e;targetView=new DataView(target.buffer,target.byteOffset,target.byteLength);position=0}clearSharedData(){if(this.structures)this.structures=[];if(this.sharedValues)this.sharedValues=undefined}updateSharedData(){let t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new SharedData(e,this.sharedValues,this.sharedVersion);let n=this.saveShared(r,e=>(e&&e.version||0)==t);if(n===false){r=this.getShared()||{};this.structures=r.structures||[];this.sharedValues=r.packedValues;this.sharedVersion=r.version;this.structures.nextId=this.structures.length}else{e.forEach((e,t)=>this.structures[t]=e)}return n}}function writeEntityLength(e,t){if(e<24)target[position++]=t|e;else if(e<256){target[position++]=t|24;target[position++]=e}else if(e<65536){target[position++]=t|25;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=t|26;targetView.setUint32(position,e);position+=4}}class SharedData{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function writeArrayHeader(e){if(e<24)target[position++]=128|e;else if(e<256){target[position++]=152;target[position++]=e}else if(e<65536){target[position++]=153;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=154;targetView.setUint32(position,e);position+=4}}const BlobConstructor=typeof Blob==="undefined"?function(){}:Blob;function isBlob(e){if(e instanceof BlobConstructor)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function findRepetitiveStrings(r,n){switch(typeof r){case"string":if(r.length>3){if(n.objectMap[r]>-1||n.values.length>=n.maxValues)return;let e=n.get(r);if(e){if(++e.count==2){n.values.push(r)}}else{n.set(r,{count:1});if(n.samplingPackedValues){let e=n.samplingPackedValues.get(r);if(e)e.count++;else n.samplingPackedValues.set(r,{count:1})}}}break;case"object":if(r){if(r instanceof Array){for(let e=0,t=r.length;e=0&&r<4294967296){target[position++]=26;targetView.setUint32(position,r);position+=4}else{target[position++]=251;targetView.setFloat64(position,r);position+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,r){writeBuffer(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||hasNodeBuffer&&this.tagUint8Array!==false)return 64}},encode(e,t,r){writeBuffer(e,r)}},typedArrayEncoder(68,1),typedArrayEncoder(69,2),typedArrayEncoder(70,4),typedArrayEncoder(71,8),typedArrayEncoder(72,1),typedArrayEncoder(77,2),typedArrayEncoder(78,4),typedArrayEncoder(79,8),typedArrayEncoder(85,4),typedArrayEncoder(86,8),{encode(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;n(r);writeArrayHeader(0);writeArrayHeader(0);packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let e=0,t=r.length;e1)e-=4;return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let a=t.buffer||t;r(hasNodeBuffer?Buffer$1.from(a,i,n):new Uint8Array(a,i,n))}}}function writeBuffer(e,t){let r=e.byteLength;if(r<24){target[position++]=64+r}else if(r<256){target[position++]=88;target[position++]=r}else if(r<65536){target[position++]=89;target[position++]=r>>8;target[position++]=r&255}else{target[position++]=90;targetView.setUint32(position,r);position+=4}if(position+r>=target.length){t(position+r)}target.set(e.buffer?e:new Uint8Array(e),position);position+=r}function insertIds(n,e){let r;let i=e.length*2;let a=n.length-i;e.sort((e,t)=>e.offset>t.offset?1:-1);for(let r=0;r>8;n[e]=r&255}}while(r=e.pop()){let e=r.offset;n.copyWithin(e+i,e,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function writeBundles(e,t){targetView.setUint32(bundledStrings.position+e,position-bundledStrings.position-e+1);let r=bundledStrings;bundledStrings=null;t(r[0]);t(r[1])}function addExtension(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");extensionClasses.unshift(e.Class);extensions.unshift(e)}addExtension$1(e)}let defaultEncoder=new Encoder({useRecords:false});defaultEncoder.encode;defaultEncoder.encodeAsIterable;defaultEncoder.encodeAsAsyncIterable;const REUSE_BUFFER_MODE=512;const RESET_BUFFER_MODE=1024;const THROW_ON_ITERABLE=2048;var lzjbPack={}; /**@license * * No Dependency fast and small LZJB Compression for Browser and Node @@ -42,4 +42,4 @@ function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.v * Released under BSD-3-Clause License * * build: Wed, 27 Oct 2021 10:43:10 GMT - */Object.defineProperty(lzjbPack,"__esModule",{value:true});const NBBY=8,MATCH_BITS=6,MATCH_MIN=3,MATCH_MAX=(1<r-MATCH_MAX){t[i++]=e[n++];continue}l=(e[n]+13^e[n+1]-13^e[n+2])&LEMPEL_SIZE-1;c=n-f[l]&OFFSET_MASK;f[l]=n;a=n-c;if(a>=0&&a!=n&&e[n]==e[a]&&e[n+1]==e[a+1]&&e[n+2]==e[a+2]){t[o]|=u;for(s=MATCH_MIN;s>NBBY;t[i++]=c;n+=s}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function decompress(e,t,r){t=t|0;var n=0,i=0,a=0,o=0,u=1<<(NBBY-1|0),s=0,c=0;while(n>(NBBY-MATCH_BITS|0))+MATCH_MIN|0;c=(e[n]<4){r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;s=s-4|0}while(s>0){r[i]=r[a];i=i+1|0;a=a+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function encode_magic$1(){const e=new TextEncoder("utf-8");return e.encode(MAGIC_STRING)}const MAGIC_STRING="@lzjb";const MAGIC=encode_magic$1();function merge_uint8_array$1(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function number_to_bytes(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function pack(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=compress(e,r);const i=number_to_bytes(e.length);const a=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){a.unshift(MAGIC)}return merge_uint8_array$1(...a)}function unpack(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,MAGIC.length));if(s!==MAGIC_STRING){throw new Error("Invalid magic value")}}const r=e?MAGIC.length:0;const n=t[r];const i=r+1;const a=r+n+1;const o=bytes_to_number(t.slice(i,a));t=t.slice(a);const u=new Uint8Array(o);decompress(t,t.length,u);return u}var pack_1=lzjbPack.pack=pack;var unpack_1=lzjbPack.unpack=unpack;function unfetch(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],a={},o=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:o,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var u in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),a[t]=a[t]?a[t]+","+r:r}),e(o())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(u,c.headers[u]);r.send(c.body||null)})}var _excluded=["token"],_excluded2=["env"],_excluded3=["stderr","stdin","stdout","command_line"],_excluded4=["use_dynamic"],_excluded5=["use_dynamic"],_excluded6=["env","dynamic_env","use_dynamic","error"];function _classPrivateFieldInitSpec(e,t,r){_checkPrivateRedeclaration(e,t);t.set(e,r)}function _checkPrivateRedeclaration(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}function _callSuper(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function e(){return!!t})()}function _createForOfIteratorHelper(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=_unsupportedIterableToArray(t))||e&&t&&typeof t.length==="number"){if(r)t=r;var n=0;var i=function e(){};return{s:i,n:function e(){if(n>=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a=true,o=false,u;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();a=t.done;return t},e:function e(t){o=true;u=t},f:function e(){try{if(!a&&r["return"]!=null)r["return"]()}finally{if(o)throw u}}}}function _unsupportedIterableToArray(e,t){if(!e)return;if(typeof e==="string")return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _arrayLikeToArray(e,t)}function _arrayLikeToArray(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1?r-1:0),i=1;i0&&arguments[0]!==undefined?arguments[0]:null;var t=user_env&&user_env.get("DEBUG",{throwError:false});if(e===null){return t===true}return(t===null||t===void 0?void 0:t.valueOf())===e.valueOf()}function num_mnemicic_re(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function gen_rational_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+/").concat(t,"+")}function gen_complex_re(e,t){return"".concat(num_mnemicic_re(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function gen_integer_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+")}var re_re=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var float_stre="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var complex_float_stre="(?:#[ie])?(?:[+-]?(?:[0-9][0-9_]*/[0-9][0-9_]*|nan.0|inf.0|".concat(float_stre,"|[+-]?[0-9]+))?(?:").concat(float_stre,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var float_re=new RegExp("^(#[ie])?".concat(float_stre,"$"),"i");function make_complex_match_re(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var complex_list_re=function(){var a={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];a[r]=make_complex_match_re(n,i)});return a}();var characters={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function ucs2decode(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);var n=r.number.split("/");var i=LRational({num:LNumber([n[0],r.radix||t]),denom:LNumber([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function parse_integer(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);if(r.inexact){return LFloat(parseInt(r.number,r.radix||t))}return LNumber([r.number,r.radix||t])}function parse_character(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\([\s\S]+)$/);if(t){r=t[1]}}if(r){return LCharacter(r)}throw new Error("Parse: invalid character")}function parse_complex(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=LNumber(1)}else if(e==="-"){t=LNumber(-1)}else if(e.match(int_bare_re)){t=LNumber([e,i])}else if(e.match(rational_bare_re)){var r=e.split("/");t=LRational({num:LNumber([r[0],i]),denom:LNumber([r[1],i])})}else if(e.match(float_re)){var n=parse_float(e);if(a.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return LNumber(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return LNumber(Number.NEGATIVE_INFINITY)}return LNumber(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(a.inexact){return LFloat(t.valueOf())}return t}var a=num_pre_parse(e);i=a.radix||i;var r;var n=a.number.match(complex_bare_match_re);if(i!==10&&n){r=n}else{r=a.number.match(complex_list_re[i])}var o,u;u=t(r[2]);if(r[1]){o=t(r[1])}else if(u instanceof LFloat){o=LFloat(0)}else{o=LNumber(0)}if(u.cmp(0)===0&&u.__type__==="bigint"){return o}return LComplex({im:u,re:o})}function is_int(e){return parseInt(e.toString(),10)===e}function parse_big_int(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var a=t[3]&&t[3].length;if(i0&&(t.exact||!t.number.match(/\./))){return LNumber(a).mul(u)}}}r=LFloat(r);if(t.exact){return r.toRational()}return r}function parse_string(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{var r=LString(JSON.parse(e));r.freeze();return r}catch(e){var n=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(n))}}function parse_symbol(e){if(e.match(/^\|.*\|$/)){e=e.replace(/(^\|)|(\|$)/g,"");var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\(.)/g,function(e,t){return r[t]||t})}return new LSymbol(e)}function parse_argument(e){if(constants.hasOwnProperty(e)){return constants[e]}if(e.match(/^"[\s\S]*"$/)){return parse_string(e)}else if(e[0]==="#"){var t=e.match(re_re);if(t){return new RegExp(t[1],t[2])}else if(e.match(char_re)){return parse_character(e)}var r=e.match(/#\\(.+)/);if(r&&ucs2decode(r[1]).length===1){return parse_character(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(int_re)){return parse_integer(e)}else if(e.match(float_re)){return parse_float(e)}else if(e.match(rational_re)){return parse_rational(e)}else if(e.match(complex_re)){return parse_complex(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return parse_symbol(e)}function is_atom_string(e){return!(["(",")","[","]"].includes(e)||specials.names().includes(e))}function is_symbol_string(e){return is_atom_string(e)&&!(e.match(re_re)||e.match(/^"[\s\S]*"$/)||e.match(int_re)||e.match(float_re)||e.match(complex_re)||e.match(rational_re)||e.match(char_re)||["#t","#f","nil"].includes(e))}var string_re=/"(?:\\[\S\s]|[^"])*"?/g;function escape_regex(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function Stack(){this.data=[]}Stack.prototype.push=function(e){this.data.push(e)};Stack.prototype.top=function(){return this.data[this.data.length-1]};Stack.prototype.pop=function(){return this.data.pop()};Stack.prototype.is_empty=function(){return!this.data.length};function tokens(e){if(e instanceof LString){e=e.valueOf()}var t=new Lexer(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===eof){break}r.push(n);t.skip()}return r}function multiline_formatter(e){var t=e.token,r=_objectWithoutProperties(e,_excluded);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return _objectSpread({token:t},r)}function Thunk(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}Thunk.prototype.toString=function(){return"#"};function trampoline(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof LString){e=e.toString()}if(t){return tokens(e)}else{var r=tokens(e).map(function(e){if(e.token==="#\\ "||e.token=="#\\\n"){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return strip_s_comments(r)}}function strip_s_comments(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof LSymbol){if(e.is_gensym()){return e}e=e.valueOf()}if(is_gensym(e)){return LSymbol(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function QuotedPromise(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=type(e);n.fulfilled=true;n.pending=false;return e});read_only(this,"_promise",e,{hidden:true});if(is_function(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});read_only(this,"__promise__",e);this.then=false}QuotedPromise.prototype.then=function(e){return new QuotedPromise(this.valueOf().then(e))};QuotedPromise.prototype["catch"]=function(e){return new QuotedPromise(this.valueOf()["catch"](e))};QuotedPromise.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};QuotedPromise.prototype.toString=function(){if(this.__pending__){return QuotedPromise.pending_str}if(this.__rejected__){return QuotedPromise.rejected_str}return"#")};QuotedPromise.pending_str="#";QuotedPromise.rejected_str="#";function promise_all(e){if(Array.isArray(e)){return Promise.all(escape_quoted_promises(e)).then(unescape_quoted_promises)}return e}function escape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof QuotedPromise){t[r]=new Value(n)}else{t[r]=n}}return t}function unescape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Value){t[r]=n.valueOf()}else{t[r]=n}}return t}var specials={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){try{return this.get(t).type}catch(e){console.log({name:t});console.log(e);return null}},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new LSymbol("quote-promise"),specials.LITERAL]];var builtins=defined_specials.map(function(e){return e[0]});Object.freeze(builtins);Object.defineProperty(specials,"__builtins__",{writable:false,value:builtins});defined_specials.forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];specials.append(r,n,i)});var Lexer=function(){function v(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;_classCallCheck(this,v);read_only(this,"__input__",e.replace(/\r/g,""));var a={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return a[r]},set:function e(t){a[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}_createClass(v,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return eof}if(this._token){read_only(this,"__token__",this.token(true));return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);return this.token(t)}return eof}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return eof}for(var r=this._i;r=r){return eof}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var a=i.match(/\n/g);if(a){this._line+=a.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return eof}return LCharacter(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},n=r.prev_char,i=r["char"],a=r.next_char;var o=_slicedToArray(t,4),u=o[0],s=o[1],c=o[2],l=o[3];if(t.length!==5){throw new Error("Lexer: Invalid rule of length ".concat(t.length))}if(is_string(u)){if(u!==i){return false}}else if(!i.match(u)){return false}if(!match_or_null(s,n)){return false}if(!match_or_null(c,a)){return false}if(l!==this._state){return false}return true}},{key:"next_token",value:function e(){if(this._i>=this.__input__.length){return false}var t=true;e:for(var r=this._i,n=this.__input__.length;r2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var a=[];for(var o=0,u=t.length;o0&&arguments[0]!==undefined?arguments[0]:{},t=e.env,r=e.meta,n=r===void 0?false:r,i=e.formatter,a=i===void 0?multiline_formatter:i;_classCallCheck(this,o);read_only(this,"_formatter",a,{hidden:true});read_only(this,"__env__",t);read_only(this,"_meta",n,{hidden:true});read_only(this,"_refs",[],{hidden:true});read_only(this,"_state",{parentheses:0,fold_case:false},{hidden:true})}_createClass(o,[{key:"_with_syntax_scope",value:function e(t){var r=this;var n=get_internal(this.__env__);var i=n.get("stdin");this.__env__.set("lips",_objectSpread(_objectSpread({},lips),{},{__parser__:this}));n.set("stdin",new ParserInputPort(this,this.__env__));var a=function e(){r.__env__.set("lips",lips);n.set("stdin",i)};return unpromise(t(),function(e){a();return e},a)}},{key:"parse",value:function e(t){if(t instanceof LString){t=t.toString()}read_only(this,"__lexer__",new Lexer(t))}},{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===eof)){t.next=4;break}return t.abrupt("return",eof);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!is_directive(r.token)){t.next=11;break}this.skip();if(r.token==="#!fold-case"){this._state.fold_case=true}else if(r.token==="#!no-fold-case"){this._state.fold_case=false}return t.abrupt("continue",0);case 11:if(!(r.token==="#;")){t.next=18;break}this.skip();if(!(this.__lexer__.peek()===eof)){t.next=15;break}throw new Error("Lexer: syntax error eof found after comment");case 15:t.next=17;return this._read_object();case 17:return t.abrupt("continue",0);case 18:return t.abrupt("break",21);case 21:r=this._formatter(r);if(this._state.fold_case){r.token=foldcase_string(r.token)}if(!this._meta){t.next=25;break}return t.abrupt("return",r);case 25:return t.abrupt("return",r.token);case 26:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){return["(","["].includes(t)}},{key:"is_close",value:function e(t){return[")","]"].includes(t)}},{key:"read_list",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r,n,i,a,o,u;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=_nil,n=r;case 1:t.next=4;return this.peek();case 4:a=t.sent;if(!(a===eof)){t.next=7;break}return t.abrupt("break",31);case 7:if(!this.is_close(a)){t.next=11;break}--this._state.parentheses;this.skip();return t.abrupt("break",31);case 11:if(!(a==="."&&!is_nil(r))){t.next=19;break}this.skip();t.next=15;return this._read_object();case 15:n.cdr=t.sent;i=true;t.next=29;break;case 19:if(!i){t.next=23;break}throw new Error("Parser: syntax error more than one element after dot");case 23:t.next=25;return this._read_object();case 25:o=t.sent;u=new Pair(o,_nil);if(is_nil(r)){r=u}else{n.cdr=u}n=u;case 29:t.next=1;break;case 31:return t.abrupt("return",r);case 32:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===eof)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",parse_argument(r));case 6:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return _evaluate(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof DatumReference){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",unpromise(this._resolve_object(r),function(e){if(is_pair(e)){e.mark_cycles()}return e}));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"balanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t,r){var n=this._state.parentheses;var i;if(n<0){i=new Error("Parser: unexpected parenthesis");i.__code__=[r.toString()+")"]}else{i=new Error("Parser: expected parenthesis but eof found");var a=new RegExp("\\){".concat(n,"}$"));i.__code__=[t.toString().replace(a,"")]}throw i}},{key:"_resolve_object",value:function(){var t=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n=this;var i;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!is_plain_object(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!is_pair(r)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!is_pair(r)){t.next=15;break}if(!(r.car instanceof DatumReference)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof DatumReference)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r=this;var n,i,a,o,u,s,c,l,f,_,p,d;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:n=t.sent;if(!(n===eof)){t.next=5;break}return t.abrupt("return",n);case 5:if(!is_special(n)){t.next=51;break}i=specials.get(n);a=is_builtin(n);this.skip();s=is_symbol_extension(n);t.t0=this;t.next=13;return this.peek();case 13:t.t1=t.sent;c=t.t0.is_close.call(t.t0,t.t1);if(!s){t.next=19;break}t.t2=undefined;t.next=22;break;case 19:t.next=21;return this._read_object();case 21:t.t2=t.sent;case 22:l=t.t2;if(!(l===eof)){t.next=25;break}throw new Unterminated("Expecting expression eof found");case 25:if(a){t.next=32;break}u=this.__env__.get(i.symbol);if(!(typeof u==="function")){t.next=32;break}if(is_literal(n)){f=[l]}else if(is_nil(l)){f=[]}else if(is_pair(l)){f=l.to_array(false)}if(!(f||s)){t.next=31;break}return t.abrupt("return",this._with_syntax_scope(function(){return call_function(u,s?[]:f,{env:r.__env__,dynamic_env:r.__env__,use_dynamic:false})}));case 31:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(i.symbol));case 32:if(!is_literal(n)){t.next=38;break}if(!c){t.next=35;break}throw new Error("Parse Error: expecting datum");case 35:o=new Pair(i.symbol,new Pair(l,_nil));t.next=39;break;case 38:o=new Pair(i.symbol,l);case 39:if(!a){t.next=41;break}return t.abrupt("return",o);case 41:if(!(u instanceof Macro)){t.next=50;break}t.next=44;return this._with_syntax_scope(function(){return r.evaluate(o)});case 44:_=t.sent;if(!(is_pair(_)||_ instanceof LSymbol)){t.next=47;break}return t.abrupt("return",Pair.fromArray([LSymbol("quote"),_]));case 47:return t.abrupt("return",_);case 50:throw new Error("Parse Error: invalid parser extension: "+i.symbol);case 51:p=this.match_datum_ref(n);if(!(p!==null)){t.next=57;break}this.skip();if(!this._refs[p]){t.next=56;break}return t.abrupt("return",new DatumReference(p,this._refs[p]));case 56:throw new Error("Parse Error: invalid datum label #".concat(p,"#"));case 57:d=this.match_datum_label(n);if(!(d!==null)){t.next=64;break}this.skip();this._refs[d]=this._read_object();return t.abrupt("return",this._refs[d]);case 64:if(!this.is_close(n)){t.next=69;break}--this._state.parentheses;this.skip();t.next=76;break;case 69:if(!this.is_open(n)){t.next=75;break}++this._state.parentheses;this.skip();return t.abrupt("return",this.read_list());case 75:return t.abrupt("return",this.read_value());case 76:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return o}();var Unterminated=function(e){_inherits(t,e);function t(){_classCallCheck(this,t);return _callSuper(this,t,arguments)}return _createClass(t)}(_wrapNativeSuper(Error));Parser.Unterminated=Unterminated;var DatumReference=function(){function r(e,t){_classCallCheck(this,r);this.name=e;this.data=t}_createClass(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function _parse(e,t){return _parse2.apply(this,arguments)}function _parse2(){_parse2=_wrapAsyncGenerator(_regeneratorRuntime.mark(function e(r,n){var i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!n){if(global_env){n=global_env.get("**interaction-environment**",{throwError:false})}else{n=user_env}}if(r instanceof Parser){i=r}else{i=new Parser({env:n});i.parse(r)}case 2:t.next=5;return _awaitAsyncGenerator(i.read_object());case 5:o=t.sent;if(!i.balanced()){i.ballancing_error(o,a)}if(!(o===eof)){t.next=9;break}return t.abrupt("break",14);case 9:a=o;t.next=12;return o;case 12:t.next=2;break;case 14:case"end":return t.stop()}},e)}));return _parse2.apply(this,arguments)}function unpromise(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(is_promise(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return unpromise_array(e,t,r)}if(is_plain_object(e)){return unpromise_object(e,t,r)}return t(e)}function unpromise_array(t,r,e){if(t.find(is_promise)){return unpromise(promise_all(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function unpromise_object(t,e,r){var i=Object.keys(t);var n=[],a=[];var o=i.length;while(o--){var u=i[o];var s=t[u];n[o]=s;if(is_promise(s)){a.push(s)}}if(a.length){return unpromise(promise_all(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function read_only(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,a=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!a})}function uniterate_async(e){return _uniterate_async.apply(this,arguments)}function _uniterate_async(){_uniterate_async=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n,i,a,o,u,s,c;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:n=[];i=false;a=false;t.prev=3;u=_asyncIterator(r);case 5:t.next=7;return u.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);a=true;o=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&u["return"]!=null)){t.next=24;break}t.next=24;return u["return"]();case 24:t.prev=24;if(!a){t.next=27;break}throw o;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}},e,null,[[3,15,19,29],[20,,24,28]])}));return _uniterate_async.apply(this,arguments)}function matcher(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(is_function(t)){return t}throw new Error("Invalid matcher")}function doc(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=trim_lines(r)}}if(e){t.__name__=e}else if(t.name&&!is_lambda(t)){t.__name__=t.name}return t}function trim_lines(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function previousSexp(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function lineIndent(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function match(e,t){return l(e,t)===t.length;function l(r,n){function e(e,t){var r=_createForOfIteratorHelper(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var a=l(i,t);if(a!==-1){return a}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[a]===Symbol["for"]("symbol")&&!is_symbol_string(n[u])}function i(){var e=r[a+1];var t=n[u+1];if(e!==undefined&&t!==undefined){return l([e],[t])}}var a=0;var o={};for(var u=0;u0){continue}}else if(t()){return-1}}else if(r[a]instanceof Array){var c=l(r[a],n.slice(u));if(c===-1||c+u>n.length){return-1}u+=c-1;a++;continue}else{return-1}a++}if(r.length!==a){return-1}return n.length}}function Formatter(e){this.__code__=e.replace(/\r/g,"")}Formatter.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*?-values|\*)?)$/],shift:{1:["&","#"]}}};Formatter.match=match;Formatter.prototype._options=function e(t){var r=Formatter.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var a=n.shift||{1:[]};return _objectSpread(_objectSpread(_objectSpread({},r),t),{},{exceptions:{specials:[].concat(_toConsumableArray(r.exceptions.specials),_toConsumableArray(i)),shift:_objectSpread(_objectSpread({},a),{},{1:[].concat(_toConsumableArray(r.exceptions.shift[1]),_toConsumableArray(a[1]))})}})};Formatter.prototype.indent=function e(t){var r=tokenize(this.__code__,true);return this._indent(r,t)};Formatter.exception_shift=function(a,e){function t(e){if(!e.length){return false}if(e.indexOf(a)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=_createForOfIteratorHelper(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(a.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){n.offset=0}if(a.toString()===t.toString()&&balanced(a)){return n.offset+a[0].col}else if(a.length===1){return n.offset+a[0].col+1}else{var s=-1;if(o){var c=Formatter.exception_shift(o.token,n);if(c!==-1){s=c}}if(s===-1){s=Formatter.exception_shift(a[1].token,n)}if(s!==-1){return n.offset+a[0].col+s}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return n.offset+a[1].col}return n.offset+a[3].col}else if(a[0].line===a[1].line){return n.offset+n.indent+a[0].col}else{var l=a.slice(2);for(var f=0;f")};Ahead.prototype.match=function(e){return e.match(this.pattern)};function Pattern(){for(var e=arguments.length,t=new Array(e),r=0;r")};Formatter.Pattern=Pattern;Formatter.Ahead=Ahead;var p_o=/^[[(]$/;var p_e=/^[\])]$/;var not_p=/[^()[\]]/;var not_close=new Ahead(/[^)\]]/);var glob=Symbol["for"]("*");var sexp_or_atom=new Pattern([p_o,glob,p_e],[not_p],"+");var sexp=new Pattern([p_o,glob,p_e],"+");var symbol=new Pattern([Symbol["for"]("symbol")],"?");var symbols=new Pattern([Symbol["for"]("symbol")],"*");var identifiers=[p_o,symbols,p_e];var let_value=new Pattern([p_o,Symbol["for"]("symbol"),glob,p_e],"+");var syntax_rules=keywords_re("syntax-rules");var def_lambda_re=keywords_re("define","lambda","define-macro","syntax-rules");var non_def=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var let_re=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function keywords_re(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!u[e]){u[e]=previousSexp(o,e)}});var s=_createForOfIteratorHelper(i),c;try{for(s.s();!(c=s.n()).done;){var l=_slicedToArray(c.value,3),f=l[0],_=l[1],p=l[2];_=_.valueOf();var d=_>0?u[_]:o;var h=d.filter(function(e){return e.trim()&&!is_special(e)});var m=r(d);var y=match(f,h);var v=n.slice(a).find(function(e){return e.trim()&&!is_special(e)});if(y&&(p instanceof Ahead&&p.match(v)||!p)){var b=a-m;if(n[b]!=="\n"){if(!n[b].trim()){n[b]="\n"}else{n.splice(b,0,"\n");a++}}a+=m;continue e}}}catch(e){s.e(e)}finally{s.f()}}this.__code__=n.join("");return this};Formatter.prototype._spaces=function(e){return" ".repeat(e)};Formatter.prototype.format=function e(t){var r=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var n=tokenize(r,true);var i=this._options(t);var a=0;var o=0;for(var u=0;u0){n=Math.floor(t()*r);r--;var i=[e[n],e[r]];e[r]=i[0];e[n]=i[1]}return e}function Nil(){}Nil.prototype.toString=function(){return"()"};Nil.prototype.valueOf=function(){return undefined};Nil.prototype.serialize=function(){return 0};Nil.prototype.to_object=function(){return{}};Nil.prototype.append=function(e){return new Pair(e,_nil)};Nil.prototype.to_array=function(){return[]};var _nil=new Nil;function Pair(e,t){if(typeof this!=="undefined"&&this.constructor!==Pair||typeof this==="undefined"){return new Pair(e,t)}this.car=e;this.cdr=t}function to_array(a,o){return function e(t){typecheck(a,t,["pair","nil"]);if(is_nil(t)){return[]}var r=[];var n=t;while(true){if(is_pair(n)){if(n.have_cycles("cdr")){break}var i=n.car;if(o&&is_pair(i)){i=this.get(a).call(this,i)}r.push(i);n=n.cdr}else if(is_nil(n)){break}else{throw new Error("".concat(a,": can't convert improper list"))}}return r}}Pair.prototype.flatten=function(){return Pair.fromArray(flatten(this.to_array()))};Pair.prototype.length=function(){var e=0;var t=this;while(true){if(!t||is_nil(t)||!is_pair(t)||t.have_cycles("cdr")){break}e++;t=t.cdr}return e};Pair.match=function(e,t){if(e instanceof LSymbol){return LSymbol.is(e,t)}else if(is_pair(e)){return Pair.match(e.car,t)||Pair.match(e.cdr,t)}else if(Array.isArray(e)){return e.some(function(e){return Pair.match(e,t)})}else if(is_plain_object(e)){return Object.values(e).some(function(e){return Pair.match(e,t)})}return false};Pair.prototype.find=function(e){return Pair.match(this,e)};Pair.prototype.clone=function(){var r=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(is_pair(e)){if(n.has(e)){return n.get(e)}var t=new Pair;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[__cycles__]=e[__cycles__];return t}return e}return i(this)};Pair.prototype.last_pair=function(){var e=this;while(true){if(!is_pair(e.cdr)){return e}if(e.have_cycles("cdr")){break}e=e.cdr}};Pair.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(is_pair(this.car)){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(is_pair(this.cdr)){t=t.concat(this.cdr.to_array(e))}return t};Pair.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(is_pair(e)||r&&e instanceof Array&&e[__data__]){return e}if(t===false){var n=_nil;for(var i=e.length;i--;){n=new Pair(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=_toConsumableArray(e)}var a=_nil;var o=e.length;while(o--){var u=e[o];if(u instanceof Array){u=Pair.fromArray(u,t,r)}else if(typeof u==="string"){u=LString(u)}else if(typeof u==="number"&&!Number.isNaN(u)){u=LNumber(u)}a=new Pair(u,a)}return a};Pair.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(is_pair(t)&&is_pair(t.car)){var n=t.car;var i=n.car;if(i instanceof LSymbol){i=i.__name__}if(i instanceof LString){i=i.valueOf()}var a=n.cdr;if(is_pair(a)){a=a.to_object(e)}if(is_native(a)){if(!e){a=a.valueOf()}}r[i]=a;t=t.cdr}else{break}}return r};Pair.fromPairs=function(e){return e.reduce(function(e,t){return new Pair(new Pair(new LSymbol(t[0]),t[1]),e)},_nil)};Pair.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return Pair.fromPairs(e)};Pair.prototype.reduce=function(e){var t=this;var r=_nil;while(true){if(!is_nil(t)){r=e(r,t.car);t=t.cdr}else{break}}return r};Pair.prototype.reverse=function(){if(this.have_cycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=_nil;while(!is_nil(e)){var r=e.cdr;e.cdr=t;t=e;e=r}return t};Pair.prototype.transform=function(n){function i(e){if(is_pair(e)){if(e.replace){delete e.replace;return e}var t=n(e.car);if(is_pair(t)){t=i(t)}var r=n(e.cdr);if(is_pair(r)){r=i(r)}return new Pair(t,r)}return e}return i(this)};Pair.prototype.map=function(e){if(typeof this.car!=="undefined"){return new Pair(e(this.car),is_nil(this.cdr)?_nil:this.cdr.map(e))}else{return _nil}};var repr=new Map;function is_plain_object(e){return e&&_typeof$1(e)==="object"&&e.constructor===Object}var props=Object.getOwnPropertyNames(Array.prototype);var array_methods=[];props.forEach(function(e){array_methods.push(Array[e],Array.prototype[e])});function is_array_method(e){e=unbind(e);return array_methods.includes(e)}function is_lips_function(e){return is_function(e)&&(is_lambda(e)||e.__doc__)}function user_repr(r){var e=r.constructor||Object;var n=is_plain_object(r);var i=is_function(r[Symbol.asyncIterator])||is_function(r[Symbol.iterator]);var a;if(repr.has(e)){a=repr.get(e)}else{repr.forEach(function(e,t){t=unbind(t);if(r instanceof t&&(t===Object&&n&&!i||t!==Object)){a=e}})}return a}var str_mapping=new Map;[[true,"#t"],[false,"#f"],[null,"#null"],[undefined,"#void"]].forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];str_mapping.set(r,n)});function symbolize(r){if(r&&_typeof$1(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=toString(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_typeof$1(t)==="object"&&t.constructor===Object){n[e]=symbolize(t)}else{n[e]=toString(t)}});return n}return r}function get_props(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function has_own_function(e,t){return e.hasOwnProperty(t)&&is_function(e.toString)}function function_to_string(e){if(is_native_function(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(is_function(t)&&is_lambda(t)){if(e[__class__]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(LString.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_typeof$1(n)==="symbol"){n=symbol_to_string(n)}if(typeof n==="string"){return"#")}}if(has_own_function(e,"toString")){return e.toString()}else if(e.name&&!is_lambda(e)){return"#")}else{return"#"}}var instances=new Map;[[Error,function(e){return e.message}],[Pair,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.mark_cycles()}return e.toString.apply(e,[r].concat(_toConsumableArray(i)))}],[LCharacter,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[LString,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];instances.set(r,n)});var native_types=[LSymbol,Macro,Values,InputPort,OutputPort,Environment,QuotedPromise];function toString(e,t,r){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(str_mapping.has(e)){return str_mapping.get(e)}if(is_prototype(e)){return"#"}if(e){var n=e.constructor;if(instances.has(n)){for(var i=arguments.length,a=new Array(i>3?i-3:0),o=3;o"}if(e===null){return"null"}if(is_function(e)){if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}return function_to_string(e)}if(_typeof$1(e)==="object"){var l=e.constructor;if(!l){l=Object}var f;if(typeof l.__class__==="string"){f=l.__class__}else{var _=user_repr(e);if(_){if(is_function(_)){return _(e,t)}else{throw new Error("toString: Invalid repr value")}}f=l.name}if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}if(type(e)==="instance"){if(is_lambda(l)&&l.__name__){f=l.__name__.valueOf()}else if(!is_native_function(l)){f="instance"}}if(is_iterator(e,Symbol.iterator)){if(f){return"#")}return"#"}if(is_iterator(e,Symbol.asyncIterator)){if(f){return"#")}return"#"}if(f!==""){return"#<"+f+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}Pair.prototype.mark_cycles=function(){mark_cycles(this);return this};Pair.prototype.have_cycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.have_cycles("car")||this.have_cycles("cdr")}return!!(this[__cycles__]&&this[__cycles__][e])};Pair.prototype.is_cycle=function(){return is_cycle(this)};function is_cycle(e){if(!is_pair(e)){return false}if(e.have_cycles()){return true}return is_cycle(e.car,fn)||is_cycle(e.cdr,fn)}function mark_cycles(e){var t=[];var i=[];var a=[];function o(e){if(!t.includes(e)){t.push(e)}}function u(e,t,r,n){if(is_pair(r)){if(n.includes(r)){if(!a.includes(r)){a.push(r)}if(!e[__cycles__]){e[__cycles__]={}}e[__cycles__][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=trampoline(function e(t,r){if(is_pair(t)){delete t[__ref__];delete t[__cycles__];o(t);r.push(t);var n=u(t,"car",t.car,r);var i=u(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new Thunk(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(is_pair(e[__cycles__][t])){var r=n.indexOf(e[__cycles__][t]);e[__cycles__][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return a.includes(e)});n.forEach(function(e,t){e[__ref__]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}Pair.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[__ref__]){i.push(this[__ref__]+"(")}else if(!n){i.push("(")}var a;if(this[__cycles__]&&this[__cycles__].car){a=this[__cycles__].car}else{a=toString(this.car,e,true)}if(a!==undefined){i.push(a)}if(is_pair(this.cdr)){if(this[__cycles__]&&this[__cycles__].cdr){i.push(" . ");i.push(this[__cycles__].cdr)}else{if(this.cdr[__ref__]){i.push(" . ")}else{i.push(" ")}var o=this.cdr.toString(e,{nested:true});i.push(o)}}else if(!is_nil(this.cdr)){i=i.concat([" . ",toString(this.cdr,e,true)])}if(!n||this[__ref__]){i.push(")")}return i.join("")};Pair.prototype.set=function(e,t){this[e]=t;if(is_pair(t)){this.mark_cycles()}};Pair.prototype.append=function(e){if(e instanceof Array){return this.append(Pair.fromArray(e))}var t=this;if(t.car===undefined){if(is_pair(e)){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(!is_nil(e)){while(true){if(is_pair(t)&&!is_nil(t.cdr)){t=t.cdr}else{break}}t.cdr=e}return this};Pair.prototype.serialize=function(){return[this.car,this.cdr]};Pair.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(is_nil(t)){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function abs(e){return e<0?-e:e}function seq_compare(e,t){var r=_toArray(t),n=r[0],i=r.slice(1);while(i.length>0){var a=i,o=_slicedToArray(a,1),u=o[0];if(!e(n,u)){return false}var s=i;var c=_toArray(s);n=c[0];i=c.slice(1)}return true}function equal(e,t){if(is_function(e)){return is_function(t)&&unbind(e)===unbind(t)}else if(e instanceof LNumber){if(!(t instanceof LNumber)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return equal(LNumber(e),LNumber(t))}else if(e instanceof LCharacter){if(!(t instanceof LCharacter)){return false}return e.__char__===t.__char__}else{return e===t}}function same_atom(e,t){if(type(e)!==type(t)){return false}if(!is_atom(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof LString){return e.valueOf()===t.valueOf()}return equal(e,t)}function is_atom(e){return e instanceof LSymbol||LString.isString(e)||is_nil(e)||e===null||e instanceof LCharacter||e instanceof LNumber||e===true||e===false}var truncate=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function Macro(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==Macro||typeof this==="undefined"){return new Macro(e,t)}typecheck("Macro",e,"string",1);typecheck("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=trim_lines(r)}}this.__name__=e;this.__fn__=t}Macro.defmacro=function(e,t,r,n){var i=new Macro(e,t,r,n);i.__defmacro__=true;return i};Macro.prototype.invoke=function(e,t,r){var n=t.env,i=_objectWithoutProperties(t,_excluded2);var a=_objectSpread(_objectSpread({},i),{},{macro_expand:r});var o=this.__fn__.call(n,e,a,this.__name__);return o};Macro.prototype.toString=function(){return"#")};var macro="define-macro";var recur_guard=-1e4;function macro_expand(c){return function(){var r=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,v){var a,b,n,i,o,g,w,D,x,L,E,S,u,A,s;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:s=function e(){s=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,n,i){var a,o,u,s,c,l,f,_,p,d,h,m,y;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!(is_pair(r)&&r.car instanceof LSymbol)){t.next=50;break}if(!r[__data__]){t.next=3;break}return t.abrupt("return",r);case 3:a=r.car.valueOf();o=i.get(r.car,{throwError:false});u=g(r.car);s=u||w(o,r)||D(o);if(!(s&&is_pair(r.cdr.car))){t.next=28;break}if(!u){t.next=15;break}b=L(r.cdr.car);t.next=12;return S(r.cdr.car,n);case 12:c=t.sent;t.next=17;break;case 15:b=x(r.cdr.car);c=r.cdr.car;case 17:t.t0=Pair;t.t1=r.car;t.t2=Pair;t.t3=c;t.next=23;return A(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!E(a,o)){t.next=50;break}l=o instanceof Syntax?r:r.cdr;t.next=32;return o.invoke(l,_objectSpread(_objectSpread({},v),{},{env:i}),true);case 32:f=t.sent;if(!(o instanceof Syntax)){t.next=41;break}_=f,p=_.expr,d=_.scope;if(!is_pair(p)){t.next=40;break}if(!(n!==-1&&n<=1||n")}return"#"};var SyntaxParameter=_createClass(function e(t){_classCallCheck(this,e);read_only(this,"_syntax",t,{hidden:true});read_only(this._syntax,"_param",true,{hidden:true})});Syntax.Parameter=SyntaxParameter;function extract_patterns(e,t,B,I){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var j={"...":{symbols:{},lists:[]},symbols:{}};var R=r.expansion,T=r.define;log(B);function M(t,e){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;log({code:e,pattern:t});if(is_atom(t)&&!(t instanceof LSymbol)){return same_atom(t,e)}if(t instanceof LSymbol&&B.includes(t.literal())){if(!LSymbol.is(e,t)){return false}var i=R.ref(t);return!i||i===T||i===global_env}if(Array.isArray(t)&&Array.isArray(e)){log("<<< a 1");if(t.length===0&&e.length===0){return true}if(LSymbol.is(t[1],I)){if(t[0]instanceof LSymbol){var a=t[0].valueOf();log("<<< a 2 "+n);if(n){var o=e.length-2;var u=o>0?e.slice(0,o):e;var s=Pair.fromArray(u,false);if(!j["..."].symbols[a]){j["..."].symbols[a]=new Pair(s,_nil)}else{j["..."].symbols[a].append(new Pair(s,_nil))}}else{j["..."].symbols[a]=Pair.fromArray(e,false)}}else if(Array.isArray(t[0])){log("<<< a 3");var c=_toConsumableArray(r);if(!e.every(function(e){return M(t[0],e,c,true)})){return false}}if(t.length>2){var l=t.slice(2);return M(l,e.slice(-l.length),r,n)}return true}var f=M(t[0],e[0],r,n);log({first:f,pattern:t[0],code:e[0]});var _=M(t.slice(1),e.slice(1),r,n);log({first:f,rest:_});return f&&_}if(is_pair(t)&&is_pair(t.car)&&is_pair(t.car.cdr)&&LSymbol.is(t.car.cdr.car,I)){log(">> 0");if(is_nil(e)){log({pattern:t});if(t.car.car instanceof LSymbol){var p=t.car.car.valueOf();if(j["..."].symbols[p]){throw new Error("syntax: named ellipsis can only "+"appear onces")}j["..."].symbols[p]=e}}}if(is_pair(t)&&is_pair(t.cdr)&&LSymbol.is(t.cdr.car,I)){if(!is_nil(t.cdr.cdr)){if(is_pair(t.cdr.cdr)){var d=t.cdr.cdr.length();if(!is_pair(e)){return false}var h=e.length();var m=e;while(h-1>d){m=m.cdr;h--}var y=m.cdr;m.cdr=_nil;if(!M(t.cdr.cdr,y,r,n)){return false}}}if(t.car instanceof LSymbol){var v=t.car.__name__;if(j["..."].symbols[v]&&!r.includes(v)&&!n){throw new Error("syntax: named ellipsis can only appear onces")}log(">> 1");if(is_nil(e)){log(">> 2");if(n){log("NIL");j["..."].symbols[v]=_nil}else{log("NULL");j["..."].symbols[v]=null}}else if(is_pair(e)&&(is_pair(e.car)||is_nil(e.car))){log(">> 3 "+n);if(n){if(j["..."].symbols[v]){var b=j["..."].symbols[v];if(is_nil(b)){b=new Pair(_nil,new Pair(e,_nil))}else{b=b.append(new Pair(e,_nil))}j["..."].symbols[v]=b}else{j["..."].symbols[v]=new Pair(e,_nil)}}else{log(">> 4");j["..."].symbols[v]=new Pair(e,_nil)}}else{log(">> 6");if(is_pair(e)){if(!is_pair(e.cdr)&&!is_nil(e.cdr)){log(">> 7 (b)");if(is_nil(t.cdr.cdr)){return false}else if(!j["..."].symbols[v]){j["..."].symbols[v]=new Pair(e.car,_nil);return M(t.cdr.cdr,e.cdr)}}var g=e.last_pair();if(!is_nil(g.cdr)){if(is_nil(t.cdr.cdr)){return false}else{var w=e.clone();w.last_pair().cdr=_nil;j["..."].symbols[v]=w;return M(t.cdr.cdr,g.cdr)}}log(">> 7 "+n);r.push(v);if(!j["..."].symbols[v]){j["..."].symbols[v]=new Pair(e,_nil)}else{var D=j["..."].symbols[v];j["..."].symbols[v]=D.append(new Pair(e,_nil))}log({IIIIII:j["..."].symbols[v]})}else if(t.car instanceof LSymbol&&is_pair(t.cdr)&&LSymbol.is(t.cdr.car,I)){log(">> 8");j["..."].symbols[v]=null;return M(t.cdr.cdr,e)}else{log(">> 9");return false}}return true}else if(is_pair(t.car)){var x=_toConsumableArray(r);if(is_nil(e)){log(">> 10");j["..."].lists.push(_nil);return true}log(">> 11");var L=e;while(is_pair(L)){if(!M(t.car,L.car,x,true)){return false}L=L.cdr}return true}if(Array.isArray(t.car)){var x=_toConsumableArray(r);var E=e;while(is_pair(E)){if(!M(t.car,E.car,x,true)){return false}E=E.cdr}return true}return false}if(t instanceof LSymbol){if(LSymbol.is(t,I)){throw new Error("syntax: invalid usage of ellipsis")}log(">> 12");var S=t.__name__;if(B.includes(S)){return true}if(n){var A,F;log(j["..."].symbols[S]);(F=(A=j["..."].symbols)[S])!==null&&F!==void 0?F:A[S]=[];j["..."].symbols[S].push(e)}else{j.symbols[S]=e}return true}if(is_pair(t)&&is_pair(e)){log(">> 13");log({a:13,code:e,pattern:t});if(is_nil(e.cdr)){var k=t.car instanceof LSymbol&&t.cdr instanceof LSymbol;if(k){if(!M(t.car,e.car,r,n)){return false}log(">> 14");var C=t.cdr.valueOf();if(!(C in j.symbols)){j.symbols[C]=_nil}C=t.car.valueOf();if(!(C in j.symbols)){j.symbols[C]=e.car}return true}}log({pattern:t,code:e});if(is_pair(t.cdr)&&is_pair(t.cdr.cdr)&&t.cdr.car instanceof LSymbol&&LSymbol.is(t.cdr.cdr.car,I)&&is_pair(t.cdr.cdr.cdr)&&!LSymbol.is(t.cdr.cdr.cdr.car,I)&&M(t.car,e.car,r,n)&&M(t.cdr.cdr.cdr,e.cdr,r,n)){var O=t.cdr.car.__name__;log({pattern:t,code:e,name:O});if(B.includes(O)){return true}j["..."].symbols[O]=null;return true}log("recur");log({pattern:t,code:e});var P=M(t.car,e.car,r,n);log({car:P,pattern:t.car,code:e.car});var N=M(t.cdr,e.cdr,r,n);log({car:P,cdr:N});if(P&&N){return true}}else if(is_nil(t)&&(is_nil(e)||e===undefined)){return true}else if(is_pair(t.car)&&LSymbol.is(t.car.car,I)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(M(e,t)){return j}}function clear_gensyms(e,i){function a(t){if(is_pair(t)){if(!i.length){return t}var e=a(t.car);var r=a(t.cdr);return new Pair(e,r)}else if(t instanceof LSymbol){var n=i.find(function(e){return e.gensym===t});if(n){return LSymbol(n.name)}return t}else{return t}}return a(e)}function transform_syntax(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var P=e.bindings,t=e.expr,N=e.scope,o=e.symbols,l=e.names,B=e.ellipsis;var f={};function u(e){if(e instanceof LSymbol){return true}return["string","symbol"].includes(_typeof$1(e))}function I(e){if(!u(e)){var t=type(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===B){throw new Error("syntax: internal error, ellipis not transformed")}var n=_typeof$1(r);if(["string","symbol"].includes(n)){if(r in P.symbols){return P.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var a=i[0];if(a in P.symbols){return Pair.fromArray([LSymbol("."),P.symbols[a]].concat(i.slice(1).map(function(e){return LString(e)})))}}}if(o.includes(r)){return e}return s(r,e)}function s(e,t){if(!f[e]){var r=N.ref(e);if(_typeof$1(e)==="symbol"&&!r){e=t.literal()}if(f[e]){return f[e]}var n=gensym(e);if(r){var i=N.get(e);N.set(n,i)}else{var a=N.get(e,{throwError:false});if(typeof a!=="undefined"){N.set(n,a)}}l.push({name:e,gensym:n});f[e]=n;if(typeof e==="string"&&e.match(/\./)){var o=e.split(".").filter(Boolean),u=_toArray(o),s=u[0],c=u.slice(1);if(f[s]){hidden_prop(n,"__object__",[f[s]].concat(_toConsumableArray(c)))}}}return f[e]}function j(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;log({bindings:t,expr:e});if(Array.isArray(e)&&!e.length){return e}if(e instanceof LSymbol){var a=e.valueOf();if(is_gensym(e)&&!t[a]);log("[t 1");if(t[a]){if(is_pair(t[a])){var o=t[a],u=o.car,s=o.cdr;if(i){var c=u.car,l=u.cdr;if(!is_nil(l)){n(a,new Pair(l,_nil))}return c}if(!is_nil(s)){n(a,s)}return u}else if(t[a]instanceof Array){n(a,t[a].slice(1));return t[a][0]}}return I(e)}var f=Array.isArray(e);if(is_pair(e)||f){var _=f?e[0]:e.car;var p=f?e[1]:is_pair(e.cdr)&&e.cdr.car;if(_ instanceof LSymbol&&LSymbol.is(p,B)){f?e.slice(2):e.cdr.cdr;log("[t 2");var d=_.valueOf();var h=t[d];if(h===null){return}else if(h){log({name:d,binding:t[d]});if(is_pair(h)){log("[t 2 Pair "+i);var m=h.car,y=h.cdr;var v=f?e.slice(2):e.cdr.cdr;if(i){if(!is_nil(y)){log("|| next 1");n(d,y)}if(f&&v.length||!is_nil(v)&&!f){var b=j(v,t,r,n);if(f){return m.concat(b)}else if(is_pair(m)){return m.append(b)}else{log("UNKNOWN")}}return m}else if(is_pair(m)){if(!is_nil(m.cdr)){log("|| next 2");n(d,new Pair(m.cdr,y))}return m.car}else if(is_nil(y)){return m}else{var g=e.last_pair();if(g.cdr instanceof LSymbol){log("|| next 3");n(d,h.last_pair());return m}}}else if(h instanceof Array){log("[t 2 Array "+i);if(i){n(d,h.slice(1));return Pair.fromArray(h)}else{var w=h.slice(1);if(w.length){n(d,w)}return h[0]}}else{return h}}}log("[t 3 recur ",e);var D=f?e.slice(1):e.cdr;var x=j(_,t,r,n);var L=j(D,t,r,n);log({head:x,rest:L});if(f){return[x].concat(L)}return new Pair(x,L)}return e}function R(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,_toConsumableArray(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return is_pair(e)||is_nil(e)||Array.isArray(e)&&e.length})}function T(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function M(i){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},t=e.disabled;log("traverse>> ",i);var a=Array.isArray(i);if(a&&i.length===0){return i}if(is_pair(i)||a){var r=a?i[0]:i.car;var n,o;if(a){n=i[1];o=i.slice(2)}else if(is_pair(i.cdr)){n=i.cdr.car;o=i.cdr.cdr}log({first:r,second:n,rest_second:o});if(!t&&is_pair(r)&&LSymbol.is(r.car,B)){return new Pair(r.cdr.car,M(i.cdr))}if(n&&LSymbol.is(n,B)&&!t){log(">> 1");var u=P["..."].symbols;var s=Object.values(u);if(s.length&&s.every(function(e){return e===null})){log(">>> 1 (a)");return M(o,{disabled:t})}var c=T(u);var l=r instanceof LSymbol&&LSymbol.is(o.car,B);if(is_pair(r)||l){log(">>> 1 (b)");if(is_nil(P["..."].lists[0])){if(!l){return M(o,{disabled:t})}log(o);return _nil}var f=r;if(l){log(">>> 1 (c)");f=new Pair(r,new Pair(n,_nil))}log(">> 2");var _;if(c.length){log(">> 2 (a)");var p=_objectSpread({},u);_=a?[]:_nil;var d=function e(){log({bind:p});if(!R(p)){return 1}var n={};var t=function e(t,r){n[t]=r};var r=j(f,p,{nested:true},t);if(r!==undefined){if(l){if(a){if(Array.isArray(r)){var i;(i=_).push.apply(i,_toConsumableArray(r))}else{log("ZONK {1}")}}else{if(is_nil(_)){_=r}else{_=_.append(r)}}}else if(a){_.push(r)}else{_=new Pair(r,_)}}p=n};while(true){if(d())break}if(!is_nil(_)&&!l&&!a){_=_.reverse()}if(a){if(o){log({rest_second:o,expr:i});var h=M(o,{disabled:t});return _.concat(h)}return _}if(!is_nil(i.cdr.cdr)&&!LSymbol.is(i.cdr.cdr.car,B)){var m=M(i.cdr.cdr,{disabled:t});return _.append(m)}return _}else{log(">> 3");var y=j(r,u,{nested:true});if(y){return new Pair(y,_nil)}return _nil}}else if(r instanceof LSymbol){log(">> 4");if(LSymbol.is(o.car,B)){log(">> 4 (a)")}else{log(">> 4 (b)")}var v=r.__name__;var b=_defineProperty({},v,u[v]);log({bind:b});var g=u[v]===null;var w=a?[]:_nil;var D=function e(){if(!R(b,true)){log({bind:b});return 1}var n={};var t=function e(t,r){n[t]=r};var r=j(i,b,{nested:false},t);log({value:r});if(typeof r!=="undefined"){if(a){w.push(r)}else{w=new Pair(r,w)}}b=n};while(true){if(D())break}if(!is_nil(w)&&!a){w=w.reverse()}if(is_pair(i.cdr)){if(is_pair(i.cdr.cdr)||i.cdr.cdr instanceof LSymbol){var x=M(i.cdr.cdr,{disabled:t});log({node:x});if(g){return x}if(is_nil(w)){w=x}else{w.append(x)}log({result:w,node:x})}}log("<<<< 2");return w}}var L=M(r,{disabled:t});var E;var S;if(r instanceof LSymbol){var A=N.get(r,{throwError:false});S=A instanceof Macro&&A.__name__==="syntax-rules"}if(S){if(i.cdr.car instanceof LSymbol){E=new Pair(M(i.cdr.car,{disabled:t}),new Pair(i.cdr.cdr.car,M(i.cdr.cdr.cdr,{disabled:t})))}else{E=new Pair(i.cdr.car,M(i.cdr.cdr,{disabled:t}))}log("REST >>>> ",E)}else{E=M(i.cdr,{disabled:t})}log({a:true,car:toString(i.car),cdr:toString(i.cdr),head:toString(L),rest:toString(E)});return new Pair(L,E)}if(i instanceof LSymbol){if(t&&LSymbol.is(i,B)){return i}var F=Object.keys(P["..."].symbols);var k=i.literal();if(F.includes(k)){var C="missing ellipsis symbol next to name `".concat(k,"'");throw new Error("syntax-rules: ".concat(C))}var O=I(i);if(typeof O!=="undefined"){return O}}return i}return M(t,{})}function is_null(e){return is_undef(e)||is_nil(e)||e===null}function is_nil(e){return e===_nil}function is_function(e){return typeof e==="function"&&typeof e.bind==="function"}function is_directive(e){return directives.includes(e)}function is_false(e){return e===false||e===null}function is_string(e){return typeof e==="string"}function is_prototype(e){return e&&_typeof$1(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}function is_continuation(e){return e instanceof Continuation}function is_context(e){return e instanceof LambdaContext}function is_parameter(e){return e instanceof Parameter}function is_pair(e){return e instanceof Pair}function is_env(e){return e instanceof Environment}function is_callable(e){return is_function(e)||is_continuation(e)||is_parameter(e)||is_macro(e)}function is_macro(e){return e instanceof Macro||e instanceof SyntaxParameter}function is_promise(e){if(e instanceof QuotedPromise){return false}if(e instanceof Promise){return true}return!!e&&is_function(e.then)}function is_undef(e){return typeof e==="undefined"}function is_iterator(e,t){if(has_own_symbol(e,t)||has_own_symbol(e.__proto__,t)){return is_function(e[t])}}function is_instance(e){if(!e){return false}if(_typeof$1(e)!=="object"){return false}if(e.__instance__){e.__instance__=false;return e.__instance__}return false}function self_evaluated(e){var t=_typeof$1(e);return["string","function"].includes(t)||_typeof$1(e)==="symbol"||e instanceof QuotedPromise||e instanceof LSymbol||e instanceof LNumber||e instanceof LString||e instanceof RegExp}function is_native(e){return e instanceof LNumber||e instanceof LString||e instanceof LCharacter}function has_own_symbol(e,t){if(e===null){return false}return _typeof$1(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function box(e){switch(_typeof$1(e)){case"string":return LString(e);case"bigint":return LNumber(e);case"number":if(Number.isNaN(e)){return nan}else{return LNumber(e)}}return e}function map_object(r,n){var e=Object.getOwnPropertyNames(r);var t=Object.getOwnPropertySymbols(r);var i={};e.concat(t).forEach(function(e){var t=n(r[e]);i[e]=t});return i}function unbox(t){var e=[LString,LNumber,LCharacter].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(unbox)}if(t instanceof QuotedPromise){delete t.then}if(is_plain_object(t)){return map_object(t,unbox)}return t}function patch_value(e,t){if(is_pair(e)){e.mark_cycles();return quote(e)}if(is_function(e)){if(t){return bind(e,t)}}return box(e)}function unbind(e){if(is_bound(e)){return e[__fn__]}return e}function bind(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=_createForOfIteratorHelper(n),a;try{for(i.s();!(a=i.n()).done;){var o=a.value;if(filter_fn_names(o)){try{r[o]=e[o]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}hidden_prop(r,"__fn__",e);hidden_prop(r,"__context__",t);hidden_prop(r,"__bound__",true);if(is_native_function(e)){hidden_prop(r,"__native__",true)}if(is_plain_object(t)&&is_lambda(e)){hidden_prop(r,"__method__",true)}r.valueOf=function(){return e};return r}function is_object_bound(e){return is_bound(e)&&e[Symbol["for"]("__context__")]===Object}function is_bound(e){return!!(is_function(e)&&e[__fn__])}function lips_context(e){if(is_function(e)){var t=e[__context__];if(t&&(t===lips||t.constructor&&t.constructor.__class__)){return true}}return false}function is_port(e){return e instanceof InputPort||e instanceof OutputPort}function is_port_method(e){if(is_function(e)){if(is_port(e[__context__])){return true}}return false}var __context__=Symbol["for"]("__context__");var __fn__=Symbol["for"]("__fn__");var __data__=Symbol["for"]("__data__");var __ref__=Symbol["for"]("__ref__");var __cycles__=Symbol["for"]("__cycles__");var __class__=Symbol["for"]("__class__");var __method__=Symbol["for"]("__method__");var __prototype__=Symbol["for"]("__prototype__");var __lambda__=Symbol["for"]("__lambda__");var exluded_names=["name","length","caller","callee","arguments","prototype"];function filter_fn_names(e){return!exluded_names.includes(e)}function hidden_prop(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function set_fn_length(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function is_lambda(e){return e&&e[__lambda__]}function is_method(e){return e&&e[__method__]}function is_raw_lambda(e){return is_lambda(e)&&!e[__prototype__]&&!is_method(e)&&!is_port_method(e)}function is_native_function(e){var t=Symbol["for"]("__native__");return is_function(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function let_macro(e){var w;switch(e){case Symbol["for"]("letrec"):w="letrec";break;case Symbol["for"]("let"):w="let";break;case Symbol["for"]("let*"):w="let*";break;default:throw new Error("Invalid let_macro value")}return Macro.defmacro(w,function(t,e){var l=e.dynamic_env;var f=e.error,r=e.macro_expand,_=e.use_dynamic;var p;if(t.car instanceof LSymbol){if(!(is_pair(t.cdr.car)||is_nil(t.cdr.car))){throw new Error("let require list of pairs")}var n;if(is_nil(t.cdr.car)){p=_nil;n=_nil}else{n=t.cdr.car.map(function(e){return e.car});p=t.cdr.car.map(function(e){return e.cdr.car})}var i=gensym("args");return Pair.fromArray([LSymbol("let"),[[i,Pair(LSymbol("list"),p)]],[LSymbol("letrec"),[[t.car,Pair(LSymbol("lambda"),Pair(n,t.cdr.cdr))]],[LSymbol("apply"),t.car,i]]])}else if(r){return}var d=this;p=global_env.get("list->array")(t.car);var h=d.inherit(w);var m,y;if(w==="let*"){y=h}else if(w==="let"){m=[]}var v=0;function b(){var e=new Pair(new LSymbol("begin"),t.cdr);return _evaluate(e,{env:h,dynamic_env:h,use_dynamic:_,error:f})}function g(e){if(e in h.__env__){throw new Error("Duplicated let variable ".concat(e))}}return function t(){var r=p[v++];l=w==="let*"?h:d;if(!r){if(m&&m.length){var e=m.map(function(e){return e.value});var n=e.filter(is_promise);if(n.length){return promise_all(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=this;var a=this;var o=[];var u=e;while(is_pair(u)){o.push(_evaluate(u.car,{env:i,dynamic_env:a,use_dynamic:r,error:n}));u=u.cdr}var s=o.filter(is_promise).length;if(s){return promise_all(o).then(c.bind(this))}else{return c.call(this,o)}})}function guard_math_call(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),a=2;a1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=u){return o.apply(n,i)}else{return a}}}();return a.apply(void 0,arguments)}}function limit(n,i){typecheck("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(LCharacter.__names__[e]){t=e;e=LCharacter.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=LCharacter.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}LCharacter.__names__=characters;LCharacter.__rev_names__={};Object.keys(LCharacter.__names__).forEach(function(e){var t=LCharacter.__names__[e];LCharacter.__rev_names__[t]=e});LCharacter.prototype.toUpperCase=function(){return LCharacter(this.__char__.toUpperCase())};LCharacter.prototype.toLowerCase=function(){return LCharacter(this.__char__.toLowerCase())};LCharacter.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};LCharacter.prototype.valueOf=LCharacter.prototype.serialize=function(){return this.__char__};function LString(e){if(typeof this!=="undefined"&&!(this instanceof LString)||typeof this==="undefined"){return new LString(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){typecheck("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var ignore=["length","constructor"];var _keys=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!ignore.includes(e)});var wrap=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof LNumber){return e}if(typeof this!=="undefined"&&!(this instanceof LNumber)||typeof this==="undefined"){return new LNumber(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=LNumber.getType(e);if(LNumber.types[r]){return LNumber.types[r](e,t)}var n=e instanceof Array&&LString.isString(e[0])&&LNumber.isNumber(e[1]);if(e instanceof LNumber){return LNumber(e.value)}if(!LNumber.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(type(e)))}if(e===null){e=0}var i;if(n){var a=e,o=_slicedToArray(a,2),u=o[0],s=o[1];if(u instanceof LString){u=u.valueOf()}if(s instanceof LNumber){s=s.valueOf()}var c=u.match(/^([+-])/);var l=false;if(c){u=u.replace(/^[+-]/,"");if(c[1]==="-"){l=true}}}if(Number.isNaN(e)){return LFloat(e)}else if(n&&Number.isNaN(parseInt(u,s))){return nan}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var f;switch(s){case 8:f="0o";break;case 16:f="0x";break;case 2:f="0b";break;case 10:f="";break}if(typeof f==="undefined"){var _=BigInt(s);i=_toConsumableArray(u).map(function(e,t){return BigInt(parseInt(e,s))*pow(_,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(f+u)}}else{i=BigInt(e)}if(l){i*=BigInt(-1)}}else{i=e}return LBigInteger(i,true)}else if(typeof BN!=="undefined"&&!(e instanceof BN)){if(e instanceof Array){return LBigInteger(_construct(BN,_toConsumableArray(e)))}return LBigInteger(new BN(e))}else if(n){this.constant(parseInt(u,s),"integer")}else{this.constant(e,"integer")}}LNumber.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};LNumber.types={float:function e(t){return new LFloat(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!LNumber.isComplex(t)){t={im:0,re:t}}return new LComplex(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!LNumber.isRational(t)){t={num:t,denom:1}}return new LRational(t,r)}};LNumber.prototype.serialize=function(){return this.__value__};LNumber.prototype.isNaN=function(){return Number.isNaN(this.__value__)};LNumber.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};LNumber.isFloat=function e(t){return t instanceof LFloat||Number(t)===t&&t%1!==0};LNumber.isNumber=function(e){return e instanceof LNumber||LNumber.isNative(e)||LNumber.isBN(e)};LNumber.isComplex=function(e){if(!e){return false}var t=e instanceof LComplex||(LNumber.isNumber(e.im)||LNumber.isRational(e.im)||Number.isNaN(e.im))&&(LNumber.isNumber(e.re)||LNumber.isRational(e.re)||Number.isNaN(e.re));return t};LNumber.isRational=function(e){if(!e){return false}return e instanceof LRational||LNumber.isNumber(e.num)&&LNumber.isNumber(e.denom)};LNumber.isInteger=function(e){if(!(LNumber.isNative(e)||e instanceof LNumber)){return false}if(LNumber.isFloat(e)){return false}if(LNumber.isRational(e)){return false}if(LNumber.isComplex(e)){return false}return true};LNumber.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};LNumber.isBigInteger=function(e){return e instanceof LBigInteger||typeof e==="bigint"||LNumber.isBN(e)};LNumber.isBN=function(e){return typeof BN!=="undefined"&&e instanceof BN};LNumber.getArgsType=function(e,t){if(e instanceof LFloat||t instanceof LFloat){return LFloat}if(e instanceof LBigInteger||t instanceof LBigInteger){return LBigInteger}return LNumber};LNumber.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>=2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};LNumber.prototype.asType=function(e){var t=LNumber.getType(this);return LNumber.types[t]?LNumber.types[t](e):LNumber(e)};LNumber.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof BN!=="undefined"&&!(this.value instanceof BN)};["floor","ceil","round"].forEach(function(e){LNumber.prototype[e]=function(){if(this["float"]||LNumber.isFloat(this.__value__)){return LNumber(Math[e](this.__value__))}else{return LNumber(Math[e](this.valueOf()))}}});LNumber.prototype.valueOf=function(){if(LNumber.isNative(this.__value__)){return Number(this.__value__)}else if(LNumber.isBN(this.__value__)){return this.__value__.toNumber()}};var matrix=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&LFloat(r.valueOf())]},integer:function e(t,r){return[t,r&&LFloat(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&LFloat(r.valueOf())]},complex:function e(t,r){return[{re:t,im:LFloat(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function e(t,r){var n=LNumber.coerce(t.__re__,r.__re__),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=LNumber.coerce(t.__im__,r.__im__),s=_slicedToArray(u,2),c=s[0],l=s[1];return[{im:c,re:a},{im:l,re:o}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:coerce(t.__type__,r.__im__.__type__,0)[0],re:coerce(t.__type__,r.__re__.__type__,t)[0]},{im:coerce(t.__type__,r.__im__.__type__,r.__im__)[0],re:coerce(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:coerce(r,e.__im__.__type__,0,e.__im__)[1],re:coerce(r,e.__re__.__type__,0,e.__re__)[1]},{im:coerce(r,e.__im__.__type__,0,0)[1],re:coerce(r,t.__type__,0,t)[1]}]}}}();function coerce(e,t,r,n){return matrix[e][t](r,n)}LNumber.coerce=function(e,t){var r=LNumber.getType(e);var n=LNumber.getType(t);if(!matrix[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!matrix[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=matrix[r][n](e,t);return i.map(function(e){return LNumber(e,true)})};LNumber.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof LNumber)){throw new Error("LNumber: you can't coerce ".concat(type(e)))}if(typeof e==="number"){e=LNumber(e)}return LNumber.coerce(this,e)};LNumber.getType=function(e){if(e instanceof LNumber){return e.__type__}if(LNumber.isFloat(e)){return"float"}if(LNumber.isComplex(e)){return"complex"}if(LNumber.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof BN!=="undefined"&&!(e instanceof BN)){return"bigint"}};LNumber.prototype.isFloat=function(){return!!(LNumber.isFloat(this.__value__)||this["float"])};var mapping={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var rev_mapping={};Object.keys(mapping).forEach(function(t){rev_mapping[mapping[t]]=t;LNumber.prototype[t]=function(e){return this.op(mapping[t],e)}});LNumber._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof LComplex)||typeof this==="undefined"){return new LComplex(e,t)}if(e instanceof LComplex){return LComplex({im:e.__im__,re:e.__re__})}if(LNumber.isNumber(e)&&t){if(!t){return Number(e)}}else if(!LNumber.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(toString(e));throw new Error(r)}var n=e.im instanceof LNumber?e.im:LNumber(e.im);var i=e.re instanceof LNumber?e.re:LNumber(e.re);this.constant(n,i)}LComplex.prototype=Object.create(LNumber.prototype);LComplex.prototype.constructor=LComplex;LComplex.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};LComplex.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};LComplex.prototype.toRational=function(e){var t=this.__im__,r=this.__re__;if(LNumber.isFloat(this.__im__)){t=LFloat(this.__im__).toRational(e)}if(LNumber.isFloat(this.__re__)){r=LFloat(this.__re__).toRational(e)}return LComplex({im:t,re:r})};LComplex.prototype.pow=function(e){e.cmp(0);if(e===0){return LNumber(1)}var t=LNumber(Math.atan2(this.__im__.valueOf(),this.__re__.valueOf()));var r=LNumber(this.modulus());if(LNumber.isComplex(e)&&e.__im__.cmp(0)!==0){var n=e.mul(Math.log(r.valueOf())).add(LComplex.i.mul(t).mul(e));if(!LNumber.isComplex(n)){return LFloat(Math.E).pow(n)}var i=LFloat(Math.E).pow(n.__re__.valueOf());return LComplex({re:i.mul(Math.cos(n.__im__.valueOf())),im:i.mul(Math.sin(n.__im__.valueOf()))})}var a=e.__re__.cmp(0)>0;e=e.__re__.valueOf();if(LNumber.isInteger(e)&&a){var o=this;while(--e){o=o.mul(this)}return o}var u=r.pow(e);var s=t.mul(e);return LComplex({re:u.mul(Math.cos(s)),im:u.mul(Math.sin(s))})};LComplex.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};LComplex.prototype.factor=function(){if(this.__im__ instanceof LFloat||this.__im__ instanceof LFloat){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof LFloat){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof LFloat){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};LComplex.prototype.modulus=function(){return this.factor().sqrt()};LComplex.prototype.conjugate=function(){return LComplex({re:this.__re__,im:this.__im__.sub()})};LComplex.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=LFloat(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=LFloat(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return LComplex({im:r,re:t})};LComplex.prototype.div=function(e){if(LNumber.isNumber(e)&&!LNumber.isComplex(e)){if(!(e instanceof LNumber)){e=LNumber(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return LComplex({re:t,im:r})}else if(!LNumber.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=a.__im__.div(o.__im__);return u.coerce(o.__re__)[0]}var s=this.coerce(e),c=_slicedToArray(s,2),l=c[0],f=c[1];var _=f.factor();var p=f.conjugate();var d=l.mul(p);if(!LNumber.isComplex(d)){return d.div(_)}var h=d.__re__.op("/",_);var m=d.__im__.op("/",_);return LComplex({re:h,im:m})};LComplex.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};LComplex.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};LComplex.prototype.complex_op=function(e,t,i){var a=this;var r=function e(t,r){var n=i(a.__re__,t,a.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return LComplex(n,true)}return n};if(typeof t==="undefined"){return r()}if(LNumber.isNumber(t)&&!LNumber.isComplex(t)){if(!(t instanceof LNumber)){t=LNumber(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!LNumber.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var o=t.__re__ instanceof LNumber?t.__re__:this.__re__.asType(t.__re__);var u=t.__im__ instanceof LNumber?t.__im__:this.__im__.asType(t.__im__);return r(o,u)};LComplex._op={"+":"add","-":"sub","*":"mul","/":"div"};LComplex.prototype._op=function(e,t){var r=LComplex._op[e];return this[r](t)};LComplex.prototype.cmp=function(e){var t=this.coerce(e),r=_slicedToArray(t,2),n=r[0],i=r[1];var a=n.__re__.coerce(i.__re__),o=_slicedToArray(a,2),u=o[0],s=o[1];var c=u.cmp(s);if(c!==0){return c}else{var l=n.__im__.coerce(i.__im__),f=_slicedToArray(l,2),_=f[0],p=f[1];return _.cmp(p)}};LComplex.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};LComplex.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[toString(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=toString(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function LFloat(e){if(typeof this!=="undefined"&&!(this instanceof LFloat)||typeof this==="undefined"){return new LFloat(e)}if(!LNumber.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof LNumber){return LFloat(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}LFloat.prototype=Object.create(LNumber.prototype);LFloat.prototype.constructor=LFloat;LFloat.prototype.toString=function(e){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}e&&(e=e.valueOf());var t=this.__value__.toString(e);if(!t.match(/e[+-]?[0-9]+$/i)){var r=t.replace(/^-/,"");var n=this.__value__<0?"-":"";if(t.match(/^-?0\.0{3}/)){var i=r.match(/^[.0]+/g)[0].length-1;var a=r.replace(/^[.0]+/,"").replace(/^([0-9a-f])/i,"$1.");return"".concat(n).concat(a,"e-").concat(i.toString(e))}if(t.match(/^-?[0-9a-f]{7,}\.?/i)){var o=r.match(/^[0-9a-f]+/gi)[0].length-1;var u=r.replace(/\./,"").replace(/^([0-9a-f])/i,"$1.").replace(/0+$/,"").replace(/\.$/,".0");return"".concat(n).concat(u,"e+").concat(o.toString(e))}if(!LNumber.isFloat(this.__value__)){var s=t+".0";return this._minus?"-"+s:s}}return t.replace(/^([0-9]+)e/,"$1.0e")};LFloat.prototype._op=function(e,t){if(t instanceof LNumber){t=t.__value__}var r=LNumber._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return LFloat(r(this.__value__,t))};LFloat.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return toRational(this.__value__.valueOf())}return approxRatio(e.valueOf())(this.__value__.valueOf())};LFloat.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=LFloat(Math.sqrt(-e));return LComplex({re:0,im:t})}return LFloat(Math.sqrt(e))};LFloat.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return LFloat(e)};var toRational=approxRatio(1e-10);function approxRatio(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=simplest_rational2(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=simplest_rational2(r,n)}else if(t.cmp(0)<0){i=LNumber(simplest_rational2(n.sub(),r.sub())).sub()}else{i=LNumber(0)}if(LNumber.isFloat(t)||LNumber.isFloat(e)){return LFloat(i)}return i}function simplest_rational2(e,t){var r=LNumber(e).floor();var n=LNumber(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=LNumber(1).div(t.sub(n));var a=LNumber(1).div(e.sub(r));return r.add(LNumber(1).div(simplest_rational2(i,a)))}else{return r.add(LNumber(1))}}function LRational(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof LRational)||typeof this==="undefined"){return new LRational(e,t)}if(!LNumber.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof LRational){r=LNumber(e.__num__);n=LNumber(e.__denom__)}else{r=LNumber(e.num);n=LNumber(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return LNumber(r.div(n))}}this.constant(r,n)}LRational.prototype=Object.create(LNumber.prototype);LRational.prototype.constructor=LRational;LRational.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};LRational.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};LRational.prototype.pow=function(e){if(LNumber.isRational(e)){return pow(this.valueOf(),e.valueOf())}var t=e.cmp(0);if(t===0){return LNumber(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return LRational({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};LRational.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof LFloat||t instanceof LFloat){return e.div(t)}return LRational({num:e,denom:t})};LRational.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return LRational({num:e,denom:t})};LRational.prototype.cmp=function(e){return LNumber(this.valueOf(),true).cmp(e)};LRational.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof LRational){t=LNumber(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof LRational){r=LNumber(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};LRational.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return LNumber._ops["/"](this.__num__.value,this.__denom__.value)}return LFloat(this.__num__.valueOf()).div(this.__denom__.valueOf())};LRational.prototype.mul=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return LRational({num:t,denom:r})}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];return a.mul(o)};LRational.prototype.div=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return LRational({num:t,denom:r})}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=a.div(o);return u};LRational.prototype._op=function(e,t){return this[rev_mapping[e]](t)};LRational.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(LRational({num:t,denom:r}))}if(!(e instanceof LNumber)){e=LNumber(e).sub()}else{e=e.sub()}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];return a.add(o)};LRational.prototype.add=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var a,o;if(t!==r){o=r.mul(n).add(i.mul(t));a=t.mul(r)}else{o=n.add(i);a=t}return LRational({num:o,denom:a})}if(LNumber.isFloat(e)){return LFloat(this.valueOf()).add(e)}var u=LNumber.coerce(this,e),s=_slicedToArray(u,2),c=s[0],l=s[1];return c.add(l)};function LBigInteger(e,t){if(typeof this!=="undefined"&&!(this instanceof LBigInteger)||typeof this==="undefined"){return new LBigInteger(e,t)}if(e instanceof LBigInteger){return LBigInteger(e.__value__,e._native)}if(!LNumber.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}LBigInteger.prototype=Object.create(LNumber.prototype);LBigInteger.prototype.constructor=LBigInteger;LBigInteger.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};LBigInteger.prototype.serialize=function(){return this.__value__.toString()};LBigInteger.prototype._op=function(e,t){if(typeof t==="undefined"){if(LNumber.isBN(this.__value__)){e=LBigInteger.bn_op[e];return LBigInteger(this.__value__.clone()[e](),false)}return LBigInteger(LNumber._ops[e](this.__value__),true)}if(LNumber.isBN(this.__value__)&&LNumber.isBN(t.__value__)){e=LBigInteger.bn_op[e];return LBigInteger(this.__value__.clone()[e](t),false)}var r=LNumber._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return LNumber(r)}return LRational({num:this,denom:t})}return LBigInteger(r,true)};LBigInteger.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(LNumber.isNative(this.__value__)){e=LNumber(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(LNumber.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return LComplex({re:0,im:e})}return e};LNumber.NaN=LNumber(NaN);LComplex.i=LComplex({im:1,re:0});function InputPort(e){var n=this;var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:global_env;if(typeof this!=="undefined"&&!(this instanceof InputPort)||typeof this==="undefined"){return new InputPort(e)}typecheck("InputPort",e,"function");read_only(this,"__type__",text_port);var a;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return a},set:function e(t){typecheck("InputPort::__parser__",t,"parser");a=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=6;break}t.next=3;return n._read();case 3:r=t.sent;a=new Parser({env:i});a.parse(r);case 6:return t.abrupt("return",n.__parser__);case 7:case"end":return t.stop()}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==eof};this._make_defaults()}InputPort.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!LNumber.isInteger(t)){var r=LNumber.getType(t);typeErrorMessage("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};InputPort.prototype._with_init_parser=function(u,s){var c=this;return _asyncToGenerator(_regeneratorRuntime.mark(function e(){var r,n,i,a,o=arguments;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return u.call(c);case 2:r=t.sent;for(n=o.length,i=new Array(n),a=0;a"};function OutputPort(e){if(typeof this!=="undefined"&&!(this instanceof OutputPort)||typeof this==="undefined"){return new OutputPort(e)}typecheck("OutputPort",e,"function");read_only(this,"__type__",text_port);this.write=e}OutputPort.prototype.is_open=function(){return this._closed!==true};OutputPort.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};OutputPort.prototype.flush=function(){};OutputPort.prototype.toString=function(){return"#"};var BufferedOutputPort=function(e){_inherits(r,e);function r(e){var t;_classCallCheck(this,r);t=_callSuper(this,r,[function(){var e;return(e=t)._write.apply(e,arguments)}]);typecheck("BufferedOutputPort",e,"function");read_only(_assertThisInitialized(t),"_fn",e,{hidden:true});read_only(_assertThisInitialized(t),"_buffer",[],{hidden:true});return t}_createClass(r,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};OutputStringPort.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function OutputFilePort(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof OutputFilePort)||typeof this==="undefined"){return new OutputFilePort(e,t)}typecheck("OutputFilePort",e,"string");read_only(this,"__filename__",e);read_only(this,"_fd",t.valueOf(),{hidden:true});read_only(this,"__type__",text_port);this.write=function(e){if(!LString.isString(e)){e=toString(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}OutputFilePort.prototype=Object.create(OutputPort.prototype);OutputFilePort.prototype.constructor=OutputFilePort;OutputFilePort.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};OutputFilePort.prototype.internal=function(e){return user_env.get("**internal-env**").get(e)};OutputFilePort.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{read_only(n,"_fd",null,{hidden:true});OutputPort.prototype.close.call(n);t()}})})};OutputFilePort.prototype.toString=function(){return"#")};function InputStringPort(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:global_env;if(typeof this!=="undefined"&&!(this instanceof InputStringPort)||typeof this==="undefined"){return new InputStringPort(e)}typecheck("InputStringPort",e,"string");e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!t.__parser__){t.__parser__=new Parser({env:r});t.__parser__.parse(e)}return t.__parser__});read_only(this,"__type__",text_port);this._make_defaults()}InputStringPort.prototype.char_ready=function(){return true};InputStringPort.prototype=Object.create(InputPort.prototype);InputStringPort.prototype.constructor=InputStringPort;InputStringPort.prototype.toString=function(){return"#"};function ParserInputPort(e){if(typeof this!=="undefined"&&!(this instanceof ParserInputPort)||typeof this==="undefined"){return new ParserInputPort(e)}this._with_parser=this._with_init_parser.bind(this,function(){return e});read_only(this,"__type__",text_port);this._make_defaults()}ParserInputPort.prototype.char_ready=function(){return true};ParserInputPort.prototype=Object.create(InputPort.prototype);ParserInputPort.prototype.constructor=ParserInputPort;ParserInputPort.prototype.toString=function(){return"#"};function InputByteVectorPort(e){if(typeof this!=="undefined"&&!(this instanceof InputByteVectorPort)||typeof this==="undefined"){return new InputByteVectorPort(e)}typecheck("InputByteVectorPort",e,"uint8array");read_only(this,"__vector__",e);read_only(this,"__type__",binary_port);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){typecheck("InputByteVectorPort::__index__",t,"number");if(t instanceof LNumber){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}InputByteVectorPort.prototype=Object.create(InputPort.prototype);InputByteVectorPort.prototype.constructor=InputByteVectorPort;InputByteVectorPort.prototype.toString=function(){return"#"};InputByteVectorPort.prototype.close=function(){var t=this;read_only(this,"__vector__",_nil);var r=function e(){throw new Error("Input-binary-port: port is closed")};["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=r});this.u8_ready=this.char_ready=function(){return false}};InputByteVectorPort.prototype.u8_ready=function(){return true};InputByteVectorPort.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return eof}return this.__vector__[this.__index__]};InputByteVectorPort.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};InputByteVectorPort.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};InputByteVectorPort.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===eof){return eof}return this.__vector__.slice(this.__index__,e)};function OutputByteVectorPort(){if(typeof this!=="undefined"&&!(this instanceof OutputByteVectorPort)||typeof this==="undefined"){return new OutputByteVectorPort}read_only(this,"__type__",binary_port);read_only(this,"_buffer",[],{hidden:true});this.write=function(e){typecheck("write",e,["number","uint8array"]);if(LNumber.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,_toConsumableArray(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}OutputByteVectorPort.prototype=Object.create(OutputPort.prototype);OutputByteVectorPort.prototype.constructor=OutputByteVectorPort;OutputByteVectorPort.prototype.close=function(){OutputPort.prototype.close.call(this);read_only(this,"_buffer",null,{hidden:true})};OutputByteVectorPort.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};OutputByteVectorPort.prototype.write_u8=function(e){typecheck("OutputByteVectorPort::write_u8",e,"number");this.write(e)};OutputByteVectorPort.prototype.write_u8_vector=function(e){typecheck("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};OutputByteVectorPort.prototype.toString=function(){return"#"};OutputByteVectorPort.prototype.valueOf=function(){return this.__buffer__};function InputFilePort(e,t){if(typeof this!=="undefined"&&!(this instanceof InputFilePort)||typeof this==="undefined"){return new InputFilePort(e,t)}InputStringPort.call(this,e);typecheck("InputFilePort",t,"string");read_only(this,"__filename__",t)}InputFilePort.prototype=Object.create(InputStringPort.prototype);InputFilePort.prototype.constructor=InputFilePort;InputFilePort.prototype.toString=function(){return"#")};function InputBinaryFilePort(e,t){if(typeof this!=="undefined"&&!(this instanceof InputBinaryFilePort)||typeof this==="undefined"){return new InputBinaryFilePort(e,t)}InputByteVectorPort.call(this,e);typecheck("InputBinaryFilePort",t,"string");read_only(this,"__filename__",t)}InputBinaryFilePort.prototype=Object.create(InputByteVectorPort.prototype);InputBinaryFilePort.prototype.constructor=InputBinaryFilePort;InputBinaryFilePort.prototype.toString=function(){return"#")};function OutputBinaryFilePort(e,t){var i=this;if(typeof this!=="undefined"&&!(this instanceof OutputBinaryFilePort)||typeof this==="undefined"){return new OutputBinaryFilePort(e,t)}typecheck("OutputBinaryFilePort",e,"string");read_only(this,"__filename__",e);read_only(this,"_fd",t.valueOf(),{hidden:true});read_only(this,"__type__",binary_port);var a;this.write=function(e){typecheck("write",e,["number","uint8array"]);var n;if(!a){a=i.internal("fs")}if(LNumber.isNumber(e)){n=new Uint8Array([e.valueOf()])}else{n=new Uint8Array(Array.from(e))}return new Promise(function(t,r){a.write(i._fd,n,function(e){if(e){r(e)}else{t()}})})}}OutputBinaryFilePort.prototype=Object.create(OutputFilePort.prototype);OutputBinaryFilePort.prototype.constructor=OutputBinaryFilePort;OutputBinaryFilePort.prototype.write_u8=function(e){typecheck("OutputByteVectorPort::write_u8",e,"number");this.write(e)};OutputBinaryFilePort.prototype.write_u8_vector=function(e){typecheck("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var binary_port=Symbol["for"]("binary");var text_port=Symbol["for"]("text");var eof=new EOF;function EOF(){}EOF.prototype.toString=function(){return"#"};function Interpreter(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.stderr,i=r.stdin,a=r.stdout,o=r.command_line,u=o===void 0?null:o,s=_objectWithoutProperties(r,_excluded3);if(typeof this!=="undefined"&&!(this instanceof Interpreter)||typeof this==="undefined"){return new Interpreter(e,_objectSpread({stdin:i,stdout:a,stderr:n,command_line:u},s))}if(typeof e==="undefined"){e="anonymous"}this.__env__=user_env.inherit(e,s);this.__parser__=new Parser({env:this.__env__});this.__env__.set("parent.frame",doc("parent.frame",function(){return t.__env__},global_env.__env__["parent.frame"].__doc__));var c="**interaction-environment-defaults**";this.set(c,get_props(s).concat(c));var l=internal_env.inherit("internal-".concat(e));if(is_port(i)){l.set("stdin",i)}if(is_port(n)){l.set("stderr",n)}if(is_port(a)){l.set("stdout",a)}l.set("command-line",u);set_interaction_env(this.__env__,l)}Interpreter.prototype.exec=function(){var t=_asyncToGenerator(function(o){var u=this;var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return _regeneratorRuntime.mark(function e(){var r,n,i,a;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=s.use_dynamic,n=r===void 0?false:r,i=s.dynamic_env,a=s.env;typecheck("Interpreter::exec",o,["string","array"],1);typecheck("Interpreter::exec",n,"boolean",2);if(!a){a=u.__env__}if(!i){i=a}global_env.set("**interaction-environment**",u.__env__);if(!Array.isArray(o)){t.next=10;break}return t.abrupt("return",exec(o,{env:a,dynamic_env:i,use_dynamic:n}));case 10:u.__parser__.parse(o);return t.abrupt("return",exec(u.__parser__,{env:a,dynamic_env:i,use_dynamic:n}));case 12:case"end":return t.stop()}},e)})()});return function(e){return t.apply(this,arguments)}}();Interpreter.prototype.get=function(e){var t=this.__env__.get(e);if(is_function(t)){var r=new LambdaContext({env:this.__env__});return t.bind(r)}return t};Interpreter.prototype.set=function(e,t){return this.__env__.set(e,t)};Interpreter.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function LipsError(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}LipsError.prototype=new Error;LipsError.prototype.constructor=LipsError;var IgnoreException=function(e){_inherits(t,e);function t(){_classCallCheck(this,t);return _callSuper(this,t,arguments)}return _createClass(t)}(_wrapNativeSuper(Error));function Environment(e,t,r){if(arguments.length===1){if(_typeof$1(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}Environment.prototype.list=function(){return get_props(this.__env__)};Environment.prototype.fs=function(){return this.get("**fs**")};Environment.prototype.unset=function(e){if(e instanceof LSymbol){e=e.valueOf()}if(e instanceof LString){e=e.valueOf()}delete this.__env__[e]};Environment.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_typeof$1(e)==="object"){t=e}if(!e||_typeof$1(e)==="object"){e="child of "+(this.__name__||"unknown")}return new Environment(t||{},this,e)};Environment.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}if(t){if(!r){t=trim_lines(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};Environment.prototype.new_frame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",doc("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!is_env(t)){return _nil}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},global_env.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};Environment.prototype._lookup=function(e){if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return Value(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};Environment.prototype.toString=function(){return"#"};Environment.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new Environment(r,this.__parent__,this.__name__)};Environment.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";typecheck("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function Value(e){if(typeof this!=="undefined"&&!(this instanceof Value)||typeof this==="undefined"){return new Value(e)}this.value=e}Value.isUndefined=function(e){return e instanceof Value&&typeof e.value==="undefined"};Value.prototype.valueOf=function(){return this.value};function Values(e){if(!e.length){return}if(e.length===1){return e[0]}if(typeof this!=="undefined"&&!(this instanceof Values)||typeof this==="undefined"){return new Values(e)}this.__values__=e}Values.prototype.toString=function(){return this.__values__.map(function(e){return toString(e)}).join("\n")};Values.prototype.valueOf=function(){return this.__values__};Environment.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};typecheck("Environment::get",e,["symbol","string"]);var r=t.throwError,n=r===void 0?true:r;var i=e;if(i instanceof LSymbol||i instanceof LString){i=i.valueOf()}var a=this._lookup(i);if(a instanceof Value){if(Value.isUndefined(a)){return undefined}return patch_value(a.valueOf())}var o;if(e instanceof LSymbol&&e[LSymbol.object]){o=e[LSymbol.object]}else if(typeof i==="string"){o=i.split(".").filter(Boolean)}if(o&&o.length>0){var u=o,s=_toArray(u),c=s[0],l=s.slice(1);a=this._lookup(c);if(l.length){try{if(a instanceof Value){a=a.valueOf()}else{a=get(root,c);if(is_function(a)){a=unbind(a)}}if(typeof a!=="undefined"){return get.apply(void 0,[a].concat(_toConsumableArray(l)))}}catch(e){throw e}}else if(a instanceof Value){return patch_value(a.valueOf())}a=get(root,i)}if(typeof a!=="undefined"){return a}if(n){throw new Error("Unbound variable `"+i.toString()+"'")}};Environment.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;typecheck("Environment::set",e,["string","symbol"]);if(LNumber.isNumber(t)){t=LNumber(t)}if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};Environment.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&is_plain_object(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};Environment.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};Environment.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};Environment.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function quote(e){if(is_promise(e)){return e.then(quote)}if(is_pair(e)||e instanceof LSymbol){e[__data__]=true}return e}var native_lambda=_parse(tokenize('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var get=doc("get",function e(t){var r;for(var n=arguments.length,i=new Array(n>1?n-1:0),a=1;a0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":doc("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("read-line",e,"input-port");return e.read_line()},"(read-line port)\n\n This function reads and returns the next line from the input\n port."),"read-char":doc("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:doc("read",function(){var e=_asyncToGenerator(function(){var i=this;var a=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;return _regeneratorRuntime.mark(function e(){var r,n;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=i.env;if(a===null){n=internal(r,"stdin")}else{n=a}typecheck_text_port("read",n,"input-port");return t.abrupt("return",n.read.call(r));case 4:case"end":return t.stop()}},e)})()});function t(){return e.apply(this,arguments)}return t}(),"(read [port])\n\n This function, if called with a port, it will parse the next\n item from the port. If called without an input, it will read\n a string from standard input (using the browser's prompt or\n a user defined input method) and parse it. This function can be\n used together with `eval` to evaluate code from port."),pprint:doc("pprint",function e(t){if(is_pair(t)){t=new lips.Formatter(t.toString(true))["break"]().format();global_env.get("display").call(global_env,t)}else{global_env.get("write").call(global_env,t)}global_env.get("newline").call(global_env)},"(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."),print:doc("print",function e(){var t=global_env.get("display");var r=global_env.get("newline");var n=this.use_dynamic;var i=global_env;var a=global_env;for(var o=arguments.length,u=new Array(o),s=0;s1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var u=0;var s=global_env.get("repr");t=t.replace(a,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[u++];if(t==="a"){return s(r)}else{return s(r,true)}}});o=t.match(/~([\S])/);if(o){throw new Error("format: Unrecognized escape sequence ".concat(o[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),display:doc("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=internal(this,"stdout")}else{typecheck("display",r,"output-port")}var n=t;if(!(r instanceof OutputBinaryFilePort)){n=global_env.get("repr")(t)}r.write.call(global_env,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."),"display-error":doc("display-error",function e(){var t=internal(this,"stderr");var r=global_env.get("repr");for(var n=arguments.length,i=new Array(n),a=0;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=_objectWithoutProperties(t,_excluded4);var i=this;var o=this;var u;var s=_objectSpread(_objectSpread({},n),{},{env:this,dynamic_env:i,use_dynamic:r});var c=_evaluate(e.cdr.car,s);c=resolve_promises(c);function l(t,r,n){if(is_promise(t)){return t.then(function(e){return l(t,e,n)})}if(is_promise(r)){return r.then(function(e){return l(t,e,n)})}if(is_promise(n)){return n.then(function(e){return l(t,r,e)})}o.get("set-obj!").call(o,t,r,n);return n}if(is_pair(e.car)&&LSymbol.is(e.car.car,".")){var f=e.car.cdr.car;var _=e.car.cdr.cdr.car;var p=_evaluate(f,s);var d=_evaluate(_,s);return l(p,d,c)}if(!(e.car instanceof LSymbol)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var h=e.car.valueOf();u=this.ref(e.car.__name__);return unpromise(c,function(e){if(!u){var t=h.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=a.get(n,{throwError:false});if(i){l(i,r,e);return}}throw new Error("Unbound variable `"+h+"'")}u.set(h,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non empty slot and sets it."),"unset!":doc(new Macro("set!",function(e){if(!(e.car instanceof LSymbol)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."),"set-car!":doc("set-car!",function(e,t){typecheck("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."),"set-cdr!":doc("set-cdr!",function(e,t){typecheck("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."),"empty?":doc("empty?",function(e){return typeof e==="undefined"||is_nil(e)},"(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."),gensym:doc("gensym",gensym,"(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."),load:doc("load",function e(u,t){typecheck("load",u,"string");var s=this;if(s.__name__==="__frame__"){s=s.__parent__}if(!(t instanceof Environment)){if(s===global_env){t=s}else{t=this.get("**interaction-environment**")}}var c="**module-path**";var l=global_env.get(c,{throwError:false});u=u.valueOf();if(!u.match(/.[^.]+$/)){u+=".scm"}var r=u.match(/\.xcb$/);function f(e){if(r){e=unserialize_bin(e)}else{if(type(e)==="buffer"){e=e.toString()}e=e.replace(/^(#!.*)/,function(e,t){if(is_directive(t)){return t}return""});if(e.match(/^\{/)){e=unserialize(e)}}return exec(e,{env:t})}function n(e){return root.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}if(is_node()){return new Promise(function(){var r=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,n){var i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:i=nodeRequire("path");if(!l){t.next=6;break}l=l.valueOf();u=i.join(l,u);t.next=12;break;case 6:a=s.get("command-line",{throwError:false});if(!a){t.next=11;break}t.next=10;return a();case 10:o=t.sent;case 11:if(o&&!is_nil(o)){process.cwd();u=i.join(i.dirname(o.car.valueOf()),u)}case 12:global_env.set(c,i.dirname(u));nodeRequire("fs").readFile(u,function(e,t){if(e){n(e);global_env.set(c,l)}else{try{f(t).then(function(){r();global_env.set(c,l)})["catch"](n)}catch(e){n(e)}}});case 14:case"end":return t.stop()}},e)}));return function(e,t){return r.apply(this,arguments)}}())}if(l){l=l.valueOf();u=l+"/"+u.replace(/^\.?\/?/,"")}return n(u).then(function(e){global_env.set(c,u.replace(/\/[^/]*$/,""));return f(e)}).then(function(){})["finally"](function(){global_env.set(c,l)})},"(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."),while:doc(new Macro("while",function(e,t){var r=e.car;var n=_objectSpread(_objectSpread({},t),{},{env:this});var i=new Pair(new LSymbol("begin"),e.cdr);return function t(){return unpromise(_evaluate(r,n),function(e){if(e){return unpromise(_evaluate(i,n),t)}})}()}),"(while cond body)\n\n Creates a loop, it executes cond and body until cond expression is false."),do:doc(new Macro("do",function(){var r=_asyncToGenerator(function(_,e){var p=this;var d=e.use_dynamic,h=e.error;return _regeneratorRuntime.mark(function e(){var u,r,s,c,n,l,f,i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:u=p;r=u;s=u.inherit("do");c=_.car;n=_.cdr.car;l=_.cdr.cdr;if(!is_nil(l)){l=new Pair(LSymbol("begin"),l)}f={env:u,dynamic_env:r,use_dynamic:d,error:h};i=c;case 9:if(is_nil(i)){t.next=20;break}a=i.car;t.t0=s;t.t1=a.car;t.next=15;return _evaluate(a.cdr.car,f);case 15:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);i=i.cdr;t.next=9;break;case 20:f={env:s,dynamic_env:r,error:h};o=_regeneratorRuntime.mark(function e(){var r,n,i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(is_nil(l)){t.next=3;break}t.next=3;return lips.evaluate(l,f);case 3:r=c;n={};case 5:if(is_nil(r)){t.next=15;break}i=r.car;if(is_nil(i.cdr.cdr)){t.next=12;break}t.next=10;return _evaluate(i.cdr.cdr.car,f);case 10:a=t.sent;n[i.car.valueOf()]=a;case 12:r=r.cdr;t.next=5;break;case 15:o=Object.getOwnPropertySymbols(n);f.env=s=u.inherit("do");Object.keys(n).concat(o).forEach(function(e){s.set(e,n[e])});case 18:case"end":return t.stop()}},e)});case 22:t.next=24;return _evaluate(n.car,f);case 24:t.t3=t.sent;if(!(t.t3===false)){t.next=29;break}return t.delegateYield(o(),"t4",27);case 27:t.next=22;break;case 29:if(is_nil(n.cdr)){t.next=33;break}t.next=32;return _evaluate(n.cdr.car,f);case 32:return t.abrupt("return",t.sent);case 33:case"end":return t.stop()}},e)})()});return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will\n evaluate and return the second expression after the loop exits."),if:doc(new Macro("if",function(r,e){var t=e.error,n=e.use_dynamic;var i=this;var a=this;var o={env:a,dynamic_env:i,use_dynamic:n,error:t};var u=function e(t){if(is_false(t)){return _evaluate(r.cdr.cdr.car,o)}else{return _evaluate(r.cdr.car,o)}};if(is_nil(r)){throw new Error("too few expressions for `if`")}var s=_evaluate(r.car,o);return unpromise(s,u)}),"(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."),"let-env":new Macro("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_env,n=e.use_dynamic,i=e.error;typecheck("let-env",t,"pair");var a=_evaluate(t.car,{env:this,dynamic_env:r,error:i,use_dynamic:n});return unpromise(a,function(e){typecheck("let-env",e,"environment");return _evaluate(Pair(LSymbol("begin"),t.cdr),{env:e,dynamic_env:r,error:i})})},"(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."),letrec:doc(let_macro(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentially and the next value can access the\n previous values/names."),"letrec*":doc(let_macro(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."),"let*":doc(let_macro(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."),let:doc(let_macro(Symbol["for"]("let")),"(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to names,\n and then evaluates the body in context of that environment. Values are evaluated\n sequentially but you can't access previous values/names when the next are\n evaluated. You can only get them in the body of the let expression. (If you want\n to define multiple variables and use them in each other's definitions, use\n `let*`.)"),"begin*":doc(parallel("begin*",function(e){return e.pop()}),"(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return\n the value of the last expression (i.e. it uses Promise.all())."),shuffle:doc("shuffle",function(e){typecheck("shuffle",e,["pair","nil","array"]);var t=global_env.get("random");if(is_nil(e)){return _nil}if(Array.isArray(e)){return shuffle(e.slice(),t)}var r=global_env.get("list->array")(e);r=shuffle(r,t);return global_env.get("array->list")(r)},"(shuffle obj)\n\n Order items in vector or list in random order."),begin:doc(new Macro("begin",function(e,t){var n=_objectSpread(_objectSpread({},t),{},{env:this});var i=global_env.get("list->array")(e);var a;return function t(){if(i.length){var e=i.shift();var r=_evaluate(e,n);return unpromise(r,function(e){a=e;return t()})}else{return a}}()}),"(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."),ignore:new Macro("ignore",function(e,t){var r=_objectSpread(_objectSpread({},t),{},{env:this,dynamic_env:this});_evaluate(new Pair(new LSymbol("begin"),e),r)},"(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It will discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":doc(Macro.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=_objectSpread({env:this},t);return unpromise(_evaluate(e.car,r),function(e){if(is_function(e)){return e(new Continuation(null))}})}),"(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORTED BY LIPS RIGHT NOW"),parameterize:doc(new Macro("parameterize",function(t,e){var i=e.dynamic_env;var a=i.inherit("parameterize").new_frame(null,{});var o=_objectSpread(_objectSpread({},e),{},{env:this});var u=t.car;if(!is_pair(u)){var r=type(u);throw new Error("Invalid syntax for parameterize expecting pair got ".concat(r))}function s(){var e=new Pair(new LSymbol("begin"),t.cdr);return _evaluate(e,_objectSpread(_objectSpread({},o),{},{dynamic_env:a}))}return function r(){var e=u.car;var n=e.car.valueOf();return unpromise(_evaluate(e.cdr.car,o),function(e){var t=i.get(n,{throwError:false});if(!is_parameter(t)){throw new Error("Unknown parameter ".concat(n))}a.set(n,t.inherit(e));if(!is_null(u.cdr)){u=u.cdr;return r()}else{return s()}})}()}),"(parameterize ((name value) ...)\n\n Macro that change the dynamic variable created by make-parameter."),"make-parameter":doc(new Macro("make-parameter",function(e,t){t.dynamic_env;var r=_evaluate(e.car,t);var n;if(is_pair(e.cdr.car)){n=_evaluate(e.cdr.car,t)}return new Parameter(r,n)}),"(make-parameter init converter)\n\n Function creates new dynamic variable that can be custimized with parameterize\n macro. The value should be assigned to a variable e.g.:\n\n (define radix (make-parameter 10))\n\n The result value is a procedure that return the value of dynamic variable."),"define-syntax-parameter":doc(new Macro("define-syntax-parameter",function(e,t){var r=e.car;var n=this;if(!(r instanceof LSymbol)){throw new Error("define-syntax-parameter: invalid syntax expecting symbol got ".concat(type(r)))}var i=_evaluate(e.cdr.car,_objectSpread({env:n},t));typecheck("define-syntax-parameter",i,"syntax",2);i.__name__=r.valueOf();if(i.__name__ instanceof LString){i.__name__=i.__name__.valueOf()}var a;if(is_pair(e.cdr.cdr)&&LString.isString(e.cdr.cdr.car)){a=e.cdr.cdr.car.valueOf()}n.set(e.car,new SyntaxParameter(i),a,true)}),"(define-syntax-parameter name syntax [__doc__])\n\n Binds to the transformer obtained by evaluating .\n The transformer provides the default expansion for the syntax parameter,\n and in the absence of syntax-parameterize, is functionally equivalent to\n define-syntax."),"syntax-parameterize":doc(new Macro("syntax-parameterize",function(e,t){var r=global_env.get("list->array")(e.car);var n=this.inherit("syntax-parameterize");while(r.length){var i=r.shift();if(!(is_pair(i)||i.car instanceof LSymbol)){var a="invalid syntax for syntax-parameterize: ".concat(repr(e,true));throw new Error("syntax-parameterize: ".concat(a))}var o=_evaluate(i.cdr.car,_objectSpread(_objectSpread({},t),{},{env:this}));var u=i.car;typecheck("syntax-parameterize",o,["syntax"]);typecheck("syntax-parameterize",u,"symbol");o.__name__=u.valueOf();if(o.__name__ instanceof LString){o.__name__=o.__name__.valueOf()}var s=new SyntaxParameter(o);if(u.is_gensym()){var c=u.literal();var l=this.get(c,{throwError:false});if(l instanceof SyntaxParameter){n.set(c,s)}}n.set(u,s)}var f=new Pair(new LSymbol("begin"),e.cdr);return _evaluate(f,_objectSpread(_objectSpread({},t),{},{env:n}))}),"(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),define:doc(Macro.defmacro("define",function(r,e){var n=this;if(is_pair(r.car)&&r.car.car instanceof LSymbol){var t=new Pair(new LSymbol("define"),new Pair(r.car.car,new Pair(new Pair(new LSymbol("lambda"),new Pair(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}e.dynamic_env=this;e.env=n;var i=r.cdr.car;var a;if(is_pair(i)){i=_evaluate(i,e);a=true}else if(i instanceof LSymbol){i=n.get(i)}typecheck("define",r.car,"symbol");return unpromise(i,function(e){if(n.__name__===Syntax.__merge_env__){n=n.__parent__}if(a&&(is_function(e)&&is_lambda(e)||e instanceof Syntax||is_parameter(e))){e.__name__=r.car.valueOf();if(e.__name__ instanceof LString){e.__name__=e.__name__.valueOf()}}var t;if(is_pair(r.cdr.cdr)&&LString.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`'),"set-obj!":doc("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_typeof$1(e);if(is_null(e)||i!=="object"&&i!=="function"){var a=typeErrorMessage("set-obj!",type(e),["object","function"]);throw new Error(a)}typecheck("set-obj!",t,["string","symbol","number"]);e=unbind(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(is_prototype(e)&&is_function(r)){e[t]=unbind(r);e[t][__prototype__]=true}else if(is_function(r)||is_native(r)||is_nil(r)){e[t]=r}else{e[t]=r&&!is_prototype(r)?r.valueOf():r}if(props){var o=e[t];Object.defineProperty(e,t,_objectSpread(_objectSpread({},n),{},{value:o}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."),"null-environment":doc("null-environment",function(){return global_env.inherit("null")},"(null-environment)\n\n Returns a clean environment with only the standard library."),values:doc("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},y=e.use_dynamic,v=e.error;var b=this;var g;if(is_pair(m.cdr)&&LString.isString(m.cdr.car)&&!is_nil(m.cdr.cdr)){g=m.cdr.car.valueOf()}function w(){var e=is_context(this)?this:{dynamic_env:b},r=e.dynamic_env;var n=b.inherit("lambda");r=r.inherit("lambda");if(this&&!is_context(this)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}n.set("this",this)}for(var t=arguments.length,i=new Array(t),a=0;a> SYNTAX");log(e);log(v);var n=w.inherit("syntax");var i=n;var a=this;if(a.__name__===Syntax.__merge_env__){var o=Object.getOwnPropertySymbols(a.__env__);o.forEach(function(e){a.__parent__.set(e,a.__env__[e])});a=a.__parent__}var u={env:n,dynamic_env:i,use_dynamic:b,error:g};var s,c,l;if(v.car instanceof LSymbol){s=v.car;l=D(v.cdr.car);c=v.cdr.cdr}else{s="...";l=D(v.car);c=v.cdr}try{while(!is_nil(c)){var f=c.car.car;var _=c.car.cdr.car;log("[[[ RULE");log(f);var p=extract_patterns(f,e,l,s,{expansion:this,define:w});if(p){if(is_debug()){console.log(JSON.stringify(symbolize(p),true,2));console.log("PATTERN: "+f.toString(true));console.log("MACRO: "+e.toString(true))}var d=[];var h=transform_syntax({bindings:p,expr:_,symbols:l,scope:n,lex_scope:a,names:d,ellipsis:s});log("OUPUT>>> ",h);if(h){_=h}var m=a.merge(n,Syntax.__merge_env__);if(r){return{expr:_,scope:m}}var y=_evaluate(_,_objectSpread(_objectSpread({},u),{},{env:m}));return clear_gensyms(y,d)}c=c.cdr}}catch(e){e.message+="\nin macro:\n ".concat(v.toString(true));throw e}throw new Error("syntax-rules: no matching syntax in macro ".concat(e.toString(true)))},w);r.__code__=v;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."),quote:doc(new Macro("quote",function(e){return quote(e.car)}),"(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."),"unquote-splicing":doc("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the\n expression, the computed value must be a pair."),unquote:doc("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."),quasiquote:Macro.defmacro("quasiquote",function(e,t){var u=t.use_dynamic,s=t.error;var c=this;var l=c;function a(e){return is_pair(e)||is_plain_object(e)||Array.isArray(e)}function f(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(is_pair(e)){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(is_promise(n)||is_promise(i)){return promise_all([n,i]).then(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return new Pair(r,n)})}else{return new Pair(n,i)}}return e}function o(e,t){if(is_pair(e)){if(!is_nil(t)){e.append(t)}}else{e=new Pair(e,t)}return e}function r(e){return!!e.filter(function(e){return is_pair(e)&&LSymbol.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function _(e,n,i){return e.reduce(function(e,t){if(!is_pair(t)){e.push(t);return e}if(LSymbol.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(is_pair(i.cdr)&&is_nil(r[0]))){return r[0]}}r=r.map(function(e){if(h.has(e)){return e.clone()}else{h.add(e);return e}});var n=m(i.cdr,0,1);if(is_nil(n)&&is_nil(r[0])){return undefined}return unpromise(n,function(e){if(is_nil(r[0])){return e}if(r.length===1){return o(r[0],e)}var t=r.reduce(function(e,t){return o(e,t)});return o(t,e)})})}(i.car.cdr)}var h=new Set;function m(e,t,r){if(is_pair(e)){if(is_pair(e.car)){if(LSymbol.is(e.car.car,"unquote-splicing")){return d(e,t+1,r)}if(LSymbol.is(e.car.car,"unquote")){if(t+2===r&&is_pair(e.car.cdr)&&is_pair(e.car.cdr.car)&&LSymbol.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new Pair(new Pair(new LSymbol("unquote"),d(n,t+2,r)),_nil)}else if(is_pair(e.car.cdr)&&!is_nil(e.car.cdr.cdr)){if(is_pair(e.car.cdr.car)){var i=[];return function t(r){if(is_nil(r)){return Pair.fromArray(i)}return unpromise(_evaluate(r.car,{env:c,dynamic_env:l,use_dynamic:u,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(LSymbol.is(e.car,"quasiquote")){var a=m(e.cdr,t,r+1);return new Pair(e.car,a)}if(LSymbol.is(e.car,"quote")){return new Pair(e.car,m(e.cdr,t,r))}if(LSymbol.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(is_pair(e.cdr)){if(!is_nil(e.cdr.cdr)){if(is_pair(e.cdr.car)){var o=[];return function t(r){if(is_nil(r)){return Pair.fromArray(o)}return unpromise(_evaluate(r.car,{env:c,dynamic_env:l,use_dynamic:u,error:s}),function(e){o.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return _evaluate(e.cdr.car,{env:c,dynamic_env:l,error:s})}}else{return e.cdr}}return f(e,function(e){return m(e,t,r)})}else if(is_plain_object(e)){return p(e,t,r)}else if(e instanceof Array){return _(e,t,r)}return e}function n(e){if(is_pair(e)){delete e[__data__];if(!e.have_cycles("car")){n(e.car)}if(!e.have_cycles("cdr")){n(e.cdr)}}}if(is_plain_object(e.car)&&!r(Object.values(e.car))){return quote(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return quote(e.car)}if(is_pair(e.car)&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return quote(e.car)}var i=m(e.car,0,1);return unpromise(i,function(e){n(e);return quote(e)})},"(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special expressions (unquote\n x) abbreviated to ,x that will evaluate x and insert its value verbatim or\n (unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\n into the result. Best used with macros but it can be used outside."),clone:doc("clone",function e(t){typecheck("clone",t,"pair");return t.clone()},"(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),append:doc("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return global_env.get("array->list")(r)}else if(Array.isArray(t)){return t.reverse()}else{throw new Error(typeErrorMessage("reverse",type(t),"array or pair"))}},"(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."),nth:doc("nth",function e(t,r){typecheck("nth",t,"number");typecheck("nth",r,["array","pair"]);if(is_pair(r)){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function that returns a string by joining elements of the list using separator."),split:doc("split",function e(t,r){typecheck("split",t,["regex","string"]);typecheck("split",r,"string");return global_env.get("array->list")(r.split(t))},"(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."),replace:doc("replace",function e(t,r,n){typecheck("replace",t,["regex","string"]);typecheck("replace",r,["string","function"]);typecheck("replace",n,"string");if(is_function(r)){var i=[];n.replace(t,function(){i.push(r.apply(void 0,arguments))});return unpromise(i,function(e){return n.replace(t,function(){return e.shift()})})}return n.replace(t,r)},"(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a\n string or regex and replacement can be function or string. See Javascript\n String.replace()."),match:doc("match",function e(t,r){typecheck("match",t,["regex","string"]);typecheck("match",r,"string");var n=r.match(t);return n?global_env.get("array->list")(n):false},"(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if\n no match."),search:doc("search",function e(t,r){typecheck("search",t,["regex","string"]);typecheck("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."),repr:doc("repr",function e(t,r){return toString(t,r)},"(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."),"escape-regex":doc("escape-regex",function(e){typecheck("escape-regex",e,"string");return escape_regex(e.valueOf())},"(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."),env:doc("env",function e(e){e=e||this.env;var t=Object.keys(e.__env__).map(LSymbol);var r;if(t.length){r=Pair.fromArray(t)}else{r=_nil}if(e.__parent__ instanceof Environment){return global_env.get("env").call(this,e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."),new:doc("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:specials.LITERAL;typecheck("set-special!",e,"string",1);typecheck("set-special!",t,"symbol",2);specials.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors.'),get:get,".":get,unbind:doc(unbind,"(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."),type:doc(type,"(type object)\n\n Function that returns the type of an object as string."),debugger:doc("debugger",function(){debugger},'(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the "debugger;" statement. If a debugger is not running this\n function does nothing.'),in:doc("in",function(e,t){if(e instanceof LSymbol||e instanceof LString||e instanceof LNumber){e=e.valueOf()}return e in unbox(t)},'(in key value)\n\n Function that uses the Javascript "in" operator to check if key is\n a valid property in the value.'),"instance?":doc("instance?",function(e){return is_instance(e)},"(instance? obj)\n\n Checks if object is an instance, created with a new operator"),instanceof:doc("instanceof",function(e,t){return t instanceof unbind(e)},"(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."),"prototype?":doc("prototype?",is_prototype,"(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."),"macro?":doc("macro?",function(e){return e instanceof Macro},"(macro? expression)\n\n Predicate that tests if value is a macro."),"continuation?":doc("continuation?",is_continuation,"(continuation? expression)\n\n Predicate that tests if value is a callable continuation."),"function?":doc("function?",is_function,"(function? expression)\n\n Predicate that tests if value is a callable function."),"real?":doc("real?",function(e){if(type(e)!=="number"){return false}if(e instanceof LNumber){return e.isFloat()}return LNumber.isFloat(e)},"(real? number)\n\n Predicate that tests if value is a real number (not complex)."),"number?":doc("number?",function(e){return Number.isNaN(e)||LNumber.isNumber(e)},"(number? expression)\n\n Predicate that tests if value is a number or NaN value."),"string?":doc("string?",function(e){return LString.isString(e)},"(string? expression)\n\n Predicate that tests if value is a string."),"pair?":doc("pair?",is_pair,"(pair? expression)\n\n Predicate that tests if value is a pair or list structure."),"regex?":doc("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Predicate that tests if value is a regular expression."),"null?":doc("null?",function(e){return is_null(e)},"(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or\n Javascript null)."),"boolean?":doc("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."),"symbol?":doc("symbol?",function(e){return e instanceof LSymbol},"(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."),"array?":doc("array?",function(e){return e instanceof Array},"(array? expression)\n\n Predicate that tests if value is an array."),"object?":doc("object?",function(e){return!is_nil(e)&&e!==null&&!(e instanceof LCharacter)&&!(e instanceof RegExp)&&!(e instanceof LString)&&!is_pair(e)&&!(e instanceof LNumber)&&_typeof$1(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."),flatten:doc("flatten",function e(t){typecheck("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Returns a shallow list from tree structure (pairs)."),"vector-append":doc("vector-append",function(){for(var e=arguments.length,t=new Array(e),r=0;rlist":doc("array->list",function(e){typecheck("array->list",e,"array");return Pair.fromArray(e)},"(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."),"tree->array":doc("tree->array",to_array("tree->array",true),"(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."),"list->array":doc("list->array",to_array("list->array"),"(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."),apply:doc("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,a));return t.apply(this,prepare_fn_args(t,n))},"(apply fn list)\n\n Function that calls fn with the list of arguments."),length:doc("length",function e(t){if(!t||is_nil(t)){return 0}if(is_pair(t)){return t.length()}if("length"in t){return t.length}},'(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a "length" property. Returns undefined if the\n length could not be found.'),"string->number":doc("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;typecheck("string->number",e,"string",1);typecheck("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(rational_bare_re)||e.match(rational_re)){return parse_rational(e,t)}else if(e.match(complex_bare_re)||e.match(complex_re)){return parse_complex(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(int_bare_re)&&r||e.match(int_re)){return parse_integer(e,t)}if(e.match(float_re)){return parse_float(e)}}return false},"(string->number number [radix])\n\n Function that parses a string into a number."),try:doc(new Macro("try",function(r,e){var f=this;var _=e.use_dynamic;e.error;return new Promise(function(t,u){var s,n;if(LSymbol.is(r.cdr.car.car,"catch")){s=r.cdr.car;if(is_pair(r.cdr.cdr)&&LSymbol.is(r.cdr.cdr.car.car,"finally")){n=r.cdr.cdr.car}}else if(LSymbol.is(r.cdr.car.car,"finally")){n=r.cdr.car}if(!(n||s)){throw new Error("try: invalid syntax")}function c(e){t(e);throw new IgnoreException("[CATCH]")}var l=function e(t,r){r(t)};if(n){l=function e(t,r){l=u;i.error=function(e){throw e};unpromise(_evaluate(new Pair(new LSymbol("begin"),n.cdr),i),function(){r(t)})}}var i={env:f,use_dynamic:_,dynamic_env:f,error:function e(t){if(t instanceof IgnoreException){throw t}if(s){var r=f.inherit("try");var n=s.cdr.car.car;if(!(n instanceof LSymbol)){throw new Error("try: invalid syntax: catch require variable name")}r.set(n,t);var i;var a={env:r,use_dynamic:_,dynamic_env:f,error:function e(t){i=true;u(t);throw new IgnoreException("[CATCH]")}};var o=_evaluate(new Pair(new LSymbol("begin"),s.cdr.cdr),a);unpromise(o,function e(t){if(!i){l(t,c)}})}else{l(undefined,function(){u(t)})}}};var e=_evaluate(r.car,i);unpromise(e,function(e){l(e,t)},i.error)})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thrown. If finally is provided it's always\n executed at the end."),raise:doc("raise",function(e){throw e},"(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."),throw:doc("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws a new exception."),find:doc("find",function t(r,n){typecheck("find",r,["regex","function"]);typecheck("find",n,["pair","nil"]);if(is_null(n)){return _nil}var e=matcher("find",r);return unpromise(e(n.car),function(e){if(e&&!is_nil(e)){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."),"for-each":doc("for-each",function(e){var t;typecheck("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),a=1;a3?n-3:0),a=3;a3?i-3:0),o=3;oarray")(r);var a=[];var o=matcher("filter",t);return function t(r){function e(e){if(e&&!is_nil(e)){a.push(n)}return t(++r)}if(r===i.length){return Pair.fromArray(a)}var n=i[r];return unpromise(o(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."),compose:doc(compose,"(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"),pipe:doc(pipe,"(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"),curry:doc(curry,"(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have partially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\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))"),gcd:doc("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;nu?a%=u:u%=a}a=abs(s*r[o])/(a+u)}return LNumber(a)},"(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."),"odd?":doc("odd?",single_math_op(function(e){return LNumber(e).isOdd()}),"(odd? number)\n\n Checks if number is odd."),"even?":doc("even?",single_math_op(function(e){return LNumber(e).isEven()}),"(even? number)\n\n Checks if number is even."),"*":doc("*",reduce_math_op(function(e,t){return LNumber(e).mul(t)},LNumber(1)),"(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."),"+":doc("+",reduce_math_op(function(e,t){return LNumber(e).add(t)},LNumber(0)),"(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."),"-":doc("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":doc(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,["bigint","float","rational"]);return seq_compare(function(e,t){return LNumber(e).cmp(t)===1},t)},"(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."),"<":doc("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":doc(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,["bigint","float","rational"]);return seq_compare(function(e,t){return[0,1].includes(LNumber(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."),"eq?":doc("eq?",equal,"(eq? a b)\n\n Function that compares two values if they are identical."),or:doc(new Macro("or",function(e,t){var i=t.use_dynamic,a=t.error;var o=global_env.get("list->array")(e);var u=this;var s=u;if(!o.length){return false}var c;return function t(){function e(e){c=e;if(!is_false(c)){return c}else{return t()}}if(!o.length){if(!is_false(c)){return c}else{return false}}else{var r=o.shift();var n=_evaluate(r,{env:u,dynamic_env:s,use_dynamic:i,error:a});return unpromise(n,e)}}()}),"(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."),and:doc(new Macro("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=global_env.get("list->array")(e);var a=this;var o=a;if(!i.length){return true}var u;var s={env:a,dynamic_env:o,use_dynamic:r,error:n};return function t(){function e(e){u=e;if(is_false(u)){return u}else{return t()}}if(!i.length){if(!is_false(u)){return u}else{return false}}else{var r=i.shift();return unpromise(_evaluate(r,s),e)}}()}),"(and . expressions)\n\n Macro that evaluates each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."),"|":doc("|",function(e,t){return LNumber(e).or(t)},"(| a b)\n\n Function that calculates the bitwise or operation."),"&":doc("&",function(e,t){return LNumber(e).and(t)},"(& a b)\n\n Function that calculates the bitwise and operation."),"~":doc("~",function(e){return LNumber(e).neg()},"(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."),">>":doc(">>",function(e,t){return LNumber(e).shr(t)},"(>> a b)\n\n Function that right shifts the value a by value b bits."),"<<":doc("<<",function(e,t){return LNumber(e).shl(t)},"(<< a b)\n\n Function that left shifts the value a by value b bits."),not:doc("not",function e(t){return!t},"(not object)\n\n Function that returns the Boolean negation of its argument.")},undefined,"global");var user_env=global_env.inherit("user-env");function set_interaction_env(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error.");global_env.set("**interaction-environment**",e)}set_interaction_env(user_env,internal_env);global_env.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr.");function set_fs(e){user_env.get("**internal-env**").set("fs",e)}(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;global_env.set(r,doc(r,function(e){typecheck(r,e,"number");if(e instanceof LNumber){return e[t]()}},"(".concat(r," number)\n\n Function that calculates the ").concat(r," of a number.")))})})();function allPossibleCases(e){if(e.length===1){return e[0]}else{var t=[];var r=allPossibleCases(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(is_function(r)){return"Invalid type: got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){var a=r[0].toLowerCase();r="a"+("aeiou".includes(a)?"n ":" ")+r[0]}else{r=new Intl.ListFormat("en",{style:"long",type:"disjunction"}).format(r)}}return"Expecting ".concat(r," got ").concat(t).concat(i)}function typecheck_number(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;typecheck(e,t,"number",n);var i=t.__type__;var a;if(is_pair(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(typeErrorMessage(e,i,r,n))}}function typecheck_numbers(r,e,n){e.forEach(function(e,t){typecheck_number(r,e,n,t+1)})}function typecheck_args(r,e,n){e.forEach(function(e,t){typecheck(r,e,n,t+1)})}function typecheck_text_port(e,t,r){typecheck(e,t,r);if(t.__type__===binary_port){throw new Error(typeErrorMessage(e,"binary-port","textual-port"))}}function typecheck(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=type(t).toLowerCase();if(is_function(r)){if(!r(t)){throw new Error(typeErrorMessage(e,i,r,n))}return}var a=false;if(is_pair(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(typeErrorMessage(e,i,r,n))}}function memoize(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}type=memoize(type);function type(e){var t=type_constants.get(e);if(t){return t}if(_typeof$1(e)==="object"){for(var r=0,n=Object.entries(type_mapping);r2&&arguments[2]!==undefined?arguments[2]:{},n=r.env,i=r.dynamic_env,a=r.use_dynamic;var o=n===null||n===void 0?void 0:n.new_frame(e,t);var u=i===null||i===void 0?void 0:i.new_frame(e,t);var s=new LambdaContext({env:o,use_dynamic:a,dynamic_env:u});return resolve_promises(e.apply(s,t))}function apply(n,e){var t=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},i=t.env,a=t.dynamic_env,o=t.use_dynamic,r=t.error,u=r===void 0?function(){}:r;e=evaluate_args(e,{env:i,dynamic_env:a,error:u,use_dynamic:o});return unpromise(e,function(e){if(is_raw_lambda(n)){n=unbind(n)}e=prepare_fn_args(n,e);var t=e.slice();var r=call_function(n,t,{env:i,dynamic_env:a,use_dynamic:o});return unpromise(r,function(e){if(is_pair(e)){e.mark_cycles();return quote(e)}return box(e)},u)})}var _p_name__=new WeakMap;var Parameter=function(){function n(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;_classCallCheck(this,n);_defineProperty(this,"__value__",void 0);_defineProperty(this,"__fn__",void 0);_classPrivateFieldInitSpec(this,_p_name__,{writable:true,value:void 0});this.__value__=e;if(t){if(!is_function(t)){throw new Error("Section argument to Parameter need to be function "+"".concat(type(t)," given"))}this.__fn__=t}if(r){_classPrivateFieldSet(this,_p_name__,r)}}_createClass(n,[{key:"__name__",get:function e(){return _classPrivateFieldGet(this,_p_name__)},set:function e(t){_classPrivateFieldSet(this,_p_name__,t);if(this.__fn__){this.__fn__.__name__="fn-".concat(t)}}},{key:"invoke",value:function e(){if(is_function(this.__fn__)){return this.__fn__(this.__value__)}return this.__value__}},{key:"inherit",value:function e(t){return new n(t,this.__fn__,this.__name__)}}]);return n}();var LambdaContext=function(){function t(e){_classCallCheck(this,t);_defineProperty(this,"env",void 0);_defineProperty(this,"dynamic_env",void 0);_defineProperty(this,"use_dynamic",void 0);Object.assign(this,e)}_createClass(t,[{key:"__name__",get:function e(){return this.env.__name__}},{key:"__parent__",get:function e(){return this.env.__parent__}},{key:"get",value:function e(){var t;return(t=this.env).get.apply(t,arguments)}}]);return t}();function search_param(e,t){var r=e.get(t.__name__,{throwError:false});if(is_parameter(r)&&r!==t){return r}var n=user_env.get("**interaction-environment**");while(true){var i=e.get("parent.frame",{throwError:false});e=i(0);if(e===n){break}r=e.get(t.__name__,{throwError:false});if(is_parameter(r)&&r!==t){return r}}return t}var Continuation=function(){function t(e){_classCallCheck(this,t);_defineProperty(this,"__value__",void 0);this.__value__=e}_createClass(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}}]);return t}();function _evaluate(u){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},s=e.env,c=e.dynamic_env,l=e.use_dynamic,t=e.error,f=t===void 0?noop:t,r=_objectWithoutProperties(e,_excluded6);return function(e){try{if(!is_env(c)){c=s===true?user_env:s||user_env}if(l){s=c}else if(s===true){s=user_env}else{s=s||global_env}var t={env:s,dynamic_env:c,use_dynamic:l,error:f};var r;if(is_null(u)){return u}if(u instanceof LSymbol){return s.get(u)}if(!is_pair(u)){return u}var n=u.car;var e=u.cdr;if(is_pair(n)){r=resolve_promises(_evaluate(n,t));if(is_promise(r)){return r.then(function(e){if(!is_callable(e)){throw new Error(type(e)+" "+s.get("repr")(e)+" is not callable while evaluating "+u.toString())}return _evaluate(new Pair(e,u.cdr),t)})}else if(!is_callable(r)){throw new Error(type(r)+" "+s.get("repr")(r)+" is not callable while evaluating "+u.toString())}}if(n instanceof LSymbol){r=s.get(n)}else if(is_function(n)){r=n}var i;if(r instanceof Syntax){i=evaluate_syntax(r,u,t)}else if(r instanceof Macro){i=evaluate_macro(r,e,t)}else if(is_function(r)){i=apply(r,e,t)}else if(r instanceof SyntaxParameter){i=evaluate_syntax(r._syntax,u,t)}else if(is_parameter(r)){var a=search_param(c,r);if(is_null(u.cdr)){i=a.invoke()}else{return unpromise(_evaluate(u.cdr.car,t),function(e){a.__value__=e})}}else if(is_continuation(r)){i=r.invoke()}else if(is_pair(u)){r=n&&n.toString();throw new Error("".concat(type(n)," ").concat(r," is not a function"))}else{return u}var o=s.get(Symbol["for"]("__promise__"),{throwError:false});if(o===true&&is_promise(i)){i=i.then(function(e){if(is_pair(e)&&!r[__data__]){return _evaluate(e,t)}return e});return new QuotedPromise(i)}return i}catch(e){f&&f.call(s,e,u)}}(r)}var compile=exec_collect(function(e){return e});var exec=exec_collect(function(e,t){return t});function exec_with_stacktrace(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.dynamic_env,i=t.use_dynamic;return _evaluate(e,{env:r,dynamic_env:n,use_dynamic:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}if(!(t instanceof IgnoreException)){throw t}}})}function exec_collect(h){return function(){var t=_asyncToGenerator(function(f){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},_=e.env,p=e.dynamic_env,d=e.use_dynamic;return _regeneratorRuntime.mark(function e(){var r,n,i,a,o,u,s,c,l;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!is_env(p)){p=_===true?user_env:_||user_env}if(_===true){_=user_env}else{_=_||user_env}r=[];if(!is_pair(f)){t.next=8;break}t.next=6;return exec_with_stacktrace(f,{env:_,dynamic_env:p,use_dynamic:d});case 6:t.t0=t.sent;return t.abrupt("return",[t.t0]);case 8:n=Array.isArray(f)?f:_parse(f);i=false;a=false;t.prev=11;u=_asyncIterator(n);case 13:t.next=15;return u.next();case 15:if(!(i=!(s=t.sent).done)){t.next=31;break}c=s.value;t.next=19;return exec_with_stacktrace(c,{env:_,dynamic_env:p,use_dynamic:d});case 19:l=t.sent;t.t1=r;t.t2=h;t.t3=c;t.next=25;return l;case 25:t.t4=t.sent;t.t5=(0,t.t2)(t.t3,t.t4);t.t1.push.call(t.t1,t.t5);case 28:i=false;t.next=13;break;case 31:t.next=37;break;case 33:t.prev=33;t.t6=t["catch"](11);a=true;o=t.t6;case 37:t.prev=37;t.prev=38;if(!(i&&u["return"]!=null)){t.next=42;break}t.next=42;return u["return"]();case 42:t.prev=42;if(!a){t.next=45;break}throw o;case 45:return t.finish(42);case 46:return t.finish(37);case 47:return t.abrupt("return",r);case 48:case"end":return t.stop()}},e,null,[[11,33,37,47],[38,,42,46]])})()});function e(e){return t.apply(this,arguments)}return e}()}function balanced(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){try{r=tokenize(e)}catch(e){if(e instanceof Unterminated){return false}throw e}}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var a=new Stack;var o=_createForOfIteratorHelper(r),u;try{for(o.s();!(u=o.n()).done;){var s=u.value;if(n.includes(s)){a.push(s)}else if(!a.is_empty()){var c=a.top();var l=t[c];if(s===l){a.pop()}else{throw new Error("Syntax error: missing closing ".concat(l))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){o.e(e)}finally{o.f()}return a.is_empty()}function fworker(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new root.Worker(r.createObjectURL(n))}function is_dev(){return lips.version.match(/^(\{\{VER\}\}|DEV)$/)}function get_current_script(){if(is_node()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var current_script=get_current_script();function bootstrap(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(current_script){e=current_script.replace(/[^/]*$/,"std.xcb")}else if(is_dev()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version,"/").concat(t)}}var r=global_env.get("load");return r.call(user_env,e,global_env)}function Worker(e){this.url=e;var o=this.worker=fworker(function(){var o;var u;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!u){i("Worker RPC: LIPS not initialized, call init first");return}u.then(function(){var e=r.params[0];var t=r.params[1];o.exec(e,{use_dynamic:t}).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var a=r.params[0];if(typeof a!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(a,"/dist/lips.min.js"));o=new lips.Interpreter("worker");u=bootstrap(a);u.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var a=++n;return new Promise(function(n,i){o.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===a){if(r.error){i(r.error)}else{n(r.result)}o.removeEventListener("message",e)}});o.postMessage({type:"RPC",method:t,id:a,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e,t){var r=t.use_dynamic,n=r===void 0?false:r;return this.rpc("eval",[e,n])}}var serialization_map={pair:function e(t){var r=_slicedToArray(t,2),n=r[0],i=r[1];return Pair(n,i)},number:function e(t){if(LString.isString(t)){return LNumber([t,10])}return LNumber(t)},regex:function e(t){var r=_slicedToArray(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return _nil},symbol:function e(t){if(LString.isString(t)){return LSymbol(t)}else if(Array.isArray(t)){return LSymbol(Symbol["for"](t[0]))}},string:LString,character:LCharacter};var available_class=Object.keys(serialization_map);var class_map={};for(var _i6=0,_Object$entries3=Object.entries(available_class);_i6<_Object$entries3.length;_i6++){var _Object$entries3$_i=_slicedToArray(_Object$entries3[_i6],2),i=_Object$entries3$_i[0],cls=_Object$entries3$_i[1];class_map[cls]=+i}function mangle_name(e){return class_map[e]}function resolve_name(e){return available_class[e]}function serialize(e){return JSON.stringify(e,function(e,t){var r=this[e];if(r){if(r instanceof RegExp){return{"@":mangle_name("regex"),"#":[r.source,r.flags]}}var n=mangle_name(r.constructor.__class__);if(!is_undef(n)){return{"@":n,"#":r.serialize()}}}return t})}function unserialize(e){return JSON.parse(e,function(e,t){if(t&&_typeof$1(t)==="object"){if(!is_undef(t["@"])){var r=resolve_name(t["@"]);if(serialization_map[r]){return serialization_map[r](t["#"])}}}return t})}var cbor=function(){var e={pair:Pair,symbol:LSymbol,number:LNumber,string:LString,character:LCharacter,nil:_nil.constructor,regex:RegExp};function t(e,t){return{deserialize:t,Class:e}}var r=new Encoder;var a={};for(var n=0,i=Object.entries(serialization_map);n1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var a=0;t.forEach(function(e){i.set(e,a);a+=e.length});return i}else if(t.length){return t[0]}}function encode_magic(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var MAGIC_LENGTH=7;function decode_magic(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,MAGIC_LENGTH));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function serialize_bin(e){var t=encode_magic();var r=cbor.encode(e);return merge_uint8_array(t,pack_1(r,{magic:false}))}function unserialize_bin(e){var t=decode_magic(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=unpack_1(e.slice(MAGIC_LENGTH),{magic:false});return cbor.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function execError(e){console.error(e.message||e);if(Array.isArray(e.code)){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function init(){var o=["text/x-lips","text/x-scheme"];var u;function s(e){var t;return(t=e.getAttribute("data-bootstrap"))!==null&&t!==void 0?t:e.getAttribute("bootstrap")}function c(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(exec).then(t)["catch"](function(e){execError(e);t()})}else{return exec(r.innerHTML).then(t)["catch"](function(e){execError(e);t()})}})}function e(){return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function e(){var t=a.shift();if(!t){i()}else{var r=t.getAttribute("type");if(o.includes(r)){var n=s(t);if(!u&&typeof n==="string"){return bootstrap(n).then(function(){return c(t)}).then(e)}else{return c(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+o.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(currentScript){var t=currentScript;var r=s(t);if(typeof r==="string"){return bootstrap(r).then(function(){u=true;return e()})}}return e()}var currentScript=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){contentLoaded(window,init)}var banner=function(){var e=LString("Mon, 27 May 2024 11:41:47 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var a="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return a}();read_only(Ahead,"__class__","ahead");read_only(Pair,"__class__","pair");read_only(Nil,"__class__","nil");read_only(Pattern,"__class__","pattern");read_only(Formatter,"__class__","formatter");read_only(Macro,"__class__","macro");read_only(Syntax,"__class__","syntax");read_only(Syntax.Parameter,"__class__","syntax-parameter");read_only(Environment,"__class__","environment");read_only(InputPort,"__class__","input-port");read_only(OutputPort,"__class__","output-port");read_only(BufferedOutputPort,"__class__","output-port");read_only(OutputStringPort,"__class__","output-string-port");read_only(InputStringPort,"__class__","input-string-port");read_only(InputFilePort,"__class__","input-file-port");read_only(OutputFilePort,"__class__","output-file-port");read_only(LipsError,"__class__","lips-error");[LNumber,LComplex,LRational,LFloat,LBigInteger].forEach(function(e){read_only(e,"__class__","number")});read_only(LCharacter,"__class__","character");read_only(LSymbol,"__class__","symbol");read_only(LString,"__class__","string");read_only(QuotedPromise,"__class__","promise");read_only(Parameter,"__class__","parameter");var version="1.0.0-beta.19";var date="Mon, 27 May 2024 11:41:47 +0000";var parse=compose(uniterate_async,_parse);var lips={version:version,banner:banner,date:date,exec:exec,parse:parse,tokenize:tokenize,evaluate:_evaluate,compile:compile,serialize:serialize,unserialize:unserialize,serialize_bin:serialize_bin,unserialize_bin:unserialize_bin,bootstrap:bootstrap,Environment:Environment,env:user_env,Worker:Worker,Interpreter:Interpreter,balanced_parenthesis:balanced,balancedParenthesis:balanced,balanced:balanced,Macro:Macro,Syntax:Syntax,Pair:Pair,Values:Values,QuotedPromise:QuotedPromise,Error:LipsError,quote:quote,InputPort:InputPort,OutputPort:OutputPort,BufferedOutputPort:BufferedOutputPort,InputFilePort:InputFilePort,OutputFilePort:OutputFilePort,InputStringPort:InputStringPort,OutputStringPort:OutputStringPort,InputByteVectorPort:InputByteVectorPort,OutputByteVectorPort:OutputByteVectorPort,InputBinaryFilePort:InputBinaryFilePort,OutputBinaryFilePort:OutputBinaryFilePort,set_fs:set_fs,Formatter:Formatter,Parser:Parser,Lexer:Lexer,specials:specials,repr:repr,nil:_nil,eof:eof,LSymbol:LSymbol,LNumber:LNumber,LFloat:LFloat,LComplex:LComplex,LRational:LRational,LBigInteger:LBigInteger,LCharacter:LCharacter,LString:LString,Parameter:Parameter,rationalize:rationalize};global_env.set("lips",lips);export{BufferedOutputPort,Environment,LipsError as Error,Formatter,InputBinaryFilePort,InputByteVectorPort,InputFilePort,InputPort,InputStringPort,Interpreter,LBigInteger,LCharacter,LComplex,LFloat,LNumber,LRational,LString,LSymbol,Lexer,Macro,OutputBinaryFilePort,OutputByteVectorPort,OutputFilePort,OutputPort,OutputStringPort,Pair,Parameter,Parser,QuotedPromise,Syntax,Values,Worker,is_directive as _is_directive,balanced,balanced as balancedParenthesis,balanced as balanced_parenthesis,banner,bootstrap,compile,date,user_env as env,eof,_evaluate as evaluate,exec,_nil as nil,parse,quote,rationalize,repr,serialize,serialize_bin,set_fs,specials,tokenize,unserialize,unserialize_bin,version}; \ No newline at end of file + */Object.defineProperty(lzjbPack,"__esModule",{value:true});const NBBY=8,MATCH_BITS=6,MATCH_MIN=3,MATCH_MAX=(1<r-MATCH_MAX){t[i++]=e[n++];continue}l=(e[n]+13^e[n+1]-13^e[n+2])&LEMPEL_SIZE-1;c=n-f[l]&OFFSET_MASK;f[l]=n;a=n-c;if(a>=0&&a!=n&&e[n]==e[a]&&e[n+1]==e[a+1]&&e[n+2]==e[a+2]){t[o]|=u;for(s=MATCH_MIN;s>NBBY;t[i++]=c;n+=s}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function decompress(e,t,r){t=t|0;var n=0,i=0,a=0,o=0,u=1<<(NBBY-1|0),s=0,c=0;while(n>(NBBY-MATCH_BITS|0))+MATCH_MIN|0;c=(e[n]<4){r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;s=s-4|0}while(s>0){r[i]=r[a];i=i+1|0;a=a+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function encode_magic$1(){const e=new TextEncoder("utf-8");return e.encode(MAGIC_STRING)}const MAGIC_STRING="@lzjb";const MAGIC=encode_magic$1();function merge_uint8_array$1(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function number_to_bytes(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function pack(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=compress(e,r);const i=number_to_bytes(e.length);const a=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){a.unshift(MAGIC)}return merge_uint8_array$1(...a)}function unpack(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,MAGIC.length));if(s!==MAGIC_STRING){throw new Error("Invalid magic value")}}const r=e?MAGIC.length:0;const n=t[r];const i=r+1;const a=r+n+1;const o=bytes_to_number(t.slice(i,a));t=t.slice(a);const u=new Uint8Array(o);decompress(t,t.length,u);return u}var pack_1=lzjbPack.pack=pack;var unpack_1=lzjbPack.unpack=unpack;function unfetch(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],a={},o=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:o,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var u in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),a[t]=a[t]?a[t]+","+r:r}),e(o())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(u,c.headers[u]);r.send(c.body||null)})}var _excluded=["token"],_excluded2=["env"],_excluded3=["stderr","stdin","stdout","command_line"],_excluded4=["use_dynamic"],_excluded5=["use_dynamic"],_excluded6=["env","dynamic_env","use_dynamic","error"];function _classPrivateFieldInitSpec(e,t,r){_checkPrivateRedeclaration(e,t);t.set(e,r)}function _checkPrivateRedeclaration(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}function _callSuper(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function e(){return!!t})()}function _createForOfIteratorHelper(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=_unsupportedIterableToArray(t))||e&&t&&typeof t.length==="number"){if(r)t=r;var n=0;var i=function e(){};return{s:i,n:function e(){if(n>=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a=true,o=false,u;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();a=t.done;return t},e:function e(t){o=true;u=t},f:function e(){try{if(!a&&r["return"]!=null)r["return"]()}finally{if(o)throw u}}}}function _unsupportedIterableToArray(e,t){if(!e)return;if(typeof e==="string")return _arrayLikeToArray(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _arrayLikeToArray(e,t)}function _arrayLikeToArray(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1?t-1:0),n=1;n0&&arguments[0]!==undefined?arguments[0]:null;var t=user_env&&user_env.get("DEBUG",{throwError:false});if(e===null){return t===true}return(t===null||t===void 0?void 0:t.valueOf())===e.valueOf()}function num_mnemicic_re(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function gen_rational_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+/").concat(t,"+")}function gen_complex_re(e,t){return"".concat(num_mnemicic_re(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function gen_integer_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+")}var re_re=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var float_stre="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var complex_float_stre="(?:#[ie])?(?:[+-]?(?:[0-9][0-9_]*/[0-9][0-9_]*|nan.0|inf.0|".concat(float_stre,"|[+-]?[0-9]+))?(?:").concat(float_stre,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var float_re=new RegExp("^(#[ie])?".concat(float_stre,"$"),"i");function make_complex_match_re(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var complex_list_re=function(){var a={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];a[r]=make_complex_match_re(n,i)});return a}();var characters={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function ucs2decode(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);var n=r.number.split("/");var i=LRational({num:LNumber([n[0],r.radix||t]),denom:LNumber([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function parse_integer(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);if(r.inexact){return LFloat(parseInt(r.number,r.radix||t))}return LNumber([r.number,r.radix||t])}function parse_character(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\([\s\S]+)$/);if(t){r=t[1]}}if(r){return LCharacter(r)}throw new Error("Parse: invalid character")}function parse_complex(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=LNumber(1)}else if(e==="-"){t=LNumber(-1)}else if(e.match(int_bare_re)){t=LNumber([e,i])}else if(e.match(rational_bare_re)){var r=e.split("/");t=LRational({num:LNumber([r[0],i]),denom:LNumber([r[1],i])})}else if(e.match(float_re)){var n=parse_float(e);if(a.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return LNumber(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return LNumber(Number.NEGATIVE_INFINITY)}return LNumber(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(a.inexact){return LFloat(t.valueOf())}return t}var a=num_pre_parse(e);i=a.radix||i;var r;var n=a.number.match(complex_bare_match_re);if(i!==10&&n){r=n}else{r=a.number.match(complex_list_re[i])}var o,u;u=t(r[2]);if(r[1]){o=t(r[1])}else if(u instanceof LFloat){o=LFloat(0)}else{o=LNumber(0)}if(u.cmp(0)===0&&u.__type__==="bigint"){return o}return LComplex({im:u,re:o})}function is_int(e){return parseInt(e.toString(),10)===e}function parse_big_int(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var a=t[3]&&t[3].length;if(i0&&(t.exact||!t.number.match(/\./))){return LNumber(a).mul(u)}}}r=LFloat(r);if(t.exact){return r.toRational()}return r}function parse_string(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{var r=LString(JSON.parse(e));r.freeze();return r}catch(e){var n=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(n))}}function parse_symbol(e){e.match(/^name/);var t=/(^|.)\|/g;if(e.match(t)){e=e.split("|").filter(Boolean).reduce(function(e,t){var r="";if(t.match(/^\\+$/)){if(t.length>1){var n=Math.floor(t.length/2);r="\\".repeat(n)}if(t.length%2!==0){r+="|"}}else{r=t}return e+r});var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\([trn])/g,function(e,t){return r[t]})}return new LSymbol(e)}function parse_argument(e){if(constants.hasOwnProperty(e)){return constants[e]}if(e.match(/^"[\s\S]*"$/)){return parse_string(e)}else if(e[0]==="#"){var t=e.match(re_re);if(t){return new RegExp(t[1],t[2])}else if(e.match(char_re)){return parse_character(e)}var r=e.match(/#\\(.+)/);if(r&&ucs2decode(r[1]).length===1){return parse_character(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(int_re)){return parse_integer(e)}else if(e.match(float_re)){return parse_float(e)}else if(e.match(rational_re)){return parse_rational(e)}else if(e.match(complex_re)){return parse_complex(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return parse_symbol(e)}function is_atom_string(e){return!(["(",")","[","]"].includes(e)||specials.names().includes(e))}function is_symbol_string(e){return is_atom_string(e)&&!(e.match(re_re)||e.match(/^"[\s\S]*"$/)||e.match(int_re)||e.match(float_re)||e.match(complex_re)||e.match(rational_re)||e.match(char_re)||["#t","#f","nil"].includes(e))}var string_re=/"(?:\\[\S\s]|[^"])*"?/g;function escape_regex(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function Stack(){this.data=[]}Stack.prototype.push=function(e){this.data.push(e)};Stack.prototype.top=function(){return this.data[this.data.length-1]};Stack.prototype.pop=function(){return this.data.pop()};Stack.prototype.is_empty=function(){return!this.data.length};function tokens(e){if(e instanceof LString){e=e.valueOf()}var t=new Lexer(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===eof){break}r.push(n);t.skip()}return r}function multiline_formatter(e){var t=e.token,r=_objectWithoutProperties(e,_excluded);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return _objectSpread({token:t},r)}function Thunk(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}Thunk.prototype.toString=function(){return"#"};function trampoline(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof LString){e=e.toString()}if(t){return tokens(e)}else{var r=tokens(e).map(function(e){if(e.token==="#\\ "||e.token=="#\\\n"){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return strip_s_comments(r)}}function strip_s_comments(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof LSymbol){if(e.is_gensym()){return e}e=e.valueOf()}if(is_gensym(e)){return LSymbol(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function hygienic_begin(e,t){var r=global_env.get("begin");var n=gensym("begin");e.forEach(function(e){e.set(n,r)});return new Pair(n,t)}function QuotedPromise(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=type(e);n.fulfilled=true;n.pending=false;return e});read_only(this,"_promise",e,{hidden:true});if(is_function(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});read_only(this,"__promise__",e);this.then=false}QuotedPromise.prototype.then=function(e){return new QuotedPromise(this.valueOf().then(e))};QuotedPromise.prototype["catch"]=function(e){return new QuotedPromise(this.valueOf()["catch"](e))};QuotedPromise.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};QuotedPromise.prototype.toString=function(){if(this.__pending__){return QuotedPromise.pending_str}if(this.__rejected__){return QuotedPromise.rejected_str}return"#")};QuotedPromise.pending_str="#";QuotedPromise.rejected_str="#";function promise_all(e){if(Array.isArray(e)){return Promise.all(escape_quoted_promises(e)).then(unescape_quoted_promises)}return e}function escape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof QuotedPromise){t[r]=new Value(n)}else{t[r]=n}}return t}function unescape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Value){t[r]=n.valueOf()}else{t[r]=n}}return t}var specials={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){try{return this.get(t).type}catch(e){console.log({name:t});console.log(e);return null}},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new LSymbol("quote-promise"),specials.LITERAL]];var builtins=defined_specials.map(function(e){return e[0]});Object.freeze(builtins);Object.defineProperty(specials,"__builtins__",{writable:false,value:builtins});defined_specials.forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];specials.append(r,n,i)});var Lexer=function(){function v(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;_classCallCheck(this,v);read_only(this,"__input__",e.replace(/\r/g,""));var a={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return a[r]},set:function e(t){a[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}_createClass(v,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return eof}if(this._token){read_only(this,"__token__",this.token(true));return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);if(!this.__token__){read_only(this,"__token__",this.token(true))}return this.token(t)}return eof}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return eof}for(var r=this._i;r=r){return eof}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var a=i.match(/\n/g);if(a){this._line+=a.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return eof}return LCharacter(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},n=r.prev_char,i=r["char"],a=r.next_char;var o=_slicedToArray(t,4),u=o[0],s=o[1],c=o[2],l=o[3];if(t.length!==5){throw new Error("Lexer: Invalid rule of length ".concat(t.length))}if(is_string(u)){if(u!==i){return false}}else if(!i.match(u)){return false}if(!match_or_null(s,n)){return false}if(!match_or_null(c,a)){return false}if(l!==this._state){return false}return true}},{key:"next_token",value:function e(){if(this._i>=this.__input__.length){return false}var t=true;e:for(var r=this._i,n=this.__input__.length;r2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var a=[];for(var o=0,u=t.length;o0&&arguments[0]!==undefined?arguments[0]:{},t=e.env,r=e.meta,n=r===void 0?false:r,i=e.formatter,a=i===void 0?multiline_formatter:i;_classCallCheck(this,o);read_only(this,"_formatter",a,{hidden:true});read_only(this,"__env__",t);read_only(this,"_meta",n,{hidden:true});read_only(this,"_refs",[],{hidden:true});read_only(this,"_state",{parentheses:0,fold_case:false},{hidden:true})}_createClass(o,[{key:"_with_syntax_scope",value:function e(t){var r=get_internal(this.__env__);var n=r.get("stdin");global_env.set("lips",_objectSpread(_objectSpread({},lips),{},{__parser__:this}));r.set("stdin",new ParserInputPort(this,this.__env__));var i=function e(){global_env.set("lips",lips);r.set("stdin",n)};return unpromise(t(),function(e){i();return e},i)}},{key:"parse",value:function e(t){if(t instanceof LString){t=t.toString()}read_only(this,"__lexer__",new Lexer(t))}},{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===eof)){t.next=4;break}return t.abrupt("return",eof);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!is_directive(r.token)){t.next=11;break}this.skip();if(r.token==="#!fold-case"){this._state.fold_case=true}else if(r.token==="#!no-fold-case"){this._state.fold_case=false}return t.abrupt("continue",0);case 11:if(!(r.token==="#;")){t.next=18;break}this.skip();if(!(this.__lexer__.peek()===eof)){t.next=15;break}throw new Error("Lexer: syntax error eof found after comment");case 15:t.next=17;return this._read_object();case 17:return t.abrupt("continue",0);case 18:return t.abrupt("break",21);case 21:r=this._formatter(r);if(this._state.fold_case){r.token=foldcase_string(r.token)}if(!this._meta){t.next=25;break}return t.abrupt("return",r);case 25:return t.abrupt("return",r.token);case 26:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){return["(","["].includes(t)}},{key:"is_close",value:function e(t){return[")","]"].includes(t)}},{key:"read_list",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r,n,i,a,o,u;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=_nil,n=r;case 1:t.next=4;return this.peek();case 4:a=t.sent;if(!(a===eof)){t.next=7;break}return t.abrupt("break",31);case 7:if(!this.is_close(a)){t.next=11;break}--this._state.parentheses;this.skip();return t.abrupt("break",31);case 11:if(!(a==="."&&!is_nil(r))){t.next=19;break}this.skip();t.next=15;return this._read_object();case 15:n.cdr=t.sent;i=true;t.next=29;break;case 19:if(!i){t.next=23;break}throw new Error("Parser: syntax error more than one element after dot");case 23:t.next=25;return this._read_object();case 25:o=t.sent;u=new Pair(o,_nil);if(is_nil(r)){r=u}else{n.cdr=u}n=u;case 29:t.next=1;break;case 31:return t.abrupt("return",r);case 32:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===eof)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",parse_argument(r));case 6:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return _evaluate(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof DatumReference){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",unpromise(this._resolve_object(r),function(e){if(is_pair(e)){e.mark_cycles()}return e}));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"balanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t,r){var n=this._state.parentheses;var i;if(n<0){i=new Error("Parser: unexpected parenthesis");i.__code__=[r.toString()+")"]}else{i=new Error("Parser: expected parenthesis but eof found");var a=new RegExp("\\){".concat(n,"}$"));i.__code__=[t.toString().replace(a,"")]}throw i}},{key:"_resolve_object",value:function(){var t=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n=this;var i;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!is_plain_object(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!is_pair(r)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!is_pair(r)){t.next=15;break}if(!(r.car instanceof DatumReference)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof DatumReference)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r=this;var n,i,a,o,u,s,c,l,f,_,p,d;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:n=t.sent;if(!(n===eof)){t.next=5;break}return t.abrupt("return",n);case 5:if(!is_special(n)){t.next=51;break}i=specials.get(n);a=is_builtin(n);this.skip();s=is_symbol_extension(n);t.t0=this;t.next=13;return this.peek();case 13:t.t1=t.sent;c=t.t0.is_close.call(t.t0,t.t1);if(!s){t.next=19;break}t.t2=undefined;t.next=22;break;case 19:t.next=21;return this._read_object();case 21:t.t2=t.sent;case 22:l=t.t2;if(!(l===eof)){t.next=25;break}throw new Unterminated("Expecting expression eof found");case 25:if(a){t.next=32;break}u=this.__env__.get(i.symbol);if(!(typeof u==="function")){t.next=32;break}if(is_literal(n)){f=[l]}else if(is_nil(l)){f=[]}else if(is_pair(l)){f=l.to_array(false)}if(!(f||s)){t.next=31;break}return t.abrupt("return",this._with_syntax_scope(function(){return call_function(u,s?[]:f,{env:r.__env__,dynamic_env:r.__env__,use_dynamic:false})}));case 31:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(i.symbol));case 32:if(!is_literal(n)){t.next=38;break}if(!c){t.next=35;break}throw new Error("Parse Error: expecting datum");case 35:o=new Pair(i.symbol,new Pair(l,_nil));t.next=39;break;case 38:o=new Pair(i.symbol,l);case 39:if(!a){t.next=41;break}return t.abrupt("return",o);case 41:if(!(u instanceof Macro)){t.next=50;break}t.next=44;return this._with_syntax_scope(function(){return r.evaluate(o)});case 44:_=t.sent;if(!(is_pair(_)||_ instanceof LSymbol)){t.next=47;break}return t.abrupt("return",Pair.fromArray([LSymbol("quote"),_]));case 47:return t.abrupt("return",_);case 50:throw new Error("Parse Error: invalid parser extension: "+i.symbol);case 51:p=this.match_datum_ref(n);if(!(p!==null)){t.next=57;break}this.skip();if(!this._refs[p]){t.next=56;break}return t.abrupt("return",new DatumReference(p,this._refs[p]));case 56:throw new Error("Parse Error: invalid datum label #".concat(p,"#"));case 57:d=this.match_datum_label(n);if(!(d!==null)){t.next=64;break}this.skip();this._refs[d]=this._read_object();return t.abrupt("return",this._refs[d]);case 64:if(!this.is_close(n)){t.next=69;break}--this._state.parentheses;this.skip();t.next=76;break;case 69:if(!this.is_open(n)){t.next=75;break}++this._state.parentheses;this.skip();return t.abrupt("return",this.read_list());case 75:return t.abrupt("return",this.read_value());case 76:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return o}();var Unterminated=function(e){_inherits(t,e);function t(){_classCallCheck(this,t);return _callSuper(this,t,arguments)}return _createClass(t)}(_wrapNativeSuper(Error));Parser.Unterminated=Unterminated;var DatumReference=function(){function r(e,t){_classCallCheck(this,r);this.name=e;this.data=t}_createClass(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function _parse(e,t){return _parse2.apply(this,arguments)}function _parse2(){_parse2=_wrapAsyncGenerator(_regeneratorRuntime.mark(function e(r,n){var i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!n){if(global_env){n=global_env.get("**interaction-environment**",{throwError:false})}else{n=user_env}}if(r instanceof Parser){i=r}else{i=new Parser({env:n});i.parse(r)}case 2:t.next=5;return _awaitAsyncGenerator(i.read_object());case 5:o=t.sent;if(!i.balanced()){i.ballancing_error(o,a)}if(!(o===eof)){t.next=9;break}return t.abrupt("break",14);case 9:a=o;t.next=12;return o;case 12:t.next=2;break;case 14:case"end":return t.stop()}},e)}));return _parse2.apply(this,arguments)}function unpromise(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(is_promise(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return unpromise_array(e,t,r)}if(is_plain_object(e)){return unpromise_object(e,t,r)}return t(e)}function unpromise_array(t,r,e){if(t.find(is_promise)){return unpromise(promise_all(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function unpromise_object(t,e,r){var i=Object.keys(t);var n=[],a=[];var o=i.length;while(o--){var u=i[o];var s=t[u];n[o]=s;if(is_promise(s)){a.push(s)}}if(a.length){return unpromise(promise_all(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function read_only(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,a=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!a})}function uniterate_async(e){return _uniterate_async.apply(this,arguments)}function _uniterate_async(){_uniterate_async=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n,i,a,o,u,s,c;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:n=[];i=false;a=false;t.prev=3;u=_asyncIterator(r);case 5:t.next=7;return u.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);a=true;o=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&u["return"]!=null)){t.next=24;break}t.next=24;return u["return"]();case 24:t.prev=24;if(!a){t.next=27;break}throw o;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}},e,null,[[3,15,19,29],[20,,24,28]])}));return _uniterate_async.apply(this,arguments)}function matcher(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(is_function(t)){return t}throw new Error("Invalid matcher")}function doc(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=trim_lines(r)}}if(e){t.__name__=e}else if(t.name&&!is_lambda(t)){t.__name__=t.name}return t}function trim_lines(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function previousSexp(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function lineIndent(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function match(e,t){return l(e,t)===t.length;function l(r,n){function e(e,t){var r=_createForOfIteratorHelper(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var a=l(i,t);if(a!==-1){return a}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[a]===Symbol["for"]("symbol")&&!is_symbol_string(n[u])}function i(){var e=r[a+1];var t=n[u+1];if(e!==undefined&&t!==undefined){return l([e],[t])}}var a=0;var o={};for(var u=0;u0){continue}}else if(t()){return-1}}else if(r[a]instanceof Array){var c=l(r[a],n.slice(u));if(c===-1||c+u>n.length){return-1}u+=c-1;a++;continue}else{return-1}a++}if(r.length!==a){return-1}return n.length}}function Formatter(e){this.__code__=e.replace(/\r/g,"")}Formatter.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*?-values|\*)?)$/],shift:{1:["&","#"]}}};Formatter.match=match;Formatter.prototype._options=function e(t){var r=Formatter.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var a=n.shift||{1:[]};return _objectSpread(_objectSpread(_objectSpread({},r),t),{},{exceptions:{specials:[].concat(_toConsumableArray(r.exceptions.specials),_toConsumableArray(i)),shift:_objectSpread(_objectSpread({},a),{},{1:[].concat(_toConsumableArray(r.exceptions.shift[1]),_toConsumableArray(a[1]))})}})};Formatter.prototype.indent=function e(t){var r=tokenize(this.__code__,true);return this._indent(r,t)};Formatter.exception_shift=function(a,e){function t(e){if(!e.length){return false}if(e.indexOf(a)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=_createForOfIteratorHelper(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(a.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){n.offset=0}if(a.toString()===t.toString()&&balanced(a)){return n.offset+a[0].col}else if(a.length===1){return n.offset+a[0].col+1}else{var s=-1;if(o){var c=Formatter.exception_shift(o.token,n);if(c!==-1){s=c}}if(s===-1){s=Formatter.exception_shift(a[1].token,n)}if(s!==-1){return n.offset+a[0].col+s}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return n.offset+a[1].col}return n.offset+a[3].col}else if(a[0].line===a[1].line){return n.offset+n.indent+a[0].col}else{var l=a.slice(2);for(var f=0;f")};Ahead.prototype.match=function(e){return e.match(this.pattern)};function Pattern(){for(var e=arguments.length,t=new Array(e),r=0;r")};Formatter.Pattern=Pattern;Formatter.Ahead=Ahead;var p_o=/^[[(]$/;var p_e=/^[\])]$/;var not_p=/[^()[\]]/;var not_close=new Ahead(/[^)\]]/);var glob=Symbol["for"]("*");var sexp_or_atom=new Pattern([p_o,glob,p_e],[not_p],"+");var sexp=new Pattern([p_o,glob,p_e],"+");var symbol=new Pattern([Symbol["for"]("symbol")],"?");var symbols=new Pattern([Symbol["for"]("symbol")],"*");var identifiers=[p_o,symbols,p_e];var let_value=new Pattern([p_o,Symbol["for"]("symbol"),glob,p_e],"+");var syntax_rules=keywords_re("syntax-rules");var def_lambda_re=keywords_re("define","lambda","define-macro","syntax-rules");var non_def=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var let_re=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function keywords_re(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!u[e]){u[e]=previousSexp(o,e)}});var s=_createForOfIteratorHelper(i),c;try{for(s.s();!(c=s.n()).done;){var l=_slicedToArray(c.value,3),f=l[0],_=l[1],p=l[2];_=_.valueOf();var d=_>0?u[_]:o;var h=d.filter(function(e){return e.trim()&&!is_special(e)});var m=r(d);var y=match(f,h);var v=n.slice(a).find(function(e){return e.trim()&&!is_special(e)});if(y&&(p instanceof Ahead&&p.match(v)||!p)){var b=a-m;if(n[b]!=="\n"){if(!n[b].trim()){n[b]="\n"}else{n.splice(b,0,"\n");a++}}a+=m;continue e}}}catch(e){s.e(e)}finally{s.f()}}this.__code__=n.join("");return this};Formatter.prototype._spaces=function(e){return" ".repeat(e)};Formatter.prototype.format=function e(t){var r=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var n=tokenize(r,true);var i=this._options(t);var a=0;var o=0;for(var u=0;u0){n=Math.floor(t()*r);r--;var i=[e[n],e[r]];e[r]=i[0];e[n]=i[1]}return e}function Nil(){}Nil.prototype.toString=function(){return"()"};Nil.prototype.valueOf=function(){return undefined};Nil.prototype.serialize=function(){return 0};Nil.prototype.to_object=function(){return{}};Nil.prototype.append=function(e){return new Pair(e,_nil)};Nil.prototype.to_array=function(){return[]};var _nil=new Nil;function Pair(e,t){if(typeof this!=="undefined"&&this.constructor!==Pair||typeof this==="undefined"){return new Pair(e,t)}this.car=e;this.cdr=t}function to_array(a,o){return function e(t){typecheck(a,t,["pair","nil"]);if(is_nil(t)){return[]}var r=[];var n=t;while(true){if(is_pair(n)){if(n.have_cycles("cdr")){break}var i=n.car;if(o&&is_pair(i)){i=this.get(a).call(this,i)}r.push(i);n=n.cdr}else if(is_nil(n)){break}else{throw new Error("".concat(a,": can't convert improper list"))}}return r}}Pair.prototype.flatten=function(){return Pair.fromArray(flatten(this.to_array()))};Pair.prototype.length=function(){var e=0;var t=this;while(true){if(!t||is_nil(t)||!is_pair(t)||t.have_cycles("cdr")){break}e++;t=t.cdr}return e};Pair.match=function(e,t){if(e instanceof LSymbol){return LSymbol.is(e,t)}else if(is_pair(e)){return Pair.match(e.car,t)||Pair.match(e.cdr,t)}else if(Array.isArray(e)){return e.some(function(e){return Pair.match(e,t)})}else if(is_plain_object(e)){return Object.values(e).some(function(e){return Pair.match(e,t)})}return false};Pair.prototype.find=function(e){return Pair.match(this,e)};Pair.prototype.clone=function(){var r=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(is_pair(e)){if(n.has(e)){return n.get(e)}var t=new Pair;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[__cycles__]=e[__cycles__];return t}return e}return i(this)};Pair.prototype.last_pair=function(){var e=this;while(true){if(!is_pair(e.cdr)){return e}if(e.have_cycles("cdr")){break}e=e.cdr}};Pair.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(is_pair(this.car)){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(is_pair(this.cdr)){t=t.concat(this.cdr.to_array(e))}return t};Pair.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(is_pair(e)||r&&e instanceof Array&&e[__data__]){return e}if(t===false){var n=_nil;for(var i=e.length;i--;){n=new Pair(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=_toConsumableArray(e)}var a=_nil;var o=e.length;while(o--){var u=e[o];if(u instanceof Array){u=Pair.fromArray(u,t,r)}else if(typeof u==="string"){u=LString(u)}else if(typeof u==="number"&&!Number.isNaN(u)){u=LNumber(u)}a=new Pair(u,a)}return a};Pair.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(is_pair(t)&&is_pair(t.car)){var n=t.car;var i=n.car;if(i instanceof LSymbol){i=i.__name__}if(i instanceof LString){i=i.valueOf()}var a=n.cdr;if(is_pair(a)){a=a.to_object(e)}if(is_native(a)){if(!e){a=a.valueOf()}}r[i]=a;t=t.cdr}else{break}}return r};Pair.fromPairs=function(e){return e.reduce(function(e,t){return new Pair(new Pair(new LSymbol(t[0]),t[1]),e)},_nil)};Pair.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return Pair.fromPairs(e)};Pair.prototype.reduce=function(e){var t=this;var r=_nil;while(true){if(!is_nil(t)){r=e(r,t.car);t=t.cdr}else{break}}return r};Pair.prototype.reverse=function(){if(this.have_cycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=_nil;while(!is_nil(e)){var r=e.cdr;e.cdr=t;t=e;e=r}return t};Pair.prototype.transform=function(n){function i(e){if(is_pair(e)){if(e.replace){delete e.replace;return e}var t=n(e.car);if(is_pair(t)){t=i(t)}var r=n(e.cdr);if(is_pair(r)){r=i(r)}return new Pair(t,r)}return e}return i(this)};Pair.prototype.map=function(e){if(typeof this.car!=="undefined"){return new Pair(e(this.car),is_nil(this.cdr)?_nil:this.cdr.map(e))}else{return _nil}};var repr=new Map;function is_plain_object(e){return e&&_typeof$1(e)==="object"&&e.constructor===Object}var props=Object.getOwnPropertyNames(Array.prototype);var array_methods=[];props.forEach(function(e){array_methods.push(Array[e],Array.prototype[e])});function is_array_method(e){e=unbind(e);return array_methods.includes(e)}function is_lips_function(e){return is_function(e)&&(is_lambda(e)||e.__doc__)}function user_repr(e){var r=e.constructor||Object;var n=is_plain_object(e);var i=is_function(e[Symbol.asyncIterator])||is_function(e[Symbol.iterator]);var a;if(repr.has(r)){a=repr.get(r)}else{repr.forEach(function(e,t){t=unbind(t);if(r===t&&(t===Object&&n&&!i||t!==Object)){a=e}})}return a}var str_mapping=new Map;[[true,"#t"],[false,"#f"],[null,"#null"],[undefined,"#void"]].forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];str_mapping.set(r,n)});function symbolize(r){if(r&&_typeof$1(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=toString(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_typeof$1(t)==="object"&&t.constructor===Object){n[e]=symbolize(t)}else{n[e]=toString(t)}});return n}return r}function get_props(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function has_own_function(e,t){return e.hasOwnProperty(t)&&is_function(e.toString)}function function_to_string(e){if(is_native_function(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(is_function(t)&&is_lambda(t)){if(e[__class__]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(LString.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_typeof$1(n)==="symbol"){n=symbol_to_string(n)}if(typeof n==="string"){return"#")}}if(has_own_function(e,"toString")){return e.toString()}else if(e.name&&!is_lambda(e)){return"#")}else{return"#"}}var instances=new Map;[[Error,function(e){return e.message}],[Pair,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.mark_cycles()}return e.toString.apply(e,[r].concat(_toConsumableArray(i)))}],[LCharacter,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[LString,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];instances.set(r,n)});var native_types=[LSymbol,Macro,Values,InputPort,OutputPort,Environment,QuotedPromise];function toString(e,t,r){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(str_mapping.has(e)){return str_mapping.get(e)}if(is_prototype(e)){return"#"}if(e){var n=e.constructor;if(instances.has(n)){for(var i=arguments.length,a=new Array(i>3?i-3:0),o=3;o"}if(e===null){return"null"}if(is_function(e)){if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}return function_to_string(e)}if(_typeof$1(e)==="object"){var l=e.constructor;if(!l){l=Object}var f;if(typeof l.__class__==="string"){f=l.__class__}else{var _=user_repr(e);if(_){if(is_function(_)){return _(e,t)}else{throw new Error("toString: Invalid repr value")}}f=l.name}if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}if(type(e)==="instance"){if(is_lambda(l)&&l.__name__){f=l.__name__.valueOf();if(_typeof$1(f)==="symbol"){f=f.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/,"$1")}}else if(!is_native_function(l)){f="instance"}}if(is_iterator(e,Symbol.iterator)){if(f){return"#")}return"#"}if(is_iterator(e,Symbol.asyncIterator)){if(f){return"#")}return"#"}if(f!==""){return"#<"+f+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}Pair.prototype.mark_cycles=function(){mark_cycles(this);return this};Pair.prototype.have_cycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.have_cycles("car")||this.have_cycles("cdr")}return!!(this[__cycles__]&&this[__cycles__][e])};Pair.prototype.is_cycle=function(){return is_cycle(this)};function is_cycle(e){if(!is_pair(e)){return false}if(e.have_cycles()){return true}return is_cycle(e.car,fn)||is_cycle(e.cdr,fn)}function mark_cycles(e){var t=[];var i=[];var a=[];function o(e){if(!t.includes(e)){t.push(e)}}function u(e,t,r,n){if(is_pair(r)){if(n.includes(r)){if(!a.includes(r)){a.push(r)}if(!e[__cycles__]){e[__cycles__]={}}e[__cycles__][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=trampoline(function e(t,r){if(is_pair(t)){delete t[__ref__];delete t[__cycles__];o(t);r.push(t);var n=u(t,"car",t.car,r);var i=u(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new Thunk(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(is_pair(e[__cycles__][t])){var r=n.indexOf(e[__cycles__][t]);e[__cycles__][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return a.includes(e)});n.forEach(function(e,t){e[__ref__]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}Pair.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[__ref__]){i.push(this[__ref__]+"(")}else if(!n){i.push("(")}var a;if(this[__cycles__]&&this[__cycles__].car){a=this[__cycles__].car}else{a=toString(this.car,e,true)}if(a!==undefined){i.push(a)}if(is_pair(this.cdr)){if(this[__cycles__]&&this[__cycles__].cdr){i.push(" . ");i.push(this[__cycles__].cdr)}else{if(this.cdr[__ref__]){i.push(" . ")}else{i.push(" ")}var o=this.cdr.toString(e,{nested:true});i.push(o)}}else if(!is_nil(this.cdr)){i=i.concat([" . ",toString(this.cdr,e,true)])}if(!n||this[__ref__]){i.push(")")}return i.join("")};Pair.prototype.set=function(e,t){this[e]=t;if(is_pair(t)){this.mark_cycles()}};Pair.prototype.append=function(e){if(e instanceof Array){return this.append(Pair.fromArray(e))}var t=this;if(t.car===undefined){if(is_pair(e)){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(!is_nil(e)){while(true){if(is_pair(t)&&!is_nil(t.cdr)){t=t.cdr}else{break}}t.cdr=e}return this};Pair.prototype.serialize=function(){return[this.car,this.cdr]};Pair.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(is_nil(t)){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function abs(e){return e<0?-e:e}function seq_compare(e,t){var r=_toArray(t),n=r[0],i=r.slice(1);while(i.length>0){var a=i,o=_slicedToArray(a,1),u=o[0];if(!e(n,u)){return false}var s=i;var c=_toArray(s);n=c[0];i=c.slice(1)}return true}function equal(e,t){if(is_function(e)){return is_function(t)&&unbind(e)===unbind(t)}else if(e instanceof LNumber){if(!(t instanceof LNumber)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return equal(LNumber(e),LNumber(t))}else if(e instanceof LCharacter){if(!(t instanceof LCharacter)){return false}return e.__char__===t.__char__}else{return e===t}}function same_atom(e,t){if(type(e)!==type(t)){return false}if(!is_atom(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof LString){return e.valueOf()===t.valueOf()}return equal(e,t)}function is_atom(e){return e instanceof LSymbol||LString.isString(e)||is_nil(e)||e===null||e instanceof LCharacter||e instanceof LNumber||e===true||e===false}var truncate=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function Macro(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==Macro||typeof this==="undefined"){return new Macro(e,t)}typecheck("Macro",e,"string",1);typecheck("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=trim_lines(r)}}this.__name__=e;this.__fn__=t}Macro.defmacro=function(e,t,r,n){var i=new Macro(e,t,r,n);i.__defmacro__=true;return i};Macro.prototype.invoke=function(e,t,r){var n=t.env,i=_objectWithoutProperties(t,_excluded2);var a=_objectSpread(_objectSpread({},i),{},{macro_expand:r});var o=this.__fn__.call(n,e,a,this.__name__);return o};Macro.prototype.toString=function(){return"#")};var macro="define-macro";var recur_guard=-1e4;function macro_expand(c){return function(){var r=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,v){var a,b,n,i,o,g,w,D,x,L,E,S,u,A,s;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:s=function e(){s=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,n,i){var a,o,u,s,c,l,f,_,p,d,h,m,y;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!(is_pair(r)&&r.car instanceof LSymbol)){t.next=50;break}if(!r[__data__]){t.next=3;break}return t.abrupt("return",r);case 3:a=r.car.valueOf();o=i.get(r.car,{throwError:false});u=g(r.car);s=u||w(o,r)||D(o);if(!(s&&is_pair(r.cdr.car))){t.next=28;break}if(!u){t.next=15;break}b=L(r.cdr.car);t.next=12;return S(r.cdr.car,n);case 12:c=t.sent;t.next=17;break;case 15:b=x(r.cdr.car);c=r.cdr.car;case 17:t.t0=Pair;t.t1=r.car;t.t2=Pair;t.t3=c;t.next=23;return A(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!E(a,o)){t.next=50;break}l=o instanceof Syntax?r:r.cdr;t.next=32;return o.invoke(l,_objectSpread(_objectSpread({},v),{},{env:i}),true);case 32:f=t.sent;if(!(o instanceof Syntax)){t.next=41;break}_=f,p=_.expr,d=_.scope;if(!is_pair(p)){t.next=40;break}if(!(n!==-1&&n<=1||n")}return"#"};var SyntaxParameter=_createClass(function e(t){_classCallCheck(this,e);read_only(this,"_syntax",t,{hidden:true});read_only(this._syntax,"_param",true,{hidden:true})});Syntax.Parameter=SyntaxParameter;function extract_patterns(e,t,K,J){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var W={"...":{symbols:{},lists:[]},symbols:{}};var Q=r.expansion,X=r.define;log(K);function Z(t,e){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var n=r.ellipsis,i=n===void 0?false:n,a=r.trailing,I=a===void 0?false:a,o=r.pattern_names,u=o===void 0?[]:o;log({code:e,pattern:t});if(is_atom(t)&&!(t instanceof LSymbol)){return same_atom(t,e)}if(t instanceof LSymbol){var s=t.literal();if(K.includes(s)){if(!LSymbol.is(e,s)&&!LSymbol.is(t,e)){return false}var c=Q.ref(s);return!c||c===X||c===global_env}}if(Array.isArray(t)&&Array.isArray(e)){log("<<< a 1");if(t.length===0&&e.length===0){return true}if(LSymbol.is(t[1],J)){if(t[0]instanceof LSymbol){var l=t[0].valueOf();log("<<< a 2 "+i);if(i){var f=e.length-2;var j=f>0?e.slice(0,f):e;var _=Pair.fromArray(j,false);if(!W["..."].symbols[l]){W["..."].symbols[l]=new Pair(_,_nil)}else{W["..."].symbols[l].append(new Pair(_,_nil))}}else{W["..."].symbols[l]=Pair.fromArray(e,false)}}else if(Array.isArray(t[0])){log("<<< a 3");var R=_toConsumableArray(u);var T=_objectSpread(_objectSpread({},r),{},{pattern_names:R,ellipsis:true});if(!e.every(function(e){return Z(t[0],e,T)})){return false}}if(t.length>2){var p=t.slice(2);return Z(p,e.slice(-p.length),r)}return true}var d=Z(t[0],e[0],r);log({first:d,pattern:t[0],code:e[0]});var h=Z(t.slice(1),e.slice(1),r);log({first:d,rest:h});return d&&h}if(is_pair(t)&&is_pair(t.car)&&is_pair(t.car.cdr)&&LSymbol.is(t.car.cdr.car,J)){log(">> 0");if(is_nil(e)){log({pattern:t});if(t.car.car instanceof LSymbol){var m=t.car.car.valueOf();if(W["..."].symbols[m]){throw new Error("syntax: named ellipsis can only "+"appear onces")}W["..."].symbols[m]=e}}}if(is_pair(t)&&is_pair(t.cdr)&&LSymbol.is(t.cdr.car,J)){log(">> 1 (a)");if(!is_nil(t.cdr.cdr)){if(is_pair(t.cdr.cdr)){log(">> 1 (b)");var M=t.cdr.cdr.length();var y=!is_nil(t.last_pair().cdr);if(!is_pair(e)){return false}var v=e.length();var b=e;var $=y?1:1;while(v-$>M){b=b.cdr;v--}var V=b.cdr;b.cdr=_nil;var q=_objectSpread(_objectSpread({},r),{},{trailing:y});if(!Z(t.cdr.cdr,V,q)){return false}}}if(t.car instanceof LSymbol){var g=t.car.__name__;if(W["..."].symbols[g]&&!u.includes(g)&&!i){throw new Error("syntax: named ellipsis can only appear onces")}log(">> 1 (next)");if(is_nil(e)){log(">> 2");if(i){log("NIL");W["..."].symbols[g]=_nil}else{log("NULL");W["..."].symbols[g]=null}}else if(is_pair(e)&&(is_pair(e.car)||is_nil(e.car))){log(">> 3 "+i);if(i){if(W["..."].symbols[g]){var w=W["..."].symbols[g];if(is_nil(w)){w=new Pair(_nil,new Pair(e,_nil))}else{w=w.append(new Pair(e,_nil))}W["..."].symbols[g]=w}else{W["..."].symbols[g]=new Pair(e,_nil)}}else{log(">> 4");W["..."].symbols[g]=new Pair(e,_nil)}}else{log(">> 6");if(is_pair(e)){log(">> 7 "+i);if(!is_pair(e.cdr)&&!is_nil(e.cdr)){log(">> 7 (b)");if(is_nil(t.cdr.cdr)){return false}else if(!W["..."].symbols[g]){W["..."].symbols[g]=new Pair(e.car,_nil);return Z(t.cdr.cdr,e.cdr,r)}}var D=e.last_pair();log({last_pair:D});if(!is_nil(D.cdr)){log(">> 7 (c)");if(is_nil(t.cdr.cdr)){return false}else{log(">> 7 (d)");var x=e.clone();x.last_pair().cdr=_nil;W["..."].symbols[g]=x;return Z(t.cdr.cdr,D.cdr,r)}}u.push(g);if(!W["..."].symbols[g]){log(">> 7 (e)");W["..."].symbols[g]=new Pair(e,_nil)}else{log(">> 7 (f)");var U=W["..."].symbols[g];W["..."].symbols[g]=U.append(new Pair(e,_nil))}log({IIIIII:W["..."].symbols[g]})}else if(t.car instanceof LSymbol&&is_pair(t.cdr)&&LSymbol.is(t.cdr.car,J)){log(">> 8");W["..."].symbols[g]=null;return Z(t.cdr.cdr,e,r)}else{log(">> 9");return false}}return true}else if(is_pair(t.car)){var L=_toConsumableArray(u);if(is_nil(e)){log(">> 10");W["..."].lists.push(_nil);return true}log(">> 11");var E=e;var z=_objectSpread(_objectSpread({},r),{},{pattern_names:L,ellipsis:true});while(is_pair(E)){if(!Z(t.car,E.car,z)){return false}E=E.cdr}return true}if(Array.isArray(t.car)){var L=_toConsumableArray(u);var S=e;var G=_objectSpread(_objectSpread({},r),{},{pattern_names:L,ellipsis:true});while(is_pair(S)){if(!Z(t.car,S.car,G)){return false}S=S.cdr}return true}return false}if(t instanceof LSymbol){if(LSymbol.is(t,J)){throw new Error("syntax: invalid usage of ellipsis")}log(">> 12");var A=t.__name__;if(K.includes(A)){return true}if(i){var F,k;log(W["..."].symbols[A]);(k=(F=W["..."].symbols)[A])!==null&&k!==void 0?k:F[A]=[];W["..."].symbols[A].push(e)}else{W.symbols[A]=e}return true}if(is_pair(t)&&is_pair(e)){log(">> 13");log({a:13,code:e,pattern:t});var C=t.car instanceof LSymbol&&t.cdr instanceof LSymbol;if(I&&C){log(">> 13 (a)");if(!is_nil(e.cdr)){return false}var H=t.car.valueOf();var Y=t.cdr.valueOf();W.symbols[H]=e.car;W.symbols[Y]=_nil;return true}if(is_nil(e.cdr)){log(">> 13 (b)");if(C){if(!Z(t.car,e.car,r)){return false}log(">> 14");var O=t.cdr.valueOf();if(!(O in W.symbols)){W.symbols[O]=_nil}O=t.car.valueOf();if(!(O in W.symbols)){W.symbols[O]=e.car}return true}}log({pattern:t,code:e});if(is_pair(t.cdr)&&is_pair(t.cdr.cdr)&&t.cdr.car instanceof LSymbol&&LSymbol.is(t.cdr.cdr.car,J)&&is_pair(t.cdr.cdr.cdr)&&!LSymbol.is(t.cdr.cdr.cdr.car,J)&&Z(t.car,e.car,r)&&Z(t.cdr.cdr.cdr,e.cdr,_objectSpread(_objectSpread({},r),{},{trailing:true}))){var P=t.cdr.car.__name__;log({pattern:t,code:e,name:P});if(K.includes(P)){return true}W["..."].symbols[P]=null;return true}log("recur");log({pattern:t,code:e});var N=Z(t.car,e.car,r);var B=Z(t.cdr,e.cdr,r);log({$car_code:e.car,$car_pattern:t.car,car:N,$cdr_code:e.cdr,$cdr_pattern:t.cdr,cdr:B});if(N&&B){return true}}else if(is_nil(t)&&(is_nil(e)||e===undefined)){return true}else if(is_pair(t.car)&&LSymbol.is(t.car.car,J)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(Z(e,t)){return W}}function clear_gensyms(e,i){function a(t){if(is_pair(t)){if(!i.length){return t}var e=a(t.car);var r=a(t.cdr);return new Pair(e,r)}else if(t instanceof LSymbol){var n=i.find(function(e){return e.gensym===t});if(n){return LSymbol(n.name)}return t}else{return t}}return a(e)}function transform_syntax(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var P=e.bindings,t=e.expr,N=e.scope,o=e.symbols,l=e.names,B=e.ellipsis;var f={};function u(e){if(e instanceof LSymbol){return true}return["string","symbol"].includes(_typeof$1(e))}function I(e){if(!u(e)){var t=type(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===B){throw new Error("syntax: internal error, ellipis not transformed")}var n=_typeof$1(r);if(["string","symbol"].includes(n)){if(r in P.symbols){return P.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var a=i[0];if(a in P.symbols){return Pair.fromArray([LSymbol("."),P.symbols[a]].concat(i.slice(1).map(function(e){return LString(e)})))}}}if(o.includes(r)){return e}return s(r,e)}function s(e,t){if(!f[e]){var r=N.ref(e);if(_typeof$1(e)==="symbol"&&!r){e=t.literal()}if(f[e]){return f[e]}var n=gensym(e);if(r){var i=N.get(e);N.set(n,i)}else{var a=N.get(e,{throwError:false});if(typeof a!=="undefined"){N.set(n,a)}}l.push({name:e,gensym:n});f[e]=n;if(typeof e==="string"&&e.match(/\./)){var o=e.split(".").filter(Boolean),u=_toArray(o),s=u[0],c=u.slice(1);if(f[s]){hidden_prop(n,"__object__",[f[s]].concat(_toConsumableArray(c)))}}}return f[e]}function j(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;log({bindings:t,expr:e});if(Array.isArray(e)&&!e.length){return e}if(e instanceof LSymbol){var a=e.valueOf();if(is_gensym(e)&&!t[a]);log("[t 1");if(t[a]){if(is_pair(t[a])){var o=t[a],u=o.car,s=o.cdr;if(i){var c=u.car,l=u.cdr;if(!is_nil(l)){n(a,new Pair(l,_nil))}return c}if(!is_nil(s)){n(a,s)}return u}else if(t[a]instanceof Array){n(a,t[a].slice(1));return t[a][0]}}return I(e)}var f=Array.isArray(e);if(is_pair(e)||f){var _=f?e[0]:e.car;var p=f?e[1]:is_pair(e.cdr)&&e.cdr.car;if(_ instanceof LSymbol&&LSymbol.is(p,B)){f?e.slice(2):e.cdr.cdr;log("[t 2");var d=_.valueOf();var h=t[d];if(h===null){return}else if(d in t){log({name:d,binding:t[d]});if(is_pair(h)){log("[t 2 Pair "+i);var m=h.car,y=h.cdr;var v=f?e.slice(2):e.cdr.cdr;if(i){if(!is_nil(y)){log("|| next 1");n(d,y)}if(f&&v.length||!is_nil(v)&&!f){var b=j(v,t,r,n);if(f){return m.concat(b)}else if(is_pair(m)){return m.append(b)}else{log("UNKNOWN")}}return m}else if(is_pair(m)){if(!is_nil(m.cdr)){log("|| next 2");n(d,new Pair(m.cdr,y))}return new Value(m.car)}else if(is_nil(y)){return m}else{var g=e.last_pair();if(g.cdr instanceof LSymbol){log("|| next 3");n(d,h.last_pair());return m}}}else if(h instanceof Array){log("[t 2 Array "+i);if(i){n(d,h.slice(1));return Pair.fromArray(h)}else{var w=h.slice(1);if(w.length){n(d,w)}return h[0]}}else{return h}}}log("[t 3 recur ",e);var D=f?e.slice(1):e.cdr;var x=j(_,t,r,n);var L=j(D,t,r,n);log({head:x,rest:L});if(f){return[x].concat(L)}return new Pair(x,L)}return e}function R(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,_toConsumableArray(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return is_pair(e)||is_nil(e)||Array.isArray(e)&&e.length})}function T(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function M(i){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},t=e.disabled;log("traverse>> ",i);var a=Array.isArray(i);if(a&&i.length===0){return i}if(is_pair(i)||a){log(">> 0");var r=a?i[0]:i.car;var n,o;if(a){n=i[1];o=i.slice(2)}else if(is_pair(i.cdr)){n=i.cdr.car;o=i.cdr.cdr}log({first:r,second:n,rest_second:o});if(!t&&is_pair(r)&&LSymbol.is(r.car,B)){return new Pair(r.cdr.car,M(i.cdr))}if(n&&LSymbol.is(n,B)&&!t){log(">> 1");var u=P["..."].symbols;var s=Object.values(u);if(s.length&&s.every(function(e){return e===null})){log(">>> 1 (a)");return M(o,{disabled:t})}var c=T(u);var l=r instanceof LSymbol&&LSymbol.is(o.car,B);if(is_pair(r)||l){log(">>> 1 (b)");if(is_nil(P["..."].lists[0])){if(!l){return M(o,{disabled:t})}log(o);return _nil}var f=r;if(l){log(">>> 1 (c)");f=new Pair(r,new Pair(n,_nil))}log(">> 2");var _;if(c.length){log(">> 2 (a)");var p=_objectSpread({},u);_=a?[]:_nil;var d=function e(){log({bind:p});if(!R(p)){return 1}var n={};var t=function e(t,r){n[t]=r};var r=j(f,p,{nested:true},t);if(r!==undefined){if(r instanceof Value){r.valueOf(),_readOnlyError("car")}if(l){if(a){if(Array.isArray(r)){var i;(i=_).push.apply(i,_toConsumableArray(r))}else{log("ZONK {1}")}}else{if(is_nil(_)){_=r}else{_=_.append(r)}}}else if(a){_.push(r)}else{_=new Pair(r,_)}}p=n};while(true){if(d())break}if(!is_nil(_)&&!l&&!a){_=_.reverse()}if(a){if(o){log({rest_second:o,expr:i});var h=M(o,{disabled:t});return _.concat(h)}return _}if(!is_nil(i.cdr.cdr)&&!LSymbol.is(i.cdr.cdr.car,B)){var m=M(i.cdr.cdr,{disabled:t});return _.append(m)}return _}else{log(">> 3");var y=j(r,u,{nested:true});if(y){if(y instanceof Value){y.valueOf(),_readOnlyError("car")}return new Pair(y,_nil)}return _nil}}else if(r instanceof LSymbol){log(">> 4");if(LSymbol.is(o.car,B)){log(">> 4 (a)")}else{log(">> 4 (b)")}var v=r.__name__;var b=_defineProperty({},v,u[v]);log({bind:b});var g=u[v]===null;var w=a?[]:_nil;var D=function e(){if(!R(b,true)){log({bind:b});return 1}var n={};var t=function e(t,r){n[t]=r};var r=j(i,b,{nested:false},t);log({value:r});if(typeof r!=="undefined"){if(r instanceof Value){r=r.valueOf()}if(a){w.push(r)}else{w=new Pair(r,w)}}b=n};while(true){if(D())break}if(!is_nil(w)&&!a){w=w.reverse()}if(is_pair(i.cdr)){if(is_pair(i.cdr.cdr)||i.cdr.cdr instanceof LSymbol){var x=M(i.cdr.cdr,{disabled:t});log({node:x});if(g){return x}if(is_nil(w)){w=x}else{w.append(x)}log({result:w,node:x})}}log("<<<< 2");log({result:w});return w}}var L=M(r,{disabled:t});var E;var S;if(r instanceof LSymbol){var A=N.get(r,{throwError:false});S=A instanceof Macro&&A.__name__==="syntax-rules"}if(S){if(i.cdr.car instanceof LSymbol){E=new Pair(M(i.cdr.car,{disabled:t}),new Pair(i.cdr.cdr.car,M(i.cdr.cdr.cdr,{disabled:t})))}else{E=new Pair(i.cdr.car,M(i.cdr.cdr,{disabled:t}))}log("REST >>>> ",E)}else{E=M(i.cdr,{disabled:t})}log({a:true,car:toString(i.car),cdr:toString(i.cdr),head:toString(L),rest:toString(E)});return new Pair(L,E)}if(i instanceof LSymbol){if(t&&LSymbol.is(i,B)){return i}var F=Object.keys(P["..."].symbols);var k=i.literal();if(F.includes(k)){var C="missing ellipsis symbol next to name `".concat(k,"'");throw new Error("syntax-rules: ".concat(C))}var O=I(i);if(typeof O!=="undefined"){return O}}return i}return M(t,{})}function is_null(e){return is_undef(e)||is_nil(e)||e===null}function is_nil(e){return e===_nil}function is_function(e){return typeof e==="function"&&typeof e.bind==="function"}function is_directive(e){return directives.includes(e)}function is_false(e){return e===false||e===null}function is_string(e){return typeof e==="string"}function is_prototype(e){return e&&_typeof$1(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}function is_continuation(e){return e instanceof Continuation}function is_context(e){return e instanceof LambdaContext}function is_parameter(e){return e instanceof Parameter}function is_pair(e){return e instanceof Pair}function is_env(e){return e instanceof Environment}function is_callable(e){return is_function(e)||is_continuation(e)||is_parameter(e)||is_macro(e)}function is_macro(e){return e instanceof Macro||e instanceof SyntaxParameter}function is_promise(e){if(e instanceof QuotedPromise){return false}if(e instanceof Promise){return true}return!!e&&is_function(e.then)}function is_undef(e){return typeof e==="undefined"}function get_proto(e){return Object.getPrototypeOf(e)}function is_iterator(e,t){if(has_own_symbol(e,t)||has_own_symbol(get_proto(e),t)){return is_function(e[t])}}function is_instance(e){if(!e){return false}if(_typeof$1(e)!=="object"){return false}if(e.__instance__){e.__instance__=false;return e.__instance__}return false}function self_evaluated(e){var t=_typeof$1(e);return["string","function"].includes(t)||_typeof$1(e)==="symbol"||e instanceof QuotedPromise||e instanceof LSymbol||e instanceof LNumber||e instanceof LString||e instanceof RegExp}function is_native(e){return e instanceof LNumber||e instanceof LString||e instanceof LCharacter}function has_own_symbol(e,t){if(e===null){return false}return _typeof$1(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function box(e){switch(_typeof$1(e)){case"string":return LString(e);case"bigint":return LNumber(e);case"number":if(Number.isNaN(e)){return nan}else{return LNumber(e)}}return e}function map_object(r,n){var e=Object.getOwnPropertyNames(r);var t=Object.getOwnPropertySymbols(r);var i={};e.concat(t).forEach(function(e){var t=n(r[e]);i[e]=t});return i}function unbox(t){var e=[LString,LNumber,LCharacter].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(unbox)}if(t instanceof QuotedPromise){delete t.then}if(is_plain_object(t)){return map_object(t,unbox)}return t}function patch_value(e,t){if(is_pair(e)){e.mark_cycles();return quote(e)}if(is_function(e)){if(t){return bind(e,t)}}return box(e)}function unbind(e){if(is_bound(e)){return e[__fn__]}return e}function bind(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=_createForOfIteratorHelper(n),a;try{for(i.s();!(a=i.n()).done;){var o=a.value;if(filter_fn_names(o)){try{r[o]=e[o]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}hidden_prop(r,"__fn__",e);hidden_prop(r,"__context__",t);hidden_prop(r,"__bound__",true);if(is_native_function(e)){hidden_prop(r,"__native__",true)}if(is_plain_object(t)&&is_lambda(e)){hidden_prop(r,"__method__",true)}r.valueOf=function(){return e};return r}function is_object_bound(e){return is_bound(e)&&e[Symbol["for"]("__context__")]===Object}function is_bound(e){return!!(is_function(e)&&e[__fn__])}function lips_context(e){if(is_function(e)){var t=e[__context__];if(t&&(t===lips||t.constructor&&t.constructor.__class__)){return true}}return false}function is_port(e){return e instanceof InputPort||e instanceof OutputPort}function is_port_method(e){if(is_function(e)){if(is_port(e[__context__])){return true}}return false}var __context__=Symbol["for"]("__context__");var __fn__=Symbol["for"]("__fn__");var __data__=Symbol["for"]("__data__");var __ref__=Symbol["for"]("__ref__");var __cycles__=Symbol["for"]("__cycles__");var __class__=Symbol["for"]("__class__");var __method__=Symbol["for"]("__method__");var __prototype__=Symbol["for"]("__prototype__");var __lambda__=Symbol["for"]("__lambda__");var exluded_names=["name","length","caller","callee","arguments","prototype"];function filter_fn_names(e){return!exluded_names.includes(e)}function hidden_prop(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function set_fn_length(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function is_lambda(e){return e&&e[__lambda__]}function is_method(e){return e&&e[__method__]}function is_raw_lambda(e){return is_lambda(e)&&!e[__prototype__]&&!is_method(e)&&!is_port_method(e)}function is_native_function(e){var t=Symbol["for"]("__native__");return is_function(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function let_macro(e){var w;switch(e){case Symbol["for"]("letrec"):w="letrec";break;case Symbol["for"]("let"):w="let";break;case Symbol["for"]("let*"):w="let*";break;default:throw new Error("Invalid let_macro value")}return Macro.defmacro(w,function(t,e){var l=e.dynamic_env;var f=e.error,r=e.macro_expand,_=e.use_dynamic;var p;if(t.car instanceof LSymbol){if(!(is_pair(t.cdr.car)||is_nil(t.cdr.car))){throw new Error("let require list of pairs")}var n;if(is_nil(t.cdr.car)){p=_nil;n=_nil}else{n=t.cdr.car.map(function(e){return e.car});p=t.cdr.car.map(function(e){return e.cdr.car})}return new Pair(Pair.fromArray([LSymbol("letrec"),[[t.car,Pair(LSymbol("lambda"),Pair(n,t.cdr.cdr))]],t.car]),p)}else if(r){return}var d=this;p=global_env.get("list->array")(t.car);var h=d.inherit(w);var m,y;if(w==="let*"){y=h}else if(w==="let"){m=[]}var v=0;function b(){var e=hygienic_begin([h],t.cdr);return _evaluate(e,{env:h,dynamic_env:h,use_dynamic:_,error:f})}function g(e){if(e in h.__env__){throw new Error("Duplicated let variable ".concat(e))}}return function t(){var r=p[v++];l=w==="let*"?h:d;if(!r){if(m&&m.length){var e=m.map(function(e){return e.value});var n=e.filter(is_promise);if(n.length){return promise_all(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=this;var a=this;var o=[];var u=e;while(is_pair(u)){o.push(_evaluate(u.car,{env:i,dynamic_env:a,use_dynamic:r,error:n}));u=u.cdr}var s=o.filter(is_promise).length;if(s){return promise_all(o).then(c.bind(this))}else{return c.call(this,o)}})}function guard_math_call(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),a=2;a1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=u){return o.apply(n,i)}else{return a}}}();return a.apply(void 0,arguments)}}function limit(n,i){typecheck("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(LCharacter.__names__[e]){t=e;e=LCharacter.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=LCharacter.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}LCharacter.__names__=characters;LCharacter.__rev_names__={};Object.keys(LCharacter.__names__).forEach(function(e){var t=LCharacter.__names__[e];LCharacter.__rev_names__[t]=e});LCharacter.prototype.toUpperCase=function(){return LCharacter(this.__char__.toUpperCase())};LCharacter.prototype.toLowerCase=function(){return LCharacter(this.__char__.toLowerCase())};LCharacter.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};LCharacter.prototype.valueOf=LCharacter.prototype.serialize=function(){return this.__char__};function LString(e){if(typeof this!=="undefined"&&!(this instanceof LString)||typeof this==="undefined"){return new LString(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){typecheck("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var ignore=["length","constructor"];var _keys=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!ignore.includes(e)});var wrap=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof LNumber){return e}if(typeof this!=="undefined"&&!(this instanceof LNumber)||typeof this==="undefined"){return new LNumber(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=LNumber.getType(e);if(LNumber.types[r]){return LNumber.types[r](e,t)}var n=e instanceof Array&&LString.isString(e[0])&&LNumber.isNumber(e[1]);if(e instanceof LNumber){return LNumber(e.value)}if(!LNumber.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(type(e)))}if(e===null){e=0}var i;if(n){var a=e,o=_slicedToArray(a,2),u=o[0],s=o[1];if(u instanceof LString){u=u.valueOf()}if(s instanceof LNumber){s=s.valueOf()}var c=u.match(/^([+-])/);var l=false;if(c){u=u.replace(/^[+-]/,"");if(c[1]==="-"){l=true}}}if(Number.isNaN(e)){return LFloat(e)}else if(n&&Number.isNaN(parseInt(u,s))){return nan}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var f;switch(s){case 8:f="0o";break;case 16:f="0x";break;case 2:f="0b";break;case 10:f="";break}if(typeof f==="undefined"){var _=BigInt(s);i=_toConsumableArray(u).map(function(e,t){return BigInt(parseInt(e,s))*pow(_,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(f+u)}}else{i=BigInt(e)}if(l){i*=BigInt(-1)}}else{i=e}return LBigInteger(i,true)}else if(typeof BN!=="undefined"&&!(e instanceof BN)){if(e instanceof Array){return LBigInteger(_construct(BN,_toConsumableArray(e)))}return LBigInteger(new BN(e))}else if(n){this.constant(parseInt(u,s),"integer")}else{this.constant(e,"integer")}}LNumber.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};LNumber.types={float:function e(t){return new LFloat(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!LNumber.isComplex(t)){t={im:0,re:t}}return new LComplex(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!LNumber.isRational(t)){t={num:t,denom:1}}return new LRational(t,r)}};LNumber.prototype.serialize=function(){return this.__value__};LNumber.prototype.isNaN=function(){return Number.isNaN(this.__value__)};LNumber.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};LNumber.isFloat=function e(t){return t instanceof LFloat||Number(t)===t&&t%1!==0};LNumber.isNumber=function(e){return e instanceof LNumber||LNumber.isNative(e)||LNumber.isBN(e)};LNumber.isComplex=function(e){if(!e){return false}var t=e instanceof LComplex||(LNumber.isNumber(e.im)||LNumber.isRational(e.im)||Number.isNaN(e.im))&&(LNumber.isNumber(e.re)||LNumber.isRational(e.re)||Number.isNaN(e.re));return t};LNumber.isRational=function(e){if(!e){return false}return e instanceof LRational||LNumber.isNumber(e.num)&&LNumber.isNumber(e.denom)};LNumber.isInteger=function(e){if(!(LNumber.isNative(e)||e instanceof LNumber)){return false}if(LNumber.isFloat(e)){return false}if(LNumber.isRational(e)){return false}if(LNumber.isComplex(e)){return false}return true};LNumber.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};LNumber.isBigInteger=function(e){return e instanceof LBigInteger||typeof e==="bigint"||LNumber.isBN(e)};LNumber.isBN=function(e){return typeof BN!=="undefined"&&e instanceof BN};LNumber.getArgsType=function(e,t){if(e instanceof LFloat||t instanceof LFloat){return LFloat}if(e instanceof LBigInteger||t instanceof LBigInteger){return LBigInteger}return LNumber};LNumber.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>=2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};LNumber.prototype.asType=function(e){var t=LNumber.getType(this);return LNumber.types[t]?LNumber.types[t](e):LNumber(e)};LNumber.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof BN!=="undefined"&&!(this.value instanceof BN)};["floor","ceil","round"].forEach(function(e){LNumber.prototype[e]=function(){if(this["float"]||LNumber.isFloat(this.__value__)){return LNumber(Math[e](this.__value__))}else{return LNumber(Math[e](this.valueOf()))}}});LNumber.prototype.valueOf=function(){if(LNumber.isNative(this.__value__)){return Number(this.__value__)}else if(LNumber.isBN(this.__value__)){return this.__value__.toNumber()}};var matrix=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&LFloat(r.valueOf())]},integer:function e(t,r){return[t,r&&LFloat(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&LFloat(r.valueOf())]},complex:function e(t,r){return[{re:t,im:LFloat(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function e(t,r){var n=LNumber.coerce(t.__re__,r.__re__),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=LNumber.coerce(t.__im__,r.__im__),s=_slicedToArray(u,2),c=s[0],l=s[1];return[{im:c,re:a},{im:l,re:o}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[LFloat(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:coerce(t.__type__,r.__im__.__type__,0)[0],re:coerce(t.__type__,r.__re__.__type__,t)[0]},{im:coerce(t.__type__,r.__im__.__type__,r.__im__)[0],re:coerce(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:coerce(r,e.__im__.__type__,0,e.__im__)[1],re:coerce(r,e.__re__.__type__,0,e.__re__)[1]},{im:coerce(r,e.__im__.__type__,0,0)[1],re:coerce(r,t.__type__,0,t)[1]}]}}}();function coerce(e,t,r,n){return matrix[e][t](r,n)}LNumber.coerce=function(e,t){var r=LNumber.getType(e);var n=LNumber.getType(t);if(!matrix[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!matrix[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=matrix[r][n](e,t);return i.map(function(e){return LNumber(e,true)})};LNumber.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof LNumber)){throw new Error("LNumber: you can't coerce ".concat(type(e)))}if(typeof e==="number"){e=LNumber(e)}return LNumber.coerce(this,e)};LNumber.getType=function(e){if(e instanceof LNumber){return e.__type__}if(LNumber.isFloat(e)){return"float"}if(LNumber.isComplex(e)){return"complex"}if(LNumber.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof BN!=="undefined"&&!(e instanceof BN)){return"bigint"}};LNumber.prototype.isFloat=function(){return!!(LNumber.isFloat(this.__value__)||this["float"])};var mapping={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var rev_mapping={};Object.keys(mapping).forEach(function(t){rev_mapping[mapping[t]]=t;LNumber.prototype[t]=function(e){return this.op(mapping[t],e)}});LNumber._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof LComplex)||typeof this==="undefined"){return new LComplex(e,t)}if(e instanceof LComplex){return LComplex({im:e.__im__,re:e.__re__})}if(LNumber.isNumber(e)&&t){if(!t){return Number(e)}}else if(!LNumber.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(toString(e));throw new Error(r)}var n=e.im instanceof LNumber?e.im:LNumber(e.im);var i=e.re instanceof LNumber?e.re:LNumber(e.re);this.constant(n,i)}LComplex.prototype=Object.create(LNumber.prototype);LComplex.prototype.constructor=LComplex;LComplex.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};LComplex.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};LComplex.prototype.toRational=function(e){var t=this.__im__,r=this.__re__;if(LNumber.isFloat(this.__im__)){t=LFloat(this.__im__).toRational(e)}if(LNumber.isFloat(this.__re__)){r=LFloat(this.__re__).toRational(e)}return LComplex({im:t,re:r})};LComplex.prototype.pow=function(e){e.cmp(0);if(e===0){return LNumber(1)}var t=LNumber(Math.atan2(this.__im__.valueOf(),this.__re__.valueOf()));var r=LNumber(this.modulus());if(LNumber.isComplex(e)&&e.__im__.cmp(0)!==0){var n=e.mul(Math.log(r.valueOf())).add(LComplex.i.mul(t).mul(e));if(!LNumber.isComplex(n)){return LFloat(Math.E).pow(n)}var i=LFloat(Math.E).pow(n.__re__.valueOf());return LComplex({re:i.mul(Math.cos(n.__im__.valueOf())),im:i.mul(Math.sin(n.__im__.valueOf()))})}var a=e.__re__.cmp(0)>0;e=e.__re__.valueOf();if(LNumber.isInteger(e)&&a){var o=this;while(--e){o=o.mul(this)}return o}var u=r.pow(e);var s=t.mul(e);return LComplex({re:u.mul(Math.cos(s)),im:u.mul(Math.sin(s))})};LComplex.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};LComplex.prototype.factor=function(){if(this.__im__ instanceof LFloat||this.__im__ instanceof LFloat){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof LFloat){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof LFloat){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};LComplex.prototype.modulus=function(){return this.factor().sqrt()};LComplex.prototype.conjugate=function(){return LComplex({re:this.__re__,im:this.__im__.sub()})};LComplex.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=LFloat(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=LFloat(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return LComplex({im:r,re:t})};LComplex.prototype.div=function(e){if(LNumber.isNumber(e)&&!LNumber.isComplex(e)){if(!(e instanceof LNumber)){e=LNumber(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return LComplex({re:t,im:r})}else if(!LNumber.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=a.__im__.div(o.__im__);return u.coerce(o.__re__)[0]}var s=this.coerce(e),c=_slicedToArray(s,2),l=c[0],f=c[1];var _=f.factor();var p=f.conjugate();var d=l.mul(p);if(!LNumber.isComplex(d)){return d.div(_)}var h=d.__re__.op("/",_);var m=d.__im__.op("/",_);return LComplex({re:h,im:m})};LComplex.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};LComplex.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};LComplex.prototype.complex_op=function(e,t,i){var a=this;var r=function e(t,r){var n=i(a.__re__,t,a.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return LComplex(n,true)}return n};if(typeof t==="undefined"){return r()}if(LNumber.isNumber(t)&&!LNumber.isComplex(t)){if(!(t instanceof LNumber)){t=LNumber(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!LNumber.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var o=t.__re__ instanceof LNumber?t.__re__:this.__re__.asType(t.__re__);var u=t.__im__ instanceof LNumber?t.__im__:this.__im__.asType(t.__im__);return r(o,u)};LComplex._op={"+":"add","-":"sub","*":"mul","/":"div"};LComplex.prototype._op=function(e,t){var r=LComplex._op[e];return this[r](t)};LComplex.prototype.cmp=function(e){var t=this.coerce(e),r=_slicedToArray(t,2),n=r[0],i=r[1];var a=n.__re__.coerce(i.__re__),o=_slicedToArray(a,2),u=o[0],s=o[1];var c=u.cmp(s);if(c!==0){return c}else{var l=n.__im__.coerce(i.__im__),f=_slicedToArray(l,2),_=f[0],p=f[1];return _.cmp(p)}};LComplex.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};LComplex.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[toString(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=toString(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function LFloat(e){if(typeof this!=="undefined"&&!(this instanceof LFloat)||typeof this==="undefined"){return new LFloat(e)}if(!LNumber.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof LNumber){return LFloat(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}LFloat.prototype=Object.create(LNumber.prototype);LFloat.prototype.constructor=LFloat;LFloat.prototype.toString=function(e){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}e&&(e=e.valueOf());var t=this.__value__.toString(e);if(!t.match(/e[+-]?[0-9]+$/i)){var r=t.replace(/^-/,"");var n=this.__value__<0?"-":"";if(t.match(/^-?0\.0{3}/)){var i=r.match(/^[.0]+/g)[0].length-1;var a=r.replace(/^[.0]+/,"").replace(/^([0-9a-f])/i,"$1.");return"".concat(n).concat(a,"e-").concat(i.toString(e))}if(t.match(/^-?[0-9a-f]{7,}\.?/i)){var o=r.match(/^[0-9a-f]+/gi)[0].length-1;var u=r.replace(/\./,"").replace(/^([0-9a-f])/i,"$1.").replace(/0+$/,"").replace(/\.$/,".0");return"".concat(n).concat(u,"e+").concat(o.toString(e))}if(!LNumber.isFloat(this.__value__)){var s=t+".0";return this._minus?"-"+s:s}}return t.replace(/^([0-9]+)e/,"$1.0e")};LFloat.prototype._op=function(e,t){if(t instanceof LNumber){t=t.__value__}var r=LNumber._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return LFloat(r(this.__value__,t))};LFloat.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return toRational(this.__value__.valueOf())}return approxRatio(e.valueOf())(this.__value__.valueOf())};LFloat.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=LFloat(Math.sqrt(-e));return LComplex({re:0,im:t})}return LFloat(Math.sqrt(e))};LFloat.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return LFloat(e)};var toRational=approxRatio(1e-10);function approxRatio(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=simplest_rational2(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=simplest_rational2(r,n)}else if(t.cmp(0)<0){i=LNumber(simplest_rational2(n.sub(),r.sub())).sub()}else{i=LNumber(0)}if(LNumber.isFloat(t)||LNumber.isFloat(e)){return LFloat(i)}return i}function simplest_rational2(e,t){var r=LNumber(e).floor();var n=LNumber(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=LNumber(1).div(t.sub(n));var a=LNumber(1).div(e.sub(r));return r.add(LNumber(1).div(simplest_rational2(i,a)))}else{return r.add(LNumber(1))}}function LRational(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof LRational)||typeof this==="undefined"){return new LRational(e,t)}if(!LNumber.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof LRational){r=LNumber(e.__num__);n=LNumber(e.__denom__)}else{r=LNumber(e.num);n=LNumber(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return LNumber(r.div(n))}}this.constant(r,n)}LRational.prototype=Object.create(LNumber.prototype);LRational.prototype.constructor=LRational;LRational.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};LRational.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};LRational.prototype.pow=function(e){if(LNumber.isRational(e)){return pow(this.valueOf(),e.valueOf())}var t=e.cmp(0);if(t===0){return LNumber(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return LRational({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};LRational.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof LFloat||t instanceof LFloat){return e.div(t)}return LRational({num:e,denom:t})};LRational.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return LRational({num:e,denom:t})};LRational.prototype.cmp=function(e){return LNumber(this.valueOf(),true).cmp(e)};LRational.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof LRational){t=LNumber(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof LRational){r=LNumber(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};LRational.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return LNumber._ops["/"](this.__num__.value,this.__denom__.value)}return LFloat(this.__num__.valueOf()).div(this.__denom__.valueOf())};LRational.prototype.mul=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return LRational({num:t,denom:r})}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];return a.mul(o)};LRational.prototype.div=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return LRational({num:t,denom:r})}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];var u=a.div(o);return u};LRational.prototype._op=function(e,t){return this[rev_mapping[e]](t)};LRational.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(LRational({num:t,denom:r}))}if(!(e instanceof LNumber)){e=LNumber(e).sub()}else{e=e.sub()}var n=LNumber.coerce(this,e),i=_slicedToArray(n,2),a=i[0],o=i[1];return a.add(o)};LRational.prototype.add=function(e){if(!(e instanceof LNumber)){e=LNumber(e)}if(LNumber.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var a,o;if(t!==r){o=r.mul(n).add(i.mul(t));a=t.mul(r)}else{o=n.add(i);a=t}return LRational({num:o,denom:a})}if(LNumber.isFloat(e)){return LFloat(this.valueOf()).add(e)}var u=LNumber.coerce(this,e),s=_slicedToArray(u,2),c=s[0],l=s[1];return c.add(l)};function LBigInteger(e,t){if(typeof this!=="undefined"&&!(this instanceof LBigInteger)||typeof this==="undefined"){return new LBigInteger(e,t)}if(e instanceof LBigInteger){return LBigInteger(e.__value__,e._native)}if(!LNumber.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}LBigInteger.prototype=Object.create(LNumber.prototype);LBigInteger.prototype.constructor=LBigInteger;LBigInteger.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};LBigInteger.prototype.serialize=function(){return this.__value__.toString()};LBigInteger.prototype._op=function(e,t){if(typeof t==="undefined"){if(LNumber.isBN(this.__value__)){e=LBigInteger.bn_op[e];return LBigInteger(this.__value__.clone()[e](),false)}return LBigInteger(LNumber._ops[e](this.__value__),true)}if(LNumber.isBN(this.__value__)&&LNumber.isBN(t.__value__)){e=LBigInteger.bn_op[e];return LBigInteger(this.__value__.clone()[e](t),false)}var r=LNumber._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return LNumber(r)}return LRational({num:this,denom:t})}return LBigInteger(r,true)};LBigInteger.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(LNumber.isNative(this.__value__)){e=LNumber(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(LNumber.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return LComplex({re:0,im:e})}return e};LNumber.NaN=LNumber(NaN);LComplex.i=LComplex({im:1,re:0});function InputPort(e){var n=this;var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:global_env;if(typeof this!=="undefined"&&!(this instanceof InputPort)||typeof this==="undefined"){return new InputPort(e)}typecheck("InputPort",e,"function");read_only(this,"__type__",text_port);var a;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return a},set:function e(t){typecheck("InputPort::__parser__",t,"parser");a=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=6;break}t.next=3;return n._read();case 3:r=t.sent;a=new Parser({env:i});a.parse(r);case 6:return t.abrupt("return",n.__parser__);case 7:case"end":return t.stop()}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==eof};this._make_defaults()}InputPort.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!LNumber.isInteger(t)){var r=LNumber.getType(t);typeErrorMessage("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};InputPort.prototype._with_init_parser=function(u,s){var c=this;return _asyncToGenerator(_regeneratorRuntime.mark(function e(){var r,n,i,a,o=arguments;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return u.call(c);case 2:r=t.sent;for(n=o.length,i=new Array(n),a=0;a"};function OutputPort(e){if(typeof this!=="undefined"&&!(this instanceof OutputPort)||typeof this==="undefined"){return new OutputPort(e)}typecheck("OutputPort",e,"function");read_only(this,"__type__",text_port);this.write=e}OutputPort.prototype.is_open=function(){return this._closed!==true};OutputPort.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};OutputPort.prototype.flush=function(){};OutputPort.prototype.toString=function(){return"#"};var BufferedOutputPort=function(e){_inherits(r,e);function r(e){var t;_classCallCheck(this,r);t=_callSuper(this,r,[function(){var e;return(e=t)._write.apply(e,arguments)}]);typecheck("BufferedOutputPort",e,"function");read_only(_assertThisInitialized(t),"_fn",e,{hidden:true});read_only(_assertThisInitialized(t),"_buffer",[],{hidden:true});return t}_createClass(r,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};OutputStringPort.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function OutputFilePort(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof OutputFilePort)||typeof this==="undefined"){return new OutputFilePort(e,t)}typecheck("OutputFilePort",e,"string");read_only(this,"__filename__",e);read_only(this,"_fd",t.valueOf(),{hidden:true});read_only(this,"__type__",text_port);this.write=function(e){if(!LString.isString(e)){e=toString(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}OutputFilePort.prototype=Object.create(OutputPort.prototype);OutputFilePort.prototype.constructor=OutputFilePort;OutputFilePort.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};OutputFilePort.prototype.internal=function(e){return user_env.get("**internal-env**").get(e)};OutputFilePort.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{read_only(n,"_fd",null,{hidden:true});OutputPort.prototype.close.call(n);t()}})})};OutputFilePort.prototype.toString=function(){return"#")};function InputStringPort(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:global_env;if(typeof this!=="undefined"&&!(this instanceof InputStringPort)||typeof this==="undefined"){return new InputStringPort(e)}typecheck("InputStringPort",e,"string");e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!t.__parser__){t.__parser__=new Parser({env:r});t.__parser__.parse(e)}return t.__parser__});read_only(this,"__type__",text_port);this._make_defaults()}InputStringPort.prototype.char_ready=function(){return true};InputStringPort.prototype=Object.create(InputPort.prototype);InputStringPort.prototype.constructor=InputStringPort;InputStringPort.prototype.toString=function(){return"#"};function ParserInputPort(e){if(typeof this!=="undefined"&&!(this instanceof ParserInputPort)||typeof this==="undefined"){return new ParserInputPort(e)}this._with_parser=this._with_init_parser.bind(this,function(){return e});read_only(this,"__type__",text_port);this._make_defaults()}ParserInputPort.prototype.char_ready=function(){return true};ParserInputPort.prototype=Object.create(InputPort.prototype);ParserInputPort.prototype.constructor=ParserInputPort;ParserInputPort.prototype.toString=function(){return"#"};function InputByteVectorPort(e){if(typeof this!=="undefined"&&!(this instanceof InputByteVectorPort)||typeof this==="undefined"){return new InputByteVectorPort(e)}typecheck("InputByteVectorPort",e,"uint8array");read_only(this,"__vector__",e);read_only(this,"__type__",binary_port);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){typecheck("InputByteVectorPort::__index__",t,"number");if(t instanceof LNumber){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}InputByteVectorPort.prototype=Object.create(InputPort.prototype);InputByteVectorPort.prototype.constructor=InputByteVectorPort;InputByteVectorPort.prototype.toString=function(){return"#"};InputByteVectorPort.prototype.close=function(){var t=this;read_only(this,"__vector__",_nil);var r=function e(){throw new Error("Input-binary-port: port is closed")};["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=r});this.u8_ready=this.char_ready=function(){return false}};InputByteVectorPort.prototype.u8_ready=function(){return true};InputByteVectorPort.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return eof}return this.__vector__[this.__index__]};InputByteVectorPort.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};InputByteVectorPort.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};InputByteVectorPort.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===eof){return eof}return this.__vector__.slice(this.__index__,e)};function OutputByteVectorPort(){if(typeof this!=="undefined"&&!(this instanceof OutputByteVectorPort)||typeof this==="undefined"){return new OutputByteVectorPort}read_only(this,"__type__",binary_port);read_only(this,"_buffer",[],{hidden:true});this.write=function(e){typecheck("write",e,["number","uint8array"]);if(LNumber.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,_toConsumableArray(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}OutputByteVectorPort.prototype=Object.create(OutputPort.prototype);OutputByteVectorPort.prototype.constructor=OutputByteVectorPort;OutputByteVectorPort.prototype.close=function(){OutputPort.prototype.close.call(this);read_only(this,"_buffer",null,{hidden:true})};OutputByteVectorPort.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};OutputByteVectorPort.prototype.write_u8=function(e){typecheck("OutputByteVectorPort::write_u8",e,"number");this.write(e)};OutputByteVectorPort.prototype.write_u8_vector=function(e){typecheck("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};OutputByteVectorPort.prototype.toString=function(){return"#"};OutputByteVectorPort.prototype.valueOf=function(){return this.__buffer__};function InputFilePort(e,t){if(typeof this!=="undefined"&&!(this instanceof InputFilePort)||typeof this==="undefined"){return new InputFilePort(e,t)}InputStringPort.call(this,e);typecheck("InputFilePort",t,"string");read_only(this,"__filename__",t)}InputFilePort.prototype=Object.create(InputStringPort.prototype);InputFilePort.prototype.constructor=InputFilePort;InputFilePort.prototype.toString=function(){return"#")};function InputBinaryFilePort(e,t){if(typeof this!=="undefined"&&!(this instanceof InputBinaryFilePort)||typeof this==="undefined"){return new InputBinaryFilePort(e,t)}InputByteVectorPort.call(this,e);typecheck("InputBinaryFilePort",t,"string");read_only(this,"__filename__",t)}InputBinaryFilePort.prototype=Object.create(InputByteVectorPort.prototype);InputBinaryFilePort.prototype.constructor=InputBinaryFilePort;InputBinaryFilePort.prototype.toString=function(){return"#")};function OutputBinaryFilePort(e,t){var i=this;if(typeof this!=="undefined"&&!(this instanceof OutputBinaryFilePort)||typeof this==="undefined"){return new OutputBinaryFilePort(e,t)}typecheck("OutputBinaryFilePort",e,"string");read_only(this,"__filename__",e);read_only(this,"_fd",t.valueOf(),{hidden:true});read_only(this,"__type__",binary_port);var a;this.write=function(e){typecheck("write",e,["number","uint8array"]);var n;if(!a){a=i.internal("fs")}if(LNumber.isNumber(e)){n=new Uint8Array([e.valueOf()])}else{n=new Uint8Array(Array.from(e))}return new Promise(function(t,r){a.write(i._fd,n,function(e){if(e){r(e)}else{t()}})})}}OutputBinaryFilePort.prototype=Object.create(OutputFilePort.prototype);OutputBinaryFilePort.prototype.constructor=OutputBinaryFilePort;OutputBinaryFilePort.prototype.write_u8=function(e){typecheck("OutputByteVectorPort::write_u8",e,"number");this.write(e)};OutputBinaryFilePort.prototype.write_u8_vector=function(e){typecheck("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var binary_port=Symbol["for"]("binary");var text_port=Symbol["for"]("text");var eof=new EOF;function EOF(){}EOF.prototype.toString=function(){return"#"};function Interpreter(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.stderr,i=r.stdin,a=r.stdout,o=r.command_line,u=o===void 0?null:o,s=_objectWithoutProperties(r,_excluded3);if(typeof this!=="undefined"&&!(this instanceof Interpreter)||typeof this==="undefined"){return new Interpreter(e,_objectSpread({stdin:i,stdout:a,stderr:n,command_line:u},s))}if(typeof e==="undefined"){e="anonymous"}this.__env__=user_env.inherit(e,s);this.__parser__=new Parser({env:this.__env__});this.__env__.set("parent.frame",doc("parent.frame",function(){return t.__env__},global_env.__env__["parent.frame"].__doc__));var c="**interaction-environment-defaults**";this.set(c,get_props(s).concat(c));var l=internal_env.inherit("internal-".concat(e));if(is_port(i)){l.set("stdin",i)}if(is_port(n)){l.set("stderr",n)}if(is_port(a)){l.set("stdout",a)}l.set("command-line",u);set_interaction_env(this.__env__,l)}Interpreter.prototype.exec=function(){var t=_asyncToGenerator(function(o){var u=this;var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return _regeneratorRuntime.mark(function e(){var r,n,i,a;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=s.use_dynamic,n=r===void 0?false:r,i=s.dynamic_env,a=s.env;typecheck("Interpreter::exec",o,["string","array"],1);typecheck("Interpreter::exec",n,"boolean",2);if(!a){a=u.__env__}if(!i){i=a}global_env.set("**interaction-environment**",u.__env__);if(!Array.isArray(o)){t.next=10;break}return t.abrupt("return",exec(o,{env:a,dynamic_env:i,use_dynamic:n}));case 10:u.__parser__.parse(o);return t.abrupt("return",exec(u.__parser__,{env:a,dynamic_env:i,use_dynamic:n}));case 12:case"end":return t.stop()}},e)})()});return function(e){return t.apply(this,arguments)}}();Interpreter.prototype.get=function(e){var t=this.__env__.get(e);if(is_function(t)){var r=new LambdaContext({env:this.__env__});return t.bind(r)}return t};Interpreter.prototype.set=function(e,t){return this.__env__.set(e,t)};Interpreter.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function LipsError(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}LipsError.prototype=new Error;LipsError.prototype.constructor=LipsError;var IgnoreException=function(e){_inherits(t,e);function t(){_classCallCheck(this,t);return _callSuper(this,t,arguments)}return _createClass(t)}(_wrapNativeSuper(Error));function Environment(e,t,r){if(arguments.length===1){if(_typeof$1(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}Environment.prototype.list=function(){return get_props(this.__env__)};Environment.prototype.fs=function(){return this.get("**fs**")};Environment.prototype.unset=function(e){if(e instanceof LSymbol){e=e.valueOf()}if(e instanceof LString){e=e.valueOf()}delete this.__env__[e]};Environment.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_typeof$1(e)==="object"){t=e}if(!e||_typeof$1(e)==="object"){e="child of "+(this.__name__||"unknown")}return new Environment(t||{},this,e)};Environment.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}if(t){if(!r){t=trim_lines(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};Environment.prototype.new_frame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",doc("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!is_env(t)){return _nil}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},global_env.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};Environment.prototype._lookup=function(e){if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return Value(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};Environment.prototype.toString=function(){return"#"};Environment.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new Environment(r,this.__parent__,this.__name__)};Environment.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";typecheck("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function Value(e){if(typeof this!=="undefined"&&!(this instanceof Value)||typeof this==="undefined"){return new Value(e)}this.value=e}Value.isUndefined=function(e){return e instanceof Value&&typeof e.value==="undefined"};Value.prototype.valueOf=function(){return this.value};function Values(e){if(!e.length){return}if(e.length===1){return e[0]}if(typeof this!=="undefined"&&!(this instanceof Values)||typeof this==="undefined"){return new Values(e)}this.__values__=e}Values.prototype.toString=function(){return this.__values__.map(function(e){return toString(e)}).join("\n")};Values.prototype.valueOf=function(){return this.__values__};Environment.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};typecheck("Environment::get",e,["symbol","string"]);var r=t.throwError,n=r===void 0?true:r;var i=e;if(i instanceof LSymbol||i instanceof LString){i=i.valueOf()}var a=this._lookup(i);if(a instanceof Value){if(Value.isUndefined(a)){return undefined}return patch_value(a.valueOf())}var o;if(e instanceof LSymbol&&e[LSymbol.object]){o=e[LSymbol.object]}else if(typeof i==="string"){o=i.split(".").filter(Boolean)}if(o&&o.length>0){var u=o,s=_toArray(u),c=s[0],l=s.slice(1);a=this._lookup(c);if(l.length){try{if(a instanceof Value){a=a.valueOf()}else{a=get(root,c);if(is_function(a)){a=unbind(a)}}if(typeof a!=="undefined"){return get.apply(void 0,[a].concat(_toConsumableArray(l)))}}catch(e){throw e}}else if(a instanceof Value){return patch_value(a.valueOf())}a=get(root,i)}if(typeof a!=="undefined"){return a}if(n){throw new Error("Unbound variable `"+i.toString()+"'")}};Environment.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;typecheck("Environment::set",e,["string","symbol"]);if(LNumber.isNumber(t)){t=LNumber(t)}if(e instanceof LSymbol){e=e.__name__}if(e instanceof LString){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};Environment.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&is_plain_object(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};Environment.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};Environment.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};Environment.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function quote(e){if(is_promise(e)){return e.then(quote)}if(is_pair(e)||e instanceof LSymbol){e[__data__]=true}return e}var native_lambda=_parse(tokenize('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var get=doc("get",function e(t){var r;for(var n=arguments.length,i=new Array(n>1?n-1:0),a=1;a0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":doc("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("read-line",e,"input-port");return e.read_line()},"(read-line port)\n\n This function reads and returns the next line from the input\n port."),"read-char":doc("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=internal(this,"stdin")}typecheck_text_port("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:doc("read",function(){var e=_asyncToGenerator(function(){var i=this;var a=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;return _regeneratorRuntime.mark(function e(){var r,n;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=i.env;if(a===null){n=internal(r,"stdin")}else{n=a}typecheck_text_port("read",n,"input-port");return t.abrupt("return",n.read.call(r));case 4:case"end":return t.stop()}},e)})()});function t(){return e.apply(this,arguments)}return t}(),"(read [port])\n\n This function, if called with a port, it will parse the next\n item from the port. If called without an input, it will read\n a string from standard input (using the browser's prompt or\n a user defined input method) and parse it. This function can be\n used together with `eval` to evaluate code from port."),pprint:doc("pprint",function e(t){if(is_pair(t)){t=new lips.Formatter(t.toString(true))["break"]().format();global_env.get("display").call(global_env,t)}else{global_env.get("write").call(global_env,t)}global_env.get("newline").call(global_env)},"(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."),print:doc("print",function e(){var t=global_env.get("display");var r=global_env.get("newline");var n=this.use_dynamic;var i=global_env;var a=global_env;for(var o=arguments.length,u=new Array(o),s=0;s1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var u=0;var s=global_env.get("repr");t=t.replace(a,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[u++];if(t==="a"){return s(r)}else{return s(r,true)}}});o=t.match(/~([\S])/);if(o){throw new Error("format: Unrecognized escape sequence ".concat(o[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),newline:doc("newline",function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var r=global_env.get("display");var n=this.use_dynamic;var i=global_env;var a=global_env;call_function(r,["\n",t],{env:i,dynamic_env:a,use_dynamic:n})},"(newline [port])\n\n Write newline character to standard output or given port"),display:doc("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=internal(this,"stdout")}else{typecheck("display",r,"output-port")}var n=t;if(!(r instanceof OutputBinaryFilePort)){n=global_env.get("repr")(t)}r.write.call(global_env,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."),"display-error":doc("display-error",function e(){var t=internal(this,"stderr");var r=global_env.get("repr");for(var n=arguments.length,i=new Array(n),a=0;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=_objectWithoutProperties(t,_excluded4);var i=this;var o=this;var u;var s=_objectSpread(_objectSpread({},n),{},{env:this,dynamic_env:i,use_dynamic:r});var c=_evaluate(e.cdr.car,s);c=resolve_promises(c);function l(t,r,n){if(is_promise(t)){return t.then(function(e){return l(t,e,n)})}if(is_promise(r)){return r.then(function(e){return l(t,e,n)})}if(is_promise(n)){return n.then(function(e){return l(t,r,e)})}o.get("set-obj!").call(o,t,r,n);return n}if(is_pair(e.car)&&LSymbol.is(e.car.car,".")){var f=e.car.cdr.car;var _=e.car.cdr.cdr.car;var p=_evaluate(f,s);var d=_evaluate(_,s);return l(p,d,c)}if(!(e.car instanceof LSymbol)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var h=e.car.valueOf();u=this.ref(e.car.__name__);return unpromise(c,function(e){if(!u){var t=h.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=a.get(n,{throwError:false});if(i){l(i,r,e);return}}throw new Error("Unbound variable `"+h+"'")}u.set(h,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non empty slot and sets it."),"unset!":doc(new Macro("set!",function(e){if(!(e.car instanceof LSymbol)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."),"set-car!":doc("set-car!",function(e,t){typecheck("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."),"set-cdr!":doc("set-cdr!",function(e,t){typecheck("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."),"empty?":doc("empty?",function(e){return typeof e==="undefined"||is_nil(e)},"(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."),gensym:doc("gensym",gensym,"(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."),load:doc("load",function e(c,t){typecheck("load",c,"string");var l=this;if(l.__name__==="__frame__"){l=l.__parent__}if(!(t instanceof Environment)){if(l===global_env){t=l}else{t=this.get("**interaction-environment**")}}var f="@lips";var _=c.startsWith(f);var p="**module-path**";var d=global_env.get(p,{throwError:false});c=c.valueOf();if(!c.match(/.[^.]+$/)){c+=".scm"}var r=c.match(/\.xcb$/);function h(e){if(r){e=unserialize_bin(e)}else{if(type(e)==="buffer"){e=e.toString()}e=e.replace(/^(#!.*)/,function(e,t){if(is_directive(t)){return t}return""});if(e.match(/^\{/)){e=unserialize(e)}}return exec(e,{env:t})}function n(e){return root.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}function m(){var e=global_env.get("__dirname");return e.replace(/[^/]+$/,"")}if(is_node()){return new Promise(function(){var r=_asyncToGenerator(_regeneratorRuntime.mark(function e(r,n){var i,a,o,u,s;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.prev=0;t.next=3;return node_ready;case 3:i=nodeRequire("path");a=nodeRequire("fs");o=m();if(_){c=c.replace(f,o)}if(!d){t.next=12;break}d=d.valueOf();if(!c.startsWith("/")){c=i.join(d,c)}t.next=19;break;case 12:if(c.startsWith("/")){t.next=19;break}u=l.get("command-line",{throwError:false});if(!u){t.next=18;break}t.next=17;return u();case 17:s=t.sent;case 18:if(s&&!is_nil(s)){process.cwd();c=i.join(i.dirname(s.car.valueOf()),c)}case 19:global_env.set(p,i.dirname(c));a.readFile(c,function(e,t){if(e){n(e);global_env.set(p,d)}else{try{h(t).then(function(){r();global_env.set(p,d)})["catch"](n)}catch(e){n(e)}}});t.next=26;break;case 23:t.prev=23;t.t0=t["catch"](0);console.error(t.t0);case 26:case"end":return t.stop()}},e,null,[[0,23]])}));return function(e,t){return r.apply(this,arguments)}}())}if(_){var i,a;var o=(i=global_env.get("__dirname",{throwError:false}))!==null&&i!==void 0?i:current_script;(a=o)!==null&&a!==void 0?a:o=current_script;var u=o.replace(/dist\/?[^\/]*$/,"");c=c.replace(f,u)}if(d){d=d.valueOf();if(!c.startsWith("/")){c=d+"/"+c.replace(/^\.?\/?/,"")}}return n(c).then(function(e){global_env.set(p,c.replace(/\/[^/]*$/,""));return h(e)}).then(function(){})["finally"](function(){global_env.set(p,d)})},"(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."),while:doc(new Macro("while",function(e,t){var r=e.car;var n=_objectSpread(_objectSpread({},t),{},{env:this});var i=new Pair(new LSymbol("begin"),e.cdr);return function t(){return unpromise(_evaluate(r,n),function(e){if(e){return unpromise(_evaluate(i,n),t)}})}()}),"(while cond body)\n\n Creates a loop, it executes cond and body until cond expression is false."),do:doc(new Macro("do",function(){var r=_asyncToGenerator(function(_,e){var p=this;var d=e.use_dynamic,h=e.error;return _regeneratorRuntime.mark(function e(){var u,r,s,c,n,l,f,i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:u=p;r=u;s=u.inherit("do");c=_.car;n=_.cdr.car;l=_.cdr.cdr;if(!is_nil(l)){l=new Pair(LSymbol("begin"),l)}f={env:u,dynamic_env:r,use_dynamic:d,error:h};i=c;case 9:if(is_nil(i)){t.next=20;break}a=i.car;t.t0=s;t.t1=a.car;t.next=15;return _evaluate(a.cdr.car,f);case 15:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);i=i.cdr;t.next=9;break;case 20:f={env:s,dynamic_env:r,error:h};o=_regeneratorRuntime.mark(function e(){var r,n,i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(is_nil(l)){t.next=3;break}t.next=3;return lips.evaluate(l,f);case 3:r=c;n={};case 5:if(is_nil(r)){t.next=15;break}i=r.car;if(is_nil(i.cdr.cdr)){t.next=12;break}t.next=10;return _evaluate(i.cdr.cdr.car,f);case 10:a=t.sent;n[i.car.valueOf()]=a;case 12:r=r.cdr;t.next=5;break;case 15:o=Object.getOwnPropertySymbols(n);f.env=s=u.inherit("do");Object.keys(n).concat(o).forEach(function(e){s.set(e,n[e])});case 18:case"end":return t.stop()}},e)});case 22:t.next=24;return _evaluate(n.car,f);case 24:t.t3=t.sent;if(!(t.t3===false)){t.next=29;break}return t.delegateYield(o(),"t4",27);case 27:t.next=22;break;case 29:if(is_nil(n.cdr)){t.next=33;break}t.next=32;return _evaluate(n.cdr.car,f);case 32:return t.abrupt("return",t.sent);case 33:case"end":return t.stop()}},e)})()});return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will\n evaluate and return the second expression after the loop exits."),if:doc(new Macro("if",function(r,e){var t=e.error,n=e.use_dynamic;var i=this;var a=this;var o={env:a,dynamic_env:i,use_dynamic:n,error:t};var u=function e(t){if(is_false(t)){return _evaluate(r.cdr.cdr.car,o)}else{return _evaluate(r.cdr.car,o)}};if(is_nil(r)){throw new Error("too few expressions for `if`")}var s=_evaluate(r.car,o);return unpromise(s,u)}),"(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."),"let-env":new Macro("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_env,n=e.use_dynamic,i=e.error;typecheck("let-env",t,"pair");var a=_evaluate(t.car,{env:this,dynamic_env:r,error:i,use_dynamic:n});return unpromise(a,function(e){typecheck("let-env",e,"environment");return _evaluate(Pair(LSymbol("begin"),t.cdr),{env:e,dynamic_env:r,error:i})})},"(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."),letrec:doc(let_macro(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentially and the next value can access the\n previous values/names."),"letrec*":doc(let_macro(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."),"let*":doc(let_macro(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."),let:doc(let_macro(Symbol["for"]("let")),"(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to names,\n and then evaluates the body in context of that environment. Values are evaluated\n sequentially but you can't access previous values/names when the next are\n evaluated. You can only get them in the body of the let expression. (If you want\n to define multiple variables and use them in each other's definitions, use\n `let*`.)"),"begin*":doc(parallel("begin*",function(e){return e.pop()}),"(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return\n the value of the last expression (i.e. it uses Promise.all())."),shuffle:doc("shuffle",function(e){typecheck("shuffle",e,["pair","nil","array"]);var t=global_env.get("random");if(is_nil(e)){return _nil}if(Array.isArray(e)){return shuffle(e.slice(),t)}var r=global_env.get("list->array")(e);r=shuffle(r,t);return global_env.get("array->list")(r)},"(shuffle obj)\n\n Order items in vector or list in random order."),begin:doc(new Macro("begin",function(e,t){var n=_objectSpread(_objectSpread({},t),{},{env:this});var i=global_env.get("list->array")(e);var a;return function t(){if(i.length){var e=i.shift();var r=_evaluate(e,n);return unpromise(r,function(e){a=e;return t()})}else{return a}}()}),"(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."),ignore:new Macro("ignore",function(e,t){var r=_objectSpread(_objectSpread({},t),{},{env:this,dynamic_env:this});_evaluate(new Pair(new LSymbol("begin"),e),r)},"(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It will discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":doc(Macro.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=_objectSpread({env:this},t);return unpromise(_evaluate(e.car,r),function(e){if(is_function(e)){return e(new Continuation(null))}})}),"(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORTED BY LIPS RIGHT NOW"),parameterize:doc(new Macro("parameterize",function(t,e){var i=e.dynamic_env;var a=i.inherit("parameterize").new_frame(null,{});var o=_objectSpread(_objectSpread({},e),{},{env:this});var u=t.car;if(!is_pair(u)){var r=type(u);throw new Error("Invalid syntax for parameterize expecting pair got ".concat(r))}function s(){var e=new Pair(new LSymbol("begin"),t.cdr);return _evaluate(e,_objectSpread(_objectSpread({},o),{},{dynamic_env:a}))}return function r(){var e=u.car;var n=e.car.valueOf();return unpromise(_evaluate(e.cdr.car,o),function(e){var t=i.get(n,{throwError:false});if(!is_parameter(t)){throw new Error("Unknown parameter ".concat(n))}a.set(n,t.inherit(e));if(!is_null(u.cdr)){u=u.cdr;return r()}else{return s()}})}()}),"(parameterize ((name value) ...)\n\n Macro that change the dynamic variable created by make-parameter."),"make-parameter":doc(new Macro("make-parameter",function(e,t){t.dynamic_env;var r=_evaluate(e.car,t);var n;if(is_pair(e.cdr.car)){n=_evaluate(e.cdr.car,t)}return new Parameter(r,n)}),"(make-parameter init converter)\n\n Function creates new dynamic variable that can be custimized with parameterize\n macro. The value should be assigned to a variable e.g.:\n\n (define radix (make-parameter 10))\n\n The result value is a procedure that return the value of dynamic variable."),"define-syntax-parameter":doc(new Macro("define-syntax-parameter",function(e,t){var r=e.car;var n=this;if(!(r instanceof LSymbol)){throw new Error("define-syntax-parameter: invalid syntax expecting symbol got ".concat(type(r)))}var i=_evaluate(e.cdr.car,_objectSpread({env:n},t));typecheck("define-syntax-parameter",i,"syntax",2);i.__name__=r.valueOf();if(i.__name__ instanceof LString){i.__name__=i.__name__.valueOf()}var a;if(is_pair(e.cdr.cdr)&&LString.isString(e.cdr.cdr.car)){a=e.cdr.cdr.car.valueOf()}n.set(e.car,new SyntaxParameter(i),a,true)}),"(define-syntax-parameter name syntax [__doc__])\n\n Binds to the transformer obtained by evaluating .\n The transformer provides the default expansion for the syntax parameter,\n and in the absence of syntax-parameterize, is functionally equivalent to\n define-syntax."),"syntax-parameterize":doc(new Macro("syntax-parameterize",function(e,t){var r=global_env.get("list->array")(e.car);var n=this.inherit("syntax-parameterize");while(r.length){var i=r.shift();if(!(is_pair(i)||i.car instanceof LSymbol)){var a="invalid syntax for syntax-parameterize: ".concat(repr(e,true));throw new Error("syntax-parameterize: ".concat(a))}var o=_evaluate(i.cdr.car,_objectSpread(_objectSpread({},t),{},{env:this}));var u=i.car;typecheck("syntax-parameterize",o,["syntax"]);typecheck("syntax-parameterize",u,"symbol");o.__name__=u.valueOf();if(o.__name__ instanceof LString){o.__name__=o.__name__.valueOf()}var s=new SyntaxParameter(o);if(u.is_gensym()){var c=u.literal();var l=this.get(c,{throwError:false});if(l instanceof SyntaxParameter){n.set(c,s)}}n.set(u,s)}var f=hygienic_begin([n,t.dynamic_env],e.cdr);return _evaluate(f,_objectSpread(_objectSpread({},t),{},{env:n}))}),"(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),define:doc(Macro.defmacro("define",function(r,e){var n=this;if(is_pair(r.car)&&r.car.car instanceof LSymbol){var t=new Pair(new LSymbol("define"),new Pair(r.car.car,new Pair(new Pair(new LSymbol("lambda"),new Pair(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}e.dynamic_env=this;e.env=n;var i=r.cdr.car;var a;if(is_pair(i)){i=_evaluate(i,e);a=true}else if(i instanceof LSymbol){i=n.get(i)}typecheck("define",r.car,"symbol");return unpromise(i,function(e){if(n.__name__===Syntax.__merge_env__){n=n.__parent__}if(a&&(is_function(e)&&is_lambda(e)||e instanceof Syntax||is_parameter(e))){e.__name__=r.car.valueOf();if(e.__name__ instanceof LString){e.__name__=e.__name__.valueOf()}}var t;if(is_pair(r.cdr.cdr)&&LString.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`'),"set-obj!":doc("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_typeof$1(e);if(is_null(e)||i!=="object"&&i!=="function"){var a=typeErrorMessage("set-obj!",type(e),["object","function"]);throw new Error(a)}typecheck("set-obj!",t,["string","symbol","number"]);e=unbind(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(is_prototype(e)&&is_function(r)){e[t]=unbind(r);e[t][__prototype__]=true}else if(is_function(r)||is_native(r)||is_nil(r)){e[t]=r}else{e[t]=r&&!is_prototype(r)?r.valueOf():r}if(props){var o=e[t];Object.defineProperty(e,t,_objectSpread(_objectSpread({},n),{},{value:o}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."),"null-environment":doc("null-environment",function(){return global_env.inherit("null")},"(null-environment)\n\n Returns a clean environment with only the standard library."),values:doc("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},y=e.use_dynamic,v=e.error;var b=this;var g;if(is_pair(m.cdr)&&LString.isString(m.cdr.car)&&!is_nil(m.cdr.cdr)){g=m.cdr.car.valueOf()}function w(){var e=is_context(this)?this:{dynamic_env:b},r=e.dynamic_env;var n=b.inherit("lambda");r=r.inherit("lambda");if(this&&!is_context(this)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}n.set("this",this)}for(var t=arguments.length,i=new Array(t),a=0;a> SYNTAX");log(e);log(v);var n=w.inherit("syntax");var i=n;var a=this;if(a.__name__===Syntax.__merge_env__){var o=Object.getOwnPropertySymbols(a.__env__);o.forEach(function(e){a.__parent__.set(e,a.__env__[e])});a=a.__parent__}var u={env:n,dynamic_env:i,use_dynamic:b,error:g};var s,c,l;if(v.car instanceof LSymbol){s=v.car;l=D(v.cdr.car);c=v.cdr.cdr}else{s="...";l=D(v.car);c=v.cdr}try{while(!is_nil(c)){var f=c.car.car;var _=c.car.cdr.car;log("[[[ RULE");log(f);var p=extract_patterns(f,e,l,s,{expansion:this,define:w});if(p){if(is_debug()){console.log(JSON.stringify(symbolize(p),true,2));console.log("PATTERN: "+f.toString(true));console.log("MACRO: "+e.toString(true))}var d=[];var h=transform_syntax({bindings:p,expr:_,symbols:l,scope:n,lex_scope:a,names:d,ellipsis:s});log("OUPUT>>> ",h);if(h){_=h}var m=a.merge(n,Syntax.__merge_env__);if(r){return{expr:_,scope:m}}var y=_evaluate(_,_objectSpread(_objectSpread({},u),{},{env:m}));return clear_gensyms(y,d)}c=c.cdr}}catch(e){e.message+="\nin macro:\n ".concat(v.toString(true));throw e}throw new Error("syntax-rules: no matching syntax in macro ".concat(e.toString(true)))},w);r.__code__=v;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."),quote:doc(new Macro("quote",function(e){return quote(e.car)}),"(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."),"unquote-splicing":doc("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the\n expression, the computed value must be a pair."),unquote:doc("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."),quasiquote:Macro.defmacro("quasiquote",function(e,t){var u=t.use_dynamic,s=t.error;var c=this;var l=c;function a(e){return is_pair(e)||is_plain_object(e)||Array.isArray(e)}function f(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(is_pair(e)){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(is_promise(n)||is_promise(i)){return promise_all([n,i]).then(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];return new Pair(r,n)})}else{return new Pair(n,i)}}return e}function o(e,t){if(is_pair(e)){if(!is_nil(t)){e.append(t)}}else{e=new Pair(e,t)}return e}function r(e){return!!e.filter(function(e){return is_pair(e)&&LSymbol.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function _(e,n,i){return e.reduce(function(e,t){if(!is_pair(t)){e.push(t);return e}if(LSymbol.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(is_pair(i.cdr)&&is_nil(r[0]))){return r[0]}}r=r.map(function(e){if(h.has(e)){return e.clone()}else{h.add(e);return e}});var n=m(i.cdr,0,1);if(is_nil(n)&&is_nil(r[0])){return undefined}return unpromise(n,function(e){if(is_nil(r[0])){return e}if(r.length===1){return o(r[0],e)}var t=r.reduce(function(e,t){return o(e,t)});return o(t,e)})})}(i.car.cdr)}var h=new Set;function m(e,t,r){if(is_pair(e)){if(is_pair(e.car)){if(LSymbol.is(e.car.car,"unquote-splicing")){return d(e,t+1,r)}if(LSymbol.is(e.car.car,"unquote")){if(t+2===r&&is_pair(e.car.cdr)&&is_pair(e.car.cdr.car)&&LSymbol.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new Pair(new Pair(new LSymbol("unquote"),d(n,t+2,r)),_nil)}else if(is_pair(e.car.cdr)&&!is_nil(e.car.cdr.cdr)){if(is_pair(e.car.cdr.car)){var i=[];return function t(r){if(is_nil(r)){return Pair.fromArray(i)}return unpromise(_evaluate(r.car,{env:c,dynamic_env:l,use_dynamic:u,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(LSymbol.is(e.car,"quasiquote")){var a=m(e.cdr,t,r+1);return new Pair(e.car,a)}if(LSymbol.is(e.car,"quote")){return new Pair(e.car,m(e.cdr,t,r))}if(LSymbol.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(is_pair(e.cdr)){if(!is_nil(e.cdr.cdr)){if(is_pair(e.cdr.car)){var o=[];return function t(r){if(is_nil(r)){return Pair.fromArray(o)}return unpromise(_evaluate(r.car,{env:c,dynamic_env:l,use_dynamic:u,error:s}),function(e){o.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return _evaluate(e.cdr.car,{env:c,dynamic_env:l,error:s})}}else{return e.cdr}}return f(e,function(e){return m(e,t,r)})}else if(is_plain_object(e)){return p(e,t,r)}else if(e instanceof Array){return _(e,t,r)}return e}function n(e){if(is_pair(e)){delete e[__data__];if(!e.have_cycles("car")){n(e.car)}if(!e.have_cycles("cdr")){n(e.cdr)}}}if(is_plain_object(e.car)&&!r(Object.values(e.car))){return quote(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return quote(e.car)}if(is_pair(e.car)&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return quote(e.car)}var i=m(e.car,0,1);return unpromise(i,function(e){n(e);return quote(e)})},"(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special expressions (unquote\n x) abbreviated to ,x that will evaluate x and insert its value verbatim or\n (unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\n into the result. Best used with macros but it can be used outside."),clone:doc("clone",function e(t){typecheck("clone",t,"pair");return t.clone()},"(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),append:doc("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return global_env.get("array->list")(r)}else if(Array.isArray(t)){return t.reverse()}else{throw new Error(typeErrorMessage("reverse",type(t),"array or pair"))}},"(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."),nth:doc("nth",function e(t,r){typecheck("nth",t,"number");typecheck("nth",r,["array","pair"]);if(is_pair(r)){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function that returns a string by joining elements of the list using separator."),split:doc("split",function e(t,r){typecheck("split",t,["regex","string"]);typecheck("split",r,"string");return global_env.get("array->list")(r.split(t))},"(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."),replace:doc("replace",function e(t,r,n){typecheck("replace",t,["regex","string"]);typecheck("replace",r,["string","function"]);typecheck("replace",n,"string");if(is_function(r)){var i=[];n.replace(t,function(){i.push(r.apply(void 0,arguments))});return unpromise(i,function(e){return n.replace(t,function(){return e.shift()})})}return n.replace(t,r)},"(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a\n string or regex and replacement can be function or string. See Javascript\n String.replace()."),match:doc("match",function e(t,r){typecheck("match",t,["regex","string"]);typecheck("match",r,"string");var n=r.match(t);return n?global_env.get("array->list")(n):false},"(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if\n no match."),search:doc("search",function e(t,r){typecheck("search",t,["regex","string"]);typecheck("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."),repr:doc("repr",function e(t,r){return toString(t,r)},"(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."),"escape-regex":doc("escape-regex",function(e){typecheck("escape-regex",e,"string");return escape_regex(e.valueOf())},"(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."),env:doc("env",function e(e){e=e||this.env;var t=Object.keys(e.__env__).map(LSymbol);var r;if(t.length){r=Pair.fromArray(t)}else{r=_nil}if(e.__parent__ instanceof Environment){return global_env.get("env").call(this,e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."),new:doc("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:specials.LITERAL;typecheck("set-special!",e,"string",1);typecheck("set-special!",t,"symbol",2);specials.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors.'),get:get,".":get,unbind:doc(unbind,"(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."),type:doc(type,"(type object)\n\n Function that returns the type of an object as string."),debugger:doc("debugger",function(){debugger},'(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the "debugger;" statement. If a debugger is not running this\n function does nothing.'),in:doc("in",function(e,t){if(e instanceof LSymbol||e instanceof LString||e instanceof LNumber){e=e.valueOf()}return e in unbox(t)},'(in key value)\n\n Function that uses the Javascript "in" operator to check if key is\n a valid property in the value.'),"instance?":doc("instance?",function(e){return is_instance(e)},"(instance? obj)\n\n Checks if object is an instance, created with a new operator"),instanceof:doc("instanceof",function(e,t){return t instanceof unbind(e)},"(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."),"prototype?":doc("prototype?",is_prototype,"(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."),"macro?":doc("macro?",function(e){return e instanceof Macro},"(macro? expression)\n\n Predicate that tests if value is a macro."),"continuation?":doc("continuation?",is_continuation,"(continuation? expression)\n\n Predicate that tests if value is a callable continuation."),"function?":doc("function?",is_function,"(function? expression)\n\n Predicate that tests if value is a callable function."),"real?":doc("real?",function(e){if(type(e)!=="number"){return false}if(e instanceof LNumber){return e.isFloat()}return LNumber.isFloat(e)},"(real? number)\n\n Predicate that tests if value is a real number (not complex)."),"number?":doc("number?",function(e){return Number.isNaN(e)||LNumber.isNumber(e)},"(number? expression)\n\n Predicate that tests if value is a number or NaN value."),"string?":doc("string?",function(e){return LString.isString(e)},"(string? expression)\n\n Predicate that tests if value is a string."),"pair?":doc("pair?",is_pair,"(pair? expression)\n\n Predicate that tests if value is a pair or list structure."),"regex?":doc("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Predicate that tests if value is a regular expression."),"null?":doc("null?",function(e){return is_null(e)},"(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or\n Javascript null)."),"boolean?":doc("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."),"symbol?":doc("symbol?",function(e){return e instanceof LSymbol},"(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."),"array?":doc("array?",function(e){return e instanceof Array},"(array? expression)\n\n Predicate that tests if value is an array."),"object?":doc("object?",function(e){return!is_nil(e)&&e!==null&&!(e instanceof LCharacter)&&!(e instanceof RegExp)&&!(e instanceof LString)&&!is_pair(e)&&!(e instanceof LNumber)&&_typeof$1(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."),flatten:doc("flatten",function e(t){typecheck("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Returns a shallow list from tree structure (pairs)."),"vector-append":doc("vector-append",function(){for(var e=arguments.length,t=new Array(e),r=0;rlist":doc("array->list",function(e){typecheck("array->list",e,"array");return Pair.fromArray(e)},"(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."),"tree->array":doc("tree->array",to_array("tree->array",true),"(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."),"list->array":doc("list->array",to_array("list->array"),"(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."),apply:doc("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,a));return t.apply(this,prepare_fn_args(t,n))},"(apply fn list)\n\n Function that calls fn with the list of arguments."),length:doc("length",function e(t){if(!t||is_nil(t)){return 0}if(is_pair(t)){return t.length()}if("length"in t){return t.length}},'(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a "length" property. Returns undefined if the\n length could not be found.'),"string->number":doc("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;typecheck("string->number",e,"string",1);typecheck("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(rational_bare_re)||e.match(rational_re)){return parse_rational(e,t)}else if(e.match(complex_bare_re)||e.match(complex_re)){return parse_complex(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(int_bare_re)&&r||e.match(int_re)){return parse_integer(e,t)}if(e.match(float_re)){return parse_float(e)}}return false},"(string->number number [radix])\n\n Function that parses a string into a number."),try:doc(new Macro("try",function(r,e){var f=this;var _=e.use_dynamic;e.error;return new Promise(function(t,u){var s,n;if(LSymbol.is(r.cdr.car.car,"catch")){s=r.cdr.car;if(is_pair(r.cdr.cdr)&&LSymbol.is(r.cdr.cdr.car.car,"finally")){n=r.cdr.cdr.car}}else if(LSymbol.is(r.cdr.car.car,"finally")){n=r.cdr.car}if(!(n||s)){throw new Error("try: invalid syntax")}function c(e){t(e);throw new IgnoreException("[CATCH]")}var l=function e(t,r){r(t)};if(n){l=function e(t,r){l=u;i.error=function(e){throw e};unpromise(_evaluate(new Pair(new LSymbol("begin"),n.cdr),i),function(){r(t)})}}var i={env:f,use_dynamic:_,dynamic_env:f,error:function e(t){if(t instanceof IgnoreException){throw t}if(s){var r=f.inherit("try");var n=s.cdr.car.car;if(!(n instanceof LSymbol)){throw new Error("try: invalid syntax: catch require variable name")}r.set(n,t);var i;var a={env:r,use_dynamic:_,dynamic_env:f,error:function e(t){i=true;u(t);throw new IgnoreException("[CATCH]")}};var o=_evaluate(new Pair(new LSymbol("begin"),s.cdr.cdr),a);unpromise(o,function e(t){if(!i){l(t,c)}})}else{l(undefined,function(){u(t)})}}};var e=_evaluate(r.car,i);unpromise(e,function(e){l(e,t)},i.error)})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thrown. If finally is provided it's always\n executed at the end."),raise:doc("raise",function(e){throw e},"(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."),throw:doc("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws a new exception."),find:doc("find",function t(r,n){typecheck("find",r,["regex","function"]);typecheck("find",n,["pair","nil"]);if(is_null(n)){return _nil}var e=matcher("find",r);return unpromise(e(n.car),function(e){if(e&&!is_nil(e)){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."),"for-each":doc("for-each",function(e){var t;typecheck("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),a=1;a3?n-3:0),a=3;a3?i-3:0),o=3;oarray")(r);var a=[];var o=matcher("filter",t);return function t(r){function e(e){if(e&&!is_nil(e)){a.push(n)}return t(++r)}if(r===i.length){return Pair.fromArray(a)}var n=i[r];return unpromise(o(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."),compose:doc(compose,"(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"),pipe:doc(pipe,"(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"),curry:doc(curry,"(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have partially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\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))"),gcd:doc("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;nu?a%=u:u%=a}a=abs(s*r[o])/(a+u)}return LNumber(a)},"(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."),"odd?":doc("odd?",single_math_op(function(e){return LNumber(e).isOdd()}),"(odd? number)\n\n Checks if number is odd."),"even?":doc("even?",single_math_op(function(e){return LNumber(e).isEven()}),"(even? number)\n\n Checks if number is even."),"*":doc("*",reduce_math_op(function(e,t){return LNumber(e).mul(t)},LNumber(1)),"(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."),"+":doc("+",reduce_math_op(function(e,t){return LNumber(e).add(t)},LNumber(0)),"(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."),"-":doc("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":doc(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,["bigint","float","rational"]);return seq_compare(function(e,t){return LNumber(e).cmp(t)===1},t)},"(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."),"<":doc("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":doc(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,["bigint","float","rational"]);return seq_compare(function(e,t){return[0,1].includes(LNumber(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."),"eq?":doc("eq?",equal,"(eq? a b)\n\n Function that compares two values if they are identical."),or:doc(new Macro("or",function(e,t){var i=t.use_dynamic,a=t.error;var o=global_env.get("list->array")(e);var u=this;var s=u;if(!o.length){return false}var c;return function t(){function e(e){c=e;if(!is_false(c)){return c}else{return t()}}if(!o.length){if(!is_false(c)){return c}else{return false}}else{var r=o.shift();var n=_evaluate(r,{env:u,dynamic_env:s,use_dynamic:i,error:a});return unpromise(n,e)}}()}),"(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."),and:doc(new Macro("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=global_env.get("list->array")(e);var a=this;var o=a;if(!i.length){return true}var u;var s={env:a,dynamic_env:o,use_dynamic:r,error:n};return function t(){function e(e){u=e;if(is_false(u)){return u}else{return t()}}if(!i.length){if(!is_false(u)){return u}else{return false}}else{var r=i.shift();return unpromise(_evaluate(r,s),e)}}()}),"(and . expressions)\n\n Macro that evaluates each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."),"|":doc("|",function(e,t){return LNumber(e).or(t)},"(| a b)\n\n Function that calculates the bitwise or operation."),"&":doc("&",function(e,t){return LNumber(e).and(t)},"(& a b)\n\n Function that calculates the bitwise and operation."),"~":doc("~",function(e){return LNumber(e).neg()},"(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."),">>":doc(">>",function(e,t){return LNumber(e).shr(t)},"(>> a b)\n\n Function that right shifts the value a by value b bits."),"<<":doc("<<",function(e,t){return LNumber(e).shl(t)},"(<< a b)\n\n Function that left shifts the value a by value b bits."),not:doc("not",function e(t){return!t},"(not object)\n\n Function that returns the Boolean negation of its argument.")},undefined,"global");var user_env=global_env.inherit("user-env");function set_interaction_env(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error.");global_env.set("**interaction-environment**",e)}set_interaction_env(user_env,internal_env);global_env.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr.");function set_fs(e){user_env.get("**internal-env**").set("fs",e)}(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;global_env.set(r,doc(r,function(e){typecheck(r,e,"number");if(e instanceof LNumber){return e[t]()}},"(".concat(r," number)\n\n Function that calculates the ").concat(r," of a number.")))})})();function allPossibleCases(e){if(e.length===1){return e[0]}else{var t=[];var r=allPossibleCases(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(is_function(r)){return"Invalid type: got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){var a=r[0].toLowerCase();r="a"+("aeiou".includes(a)?"n ":" ")+r[0]}else{r=new Intl.ListFormat("en",{style:"long",type:"disjunction"}).format(r)}}return"Expecting ".concat(r," got ").concat(t).concat(i)}function typecheck_number(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;typecheck(e,t,"number",n);var i=t.__type__;var a;if(is_pair(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(typeErrorMessage(e,i,r,n))}}function typecheck_numbers(r,e,n){e.forEach(function(e,t){typecheck_number(r,e,n,t+1)})}function typecheck_args(r,e,n){e.forEach(function(e,t){typecheck(r,e,n,t+1)})}function typecheck_text_port(e,t,r){typecheck(e,t,r);if(t.__type__===binary_port){throw new Error(typeErrorMessage(e,"binary-port","textual-port"))}}function typecheck(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=type(t).toLowerCase();if(is_function(r)){if(!r(t)){throw new Error(typeErrorMessage(e,i,r,n))}return}var a=false;if(is_pair(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(typeErrorMessage(e,i,r,n))}}function memoize(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}type=memoize(type);function type(e){var t=type_constants.get(e);if(t){return t}if(_typeof$1(e)==="object"){for(var r=0,n=Object.entries(type_mapping);r2&&arguments[2]!==undefined?arguments[2]:{},n=r.env,i=r.dynamic_env,a=r.use_dynamic;var o=n===null||n===void 0?void 0:n.new_frame(e,t);var u=i===null||i===void 0?void 0:i.new_frame(e,t);var s=new LambdaContext({env:o,use_dynamic:a,dynamic_env:u});return resolve_promises(e.apply(s,t))}function apply(n,e){var t=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},i=t.env,a=t.dynamic_env,o=t.use_dynamic,r=t.error,u=r===void 0?function(){}:r;e=evaluate_args(e,{env:i,dynamic_env:a,error:u,use_dynamic:o});return unpromise(e,function(e){if(is_raw_lambda(n)){n=unbind(n)}e=prepare_fn_args(n,e);var t=e.slice();var r=call_function(n,t,{env:i,dynamic_env:a,use_dynamic:o});return unpromise(r,function(e){if(is_pair(e)){e.mark_cycles();return quote(e)}return box(e)},u)})}var _p_name__=new WeakMap;var Parameter=function(){function n(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;_classCallCheck(this,n);_defineProperty(this,"__value__",void 0);_defineProperty(this,"__fn__",void 0);_classPrivateFieldInitSpec(this,_p_name__,{writable:true,value:void 0});this.__value__=e;if(t){if(!is_function(t)){throw new Error("Section argument to Parameter need to be function "+"".concat(type(t)," given"))}this.__fn__=t}if(r){_classPrivateFieldSet(this,_p_name__,r)}}_createClass(n,[{key:"__name__",get:function e(){return _classPrivateFieldGet(this,_p_name__)},set:function e(t){_classPrivateFieldSet(this,_p_name__,t);if(this.__fn__){this.__fn__.__name__="fn-".concat(t)}}},{key:"invoke",value:function e(){if(is_function(this.__fn__)){return this.__fn__(this.__value__)}return this.__value__}},{key:"inherit",value:function e(t){return new n(t,this.__fn__,this.__name__)}}]);return n}();var LambdaContext=function(){function t(e){_classCallCheck(this,t);_defineProperty(this,"env",void 0);_defineProperty(this,"dynamic_env",void 0);_defineProperty(this,"use_dynamic",void 0);Object.assign(this,e)}_createClass(t,[{key:"__name__",get:function e(){return this.env.__name__}},{key:"__parent__",get:function e(){return this.env.__parent__}},{key:"get",value:function e(){var t;return(t=this.env).get.apply(t,arguments)}}]);return t}();function search_param(e,t){var r=e.get(t.__name__,{throwError:false});if(is_parameter(r)&&r!==t){return r}var n=user_env.get("**interaction-environment**");while(true){var i=e.get("parent.frame",{throwError:false});e=i(0);if(e===n){break}r=e.get(t.__name__,{throwError:false});if(is_parameter(r)&&r!==t){return r}}return t}var Continuation=function(){function t(e){_classCallCheck(this,t);_defineProperty(this,"__value__",void 0);this.__value__=e}_createClass(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}}]);return t}();function _evaluate(u){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},s=e.env,c=e.dynamic_env,l=e.use_dynamic,t=e.error,f=t===void 0?noop:t,r=_objectWithoutProperties(e,_excluded6);return function(e){try{if(!is_env(c)){c=s===true?user_env:s||user_env}if(l){s=c}else if(s===true){s=user_env}else{s=s||global_env}var t={env:s,dynamic_env:c,use_dynamic:l,error:f};var r;if(is_null(u)){return u}if(u instanceof LSymbol){return s.get(u)}if(!is_pair(u)){return u}var n=u.car;var e=u.cdr;if(is_pair(n)){r=resolve_promises(_evaluate(n,t));if(is_promise(r)){return r.then(function(e){if(!is_callable(e)){throw new Error(type(e)+" "+s.get("repr")(e)+" is not callable while evaluating "+u.toString())}return _evaluate(new Pair(e,u.cdr),t)})}else if(!is_callable(r)){throw new Error(type(r)+" "+s.get("repr")(r)+" is not callable while evaluating "+u.toString())}}if(n instanceof LSymbol){r=s.get(n)}else if(is_function(n)){r=n}var i;if(r instanceof Syntax){i=evaluate_syntax(r,u,t)}else if(r instanceof Macro){i=evaluate_macro(r,e,t)}else if(is_function(r)){i=apply(r,e,t)}else if(r instanceof SyntaxParameter){i=evaluate_syntax(r._syntax,u,t)}else if(is_parameter(r)){var a=search_param(c,r);if(is_null(u.cdr)){i=a.invoke()}else{return unpromise(_evaluate(u.cdr.car,t),function(e){a.__value__=e})}}else if(is_continuation(r)){i=r.invoke()}else if(is_pair(u)){r=n&&n.toString();throw new Error("".concat(type(n)," ").concat(r," is not a function"))}else{return u}var o=s.get(Symbol["for"]("__promise__"),{throwError:false});if(o===true&&is_promise(i)){i=i.then(function(e){if(is_pair(e)&&!r[__data__]){return _evaluate(e,t)}return e});return new QuotedPromise(i)}return i}catch(e){f&&f.call(s,e,u)}}(r)}var compile=exec_collect(function(e){return e});var exec=exec_collect(function(e,t){return t});function exec_with_stacktrace(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.dynamic_env,i=t.use_dynamic;return _evaluate(e,{env:r,dynamic_env:n,use_dynamic:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}if(!(t instanceof IgnoreException)){throw t}}})}function exec_collect(h){return function(){var t=_asyncToGenerator(function(f){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},_=e.env,p=e.dynamic_env,d=e.use_dynamic;return _regeneratorRuntime.mark(function e(){var r,n,i,a,o,u,s,c,l;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!is_env(p)){p=_===true?user_env:_||user_env}if(_===true){_=user_env}else{_=_||user_env}r=[];if(!is_pair(f)){t.next=8;break}t.next=6;return exec_with_stacktrace(f,{env:_,dynamic_env:p,use_dynamic:d});case 6:t.t0=t.sent;return t.abrupt("return",[t.t0]);case 8:n=Array.isArray(f)?f:_parse(f);i=false;a=false;t.prev=11;u=_asyncIterator(n);case 13:t.next=15;return u.next();case 15:if(!(i=!(s=t.sent).done)){t.next=31;break}c=s.value;t.next=19;return exec_with_stacktrace(c,{env:_,dynamic_env:p,use_dynamic:d});case 19:l=t.sent;t.t1=r;t.t2=h;t.t3=c;t.next=25;return l;case 25:t.t4=t.sent;t.t5=(0,t.t2)(t.t3,t.t4);t.t1.push.call(t.t1,t.t5);case 28:i=false;t.next=13;break;case 31:t.next=37;break;case 33:t.prev=33;t.t6=t["catch"](11);a=true;o=t.t6;case 37:t.prev=37;t.prev=38;if(!(i&&u["return"]!=null)){t.next=42;break}t.next=42;return u["return"]();case 42:t.prev=42;if(!a){t.next=45;break}throw o;case 45:return t.finish(42);case 46:return t.finish(37);case 47:return t.abrupt("return",r);case 48:case"end":return t.stop()}},e,null,[[11,33,37,47],[38,,42,46]])})()});function e(e){return t.apply(this,arguments)}return e}()}function balanced(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){try{r=tokenize(e)}catch(e){if(e instanceof Unterminated){return false}throw e}}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var a=new Stack;var o=_createForOfIteratorHelper(r),u;try{for(o.s();!(u=o.n()).done;){var s=u.value;if(n.includes(s)){a.push(s)}else if(!a.is_empty()){var c=a.top();var l=t[c];if(s===l){a.pop()}else{throw new Error("Syntax error: missing closing ".concat(l))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){o.e(e)}finally{o.f()}return a.is_empty()}function fworker(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new root.Worker(r.createObjectURL(n))}function is_dev(){return lips.version.match(/^(\{\{VER\}\}|DEV)$/)}function get_current_script(){if(is_node()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var current_script=get_current_script();function bootstrap(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(current_script){e=current_script.replace(/[^/]*$/,"std.xcb")}else if(is_dev()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version,"/").concat(t)}}global_env.set("__dirname",e.replace(/[^/]+$/,""));var r=global_env.get("load");return r.call(user_env,e,global_env)}function Worker(e){this.url=e;var o=this.worker=fworker(function(){var o;var u;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!u){i("Worker RPC: LIPS not initialized, call init first");return}u.then(function(){var e=r.params[0];var t=r.params[1];o.exec(e,{use_dynamic:t}).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var a=r.params[0];if(typeof a!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(a,"/dist/lips.min.js"));o=new lips.Interpreter("worker");u=bootstrap(a);u.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var a=++n;return new Promise(function(n,i){o.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===a){if(r.error){i(r.error)}else{n(r.result)}o.removeEventListener("message",e)}});o.postMessage({type:"RPC",method:t,id:a,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e,t){var r=t.use_dynamic,n=r===void 0?false:r;return this.rpc("eval",[e,n])}}var serialization_map={pair:function e(t){var r=_slicedToArray(t,2),n=r[0],i=r[1];return Pair(n,i)},number:function e(t){if(LString.isString(t)){return LNumber([t,10])}return LNumber(t)},regex:function e(t){var r=_slicedToArray(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return _nil},symbol:function e(t){if(LString.isString(t)){return LSymbol(t)}else if(Array.isArray(t)){return LSymbol(Symbol["for"](t[0]))}},string:LString,character:LCharacter};var available_class=Object.keys(serialization_map);var class_map={};for(var _i6=0,_Object$entries3=Object.entries(available_class);_i6<_Object$entries3.length;_i6++){var _Object$entries3$_i=_slicedToArray(_Object$entries3[_i6],2),i=_Object$entries3$_i[0],cls=_Object$entries3$_i[1];class_map[cls]=+i}function mangle_name(e){return class_map[e]}function resolve_name(e){return available_class[e]}function serialize(e){return JSON.stringify(e,function(e,t){var r=this[e];if(r){if(r instanceof RegExp){return{"@":mangle_name("regex"),"#":[r.source,r.flags]}}var n=mangle_name(r.constructor.__class__);if(!is_undef(n)){return{"@":n,"#":r.serialize()}}}return t})}function unserialize(e){return JSON.parse(e,function(e,t){if(t&&_typeof$1(t)==="object"){if(!is_undef(t["@"])){var r=resolve_name(t["@"]);if(serialization_map[r]){return serialization_map[r](t["#"])}}}return t})}var cbor=function(){var e={pair:Pair,symbol:LSymbol,number:LNumber,string:LString,character:LCharacter,nil:_nil.constructor,regex:RegExp};function t(e,t){return{deserialize:t,Class:e}}var r=new Encoder;var a={};for(var n=0,i=Object.entries(serialization_map);n1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var a=0;t.forEach(function(e){i.set(e,a);a+=e.length});return i}else if(t.length){return t[0]}}function encode_magic(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var MAGIC_LENGTH=7;function decode_magic(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,MAGIC_LENGTH));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function serialize_bin(e){var t=encode_magic();var r=cbor.encode(e);return merge_uint8_array(t,pack_1(r,{magic:false}))}function unserialize_bin(e){var t=decode_magic(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=unpack_1(e.slice(MAGIC_LENGTH),{magic:false});return cbor.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function execError(e){console.error(e.message||e);if(Array.isArray(e.code)){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function init(){var o=["text/x-lips","text/x-scheme"];var u;function s(e){var t;return(t=e.getAttribute("data-bootstrap"))!==null&&t!==void 0?t:e.getAttribute("bootstrap")}function c(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(exec).then(t)["catch"](function(e){execError(e);t()})}else{return exec(r.innerHTML).then(t)["catch"](function(e){execError(e);t()})}})}function e(){return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function e(){var t=a.shift();if(!t){i()}else{var r=t.getAttribute("type");if(o.includes(r)){var n=s(t);if(!u&&typeof n==="string"){return bootstrap(n).then(function(){return c(t)}).then(e)}else{return c(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+o.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(currentScript){var t=currentScript;var r=s(t);if(typeof r==="string"){return bootstrap(r).then(function(){u=true;return e()})}}return e()}var currentScript=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){contentLoaded(window,init)}var banner=function(){var e=LString("Fri, 08 Nov 2024 13:26:12 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var a="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return a}();read_only(Ahead,"__class__","ahead");read_only(Pair,"__class__","pair");read_only(Nil,"__class__","nil");read_only(Pattern,"__class__","pattern");read_only(Formatter,"__class__","formatter");read_only(Macro,"__class__","macro");read_only(Syntax,"__class__","syntax");read_only(Syntax.Parameter,"__class__","syntax-parameter");read_only(Environment,"__class__","environment");read_only(InputPort,"__class__","input-port");read_only(OutputPort,"__class__","output-port");read_only(BufferedOutputPort,"__class__","output-port");read_only(OutputStringPort,"__class__","output-string-port");read_only(InputStringPort,"__class__","input-string-port");read_only(InputFilePort,"__class__","input-file-port");read_only(OutputFilePort,"__class__","output-file-port");read_only(LipsError,"__class__","lips-error");[LNumber,LComplex,LRational,LFloat,LBigInteger].forEach(function(e){read_only(e,"__class__","number")});read_only(LCharacter,"__class__","character");read_only(LSymbol,"__class__","symbol");read_only(LString,"__class__","string");read_only(QuotedPromise,"__class__","promise");read_only(Parameter,"__class__","parameter");var version="DEV";var date="Fri, 08 Nov 2024 13:26:12 +0000";var parse=compose(uniterate_async,_parse);var lips={version:version,banner:banner,date:date,exec:exec,parse:parse,tokenize:tokenize,evaluate:_evaluate,compile:compile,serialize:serialize,unserialize:unserialize,serialize_bin:serialize_bin,unserialize_bin:unserialize_bin,bootstrap:bootstrap,Environment:Environment,env:user_env,Worker:Worker,Interpreter:Interpreter,balanced_parenthesis:balanced,balancedParenthesis:balanced,balanced:balanced,Macro:Macro,Syntax:Syntax,Pair:Pair,Values:Values,QuotedPromise:QuotedPromise,Error:LipsError,quote:quote,InputPort:InputPort,OutputPort:OutputPort,BufferedOutputPort:BufferedOutputPort,InputFilePort:InputFilePort,OutputFilePort:OutputFilePort,InputStringPort:InputStringPort,OutputStringPort:OutputStringPort,InputByteVectorPort:InputByteVectorPort,OutputByteVectorPort:OutputByteVectorPort,InputBinaryFilePort:InputBinaryFilePort,OutputBinaryFilePort:OutputBinaryFilePort,set_fs:set_fs,Formatter:Formatter,Parser:Parser,Lexer:Lexer,specials:specials,repr:repr,nil:_nil,eof:eof,LSymbol:LSymbol,LNumber:LNumber,LFloat:LFloat,LComplex:LComplex,LRational:LRational,LBigInteger:LBigInteger,LCharacter:LCharacter,LString:LString,Parameter:Parameter,rationalize:rationalize};global_env.set("lips",lips);export{BufferedOutputPort,Environment,LipsError as Error,Formatter,InputBinaryFilePort,InputByteVectorPort,InputFilePort,InputPort,InputStringPort,Interpreter,LBigInteger,LCharacter,LComplex,LFloat,LNumber,LRational,LString,LSymbol,Lexer,Macro,OutputBinaryFilePort,OutputByteVectorPort,OutputFilePort,OutputPort,OutputStringPort,Pair,Parameter,Parser,QuotedPromise,Syntax,Values,Worker,is_directive as _is_directive,balanced,balanced as balancedParenthesis,balanced as balanced_parenthesis,banner,bootstrap,compile,date,user_env as env,eof,_evaluate as evaluate,exec,_nil as nil,parse,quote,rationalize,repr,serialize,serialize_bin,set_fs,specials,tokenize,unserialize,unserialize_bin,version}; \ No newline at end of file diff --git a/dist/lips.js b/dist/lips.js index c82097b14..c20afd7c5 100644 --- a/dist/lips.js +++ b/dist/lips.js @@ -4,7 +4,7 @@ * | | \ \ | | | || . \/ __> | | * | | > \ | |_ | || _/\__ \ | | * | | / ^ \ |___||_||_| <___/ | | - * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19 + * \_\ /_/ \_\ /_/ v. DEV * * LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript * @@ -31,7 +31,7 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Mon, 27 May 2024 11:41:47 +0000 + * build: Fri, 08 Nov 2024 13:26:12 +0000 */ (function (global, factory) { @@ -109,6 +109,10 @@ return r && _setPrototypeOf(p, r.prototype), p; } + function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); + } + function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -3506,25 +3510,23 @@ } } // ------------------------------------------------------------------------- - /* eslint-disable */ /* c8 ignore next 13 */ function log(x) { - if (is_debug()) { - if (is_plain_object(x)) { - console.log(map_object(x, function (value) { - return toString(value, true); - })); - } else { - var _console; - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { - return toString(item, true); - })))); - } + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + if (is_plain_object(x) && is_debug(args[0])) { + console.log(map_object(x, function (value) { + return toString(value, true); + })); + } else if (is_debug()) { + var _console; + (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) { + return toString(item, true); + })))); } } + /* eslint-enable */ // ---------------------------------------------------------------------- /* c8 ignore next */ function is_debug() { @@ -3913,8 +3915,25 @@ } // ---------------------------------------------------------------------- function parse_symbol(arg) { - if (arg.match(/^\|.*\|$/)) { - arg = arg.replace(/(^\|)|(\|$)/g, ''); + arg.match(/^name/); + var re = /(^|.)\|/g; + if (arg.match(re)) { + // handle escaped bar and escaped slash + arg = arg.split('|').filter(Boolean).reduce(function (acc, str) { + var result = ''; + if (str.match(/^\\+$/)) { + if (str.length > 1) { + var count = Math.floor(str.length / 2); + result = '\\'.repeat(count); + } + if (str.length % 2 !== 0) { + result += '|'; + } + } else { + result = str; + } + return acc + result; + }); var chars = { t: '\t', r: '\r', @@ -3922,8 +3941,8 @@ }; arg = arg.replace(/\\(x[^;]+);/g, function (_, chr) { return String.fromCharCode(parseInt('0' + chr, 16)); - }).replace(/\\(.)/g, function (_, chr) { - return chars[chr] || chr; + }).replace(/\\([trn])/g, function (_, chr) { + return chars[chr]; }); } return new LSymbol(arg); @@ -4224,6 +4243,18 @@ return with_props(count, Symbol("#:g".concat(count))); }; }(); + // ---------------------------------------------------------------------- + // :: helper function that make symbols in names array hygienic + // ---------------------------------------------------------------------- + function hygienic_begin(envs, expr) { + var begin = global_env.get('begin'); + var g_begin = gensym('begin'); + envs.forEach(function (env) { + env.set(g_begin, begin); + }); + return new Pair(g_begin, expr); + } + // ---------------------------------------------------------------------- // Class used to escape promises: feature #54 // ---------------------------------------------------------------------- @@ -4521,6 +4552,11 @@ var found = this.next_token(); if (found) { this._token = this.__input__.substring(this._i, this._next); + if (!this.__token__) { + // handle case when accessing __token__ from the syntax extension + // (e.g. string interpolation) as the first expression in a REPL + read_only(this, '__token__', this.token(true)); + } return this.token(meta); } return eof; @@ -4769,6 +4805,7 @@ Lexer.character = Symbol["for"]('character'); Lexer.bracket = Symbol["for"]('bracket'); Lexer.b_symbol = Symbol["for"]('b_symbol'); + Lexer.b_symbol_ex = Symbol["for"]('b_symbol_ex'); Lexer.b_comment = Symbol["for"]('b_comment'); Lexer.i_comment = Symbol["for"]('i_comment'); Lexer.l_datum = Symbol["for"]('l_datum'); @@ -4799,7 +4836,7 @@ // for dot comma `(a .,b) [/\./, Lexer.boundary, /,/, null, null], // block symbols - [/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null]]; + [/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null]]; // ---------------------------------------------------------------------- Lexer._brackets = [[/[()[\]]/, null, null, null, null]]; // ---------------------------------------------------------------------- @@ -4901,17 +4938,16 @@ _createClass(Parser, [{ key: "_with_syntax_scope", value: function _with_syntax_scope(fn) { - var _this5 = this; // expose parser and change stdin so parser extension can use current-input // to read data from the parser stream #150 var internal = get_internal(this.__env__); var stdin = internal.get('stdin'); - this.__env__.set('lips', _objectSpread(_objectSpread({}, lips), {}, { + global_env.set('lips', _objectSpread(_objectSpread({}, lips), {}, { __parser__: this })); internal.set('stdin', new ParserInputPort(this, this.__env__)); var cleanup = function cleanup() { - _this5.__env__.set('lips', lips); + global_env.set('lips', lips); internal.set('stdin', stdin); }; return unpromise(fn(), function (result) { @@ -5250,7 +5286,7 @@ key: "_resolve_object", value: function () { var _resolve_object2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(object) { - var _this6 = this; + var _this5 = this; var result; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { @@ -5260,7 +5296,7 @@ break; } return _context6.abrupt("return", object.map(function (item) { - return _this6._resolve_object(item); + return _this5._resolve_object(item); })); case 2: if (!is_plain_object(object)) { @@ -5269,7 +5305,7 @@ } result = {}; Object.keys(object).forEach(function (key) { - result[key] = _this6._resolve_object(object[key]); + result[key] = _this5._resolve_object(object[key]); }); return _context6.abrupt("return", result); case 6: @@ -5344,7 +5380,7 @@ key: "_read_object", value: function () { var _read_object3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { - var _this7 = this; + var _this6 = this; var token, special, builtin, expr, extension, is_symbol, was_close_paren, object, args, result, ref, ref_label; return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { @@ -5422,8 +5458,8 @@ } return _context8.abrupt("return", this._with_syntax_scope(function () { return call_function(extension, is_symbol ? [] : args, { - env: _this7.__env__, - dynamic_env: _this7.__env__, + env: _this6.__env__, + dynamic_env: _this6.__env__, use_dynamic: false }); })); @@ -5458,7 +5494,7 @@ } _context8.next = 44; return this._with_syntax_scope(function () { - return _this7.evaluate(expr); + return _this6.evaluate(expr); }); case 44: result = _context8.sent; @@ -6195,7 +6231,7 @@ return new RegExp("^(?:#:)?(?:".concat(args.join('|'), ")$")); } // line breaking rules - Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1], [[p_o, let_re, symbol, p_o, let_value, p_e], 1], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; + Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]]; // ---------------------------------------------------------------------- Formatter.prototype["break"] = function () { var code = this.__code__.replace(/\n[ \t]*/g, '\n ').replace(/^\s+/, ''); @@ -8160,7 +8196,7 @@ // if key is Object it should only work for plain_object // because otherwise it will match every object // we don't use instanceof so it don't work for subclasses - if (obj instanceof key && (key === Object && plain_object && !iterator || key !== Object)) { + if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) { fn = value; } }); @@ -8367,6 +8403,9 @@ if (type(obj) === 'instance') { if (is_lambda(constructor) && constructor.__name__) { name = constructor.__name__.valueOf(); + if (_typeof$1(name) === 'symbol') { + name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1'); + } } else if (!is_native_function(constructor)) { name = 'instance'; } @@ -9087,8 +9126,13 @@ log(symbols); /* eslint-disable complexity */ function traverse(pattern, code) { - var pattern_names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var ellipsis = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var _state$ellipsis = state.ellipsis, + ellipsis = _state$ellipsis === void 0 ? false : _state$ellipsis, + _state$trailing = state.trailing, + trailing = _state$trailing === void 0 ? false : _state$trailing, + _state$pattern_names = state.pattern_names, + pattern_names = _state$pattern_names === void 0 ? [] : _state$pattern_names; log({ code: code, pattern: pattern @@ -9096,13 +9140,15 @@ if (is_atom(pattern) && !(pattern instanceof LSymbol)) { return same_atom(pattern, code); } - if (pattern instanceof LSymbol && symbols.includes(pattern.literal())) { - // TODO: literal() may be SLOW - if (!LSymbol.is(code, pattern)) { - return false; + if (pattern instanceof LSymbol) { + var literal = pattern.literal(); // TODO: literal() may be SLOW + if (symbols.includes(literal)) { + if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) { + return false; + } + var ref = expansion.ref(literal); + return !ref || ref === define || ref === global_env; } - var ref = expansion.ref(pattern); - return !ref || ref === define || ref === global_env; } if (Array.isArray(pattern) && Array.isArray(code)) { log('<<< a 1'); @@ -9128,25 +9174,29 @@ } else if (Array.isArray(pattern[0])) { log('<<< a 3'); var _names = _toConsumableArray(pattern_names); + var new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: _names, + ellipsis: true + }); if (!code.every(function (node) { - return traverse(pattern[0], node, _names, true); + return traverse(pattern[0], node, new_state); })) { return false; } } if (pattern.length > 2) { var pat = pattern.slice(2); - return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis); + return traverse(pat, code.slice(-pat.length), state); } return true; } - var first = traverse(pattern[0], code[0], pattern_names, ellipsis); + var first = traverse(pattern[0], code[0], state); log({ first: first, pattern: pattern[0], code: code[0] }); - var rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis); + var rest = traverse(pattern.slice(1), code.slice(1), state); log({ first: first, rest: rest @@ -9170,23 +9220,30 @@ } } if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) { + log('>> 1 (a)'); // pattern (... ???) - SRFI-46 if (!is_nil(pattern.cdr.cdr)) { if (is_pair(pattern.cdr.cdr)) { + log('>> 1 (b)'); // if we have (x ... a b) we need to remove two from the end var list_len = pattern.cdr.cdr.length(); + var improper_list = !is_nil(pattern.last_pair().cdr); if (!is_pair(code)) { return false; } var code_len = code.length(); var list = code; - while (code_len - 1 > list_len) { + var _trailing = improper_list ? 1 : 1; + while (code_len - _trailing > list_len) { list = list.cdr; code_len--; } var _rest5 = list.cdr; list.cdr = _nil; - if (!traverse(pattern.cdr.cdr, _rest5, pattern_names, ellipsis)) { + var new_sate = _objectSpread(_objectSpread({}, state), {}, { + trailing: improper_list + }); + if (!traverse(pattern.cdr.cdr, _rest5, new_sate)) { return false; } } @@ -9196,7 +9253,7 @@ if (bindings['...'].symbols[_name3] && !pattern_names.includes(_name3) && !ellipsis) { throw new Error('syntax: named ellipsis can only appear onces'); } - log('>> 1'); + log('>> 1 (next)'); if (is_nil(code)) { log('>> 2'); if (ellipsis) { @@ -9227,6 +9284,7 @@ } else { log('>> 6'); if (is_pair(code)) { + log('>> 7 ' + ellipsis); // cons (a . b) => (var ... . x) if (!is_pair(code.cdr) && !is_nil(code.cdr)) { log('>> 7 (b)'); @@ -9234,28 +9292,34 @@ return false; } else if (!bindings['...'].symbols[_name3]) { bindings['...'].symbols[_name3] = new Pair(code.car, _nil); - return traverse(pattern.cdr.cdr, code.cdr); + return traverse(pattern.cdr.cdr, code.cdr, state); } } // code as improper list var last_pair = code.last_pair(); + log({ + last_pair: last_pair + }); if (!is_nil(last_pair.cdr)) { + log('>> 7 (c)'); if (is_nil(pattern.cdr.cdr)) { // case (a ...) for (a b . x) return false; } else { + log('>> 7 (d)'); // case (a ... . b) for (a b . x) var copy = code.clone(); copy.last_pair().cdr = _nil; bindings['...'].symbols[_name3] = copy; - return traverse(pattern.cdr.cdr, last_pair.cdr); + return traverse(pattern.cdr.cdr, last_pair.cdr, state); } } - log('>> 7 ' + ellipsis); pattern_names.push(_name3); if (!bindings['...'].symbols[_name3]) { + log('>> 7 (e)'); bindings['...'].symbols[_name3] = new Pair(code, _nil); } else { + log('>> 7 (f)'); var _node2 = bindings['...'].symbols[_name3]; bindings['...'].symbols[_name3] = _node2.append(new Pair(code, _nil)); } @@ -9266,7 +9330,7 @@ // empty ellipsis with rest (a b ... . d) #290 log('>> 8'); bindings['...'].symbols[_name3] = null; - return traverse(pattern.cdr.cdr, code); + return traverse(pattern.cdr.cdr, code, state); } else { log('>> 9'); return false; @@ -9283,8 +9347,12 @@ } log('>> 11'); var _node3 = code; + var _new_state = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node3)) { - if (!traverse(pattern.car, _node3.car, names, true)) { + if (!traverse(pattern.car, _node3.car, _new_state)) { return false; } _node3 = _node3.cdr; @@ -9294,8 +9362,12 @@ if (Array.isArray(pattern.car)) { var names = _toConsumableArray(pattern_names); var _node4 = code; + var _new_state2 = _objectSpread(_objectSpread({}, state), {}, { + pattern_names: names, + ellipsis: true + }); while (is_pair(_node4)) { - if (!traverse(pattern.car, _node4.car, names, true)) { + if (!traverse(pattern.car, _node4.car, _new_state2)) { return false; } _node4 = _node4.cdr; @@ -9330,15 +9402,29 @@ code: code, pattern: pattern }); + var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol; + if (trailing && rest_pattern) { + log('>> 13 (a)'); + // handle (x ... y . z) + if (!is_nil(code.cdr)) { + return false; + } + var _car = pattern.car.valueOf(); + var _cdr = pattern.cdr.valueOf(); + bindings.symbols[_car] = code.car; + bindings.symbols[_cdr] = _nil; + return true; + //return is_pair(code.cdr) && code.cdr.length() > 1; + } if (is_nil(code.cdr)) { + log('>> 13 (b)'); // 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) { // fix for SRFI-26 in recursive call of (b) ==> (<> . x) // where <> is symbol - if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) { + if (!traverse(pattern.car, code.car, state)) { return false; } log('>> 14'); @@ -9358,7 +9444,10 @@ code: code }); // case (x y) ===> (var0 var1 ... warn) where var1 match nil - if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) { + // trailing: true start processing of (var ... x . y) + if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, state) && traverse(pattern.cdr.cdr.cdr, code.cdr, _objectSpread(_objectSpread({}, state), {}, { + trailing: true + }))) { var _name6 = pattern.cdr.car.__name__; log({ pattern: pattern, @@ -9376,15 +9465,14 @@ pattern: pattern, code: code }); - var car = traverse(pattern.car, code.car, pattern_names, ellipsis); - log({ - car: car, - pattern: pattern.car, - code: code.car - }); - var cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis); + var car = traverse(pattern.car, code.car, state); + var cdr = traverse(pattern.cdr, code.cdr, state); log({ + $car_code: code.car, + $car_pattern: pattern.car, car: car, + $cdr_code: code.cdr, + $cdr_pattern: pattern.cdr, cdr: cdr }); if (car && cdr) { @@ -9577,46 +9665,47 @@ var item = bindings[_name7]; if (item === null) { return; - } else if (item) { + } else if (_name7 in bindings) { log({ name: _name7, binding: bindings[_name7] }); if (is_pair(item)) { log('[t 2 Pair ' + nested); - var _car = item.car, - _cdr = item.cdr; + var _car2 = item.car, + _cdr2 = item.cdr; var _rest_expr = is_array ? expr.slice(2) : expr.cdr.cdr; if (nested) { - if (!is_nil(_cdr)) { + if (!is_nil(_cdr2)) { log('|| next 1'); - next(_name7, _cdr); + next(_name7, _cdr2); } if (is_array && _rest_expr.length || !is_nil(_rest_expr) && !is_array) { var _rest7 = transform_ellipsis_expr(_rest_expr, bindings, state, next); if (is_array) { - return _car.concat(_rest7); - } else if (is_pair(_car)) { - return _car.append(_rest7); + return _car2.concat(_rest7); + } else if (is_pair(_car2)) { + return _car2.append(_rest7); } else { log('UNKNOWN'); } } - return _car; - } else if (is_pair(_car)) { - if (!is_nil(_car.cdr)) { + return _car2; + } else if (is_pair(_car2)) { + if (!is_nil(_car2.cdr)) { log('|| next 2'); - next(_name7, new Pair(_car.cdr, _cdr)); + next(_name7, new Pair(_car2.cdr, _cdr2)); } - return _car.car; - } else if (is_nil(_cdr)) { - return _car; + // wrap with Value to handle undefined + return new Value(_car2.car); + } else if (is_nil(_cdr2)) { + return _car2; } else { var last_pair = expr.last_pair(); if (last_pair.cdr instanceof LSymbol) { log('|| next 3'); next(_name7, item.last_pair()); - return _car; + return _car2; } } } else if (item instanceof Array) { @@ -9679,6 +9768,7 @@ return expr; } if (is_pair(expr) || is_array) { + log('>> 0'); var first = is_array ? expr[0] : expr.car; var second, rest_second; if (is_array) { @@ -9763,6 +9853,9 @@ // undefined can be null caused by null binding // on empty ellipsis if (car !== undefined) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } if (is_spread) { if (is_array) { if (Array.isArray(car)) { @@ -9819,6 +9912,9 @@ nested: true }); if (car) { + if (car instanceof Value) { + car.valueOf(), _readOnlyError("car"); + } return new Pair(car, _nil); } return _nil; @@ -9857,6 +9953,9 @@ value: value }); if (typeof value !== 'undefined') { + if (value instanceof Value) { + value = value.valueOf(); + } if (is_array) { _result3.push(value); } else { @@ -9897,6 +9996,9 @@ } } log('<<<< 2'); + log({ + result: _result3 + }); return _result3; } } @@ -10030,8 +10132,12 @@ return typeof value === 'undefined'; } // ------------------------------------------------------------------------- + function get_proto(obj) { + return Object.getPrototypeOf(obj); + } + // ------------------------------------------------------------------------- function is_iterator(obj, symbol) { - if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) { + if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) { return is_function(obj[symbol]); } } @@ -10326,8 +10432,7 @@ return pair.cdr.car; }); } - var args_name = gensym('args'); - return Pair.fromArray([LSymbol('let'), [[args_name, Pair(LSymbol('list'), args)]], [LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], [LSymbol('apply'), code.car, args_name]]]); + return new Pair(Pair.fromArray([LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], code.car]), args); } else if (macro_expand) { // Macro.defmacro are special macros that should return lips code // here we use evaluate, so we need to check special flag set by @@ -10345,7 +10450,7 @@ } var i = 0; function exec() { - var output = new Pair(new LSymbol('begin'), code.cdr); + var output = hygienic_begin([env], code.cdr); return _evaluate(output, { env: env, dynamic_env: env, @@ -10465,7 +10570,7 @@ } // ---------------------------------------------------------------------- function pipe() { - var _this8 = this; + var _this7 = this; for (var _len8 = arguments.length, fns = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { fns[_key8] = arguments[_key8]; } @@ -10477,7 +10582,7 @@ args[_key9] = arguments[_key9]; } return fns.reduce(function (args, f) { - return [f.apply(_this8, args)]; + return [f.apply(_this7, args)]; }, args)[0]; }; } @@ -10542,7 +10647,7 @@ typecheck('curry', fn, 'function'); var len = fn.length; return function () { - var _this9 = this; + var _this8 = this; var args = init_args.slice(); // HACK: we use IIFE here to get rid of the name of the function. // The JavaScript is smart and add name property to a function @@ -10555,7 +10660,7 @@ } args = args.concat(more_args); if (args.length >= len) { - return fn.apply(_this9, args); + return fn.apply(_this8, args); } else { return curried; } @@ -11618,9 +11723,9 @@ }; // ------------------------------------------------------------------------- LComplex.prototype.complex_op = function (name, n, fn) { - var _this10 = this; + var _this9 = this; var calc = function calc(re, im) { - var result = fn(_this10.__re__, re, _this10.__im__, im); + var result = fn(_this9.__re__, re, _this9.__im__, im); if ('im' in result && 're' in result) { if (result.im.cmp(0) === 0) { return result.re; @@ -12216,7 +12321,7 @@ // :: Port abstraction - read should be a function that return next line // ------------------------------------------------------------------------- function InputPort(read) { - var _this11 = this; + var _this10 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputPort) || typeof this === 'undefined') { return new InputPort(read); @@ -12240,12 +12345,12 @@ return _regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) switch (_context14.prev = _context14.next) { case 0: - if (_this11.char_ready()) { + if (_this10.char_ready()) { _context14.next = 6; break; } _context14.next = 3; - return _this11._read(); + return _this10._read(); case 3: line = _context14.sent; parser = new Parser({ @@ -12253,7 +12358,7 @@ }); parser.parse(line); case 6: - return _context14.abrupt("return", _this11.__parser__); + return _context14.abrupt("return", _this10.__parser__); case 7: case "end": return _context14.stop(); @@ -12316,13 +12421,13 @@ return this._with_parser !== null; }; InputPort.prototype.close = function () { - var _this12 = this; + var _this11 = this; this.__parser__ = null; // make content garbage collected, we assign null, // because the value is in prototype this._with_parser = null; ['read', 'close', 'read_char', 'peek-char', 'read_line'].forEach(function (name) { - _this12[name] = function () { + _this11[name] = function () { throw new Error('input-port: port is closed'); }; }); @@ -12368,20 +12473,20 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) { _inherits(BufferedOutputPort, _OutputPort); function BufferedOutputPort(fn) { - var _this13; + var _this12; _classCallCheck(this, BufferedOutputPort); - _this13 = _callSuper(this, BufferedOutputPort, [function () { - var _this14; - return (_this14 = _this13)._write.apply(_this14, arguments); + _this12 = _callSuper(this, BufferedOutputPort, [function () { + var _this13; + return (_this13 = _this12)._write.apply(_this13, arguments); }]); typecheck('BufferedOutputPort', fn, 'function'); - read_only(_assertThisInitialized(_this13), '_fn', fn, { + read_only(_assertThisInitialized(_this12), '_fn', fn, { hidden: true }); - read_only(_assertThisInitialized(_this13), '_buffer', [], { + read_only(_assertThisInitialized(_this12), '_buffer', [], { hidden: true }); - return _this13; + return _this12; } _createClass(BufferedOutputPort, [{ key: "flush", @@ -12394,13 +12499,13 @@ }, { key: "_write", value: function _write() { - var _this15 = this; + var _this14 = this; for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) { args[_key18] = arguments[_key18]; } if (args.length) { args.forEach(function (arg) { - _this15._buffer.push(arg); + _this14._buffer.push(arg); }); var last_value = this._buffer[this._buffer.length - 1]; if (last_value.match(/\n$/)) { @@ -12413,7 +12518,7 @@ return BufferedOutputPort; }(OutputPort); // ------------------------------------------------------------------------- function OutputStringPort(toString) { - var _this16 = this; + var _this15 = this; if (typeof this !== 'undefined' && !(this instanceof OutputStringPort) || typeof this === 'undefined') { return new OutputStringPort(toString); } @@ -12426,7 +12531,7 @@ } else { x = x.valueOf(); } - _this16.__buffer__.push(x); + _this15.__buffer__.push(x); }; } OutputStringPort.prototype = Object.create(OutputPort.prototype); @@ -12441,7 +12546,7 @@ }; // ------------------------------------------------------------------------- function OutputFilePort(filename, fd) { - var _this17 = this; + var _this16 = this; if (typeof this !== 'undefined' && !(this instanceof OutputFilePort) || typeof this === 'undefined') { return new OutputFilePort(filename, fd); } @@ -12457,7 +12562,7 @@ } else { x = x.valueOf(); } - _this17.fs().write(_this17._fd, x, function (err) { + _this16.fs().write(_this16._fd, x, function (err) { if (err) { throw err; } @@ -12476,16 +12581,16 @@ return user_env.get('**internal-env**').get(name); }; OutputFilePort.prototype.close = function () { - var _this18 = this; + var _this17 = this; return new Promise(function (resolve, reject) { - _this18.fs().close(_this18._fd, function (err) { + _this17.fs().close(_this17._fd, function (err) { if (err) { reject(err); } else { - read_only(_this18, '_fd', null, { + read_only(_this17, '_fd', null, { hidden: true }); - OutputPort.prototype.close.call(_this18); + OutputPort.prototype.close.call(_this17); resolve(); } }); @@ -12496,7 +12601,7 @@ }; // ------------------------------------------------------------------------- function InputStringPort(string) { - var _this19 = this; + var _this18 = this; var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env; if (typeof this !== 'undefined' && !(this instanceof InputStringPort) || typeof this === 'undefined') { return new InputStringPort(string); @@ -12504,13 +12609,13 @@ typecheck('InputStringPort', string, 'string'); string = string.valueOf(); this._with_parser = this._with_init_parser.bind(this, function () { - if (!_this19.__parser__) { - _this19.__parser__ = new Parser({ + if (!_this18.__parser__) { + _this18.__parser__ = new Parser({ env: env }); - _this19.__parser__.parse(string); + _this18.__parser__.parse(string); } - return _this19.__parser__; + return _this18.__parser__; }); read_only(this, '__type__', text_port); this._make_defaults(); @@ -12577,13 +12682,13 @@ return "#"; }; InputByteVectorPort.prototype.close = function () { - var _this20 = this; + var _this19 = this; read_only(this, '__vector__', _nil); var err = function err() { throw new Error('Input-binary-port: port is closed'); }; ['read_u8', 'close', 'peek_u8', 'read_u8_vector'].forEach(function (name) { - _this20[name] = err; + _this19[name] = err; }); this.u8_ready = this.char_ready = function () { return false; @@ -12701,7 +12806,7 @@ }; // ------------------------------------------------------------------------- function OutputBinaryFilePort(filename, fd) { - var _this21 = this; + var _this20 = this; if (typeof this !== 'undefined' && !(this instanceof OutputBinaryFilePort) || typeof this === 'undefined') { return new OutputBinaryFilePort(filename, fd); } @@ -12716,7 +12821,7 @@ typecheck('write', x, ['number', 'uint8array']); var buffer; if (!fs) { - fs = _this21.internal('fs'); + fs = _this20.internal('fs'); } if (LNumber.isNumber(x)) { buffer = new Uint8Array([x.valueOf()]); @@ -12724,7 +12829,7 @@ buffer = new Uint8Array(Array.from(x)); } return new Promise(function (resolve, reject) { - fs.write(_this21._fd, buffer, function (err) { + fs.write(_this20._fd, buffer, function (err) { if (err) { reject(err); } else { @@ -12756,7 +12861,7 @@ // Simpler way to create interpreter with interaction-environment // ------------------------------------------------------------------------- function Interpreter(name) { - var _this22 = this; + var _this21 = this; var _ref27 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, stderr = _ref27.stderr, stdin = _ref27.stdin, @@ -12780,7 +12885,7 @@ env: this.__env__ }); this.__env__.set('parent.frame', doc('parent.frame', function () { - return _this22.__env__; + return _this21.__env__; }, global_env.__env__['parent.frame'].__doc__)); var defaults_name = '**interaction-environment-defaults**'; this.set(defaults_name, get_props(obj).concat(defaults_name)); @@ -12800,7 +12905,7 @@ // ------------------------------------------------------------------------- Interpreter.prototype.exec = /*#__PURE__*/function () { var _ref28 = _asyncToGenerator(function (arg) { - var _this23 = this; + var _this22 = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() { var _options$use_dynamic, use_dynamic, dynamic_env, env; @@ -12813,12 +12918,12 @@ // simple solution to overwrite this variable in each interpreter // before evaluation of user code if (!env) { - env = _this23.__env__; + env = _this22.__env__; } if (!dynamic_env) { dynamic_env = env; } - global_env.set('**interaction-environment**', _this23.__env__); + global_env.set('**interaction-environment**', _this22.__env__); if (!Array.isArray(arg)) { _context16.next = 10; break; @@ -12829,8 +12934,8 @@ use_dynamic: use_dynamic })); case 10: - _this23.__parser__.parse(arg); - return _context16.abrupt("return", exec(_this23.__parser__, { + _this22.__parser__.parse(arg); + return _context16.abrupt("return", exec(_this22.__parser__, { env: env, dynamic_env: dynamic_env, use_dynamic: use_dynamic @@ -13006,12 +13111,12 @@ }; // ------------------------------------------------------------------------- Environment.prototype.clone = function () { - var _this24 = this; + var _this23 = this; // duplicate refs var env = {}; // TODO: duplicated Symbols Object.keys(this.__env__).forEach(function (key) { - env[key] = _this24.__env__[key]; + env[key] = _this23.__env__[key]; }); return new Environment(env, this.__parent__, this.__name__); }; @@ -13145,14 +13250,14 @@ // For internal use only // ------------------------------------------------------------------------- Environment.prototype.constant = function (name, value) { - var _this25 = this; + var _this24 = this; if (this.__env__.hasOwnProperty(name)) { throw new Error("Environment::constant: ".concat(name, " already exists")); } if (arguments.length === 1 && is_plain_object(arguments[0])) { var obj = arguments[0]; Object.keys(obj).forEach(function (key) { - _this25.constant(name, obj[key]); + _this24.constant(name, obj[key]); }); } else { Object.defineProperty(this.__env__, name, { @@ -13328,14 +13433,14 @@ // ------------------------------------------------------------------ read: doc('read', /*#__PURE__*/function () { var _read2 = _asyncToGenerator(function () { - var _this26 = this; + var _this25 = this; var arg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() { var env, port; return _regeneratorRuntime.wrap(function _callee17$(_context17) { while (1) switch (_context17.prev = _context17.next) { case 0: - env = _this26.env; + env = _this25.env; if (arg === null) { port = internal(env, 'stdin'); } else { @@ -13423,6 +13528,19 @@ return str; }, "(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."), // ------------------------------------------------------------------ + newline: doc('newline', function newline() { + var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var display = global_env.get('display'); + var use_dynamic = this.use_dynamic; + var env = global_env; + var dynamic_env = global_env; + call_function(display, ['\n', port], { + env: env, + dynamic_env: dynamic_env, + use_dynamic: use_dynamic + }); + }, "(newline [port])\n\n Write newline character to standard output or given port"), + // ------------------------------------------------------------------ display: doc('display', function display(arg) { var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (port === null) { @@ -13445,7 +13563,7 @@ } var value = args.map(repr).join(' '); port.write.call(global_env, value); - global_env.get('newline')(port); + global_env.get('newline').call(this, port); }, "(display-error . args)\n\n Display an error message on stderr."), // ------------------------------------------------------------------ '%foldcase-string': doc('%foldcase-string', foldcase_string, "(%foldcase-string string)\n\n Same as string-foldcase but without typechecking"), @@ -13513,7 +13631,7 @@ }, "(cdr pair)\n\n This function returns the cdr (all but first) of the list."), // ------------------------------------------------------------------ 'set!': doc(new Macro('set!', function (code) { - var _this27 = this; + var _this26 = this; var _ref30 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, use_dynamic = _ref30.use_dynamic, rest = _objectWithoutProperties(_ref30, _excluded4); @@ -13567,7 +13685,7 @@ if (parts.length > 1) { var key = parts.pop(); var name = parts.join('.'); - var obj = _this27.get(name, { + var obj = _this26.get(name, { throwError: false }); if (obj) { @@ -13623,6 +13741,8 @@ env = this.get('**interaction-environment**'); } } + var package_name = '@lips'; + var has_package = file.startsWith(package_name); // TODO: move **module-path** to internal env var PATH = '**module-path**'; var module_path = global_env.get(PATH, { @@ -13664,42 +13784,61 @@ return code; }); } + function get_root_dir() { + var __dirname = global_env.get('__dirname'); + return __dirname.replace(/[^/]+$/, ''); + } if (is_node()) { return new Promise( /*#__PURE__*/function () { var _ref31 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(resolve, reject) { - var path, cmd, _args20; + var _path, _fs, root_dir, cmd, _args20; return _regeneratorRuntime.wrap(function _callee18$(_context18) { while (1) switch (_context18.prev = _context18.next) { case 0: - path = nodeRequire('path'); + _context18.prev = 0; + _context18.next = 3; + return node_ready; + case 3: + _path = nodeRequire('path'); + _fs = nodeRequire('fs'); + root_dir = get_root_dir(); + if (has_package) { + file = file.replace(package_name, root_dir); + } if (!module_path) { - _context18.next = 6; + _context18.next = 12; break; } module_path = module_path.valueOf(); - file = path.join(module_path, file); - _context18.next = 12; + if (!file.startsWith('/')) { + file = _path.join(module_path, file); + } + _context18.next = 19; break; - case 6: + case 12: + if (file.startsWith('/')) { + _context18.next = 19; + break; + } cmd = g_env.get('command-line', { throwError: false }); if (!cmd) { - _context18.next = 11; + _context18.next = 18; break; } - _context18.next = 10; + _context18.next = 17; return cmd(); - case 10: + case 17: _args20 = _context18.sent; - case 11: + case 18: if (_args20 && !is_nil(_args20)) { process.cwd(); - file = path.join(path.dirname(_args20.car.valueOf()), file); + file = _path.join(_path.dirname(_args20.car.valueOf()), file); } - case 12: - global_env.set(PATH, path.dirname(file)); - nodeRequire('fs').readFile(file, function (err, data) { + case 19: + global_env.set(PATH, _path.dirname(file)); + _fs.readFile(file, function (err, data) { if (err) { reject(err); global_env.set(PATH, module_path); @@ -13714,20 +13853,37 @@ } } }); - case 14: + _context18.next = 26; + break; + case 23: + _context18.prev = 23; + _context18.t0 = _context18["catch"](0); + console.error(_context18.t0); + case 26: case "end": return _context18.stop(); } - }, _callee18); + }, _callee18, null, [[0, 23]]); })); return function (_x14, _x15) { return _ref31.apply(this, arguments); }; }()); } + if (has_package) { + var _global_env$get, _path3; + var _path2 = (_global_env$get = global_env.get('__dirname', { + throwError: false + })) !== null && _global_env$get !== void 0 ? _global_env$get : current_script; + (_path3 = _path2) !== null && _path3 !== void 0 ? _path3 : _path2 = current_script; + var _root = _path2.replace(/dist\/?[^\/]*$/, ''); + file = file.replace(package_name, _root); + } if (module_path) { module_path = module_path.valueOf(); - file = module_path + '/' + file.replace(/^\.?\/?/, ''); + if (!file.startsWith('/')) { + file = module_path + '/' + file.replace(/^\.?\/?/, ''); + } } return fetch(file).then(function (code) { global_env.set(PATH, file.replace(/\/[^/]*$/, '')); @@ -13754,7 +13910,7 @@ // ------------------------------------------------------------------ 'do': doc(new Macro('do', /*#__PURE__*/function () { var _ref32 = _asyncToGenerator(function (code, _ref33) { - var _this28 = this; + var _this27 = this; var use_dynamic = _ref33.use_dynamic, error = _ref33.error; return /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() { @@ -13762,7 +13918,7 @@ return _regeneratorRuntime.wrap(function _callee19$(_context20) { while (1) switch (_context20.prev = _context20.next) { case 0: - self = _this28; + self = _this27; dynamic_env = self; scope = self.inherit('do'); vars = code.car; @@ -14094,8 +14250,8 @@ } env.set(name, parameter); } - var body = new Pair(new LSymbol('begin'), code.cdr); - return _evaluate(body, _objectSpread(_objectSpread({}, eval_args), {}, { + var expr = hygienic_begin([env, eval_args.dynamic_env], code.cdr); + return _evaluate(expr, _objectSpread(_objectSpread({}, eval_args), {}, { env: env })); }), "(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."), @@ -14199,21 +14355,14 @@ }, "(parent.frame)\n\n Returns the parent environment if called from inside a function.\n If no parent frame can be found it returns nil."), // ------------------------------------------------------------------ 'eval': doc('eval', function (code, env) { - var _this29 = this; env = env || this.get('interaction-environment').call(this); - return _evaluate(code, { - env: env, - dynamic_env: env, - error: function error(e) { - var error = global_env.get('display-error'); - error.call(_this29, e.message); - if (e.code) { - var stack = e.code.map(function (line, i) { - return "[".concat(i + 1, "]: ").concat(line); - }).join('\n'); - error.call(_this29, stack); - } - } + return new Promise(function (resolve, reject) { + var result = _evaluate(code, { + env: env, + dynamic_env: env, + error: reject + }); + resolve(result); }); }, "(eval expr)\n (eval expr environment)\n\n Function that evaluates LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."), // ------------------------------------------------------------------ @@ -14291,7 +14440,7 @@ } } var rest = __doc__ ? code.cdr.cdr : code.cdr; - var output = new Pair(new LSymbol('begin'), rest); + var output = hygienic_begin([env, dynamic_env], rest); var eval_args = { env: env, dynamic_env: dynamic_env, @@ -14624,7 +14773,11 @@ // ----------------------------------------------------------------- function unquote_splice(pair, unquote_cnt, max_unq) { if (unquote_cnt < max_unq) { - return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), _nil); + var cdr = _nil; + if (!is_nil(pair.cdr)) { + cdr = recur(pair.cdr, unquote_cnt - 1, max_unq); + } + return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), cdr); } var lists = []; return function next(node) { @@ -14823,7 +14976,7 @@ }, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."), // ------------------------------------------------------------------ append: doc('append', function append() { - var _global_env$get; + var _global_env$get2; for (var _len25 = arguments.length, items = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) { items[_key25] = arguments[_key25]; } @@ -14833,7 +14986,7 @@ } return item; }); - return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items))); + return (_global_env$get2 = global_env.get('append!')).call.apply(_global_env$get2, [this].concat(_toConsumableArray(items))); }, "(append item ...)\n\n Function that creates a new list with each argument appended end-to-end.\n It will always return a new list and not modify its arguments."), // ------------------------------------------------------------------ 'append!': doc('append!', function () { @@ -15170,7 +15323,7 @@ }, "(string->number number [radix])\n\n Function that parses a string into a number."), // ------------------------------------------------------------------ 'try': doc(new Macro('try', function (code, _ref41) { - var _this30 = this; + var _this28 = this; var use_dynamic = _ref41.use_dynamic; _ref41.error; return new Promise(function (resolve, reject) { @@ -15206,15 +15359,15 @@ }; } var args = { - env: _this30, + env: _this28, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { if (e instanceof IgnoreException) { throw e; } if (catch_clause) { - var env = _this30.inherit('try'); + var env = _this28.inherit('try'); var name = catch_clause.cdr.car.car; if (!(name instanceof LSymbol)) { throw new Error('try: invalid syntax: catch require variable name'); @@ -15224,7 +15377,7 @@ var catch_args = { env: env, use_dynamic: use_dynamic, - dynamic_env: _this30, + dynamic_env: _this28, error: function error(e) { catch_error = true; reject(e); @@ -15274,7 +15427,7 @@ }, "(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."), // ------------------------------------------------------------------ 'for-each': doc('for-each', function (fn) { - var _global_env$get2; + var _global_env$get3; typecheck('for-each', fn, 'function'); for (var _len32 = arguments.length, lists = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) { lists[_key32 - 1] = arguments[_key32]; @@ -15285,14 +15438,14 @@ // we need to use call(this because babel transpile this code into: // var ret = map.apply(void 0, [fn].concat(lists)); // it don't work with weakBind - var ret = (_global_env$get2 = global_env.get('map')).call.apply(_global_env$get2, [this, fn].concat(lists)); + var ret = (_global_env$get3 = global_env.get('map')).call.apply(_global_env$get3, [this, fn].concat(lists)); if (is_promise(ret)) { return ret.then(function () {}); } }, "(for-each fn . lists)\n\n Higher-order function that calls function `fn` on each\n value of the argument. If you provide more than one list\n it will take each value from each list and call `fn` function\n with that many arguments as number of list arguments."), // ------------------------------------------------------------------ map: doc('map', function map(fn) { - var _this31 = this; + var _this29 = this; for (var _len33 = arguments.length, lists = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) { lists[_key33 - 1] = arguments[_key33]; } @@ -15301,7 +15454,7 @@ lists.forEach(function (arg, i) { typecheck('map', arg, ['pair', 'nil'], i + 1); // detect cycles - if (is_pair(arg) && !is_list.call(_this31, arg)) { + if (is_pair(arg) && !is_list.call(_this29, arg)) { throw new Error("map: argument ".concat(i + 1, " is not a list")); } }); @@ -15323,7 +15476,7 @@ use_dynamic: use_dynamic }); return unpromise(result, function (head) { - return unpromise(map.call.apply(map, [_this31, fn].concat(_toConsumableArray(lists.map(function (l) { + return unpromise(map.call.apply(map, [_this29, fn].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))), function (rest) { return new Pair(head, rest); @@ -15347,18 +15500,6 @@ } }, "(list? obj)\n\n Predicate that tests if value is a proper linked list structure.\n The car of each pair can be any value. It returns false on cyclic lists.\""), // ------------------------------------------------------------------ - some: doc('some', function some(fn, list) { - typecheck('some', fn, 'function'); - typecheck('some', list, ['pair', 'nil']); - if (is_null(list)) { - return false; - } else { - return unpromise(fn(list.car), function (value) { - return value || some(fn, list.cdr); - }); - } - }, "(some fn list)\n\n Higher-order function that calls fn on each element of the list.\n It stops and returns true when fn returns true for a value.\n If none of the values give true, some will return false.\n Analogous to Python any(map(fn, list))."), - // ------------------------------------------------------------------ fold: doc('fold', fold('fold', function (fold, fn, init) { for (var _len34 = arguments.length, lists = new Array(_len34 > 3 ? _len34 - 3 : 0), _key34 = 3; _key34 < _len34; _key34++) { lists[_key34 - 3] = arguments[_key34]; @@ -15405,7 +15546,7 @@ }, "(pluck . strings)\n\n If called with a single string it will return a function that when\n called with an object will return that key from the object.\n If called with more then one string the returned function will\n create a new object by copying all properties from the given object."), // ------------------------------------------------------------------ reduce: doc('reduce', fold('reduce', function (reduce, fn, init) { - var _this32 = this; + var _this30 = this; for (var _len36 = arguments.length, lists = new Array(_len36 > 3 ? _len36 - 3 : 0), _key37 = 3; _key37 < _len36; _key37++) { lists[_key37 - 3] = arguments[_key37]; } @@ -15419,7 +15560,7 @@ return unpromise(fn.apply(void 0, _toConsumableArray(lists.map(function (l) { return l.car; })).concat([init])), function (value) { - return reduce.call.apply(reduce, [_this32, fn, value].concat(_toConsumableArray(lists.map(function (l) { + return reduce.call.apply(reduce, [_this30, fn, value].concat(_toConsumableArray(lists.map(function (l) { return l.cdr; })))); }); @@ -15813,8 +15954,8 @@ function reversseFind(dir, fn) { var parts = dir.split(path.sep).filter(Boolean); for (var i = parts.length; i--;) { - var _path; - var p = (_path = path).join.apply(_path, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); + var _path4; + var p = (_path4 = path).join.apply(_path4, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1)))); if (fn(p)) { return p; } @@ -15838,7 +15979,7 @@ function node_specific() { return _node_specific.apply(this, arguments); } // ------------------------------------------------------------------------- - /* c8 ignore next 11 */ + /* c8 ignore next 15 */ function _node_specific() { _node_specific = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() { var _yield$import, createRequire, moduleURL, __dirname__, __filename__; @@ -15912,16 +16053,20 @@ })); return _node_specific.apply(this, arguments); } + var node_ready; // Scheme load function need to wait for node_specific if (is_node()) { - node_specific(); - } else if (typeof window !== 'undefined' && window === root) { - global_env.set('window', window); - global_env.set('global', undefined); - global_env.set('self', window); - } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { - global_env.set('self', self); - global_env.set('window', undefined); - global_env.set('global', undefined); + node_ready = node_specific(); + } else { + node_ready = Promise.resolve(); + if (typeof window !== 'undefined' && window === root) { + global_env.set('window', window); + global_env.set('global', undefined); + global_env.set('self', window); + } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { + global_env.set('self', self); + global_env.set('window', undefined); + global_env.set('global', undefined); + } } // ------------------------------------------------------------------------- function typeErrorMessage(fn, got, expected) { @@ -16837,6 +16982,7 @@ url = "https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version, "/").concat(std); } } + global_env.set('__dirname', url.replace(/[^/]+$/, '')); var load = global_env.get('load'); return load.call(user_env, url, global_env); } @@ -17250,17 +17396,17 @@ // ------------------------------------------------------------------------- var banner = function () { // Rollup tree-shaking is removing the variable if it's normal string because - // obviously 'Mon, 27 May 2024 11:41:47 +0000' == '{{' + 'DATE}}'; can be removed + // obviously 'Fri, 08 Nov 2024 13:26:12 +0000' == '{{' + 'DATE}}'; can be removed // but disabling Tree-shaking is adding lot of not used code so we use this // hack instead - var date = LString('Mon, 27 May 2024 11:41:47 +0000').valueOf(); + var date = LString('Fri, 08 Nov 2024 13:26:12 +0000').valueOf(); var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date); var _format = function _format(x) { return x.toString().padStart(2, '0'); }; var _year = _date.getFullYear(); var _build = [_year, _format(_date.getMonth() + 1), _format(_date.getDate())].join('-'); - var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); + var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/, ''); return banner; }(); // ------------------------------------------------------------------------- @@ -17292,8 +17438,8 @@ read_only(QuotedPromise, '__class__', 'promise'); read_only(Parameter, '__class__', 'parameter'); // ------------------------------------------------------------------------- - var version = '1.0.0-beta.19'; - var date = 'Mon, 27 May 2024 11:41:47 +0000'; + var version = 'DEV'; + var date = 'Fri, 08 Nov 2024 13:26:12 +0000'; // unwrap async generator into Promise var parse = compose(uniterate_async, _parse); diff --git a/dist/lips.min.js b/dist/lips.min.js index 4d00901bd..b8e54dbb8 100644 --- a/dist/lips.min.js +++ b/dist/lips.min.js @@ -4,7 +4,7 @@ * | | \ \ | | | || . \/ __> | | * | | > \ | |_ | || _/\__ \ | | * | | / ^ \ |___||_||_| <___/ | | - * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19 + * \_\ /_/ \_\ /_/ v. DEV * * LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript * @@ -31,9 +31,9 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Mon, 27 May 2024 11:41:47 +0000 + * build: Fri, 08 Nov 2024 13:26:12 +0000 */ -(function(e,t){typeof exports==="object"&&typeof module!=="undefined"?t(exports):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis!=="undefined"?globalThis:e||self,t(e.lips={}))})(this,function(e){"use strict";var c=typeof document!=="undefined"?document.currentScript:null;function n(e,t){if(t.get){return t.get.call(e)}return t.value}function i(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function t(e,t){var r=i(e,t,"get");return n(e,r)}function u(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function f(e,t,r){var n=i(e,t,"set");u(e,n,r);return r}function I(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function P(e,t){P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return P(e,t)}function N(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(N=function e(){return!!t})()}function T(e,t,r){if(N())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&P(i,r.prototype),i}function r(e){if(Array.isArray(e))return e}function L(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function M(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function he(e,t){if(e==null)return{};var r=le(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function _e(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,u,o=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(o.push(n.value),o.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(u=r["return"](),Object(u)!==u))return}finally{if(c)throw i}}return o}}function b(e,t){return r(e)||_e(e,t)||R(e,t)||W()}function pe(e){if(Array.isArray(e))return M(e)}function de(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function q(e){return pe(e)||L(e)||R(e)||de()}function ve(e,t){this.v=e,this.k=t}function ye(e){return new ve(e,0)}function me(u){var a,o;function s(r,e){try{var n=u[r](e),i=n.value,a=i instanceof ve;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=u[t](e).value}c(n.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):o=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};o?o=o.next=r:(a=o=r,s(n,i))})},"function"!=typeof u["return"]&&(this["return"]=void 0)}me.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},me.prototype.next=function(e){return this._invoke("next",e)},me.prototype["throw"]=function(e){return this._invoke("throw",e)},me.prototype["return"]=function(e){return this._invoke("return",e)};function ge(e){return function(){return new me(e.apply(this,arguments))}}function be(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var we={exports:{}};var De={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(De);var xe=De.exports;(function(B){var I=xe["default"];function P(){B.exports=P=function e(){return u},B.exports.__esModule=true,B.exports["default"]=B.exports;var c,u={},e=Object.prototype,f=e.hasOwnProperty,l=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function o(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),u=new S(n||[]);return l(a,"_invoke",{value:A(e,r,u)}),a}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}u.wrap=o;var _="suspendedStart",p="suspendedYield",d="executing",v="completed",y={};function s(){}function m(){}function g(){}var b={};a(b,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(j([])));D&&D!==e&&f.call(D,i)&&(b=D);var x=g.prototype=s.prototype=Object.create(b);function E(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function F(o,s){function c(e,t,r,n){var i=h(o[e],o,t);if("throw"!==i.type){var a=i.arg,u=a.value;return u&&"object"==I(u)&&f.call(u,"__await")?s.resolve(u.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(u).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;l(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function A(a,u,o){var s=_;return function(e,t){if(s===d)throw new Error("Generator is already running");if(s===v){if("throw"===e)throw t;return{value:c,done:!0}}for(o.method=e,o.arg=t;;){var r=o.delegate;if(r){var n=k(r,o);if(n){if(n===y)continue;return n}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(s===_)throw s=v,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);s=d;var i=h(a,u,o);if("normal"===i.type){if(s=o.done?v:p,i.arg===y)continue;return{value:i.arg,done:o.done}}"throw"===i.type&&(s=v,o.method="throw",o.arg=i.arg)}}}function k(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,k(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=h(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function O(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function S(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(O,this),this.reset(!0)}function j(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var o=f.call(a,"catchLoc"),s=f.call(a,"finallyLoc");if(o&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&f.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},u}B.exports=P,B.exports.__esModule=true,B.exports["default"]=B.exports})(we);var Ee=we.exports;var Fe=Ee();var Ae=Fe;try{regeneratorRuntime=Fe}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=Fe}else{Function("r","regeneratorRuntime = r")(Fe)}}var O=be(Ae);let ke;try{ke=new TextDecoder}catch(e){}let v;let Oe;let y=0;const Ce=105;const Se=57342;const je=57343;const Be=57337;const Ie=6;const Pe={};let p={};let Ne;let Te;let Le=0;let Me=0;let Re;let qe;let Ue=[];let ze=[];let Ve;let $e;let Ye;let Je={useRecords:false,mapsAsObjects:true};let Ke=false;let He=2;try{new Function("")}catch(e){He=Infinity}class Ge{constructor(r){if(r){if((r.keyMap||r._keyMap)&&!r.useRecords){r.useRecords=false;r.mapsAsObjects=true}if(r.useRecords===false&&r.mapsAsObjects===undefined)r.mapsAsObjects=true;if(r.getStructures)r.getShared=r.getStructures;if(r.getShared&&!r.structures)(r.structures=[]).uninitialized=true;if(r.keyMap){this.mapKey=new Map;for(let[e,t]of Object.entries(r.keyMap))this.mapKey.set(t,e)}}Object.assign(this,r)}decodeKey(e){return this.keyMap?this.mapKey.get(e)||e:e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(r){if(!this._keyMap)return r;let n=new Map;for(let[e,t]of Object.entries(r))n.set(this._keyMap.hasOwnProperty(e)?this._keyMap[e]:e,t);return n}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let r={};e.forEach((e,t)=>r[Xe(this._mapKey.has(t)?this._mapKey.get(t):t)]=e);return r}mapDecode(e,t){let r=this.decode(e);if(this._keyMap){switch(r.constructor.name){case"Array":return r.map(e=>this.decodeKeys(e))}}return r}decode(t,e){if(v){return xt(()=>{Et();return this?this.decode(t,e):Ge.prototype.decode.call(Je,t,e)})}Oe=e>-1?e:t.length;y=0;Me=0;Te=null;Re=null;v=t;try{$e=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){v=null;if(t instanceof Uint8Array)throw e;throw new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Ge){p=this;Ve=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues);if(this.structures){Ne=this.structures;return We()}else if(!Ne||Ne.length>0){Ne=[]}}else{p=Je;if(!Ne||Ne.length>0)Ne=[];Ve=null}return We()}decodeMultiple(r,n){let i,a=0;try{let e=r.length;Ke=true;let t=this?this.decode(r,e):kt.decode(r,e);if(n){if(n(t)===false){return}while(y=Re.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}y=Re.postBundlePosition;Re=null}if(y==Oe){Ne=null;v=null;if(qe)qe=null}else if(y>Oe){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!Ke){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){Et();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function a(){let n=v[y++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=v[y++];break;case 25:if(i==7){return st()}n=$e.getUint16(y);y+=2;break;case 26:if(i==7){let t=$e.getFloat32(y);if(p.useFloat32>2){let e=At[(v[y]&127)<<1|v[y+1]>>7];y+=4;return(e*t+(t>0?.5:-.5)>>0)/e}y+=4;return t}n=$e.getUint32(y);y+=4;break;case 27:if(i==7){let e=$e.getFloat64(y);y+=8;return e}if(i>1){if($e.getUint32(y)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=$e.getUint32(y+4)}else if(p.int64AsNumber){n=$e.getUint32(y)*4294967296;n+=$e.getUint32(y+4)}else n=$e.getBigUint64(y);y+=8;break;case 31:switch(i){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e=[];let t,r=0;while((t=a())!=Pe){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(p.mapsAsObjects){let e={};if(p.keyMap)while((n=a())!=Pe)e[Xe(p.decodeKey(n))]=a();else while((n=a())!=Pe)e[Xe(n)]=a();return e}else{if(Ye){p.mapsAsObjects=true;Ye=false}let e=new Map;if(p.keyMap)while((n=a())!=Pe)e.set(p.decodeKey(n),a());else while((n=a())!=Pe)e.set(n,a());return e}case 7:return Pe;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+n)}}switch(i){case 0:return n;case 1:return~n;case 2:return at(n);case 3:if(Me>=y){return Te.slice(y-Le,(y+=n)-Le)}if(Me==0&&Oe<140&&n<32){let e=n<16?it(n):nt(n);if(e!=null)return e}return et(n);case 4:let t=new Array(n);for(let e=0;e=Be){let e=Ne[n&8191];if(e){if(!e.read)e.read=Ze(e);return e.read()}if(n<65536){if(n==je){let e=wt();let t=a();let r=a();ft(t,r);let n={};if(p.keyMap)for(let t=2;t23){switch(t){case 24:t=v[y++];break;case 25:t=$e.getUint16(y);y+=2;break;case 26:t=$e.getUint32(y);y+=4;break;default:throw new Error("Expected array header, but got "+v[y-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(a);r=r.next}if(this.slowReads++>=He){let e=this.length==t?this:this.slice(0,t);r=p.keyMap?new Function("r","return {"+e.map(e=>p.decodeKey(e)).map(e=>Qe.test(e)?Xe(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>Qe.test(e)?Xe(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(a)}let n={};if(p.keyMap)for(let e=0;e64&&ke)return ke.decode(v.subarray(y,y+=e));const r=y+e;const n=[];t="";while(y65535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=rt.apply(String,n);n.length=0}}if(n.length>0){t+=rt.apply(String,n)}return t}let rt=String.fromCharCode;function nt(t){let r=y;let n=new Array(t);for(let e=0;e0){y=r;return}n[e]=i}return rt.apply(String,n)}function it(d){if(d<4){if(d<2){if(d===0)return"";else{let e=v[y++];if((e&128)>1){y-=1;return}return rt(e)}}else{let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=2;return}if(d<3)return rt(e,t);let r=v[y++];if((r&128)>0){y-=3;return}return rt(e,t,r)}}else{let l=v[y++];let h=v[y++];let _=v[y++];let p=v[y++];if((l&128)>0||(h&128)>0||(_&128)>0||(p&128)>0){y-=4;return}if(d<6){if(d===4)return rt(l,h,_,p);else{let e=v[y++];if((e&128)>0){y-=5;return}return rt(l,h,_,p,e)}}else if(d<8){let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=6;return}if(d<7)return rt(l,h,_,p,e,t);let r=v[y++];if((r&128)>0){y-=7;return}return rt(l,h,_,p,e,t,r)}else{let o=v[y++];let s=v[y++];let c=v[y++];let f=v[y++];if((o&128)>0||(s&128)>0||(c&128)>0||(f&128)>0){y-=8;return}if(d<10){if(d===8)return rt(l,h,_,p,o,s,c,f);else{let e=v[y++];if((e&128)>0){y-=9;return}return rt(l,h,_,p,o,s,c,f,e)}}else if(d<12){let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=10;return}if(d<11)return rt(l,h,_,p,o,s,c,f,e,t);let r=v[y++];if((r&128)>0){y-=11;return}return rt(l,h,_,p,o,s,c,f,e,t,r)}else{let n=v[y++];let i=v[y++];let a=v[y++];let u=v[y++];if((n&128)>0||(i&128)>0||(a&128)>0||(u&128)>0){y-=12;return}if(d<14){if(d===12)return rt(l,h,_,p,o,s,c,f,n,i,a,u);else{let e=v[y++];if((e&128)>0){y-=13;return}return rt(l,h,_,p,o,s,c,f,n,i,a,u,e)}}else{let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=14;return}if(d<15)return rt(l,h,_,p,o,s,c,f,n,i,a,u,e,t);let r=v[y++];if((r&128)>0){y-=15;return}return rt(l,h,_,p,o,s,c,f,n,i,a,u,e,t,r)}}}}}function at(e){return p.copyBuffers?Uint8Array.prototype.slice.call(v,y,y+=e):v.subarray(y,y+=e)}let ut=new Float32Array(1);let ot=new Uint8Array(ut.buffer,0,4);function st(){let t=v[y++];let r=v[y++];let e=(t&127)>>2;if(e===31){if(r||t&3)return NaN;return t&128?-Infinity:Infinity}if(e===0){let e=((t&3)<<8|r)/(1<<24);return t&128?-e:e}ot[3]=t&128|(e>>1)+56;ot[2]=(t&7)<<5|r>>3;ot[1]=r<<5;ot[0]=0;return ut[0]}new Array(4096);class ct{constructor(e,t){this.value=e;this.tag=t}}Ue[0]=e=>{return new Date(e)};Ue[1]=e=>{return new Date(Math.round(e*1e3))};Ue[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-Ue[2](e)};Ue[4]=e=>{return+(e[1]+"e"+e[0])};Ue[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const ft=(e,t)=>{e=e-57344;let r=Ne[e];if(r&&r.isShared){(Ne.restoreStructures||(Ne.restoreStructures=[]))[e]=r}Ne[e]=t;t.read=Ze(t)};Ue[Ce]=r=>{let e=r.length;let n=r[1];ft(r[0],n);let i={};for(let t=2;t{if(Re)return Re[0].slice(Re.position0,Re.position0+=e);return new ct(e,14)};Ue[15]=e=>{if(Re)return Re[1].slice(Re.position1,Re.position1+=e);return new ct(e,15)};let lt={Error:Error,RegExp:RegExp};Ue[27]=e=>{return(lt[e[0]]||Error)(e[1],e[2])};const ht=e=>{if(v[y++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(v.length{if(!Ve){if(p.getShared)Dt();else return new ct(e,Ie)}if(typeof e=="number")return Ve[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};Ue[28]=e=>{if(!qe){qe=new Map;qe.id=0}let t=qe.id++;let r=v[y];let n;if(r>>5==4)n=[];else n={};let i={target:n};qe.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};Ue[28].handlesRead=true;Ue[29]=e=>{let t=qe.get(e);t.used=true;return t.target};Ue[258]=e=>new Set(e);(Ue[259]=e=>{if(p.mapsAsObjects){p.mapsAsObjects=false;Ye=true}return e()}).handlesRead=true;function _t(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function pt(){if(!Ve){if(p.getShared)Dt();else throw new Error("No packed values available")}return Ve}const dt=1399353956;ze.push((e,t)=>{if(e>=225&&e<=255)return _t(pt().prefixes[e-224],t);if(e>=28704&&e<=32767)return _t(pt().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return _t(pt().prefixes[e-1879048192],t);if(e>=216&&e<=223)return _t(t,pt().suffixes[e-216]);if(e>=27647&&e<=28671)return _t(t,pt().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return _t(t,pt().suffixes[e-1811939328]);if(e==dt){return{packedValues:Ve,structures:Ne.slice(0),version:t}}if(e==55799)return t});const vt=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;const yt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array=="undefined"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array=="undefined"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array];const mt=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e{if(!o)throw new Error("Could not find typed array for code "+s);if(!p.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new o(e.buffer,e.byteOffset,e.byteLength)}return new o(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!o)throw new Error("Could not find typed array for code "+s);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=e.length>>a;let n=new o(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=v[y++];break;case 25:e=$e.getUint16(y);y+=2;break;case 26:e=$e.getUint32(y);y+=4;break}}return e}function Dt(){if(p.getShared){let e=xt(()=>{v=null;return p.getShared()})||{};let t=e.structures||[];p.sharedVersion=e.version;Ve=p.sharedValues=e.packedValues;if(Ne===true)p.structures=Ne=t;else Ne.splice.apply(Ne,[0,t.length].concat(t))}}function xt(e){let t=Oe;let r=y;let n=Le;let i=Me;let a=Te;let u=qe;let o=Re;let s=new Uint8Array(v.slice(0,Oe));let c=Ne;let f=p;let l=Ke;let h=e();Oe=t;y=r;Le=n;Me=i;Te=a;qe=u;Re=o;v=s;Ke=l;Ne=c;p=f;$e=new DataView(v.buffer,v.byteOffset,v.byteLength);return h}function Et(){v=null;qe=null;Ne=null}function Ft(e){Ue[e.tag]=e.decode}const At=new Array(147);for(let e=0;e<256;e++){At[e]=+("1e"+Math.floor(45.15-e*.30103))}let kt=new Ge({useRecords:false});kt.decode;kt.decodeMultiple;let Ot;try{Ot=new TextEncoder}catch(e){}let Ct,St;const jt=typeof globalThis==="object"&&globalThis.Buffer;const Bt=typeof jt!=="undefined";const It=Bt?jt.allocUnsafeSlow:Uint8Array;const Pt=Bt?jt:Uint8Array;const Nt=256;const Tt=Bt?4294967296:2144337920;let Lt;let C;let S;let j=0;let Mt;let Rt=null;const qt=61440;const Ut=/[\u0080-\uFFFF]/;const zt=Symbol("record-id");class Vt extends Ge{constructor(r){super(r);this.offset=0;let s;let u;let f;let l;let n;r=r||{};let c=Pt.prototype.utf8Write?function(e,t,r){return C.utf8Write(e,t,r)}:Ot&&Ot.encodeInto?function(e,t){return Ot.encodeInto(e,C.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let h=r.maxSharedStructures;if(h==null)h=e?128:0;if(h>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){h=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let _,p,o=r.sharedValues;let d;if(o){d=Object.create(null);for(let e=0,t=o.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!C){C=new It(8192);S=new DataView(C.buffer,0,8192);j=0}Mt=C.length-10;if(Mt-j<2048){C=new It(C.length);S=new DataView(C.buffer,0,C.length);Mt=C.length-10;j=0}else if(e===nr)j=j+7&2147483640;s=j;if(a.useSelfDescribedHeader){S.setUint32(j,3654940416);j+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){Rt=[];Rt.size=Infinity}else Rt=null;u=a.structures;if(u){if(u.uninitialized){let e=a.getShared()||{};a.structures=u=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){d={};for(let e=0,t=r.length;eh&&!i)e=h;if(!u.transitions){u.transitions=Object.create(null);for(let a=0;a0){C[j++]=216;C[j++]=51;Jt(4);let r=e.values;g(r);Jt(0);Jt(0);p=Object.create(d||null);for(let e=0,t=r.length;eMt)w(j);a.offset=j;let e=Xt(C.subarray(s,j),n.idsToInsert);n=null;return e}if(e&nr){C.start=s;C.end=j;return C}return C.subarray(s,j)}finally{if(u){if(m<10)m++;if(u.length>h)u.length=h;if(y>1e4){u.transitions=null;m=0;y=0;if(v.length>0)v=[]}else if(v.length>0&&!i){for(let e=0,t=v.length;eh){a.structures=a.structures.slice(0,h)}let e=C.subarray(s,j);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&ir)j=s}};this.findCommonStringsToPack=()=>{_=new Map;if(!d)d=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!o)o=this.sharedValues=[];for(let[e,t]of _){if(t.count>r){d[e]=n++;o.push(e);f=true}}while(this.saveShared&&this.updateSharedData()===false){}_=null}};const g=u=>{if(j>Mt)C=w(j);var e=typeof u;var o;if(e==="string"){if(p){let e=p[u];if(e>=0){if(e<16)C[j++]=e+224;else{C[j++]=198;if(e&1)g(15-e>>1);else g(e-16>>1)}return}else if(_&&!r.pack){let e=_.get(u);if(e)e.count++;else _.set(u,{count:1})}}let i=u.length;if(Rt&&i>=4&&i<1024){if((Rt.size+=i)>qt){let e;let t=(Rt[0]?Rt[0].length*3+Rt[1].length:0)+10;if(j+t>Mt)C=w(j+t);C[j++]=217;C[j++]=223;C[j++]=249;C[j++]=Rt.position?132:130;C[j++]=26;e=j-s;j+=4;if(Rt.position){er(s,g)}Rt=["",""];Rt.size=0;Rt.position=e}let e=Ut.test(u);Rt[e?0:1]+=u;C[j++]=e?206:207;g(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(j+e>Mt)C=w(j+e);if(i<64||!c){let e,t,r,n=j+a;for(e=0;e>6|192;C[n++]=t&63|128}else if((t&64512)===55296&&((r=u.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;C[n++]=t>>18|240;C[n++]=t>>12&63|128;C[n++]=t>>6&63|128;C[n++]=t&63|128}else{C[n++]=t>>12|224;C[n++]=t>>6&63|128;C[n++]=t&63|128}}o=n-j-a}else{o=c(u,j+a,e)}if(o<24){C[j++]=96|o}else if(o<256){if(a<2){C.copyWithin(j+2,j+1,j+1+o)}C[j++]=120;C[j++]=o}else if(o<65536){if(a<3){C.copyWithin(j+3,j+2,j+2+o)}C[j++]=121;C[j++]=o>>8;C[j++]=o&255}else{if(a<5){C.copyWithin(j+5,j+3,j+3+o)}C[j++]=122;S.setUint32(j,o);j+=4}j+=o}else if(e==="number"){if(!this.alwaysUseFloat&&u>>>0===u){if(u<24){C[j++]=u}else if(u<256){C[j++]=24;C[j++]=u}else if(u<65536){C[j++]=25;C[j++]=u>>8;C[j++]=u&255}else{C[j++]=26;S.setUint32(j,u);j+=4}}else if(!this.alwaysUseFloat&&u>>0===u){if(u>=-24){C[j++]=31-u}else if(u>=-256){C[j++]=56;C[j++]=~u}else if(u>=-65536){C[j++]=57;S.setUint16(j,~u);j+=2}else{C[j++]=58;S.setUint32(j,~u);j+=4}}else{let t;if((t=this.useFloat32)>0&&u<4294967296&&u>=-2147483648){C[j++]=250;S.setFloat32(j,u);let e;if(t<4||(e=u*At[(C[j]&127)<<1|C[j+1]>>7])>>0===e){j+=4;return}else j--}C[j++]=251;S.setFloat64(j,u);j+=8}}else if(e==="object"){if(!u)C[j++]=246;else{if(n){let t=n.get(u);if(t){C[j++]=216;C[j++]=29;C[j++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(j-s);j+=2;return}else n.set(u,{offset:j-s})}let e=u.constructor;if(e===Object){b(u,true)}else if(e===Array){o=u.length;if(o<24){C[j++]=128|o}else{Jt(o)}for(let e=0;e>8;C[j++]=o&255}else{C[j++]=186;S.setUint32(j,o);j+=4}if(a.keyMap){for(let[e,t]of u){g(a.encodeKey(e));g(t)}}else{for(let[e,t]of u){g(e);g(t)}}}else{for(let r=0,e=Ct.length;r>8;C[j++]=t&255}else if(t>-1){C[j++]=218;S.setUint32(j,t);j+=4}e.encode.call(this,u,g,w);return}}if(u[Symbol.iterator]){if(Lt){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}C[j++]=159;for(let e of u){g(e)}C[j++]=255;return}if(u[Symbol.asyncIterator]||Ht(u)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&u.toJSON){const t=u.toJSON();if(t!==u)return g(t)}b(u,!u.hasOwnProperty)}}}else if(e==="boolean"){C[j++]=u?245:244}else if(e==="bigint"){if(u=0){C[j++]=27;S.setBigUint64(j,u)}else if(u>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){C[j++]=160|n}else if(n<256){C[j++]=184;C[j++]=n}else if(n<65536){C[j++]=185;C[j++]=n>>8;C[j++]=n&255}else{C[j++]=186;S.setUint32(j,n);j+=4}if(a.keyMap){for(let e=0;e{C[j++]=185;let e=j-s;j+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){g(a.encodeKey(e));g(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){g(e);g(t[e]);n++}}C[e+++s]=n>>8;C[e+s]=n&255}:(t,r)=>{let n,i=l.transitions||(l.transitions=Object.create(null));let a=0;let u=0;let o;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));u=s.length;for(let t=0;t>8|224;C[j++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(o===undefined){c=l.nextId++;if(!c){c=0;l.nextId=1}if(c>=Nt){l.nextId=(c=h)+1}}else{c=o}l[c]=s;if(c>8|224;C[j++]=c&255;i=l.transitions;for(let e=0;e=Nt-h)v.shift()[zt]=undefined;v.push(i);Jt(u+2);g(57344+c);g(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))g(t[e]);return}}if(u<24){C[j++]=128|u}else{Jt(u)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))g(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>Tt)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(Tt,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,C.length-1)>>12)+1<<12;let r=new It(t);S=new DataView(r.buffer,0,t);if(C.copy)C.copy(r,0,s,e);else r.set(C.slice(s,e));j-=s;s=0;Mt=r.length-10;return C=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return k(e,t,E)};this.encodeAsAsyncIterable=function(e,t){return k(e,t,O)};function*E(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)b(n,null);else $t(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)g(t);if(e&&typeof e==="object"){if(i[t])yield*E(e,i[t]);else yield*F(e,i,t)}else g(e)}}else if(t===Array){let e=n.length;Jt(e);for(let t=0;tD)){if(i.element)yield*E(e,i.element);else yield*F(e,i,"element")}else g(e)}}else if(n[Symbol.iterator]){C[j++]=159;for(let e of n){if(e&&(typeof e==="object"||j-s>D)){if(i.element)yield*E(e,i.element);else yield*F(e,i,"element")}else g(e)}C[j++]=255}else if(Ht(n)){$t(n.size,64);yield C.subarray(s,j);yield n;A()}else if(n[Symbol.asyncIterator]){C[j++]=159;yield C.subarray(s,j);yield n;A();C[j++]=255}else{g(n)}if(e&&j>s)yield C.subarray(s,j);else if(j-s>D){yield C.subarray(s,j);A()}}function*F(t,r,n){let i=j-s;try{g(t);if(j-s>D){yield C.subarray(s,j);A()}}catch(e){if(e.iteratorNotHandled){r[n]={};j=s+i;yield*E.call(this,t,r[n])}else throw e}}function A(){D=x;a.encode(null,ar)}function k(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,ar);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*O(e,t){for(let r of E(e,t,true)){let e=r.constructor;if(e===Pt||e===Uint8Array)yield r;else if(Ht(r)){let e=r.stream().getReader();let t;while(!(t=await e.read()).done){yield t.value}}else if(r[Symbol.asyncIterator]){for await(let e of r){A();if(e)yield*O(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){C=e;S=new DataView(C.buffer,C.byteOffset,C.byteLength);j=0}clearSharedData(){if(this.structures)this.structures=[];if(this.sharedValues)this.sharedValues=undefined}updateSharedData(){let t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new Yt(e,this.sharedValues,this.sharedVersion);let n=this.saveShared(r,e=>(e&&e.version||0)==t);if(n===false){r=this.getShared()||{};this.structures=r.structures||[];this.sharedValues=r.packedValues;this.sharedVersion=r.version;this.structures.nextId=this.structures.length}else{e.forEach((e,t)=>this.structures[t]=e)}return n}}function $t(e,t){if(e<24)C[j++]=t|e;else if(e<256){C[j++]=t|24;C[j++]=e}else if(e<65536){C[j++]=t|25;C[j++]=e>>8;C[j++]=e&255}else{C[j++]=t|26;S.setUint32(j,e);j+=4}}class Yt{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function Jt(e){if(e<24)C[j++]=128|e;else if(e<256){C[j++]=152;C[j++]=e}else if(e<65536){C[j++]=153;C[j++]=e>>8;C[j++]=e&255}else{C[j++]=154;S.setUint32(j,e);j+=4}}const Kt=typeof Blob==="undefined"?function(){}:Blob;function Ht(e){if(e instanceof Kt)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function Gt(r,n){switch(typeof r){case"string":if(r.length>3){if(n.objectMap[r]>-1||n.values.length>=n.maxValues)return;let e=n.get(r);if(e){if(++e.count==2){n.values.push(r)}}else{n.set(r,{count:1});if(n.samplingPackedValues){let e=n.samplingPackedValues.get(r);if(e)e.count++;else n.samplingPackedValues.set(r,{count:1})}}}break;case"object":if(r){if(r instanceof Array){for(let e=0,t=r.length;e=0&&r<4294967296){C[j++]=26;S.setUint32(j,r);j+=4}else{C[j++]=251;S.setFloat64(j,r);j+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,r){Zt(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||Bt&&this.tagUint8Array!==false)return 64}},encode(e,t,r){Zt(e,r)}},Qt(68,1),Qt(69,2),Qt(70,4),Qt(71,8),Qt(72,1),Qt(77,2),Qt(78,4),Qt(79,8),Qt(85,4),Qt(86,8),{encode(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){C[j++]=216;C[j++]=51;Jt(4);let r=e.values;n(r);Jt(0);Jt(0);packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let e=0,t=r.length;e1)e-=4;return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let a=t.buffer||t;r(Bt?jt.from(a,i,n):new Uint8Array(a,i,n))}}}function Zt(e,t){let r=e.byteLength;if(r<24){C[j++]=64+r}else if(r<256){C[j++]=88;C[j++]=r}else if(r<65536){C[j++]=89;C[j++]=r>>8;C[j++]=r&255}else{C[j++]=90;S.setUint32(j,r);j+=4}if(j+r>=C.length){t(j+r)}C.set(e.buffer?e:new Uint8Array(e),j);j+=r}function Xt(n,e){let r;let i=e.length*2;let a=n.length-i;e.sort((e,t)=>e.offset>t.offset?1:-1);for(let r=0;r>8;n[e]=r&255}}while(r=e.pop()){let e=r.offset;n.copyWithin(e+i,e,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function er(e,t){S.setUint32(Rt.position+e,j-Rt.position-e+1);let r=Rt;Rt=null;t(r[0]);t(r[1])}function tr(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");St.unshift(e.Class);Ct.unshift(e)}Ft(e)}let rr=new Vt({useRecords:false});rr.encode;rr.encodeAsIterable;rr.encodeAsAsyncIterable;const nr=512;const ir=1024;const ar=2048;var ur={}; +(function(e,t){typeof exports==="object"&&typeof module!=="undefined"?t(exports):typeof define==="function"&&define.amd?define(["exports"],t):(e=typeof globalThis!=="undefined"?globalThis:e||self,t(e.lips={}))})(this,function(e){"use strict";var c=typeof document!=="undefined"?document.currentScript:null;function n(e,t){if(t.get){return t.get.call(e)}return t.value}function i(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function t(e,t){var r=i(e,t,"get");return n(e,r)}function u(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function f(e,t,r){var n=i(e,t,"set");u(e,n,r);return r}function I(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function P(e,t){P=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return P(e,t)}function N(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(N=function e(){return!!t})()}function T(e,t,r){if(N())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&P(i,r.prototype),i}function U(e){throw new TypeError('"'+e+'" is read-only')}function r(e){if(Array.isArray(e))return e}function L(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function M(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function _e(e,t){if(e==null)return{};var r=he(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function pe(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,u,o=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(o.push(n.value),o.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(u=r["return"](),Object(u)!==u))return}finally{if(c)throw i}}return o}}function b(e,t){return r(e)||pe(e,t)||R(e,t)||z()}function de(e){if(Array.isArray(e))return M(e)}function ve(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ee(e){return de(e)||L(e)||R(e)||ve()}function ye(e,t){this.v=e,this.k=t}function me(e){return new ye(e,0)}function ge(u){var a,o;function s(r,e){try{var n=u[r](e),i=n.value,a=i instanceof ye;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=u[t](e).value}c(n.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):o=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};o?o=o.next=r:(a=o=r,s(n,i))})},"function"!=typeof u["return"]&&(this["return"]=void 0)}ge.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},ge.prototype.next=function(e){return this._invoke("next",e)},ge.prototype["throw"]=function(e){return this._invoke("throw",e)},ge.prototype["return"]=function(e){return this._invoke("return",e)};function be(e){return function(){return new ge(e.apply(this,arguments))}}function we(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var De={exports:{}};var xe={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(xe);var Ee=xe.exports;(function(B){var I=Ee["default"];function P(){B.exports=P=function e(){return u},B.exports.__esModule=true,B.exports["default"]=B.exports;var c,u={},e=Object.prototype,f=e.hasOwnProperty,l=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function o(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),u=new S(n||[]);return l(a,"_invoke",{value:A(e,r,u)}),a}function h(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}u.wrap=o;var _="suspendedStart",p="suspendedYield",d="executing",v="completed",y={};function s(){}function m(){}function g(){}var b={};a(b,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(j([])));D&&D!==e&&f.call(D,i)&&(b=D);var x=g.prototype=s.prototype=Object.create(b);function E(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function F(o,s){function c(e,t,r,n){var i=h(o[e],o,t);if("throw"!==i.type){var a=i.arg,u=a.value;return u&&"object"==I(u)&&f.call(u,"__await")?s.resolve(u.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(u).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;l(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function A(a,u,o){var s=_;return function(e,t){if(s===d)throw new Error("Generator is already running");if(s===v){if("throw"===e)throw t;return{value:c,done:!0}}for(o.method=e,o.arg=t;;){var r=o.delegate;if(r){var n=k(r,o);if(n){if(n===y)continue;return n}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(s===_)throw s=v,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);s=d;var i=h(a,u,o);if("normal"===i.type){if(s=o.done?v:p,i.arg===y)continue;return{value:i.arg,done:o.done}}"throw"===i.type&&(s=v,o.method="throw",o.arg=i.arg)}}}function k(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,k(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=h(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function O(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function S(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(O,this),this.reset(!0)}function j(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],u=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var o=f.call(a,"catchLoc"),s=f.call(a,"finallyLoc");if(o&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&f.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),C(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;C(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:j(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},u}B.exports=P,B.exports.__esModule=true,B.exports["default"]=B.exports})(De);var Fe=De.exports;var Ae=Fe();var ke=Ae;try{regeneratorRuntime=Ae}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=Ae}else{Function("r","regeneratorRuntime = r")(Ae)}}var O=we(ke);let Oe;try{Oe=new TextDecoder}catch(e){}let v;let Ce;let y=0;const Se=105;const je=57342;const Be=57343;const Ie=57337;const Pe=6;const Ne={};let p={};let Te;let Le;let Me=0;let Re=0;let qe;let Ue;let ze=[];let Ve=[];let $e;let Ye;let Je;let Ke={useRecords:false,mapsAsObjects:true};let We=false;let Ge=2;try{new Function("")}catch(e){Ge=Infinity}class He{constructor(r){if(r){if((r.keyMap||r._keyMap)&&!r.useRecords){r.useRecords=false;r.mapsAsObjects=true}if(r.useRecords===false&&r.mapsAsObjects===undefined)r.mapsAsObjects=true;if(r.getStructures)r.getShared=r.getStructures;if(r.getShared&&!r.structures)(r.structures=[]).uninitialized=true;if(r.keyMap){this.mapKey=new Map;for(let[e,t]of Object.entries(r.keyMap))this.mapKey.set(t,e)}}Object.assign(this,r)}decodeKey(e){return this.keyMap?this.mapKey.get(e)||e:e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(r){if(!this._keyMap)return r;let n=new Map;for(let[e,t]of Object.entries(r))n.set(this._keyMap.hasOwnProperty(e)?this._keyMap[e]:e,t);return n}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let r={};e.forEach((e,t)=>r[et(this._mapKey.has(t)?this._mapKey.get(t):t)]=e);return r}mapDecode(e,t){let r=this.decode(e);if(this._keyMap){switch(r.constructor.name){case"Array":return r.map(e=>this.decodeKeys(e))}}return r}decode(t,e){if(v){return Et(()=>{Ft();return this?this.decode(t,e):He.prototype.decode.call(Ke,t,e)})}Ce=e>-1?e:t.length;y=0;Re=0;Le=null;qe=null;v=t;try{Ye=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){v=null;if(t instanceof Uint8Array)throw e;throw new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof He){p=this;$e=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues);if(this.structures){Te=this.structures;return Qe()}else if(!Te||Te.length>0){Te=[]}}else{p=Ke;if(!Te||Te.length>0)Te=[];$e=null}return Qe()}decodeMultiple(r,n){let i,a=0;try{let e=r.length;We=true;let t=this?this.decode(r,e):Ot.decode(r,e);if(n){if(n(t)===false){return}while(y=qe.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}y=qe.postBundlePosition;qe=null}if(y==Ce){Te=null;v=null;if(Ue)Ue=null}else if(y>Ce){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!We){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){Ft();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function a(){let n=v[y++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=v[y++];break;case 25:if(i==7){return ct()}n=Ye.getUint16(y);y+=2;break;case 26:if(i==7){let t=Ye.getFloat32(y);if(p.useFloat32>2){let e=kt[(v[y]&127)<<1|v[y+1]>>7];y+=4;return(e*t+(t>0?.5:-.5)>>0)/e}y+=4;return t}n=Ye.getUint32(y);y+=4;break;case 27:if(i==7){let e=Ye.getFloat64(y);y+=8;return e}if(i>1){if(Ye.getUint32(y)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=Ye.getUint32(y+4)}else if(p.int64AsNumber){n=Ye.getUint32(y)*4294967296;n+=Ye.getUint32(y+4)}else n=Ye.getBigUint64(y);y+=8;break;case 31:switch(i){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e=[];let t,r=0;while((t=a())!=Ne){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(p.mapsAsObjects){let e={};if(p.keyMap)while((n=a())!=Ne)e[et(p.decodeKey(n))]=a();else while((n=a())!=Ne)e[et(n)]=a();return e}else{if(Je){p.mapsAsObjects=true;Je=false}let e=new Map;if(p.keyMap)while((n=a())!=Ne)e.set(p.decodeKey(n),a());else while((n=a())!=Ne)e.set(n,a());return e}case 7:return Ne;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+n)}}switch(i){case 0:return n;case 1:return~n;case 2:return ut(n);case 3:if(Re>=y){return Le.slice(y-Me,(y+=n)-Me)}if(Re==0&&Ce<140&&n<32){let e=n<16?at(n):it(n);if(e!=null)return e}return tt(n);case 4:let t=new Array(n);for(let e=0;e=Ie){let e=Te[n&8191];if(e){if(!e.read)e.read=Xe(e);return e.read()}if(n<65536){if(n==Be){let e=Dt();let t=a();let r=a();lt(t,r);let n={};if(p.keyMap)for(let t=2;t23){switch(t){case 24:t=v[y++];break;case 25:t=Ye.getUint16(y);y+=2;break;case 26:t=Ye.getUint32(y);y+=4;break;default:throw new Error("Expected array header, but got "+v[y-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(a);r=r.next}if(this.slowReads++>=Ge){let e=this.length==t?this:this.slice(0,t);r=p.keyMap?new Function("r","return {"+e.map(e=>p.decodeKey(e)).map(e=>Ze.test(e)?et(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>Ze.test(e)?et(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(a)}let n={};if(p.keyMap)for(let e=0;e64&&Oe)return Oe.decode(v.subarray(y,y+=e));const r=y+e;const n=[];t="";while(y65535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=nt.apply(String,n);n.length=0}}if(n.length>0){t+=nt.apply(String,n)}return t}let nt=String.fromCharCode;function it(t){let r=y;let n=new Array(t);for(let e=0;e0){y=r;return}n[e]=i}return nt.apply(String,n)}function at(d){if(d<4){if(d<2){if(d===0)return"";else{let e=v[y++];if((e&128)>1){y-=1;return}return nt(e)}}else{let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=2;return}if(d<3)return nt(e,t);let r=v[y++];if((r&128)>0){y-=3;return}return nt(e,t,r)}}else{let l=v[y++];let h=v[y++];let _=v[y++];let p=v[y++];if((l&128)>0||(h&128)>0||(_&128)>0||(p&128)>0){y-=4;return}if(d<6){if(d===4)return nt(l,h,_,p);else{let e=v[y++];if((e&128)>0){y-=5;return}return nt(l,h,_,p,e)}}else if(d<8){let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=6;return}if(d<7)return nt(l,h,_,p,e,t);let r=v[y++];if((r&128)>0){y-=7;return}return nt(l,h,_,p,e,t,r)}else{let o=v[y++];let s=v[y++];let c=v[y++];let f=v[y++];if((o&128)>0||(s&128)>0||(c&128)>0||(f&128)>0){y-=8;return}if(d<10){if(d===8)return nt(l,h,_,p,o,s,c,f);else{let e=v[y++];if((e&128)>0){y-=9;return}return nt(l,h,_,p,o,s,c,f,e)}}else if(d<12){let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=10;return}if(d<11)return nt(l,h,_,p,o,s,c,f,e,t);let r=v[y++];if((r&128)>0){y-=11;return}return nt(l,h,_,p,o,s,c,f,e,t,r)}else{let n=v[y++];let i=v[y++];let a=v[y++];let u=v[y++];if((n&128)>0||(i&128)>0||(a&128)>0||(u&128)>0){y-=12;return}if(d<14){if(d===12)return nt(l,h,_,p,o,s,c,f,n,i,a,u);else{let e=v[y++];if((e&128)>0){y-=13;return}return nt(l,h,_,p,o,s,c,f,n,i,a,u,e)}}else{let e=v[y++];let t=v[y++];if((e&128)>0||(t&128)>0){y-=14;return}if(d<15)return nt(l,h,_,p,o,s,c,f,n,i,a,u,e,t);let r=v[y++];if((r&128)>0){y-=15;return}return nt(l,h,_,p,o,s,c,f,n,i,a,u,e,t,r)}}}}}function ut(e){return p.copyBuffers?Uint8Array.prototype.slice.call(v,y,y+=e):v.subarray(y,y+=e)}let ot=new Float32Array(1);let st=new Uint8Array(ot.buffer,0,4);function ct(){let t=v[y++];let r=v[y++];let e=(t&127)>>2;if(e===31){if(r||t&3)return NaN;return t&128?-Infinity:Infinity}if(e===0){let e=((t&3)<<8|r)/(1<<24);return t&128?-e:e}st[3]=t&128|(e>>1)+56;st[2]=(t&7)<<5|r>>3;st[1]=r<<5;st[0]=0;return ot[0]}new Array(4096);class ft{constructor(e,t){this.value=e;this.tag=t}}ze[0]=e=>{return new Date(e)};ze[1]=e=>{return new Date(Math.round(e*1e3))};ze[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-ze[2](e)};ze[4]=e=>{return+(e[1]+"e"+e[0])};ze[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const lt=(e,t)=>{e=e-57344;let r=Te[e];if(r&&r.isShared){(Te.restoreStructures||(Te.restoreStructures=[]))[e]=r}Te[e]=t;t.read=Xe(t)};ze[Se]=r=>{let e=r.length;let n=r[1];lt(r[0],n);let i={};for(let t=2;t{if(qe)return qe[0].slice(qe.position0,qe.position0+=e);return new ft(e,14)};ze[15]=e=>{if(qe)return qe[1].slice(qe.position1,qe.position1+=e);return new ft(e,15)};let ht={Error:Error,RegExp:RegExp};ze[27]=e=>{return(ht[e[0]]||Error)(e[1],e[2])};const _t=e=>{if(v[y++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(v.length{if(!$e){if(p.getShared)xt();else return new ft(e,Pe)}if(typeof e=="number")return $e[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};ze[28]=e=>{if(!Ue){Ue=new Map;Ue.id=0}let t=Ue.id++;let r=v[y];let n;if(r>>5==4)n=[];else n={};let i={target:n};Ue.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};ze[28].handlesRead=true;ze[29]=e=>{let t=Ue.get(e);t.used=true;return t.target};ze[258]=e=>new Set(e);(ze[259]=e=>{if(p.mapsAsObjects){p.mapsAsObjects=false;Je=true}return e()}).handlesRead=true;function pt(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function dt(){if(!$e){if(p.getShared)xt();else throw new Error("No packed values available")}return $e}const vt=1399353956;Ve.push((e,t)=>{if(e>=225&&e<=255)return pt(dt().prefixes[e-224],t);if(e>=28704&&e<=32767)return pt(dt().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return pt(dt().prefixes[e-1879048192],t);if(e>=216&&e<=223)return pt(t,dt().suffixes[e-216]);if(e>=27647&&e<=28671)return pt(t,dt().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return pt(t,dt().suffixes[e-1811939328]);if(e==vt){return{packedValues:$e,structures:Te.slice(0),version:t}}if(e==55799)return t});const yt=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;const mt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array=="undefined"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array=="undefined"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array];const gt=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e{if(!o)throw new Error("Could not find typed array for code "+s);if(!p.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new o(e.buffer,e.byteOffset,e.byteLength)}return new o(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!o)throw new Error("Could not find typed array for code "+s);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=e.length>>a;let n=new o(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=v[y++];break;case 25:e=Ye.getUint16(y);y+=2;break;case 26:e=Ye.getUint32(y);y+=4;break}}return e}function xt(){if(p.getShared){let e=Et(()=>{v=null;return p.getShared()})||{};let t=e.structures||[];p.sharedVersion=e.version;$e=p.sharedValues=e.packedValues;if(Te===true)p.structures=Te=t;else Te.splice.apply(Te,[0,t.length].concat(t))}}function Et(e){let t=Ce;let r=y;let n=Me;let i=Re;let a=Le;let u=Ue;let o=qe;let s=new Uint8Array(v.slice(0,Ce));let c=Te;let f=p;let l=We;let h=e();Ce=t;y=r;Me=n;Re=i;Le=a;Ue=u;qe=o;v=s;We=l;Te=c;p=f;Ye=new DataView(v.buffer,v.byteOffset,v.byteLength);return h}function Ft(){v=null;Ue=null;Te=null}function At(e){ze[e.tag]=e.decode}const kt=new Array(147);for(let e=0;e<256;e++){kt[e]=+("1e"+Math.floor(45.15-e*.30103))}let Ot=new He({useRecords:false});Ot.decode;Ot.decodeMultiple;let Ct;try{Ct=new TextEncoder}catch(e){}let St,jt;const Bt=typeof globalThis==="object"&&globalThis.Buffer;const It=typeof Bt!=="undefined";const Pt=It?Bt.allocUnsafeSlow:Uint8Array;const Nt=It?Bt:Uint8Array;const Tt=256;const Lt=It?4294967296:2144337920;let Mt;let C;let S;let j=0;let Rt;let qt=null;const Ut=61440;const zt=/[\u0080-\uFFFF]/;const Vt=Symbol("record-id");class $t extends He{constructor(r){super(r);this.offset=0;let s;let u;let f;let l;let n;r=r||{};let c=Nt.prototype.utf8Write?function(e,t,r){return C.utf8Write(e,t,r)}:Ct&&Ct.encodeInto?function(e,t){return Ct.encodeInto(e,C.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let h=r.maxSharedStructures;if(h==null)h=e?128:0;if(h>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){h=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let _,p,o=r.sharedValues;let d;if(o){d=Object.create(null);for(let e=0,t=o.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!C){C=new Pt(8192);S=new DataView(C.buffer,0,8192);j=0}Rt=C.length-10;if(Rt-j<2048){C=new Pt(C.length);S=new DataView(C.buffer,0,C.length);Rt=C.length-10;j=0}else if(e===ir)j=j+7&2147483640;s=j;if(a.useSelfDescribedHeader){S.setUint32(j,3654940416);j+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){qt=[];qt.size=Infinity}else qt=null;u=a.structures;if(u){if(u.uninitialized){let e=a.getShared()||{};a.structures=u=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){d={};for(let e=0,t=r.length;eh&&!i)e=h;if(!u.transitions){u.transitions=Object.create(null);for(let a=0;a0){C[j++]=216;C[j++]=51;Kt(4);let r=e.values;g(r);Kt(0);Kt(0);p=Object.create(d||null);for(let e=0,t=r.length;eRt)w(j);a.offset=j;let e=er(C.subarray(s,j),n.idsToInsert);n=null;return e}if(e&ir){C.start=s;C.end=j;return C}return C.subarray(s,j)}finally{if(u){if(m<10)m++;if(u.length>h)u.length=h;if(y>1e4){u.transitions=null;m=0;y=0;if(v.length>0)v=[]}else if(v.length>0&&!i){for(let e=0,t=v.length;eh){a.structures=a.structures.slice(0,h)}let e=C.subarray(s,j);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&ar)j=s}};this.findCommonStringsToPack=()=>{_=new Map;if(!d)d=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!o)o=this.sharedValues=[];for(let[e,t]of _){if(t.count>r){d[e]=n++;o.push(e);f=true}}while(this.saveShared&&this.updateSharedData()===false){}_=null}};const g=u=>{if(j>Rt)C=w(j);var e=typeof u;var o;if(e==="string"){if(p){let e=p[u];if(e>=0){if(e<16)C[j++]=e+224;else{C[j++]=198;if(e&1)g(15-e>>1);else g(e-16>>1)}return}else if(_&&!r.pack){let e=_.get(u);if(e)e.count++;else _.set(u,{count:1})}}let i=u.length;if(qt&&i>=4&&i<1024){if((qt.size+=i)>Ut){let e;let t=(qt[0]?qt[0].length*3+qt[1].length:0)+10;if(j+t>Rt)C=w(j+t);C[j++]=217;C[j++]=223;C[j++]=249;C[j++]=qt.position?132:130;C[j++]=26;e=j-s;j+=4;if(qt.position){tr(s,g)}qt=["",""];qt.size=0;qt.position=e}let e=zt.test(u);qt[e?0:1]+=u;C[j++]=e?206:207;g(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(j+e>Rt)C=w(j+e);if(i<64||!c){let e,t,r,n=j+a;for(e=0;e>6|192;C[n++]=t&63|128}else if((t&64512)===55296&&((r=u.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;C[n++]=t>>18|240;C[n++]=t>>12&63|128;C[n++]=t>>6&63|128;C[n++]=t&63|128}else{C[n++]=t>>12|224;C[n++]=t>>6&63|128;C[n++]=t&63|128}}o=n-j-a}else{o=c(u,j+a,e)}if(o<24){C[j++]=96|o}else if(o<256){if(a<2){C.copyWithin(j+2,j+1,j+1+o)}C[j++]=120;C[j++]=o}else if(o<65536){if(a<3){C.copyWithin(j+3,j+2,j+2+o)}C[j++]=121;C[j++]=o>>8;C[j++]=o&255}else{if(a<5){C.copyWithin(j+5,j+3,j+3+o)}C[j++]=122;S.setUint32(j,o);j+=4}j+=o}else if(e==="number"){if(!this.alwaysUseFloat&&u>>>0===u){if(u<24){C[j++]=u}else if(u<256){C[j++]=24;C[j++]=u}else if(u<65536){C[j++]=25;C[j++]=u>>8;C[j++]=u&255}else{C[j++]=26;S.setUint32(j,u);j+=4}}else if(!this.alwaysUseFloat&&u>>0===u){if(u>=-24){C[j++]=31-u}else if(u>=-256){C[j++]=56;C[j++]=~u}else if(u>=-65536){C[j++]=57;S.setUint16(j,~u);j+=2}else{C[j++]=58;S.setUint32(j,~u);j+=4}}else{let t;if((t=this.useFloat32)>0&&u<4294967296&&u>=-2147483648){C[j++]=250;S.setFloat32(j,u);let e;if(t<4||(e=u*kt[(C[j]&127)<<1|C[j+1]>>7])>>0===e){j+=4;return}else j--}C[j++]=251;S.setFloat64(j,u);j+=8}}else if(e==="object"){if(!u)C[j++]=246;else{if(n){let t=n.get(u);if(t){C[j++]=216;C[j++]=29;C[j++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(j-s);j+=2;return}else n.set(u,{offset:j-s})}let e=u.constructor;if(e===Object){b(u,true)}else if(e===Array){o=u.length;if(o<24){C[j++]=128|o}else{Kt(o)}for(let e=0;e>8;C[j++]=o&255}else{C[j++]=186;S.setUint32(j,o);j+=4}if(a.keyMap){for(let[e,t]of u){g(a.encodeKey(e));g(t)}}else{for(let[e,t]of u){g(e);g(t)}}}else{for(let r=0,e=St.length;r>8;C[j++]=t&255}else if(t>-1){C[j++]=218;S.setUint32(j,t);j+=4}e.encode.call(this,u,g,w);return}}if(u[Symbol.iterator]){if(Mt){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}C[j++]=159;for(let e of u){g(e)}C[j++]=255;return}if(u[Symbol.asyncIterator]||Gt(u)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&u.toJSON){const t=u.toJSON();if(t!==u)return g(t)}b(u,!u.hasOwnProperty)}}}else if(e==="boolean"){C[j++]=u?245:244}else if(e==="bigint"){if(u=0){C[j++]=27;S.setBigUint64(j,u)}else if(u>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){C[j++]=160|n}else if(n<256){C[j++]=184;C[j++]=n}else if(n<65536){C[j++]=185;C[j++]=n>>8;C[j++]=n&255}else{C[j++]=186;S.setUint32(j,n);j+=4}if(a.keyMap){for(let e=0;e{C[j++]=185;let e=j-s;j+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){g(a.encodeKey(e));g(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){g(e);g(t[e]);n++}}C[e+++s]=n>>8;C[e+s]=n&255}:(t,r)=>{let n,i=l.transitions||(l.transitions=Object.create(null));let a=0;let u=0;let o;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));u=s.length;for(let t=0;t>8|224;C[j++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(o===undefined){c=l.nextId++;if(!c){c=0;l.nextId=1}if(c>=Tt){l.nextId=(c=h)+1}}else{c=o}l[c]=s;if(c>8|224;C[j++]=c&255;i=l.transitions;for(let e=0;e=Tt-h)v.shift()[Vt]=undefined;v.push(i);Kt(u+2);g(57344+c);g(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))g(t[e]);return}}if(u<24){C[j++]=128|u}else{Kt(u)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))g(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>Lt)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(Lt,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,C.length-1)>>12)+1<<12;let r=new Pt(t);S=new DataView(r.buffer,0,t);if(C.copy)C.copy(r,0,s,e);else r.set(C.slice(s,e));j-=s;s=0;Rt=r.length-10;return C=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return k(e,t,E)};this.encodeAsAsyncIterable=function(e,t){return k(e,t,O)};function*E(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)b(n,null);else Yt(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)g(t);if(e&&typeof e==="object"){if(i[t])yield*E(e,i[t]);else yield*F(e,i,t)}else g(e)}}else if(t===Array){let e=n.length;Kt(e);for(let t=0;tD)){if(i.element)yield*E(e,i.element);else yield*F(e,i,"element")}else g(e)}}else if(n[Symbol.iterator]){C[j++]=159;for(let e of n){if(e&&(typeof e==="object"||j-s>D)){if(i.element)yield*E(e,i.element);else yield*F(e,i,"element")}else g(e)}C[j++]=255}else if(Gt(n)){Yt(n.size,64);yield C.subarray(s,j);yield n;A()}else if(n[Symbol.asyncIterator]){C[j++]=159;yield C.subarray(s,j);yield n;A();C[j++]=255}else{g(n)}if(e&&j>s)yield C.subarray(s,j);else if(j-s>D){yield C.subarray(s,j);A()}}function*F(t,r,n){let i=j-s;try{g(t);if(j-s>D){yield C.subarray(s,j);A()}}catch(e){if(e.iteratorNotHandled){r[n]={};j=s+i;yield*E.call(this,t,r[n])}else throw e}}function A(){D=x;a.encode(null,ur)}function k(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,ur);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*O(e,t){for(let r of E(e,t,true)){let e=r.constructor;if(e===Nt||e===Uint8Array)yield r;else if(Gt(r)){let e=r.stream().getReader();let t;while(!(t=await e.read()).done){yield t.value}}else if(r[Symbol.asyncIterator]){for await(let e of r){A();if(e)yield*O(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){C=e;S=new DataView(C.buffer,C.byteOffset,C.byteLength);j=0}clearSharedData(){if(this.structures)this.structures=[];if(this.sharedValues)this.sharedValues=undefined}updateSharedData(){let t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new Jt(e,this.sharedValues,this.sharedVersion);let n=this.saveShared(r,e=>(e&&e.version||0)==t);if(n===false){r=this.getShared()||{};this.structures=r.structures||[];this.sharedValues=r.packedValues;this.sharedVersion=r.version;this.structures.nextId=this.structures.length}else{e.forEach((e,t)=>this.structures[t]=e)}return n}}function Yt(e,t){if(e<24)C[j++]=t|e;else if(e<256){C[j++]=t|24;C[j++]=e}else if(e<65536){C[j++]=t|25;C[j++]=e>>8;C[j++]=e&255}else{C[j++]=t|26;S.setUint32(j,e);j+=4}}class Jt{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function Kt(e){if(e<24)C[j++]=128|e;else if(e<256){C[j++]=152;C[j++]=e}else if(e<65536){C[j++]=153;C[j++]=e>>8;C[j++]=e&255}else{C[j++]=154;S.setUint32(j,e);j+=4}}const Wt=typeof Blob==="undefined"?function(){}:Blob;function Gt(e){if(e instanceof Wt)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function Ht(r,n){switch(typeof r){case"string":if(r.length>3){if(n.objectMap[r]>-1||n.values.length>=n.maxValues)return;let e=n.get(r);if(e){if(++e.count==2){n.values.push(r)}}else{n.set(r,{count:1});if(n.samplingPackedValues){let e=n.samplingPackedValues.get(r);if(e)e.count++;else n.samplingPackedValues.set(r,{count:1})}}}break;case"object":if(r){if(r instanceof Array){for(let e=0,t=r.length;e=0&&r<4294967296){C[j++]=26;S.setUint32(j,r);j+=4}else{C[j++]=251;S.setFloat64(j,r);j+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,r){Xt(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||It&&this.tagUint8Array!==false)return 64}},encode(e,t,r){Xt(e,r)}},Zt(68,1),Zt(69,2),Zt(70,4),Zt(71,8),Zt(72,1),Zt(77,2),Zt(78,4),Zt(79,8),Zt(85,4),Zt(86,8),{encode(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){C[j++]=216;C[j++]=51;Kt(4);let r=e.values;n(r);Kt(0);Kt(0);packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let e=0,t=r.length;e1)e-=4;return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let a=t.buffer||t;r(It?Bt.from(a,i,n):new Uint8Array(a,i,n))}}}function Xt(e,t){let r=e.byteLength;if(r<24){C[j++]=64+r}else if(r<256){C[j++]=88;C[j++]=r}else if(r<65536){C[j++]=89;C[j++]=r>>8;C[j++]=r&255}else{C[j++]=90;S.setUint32(j,r);j+=4}if(j+r>=C.length){t(j+r)}C.set(e.buffer?e:new Uint8Array(e),j);j+=r}function er(n,e){let r;let i=e.length*2;let a=n.length-i;e.sort((e,t)=>e.offset>t.offset?1:-1);for(let r=0;r>8;n[e]=r&255}}while(r=e.pop()){let e=r.offset;n.copyWithin(e+i,e,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function tr(e,t){S.setUint32(qt.position+e,j-qt.position-e+1);let r=qt;qt=null;t(r[0]);t(r[1])}function rr(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");jt.unshift(e.Class);St.unshift(e)}At(e)}let nr=new $t({useRecords:false});nr.encode;nr.encodeAsIterable;nr.encodeAsAsyncIterable;const ir=512;const ar=1024;const ur=2048;var or={}; /**@license * * No Dependency fast and small LZJB Compression for Browser and Node @@ -42,4 +42,4 @@ * Released under BSD-3-Clause License * * build: Wed, 27 Oct 2021 10:43:10 GMT - */Object.defineProperty(ur,"__esModule",{value:true});const or=8,sr=6,cr=3,fr=(1<r-fr){t[i++]=e[n++];continue}f=(e[n]+13^e[n+1]-13^e[n+2])&hr-1;c=n-l[f]&lr;l[f]=n;a=n-c;if(a>=0&&a!=n&&e[n]==e[a]&&e[n+1]==e[a+1]&&e[n+2]==e[a+2]){t[u]|=o;for(s=cr;s>or;t[i++]=c;n+=s}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function pr(e,t,r){t=t|0;var n=0,i=0,a=0,u=0,o=1<<(or-1|0),s=0,c=0;while(n>(or-sr|0))+cr|0;c=(e[n]<4){r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;s=s-4|0}while(s>0){r[i]=r[a];i=i+1|0;a=a+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function dr(){const e=new TextEncoder("utf-8");return e.encode(vr)}const vr="@lzjb";const yr=dr();function mr(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function gr(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function wr(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=_r(e,r);const i=gr(e.length);const a=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){a.unshift(yr)}return mr(...a)}function Dr(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,yr.length));if(s!==vr){throw new Error("Invalid magic value")}}const r=e?yr.length:0;const n=t[r];const i=r+1;const a=r+n+1;const u=br(t.slice(i,a));t=t.slice(a);const o=new Uint8Array(u);pr(t,t.length,o);return o}var xr=ur.pack=wr;var Er=ur.unpack=Dr;function Fr(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],a={},u=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:u,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var o in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),a[t]=a[t]?a[t]+","+r:r}),e(u())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(o,c.headers[o]);r.send(c.body||null)})}var Ar=["token"],kr=["env"],Or=["stderr","stdin","stdout","command_line"],Cr=["use_dynamic"],Sr=["use_dynamic"],jr=["env","dynamic_env","use_dynamic","error"];function Br(e,t,r){Ir(e,t);t.set(e,r)}function Ir(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}function Pr(e,t,r){return t=X(t),Z(e,Nr()?Reflect.construct(t,r||[],X(e).constructor):t.apply(e,r))}function Nr(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Nr=function e(){return!!t})()}function Tr(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=Lr(t))||e&&t&&typeof t.length==="number"){if(r)t=r;var n=0;var i=function e(){};return{s:i,n:function e(){if(n>=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a=true,u=false,o;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();a=t.done;return t},e:function e(t){u=true;o=t},f:function e(){try{if(!a&&r["return"]!=null)r["return"]()}finally{if(u)throw o}}}}function Lr(e,t){if(!e)return;if(typeof e==="string")return Mr(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Mr(e,t)}function Mr(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1?r-1:0),i=1;i0&&arguments[0]!==undefined?arguments[0]:null;var t=Ao&&Ao.get("DEBUG",{throwError:false});if(e===null){return t===true}return(t===null||t===void 0?void 0:t.valueOf())===e.valueOf()}function Qr(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function Zr(e,t){return"".concat(Qr(e),"[+-]?").concat(t,"+/").concat(t,"+")}function Xr(e,t){return"".concat(Qr(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function en(e,t){return"".concat(Qr(e),"[+-]?").concat(t,"+")}var tn=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var rn="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var nn="(?:#[ie])?(?:[+-]?(?:[0-9][0-9_]*/[0-9][0-9_]*|nan.0|inf.0|".concat(rn,"|[+-]?[0-9]+))?(?:").concat(rn,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var an=new RegExp("^(#[ie])?".concat(rn,"$"),"i");function un(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var on=function(){var a={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=b(e,3),r=t[0],n=t[1],i=t[2];a[r]=un(n,i)});return a}();var sn={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function cn(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=En(e);var n=r.number.split("/");var i=w({num:B([n[0],r.radix||t]),denom:B([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function An(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=En(e);if(r.inexact){return g(parseInt(r.number,r.radix||t))}return B([r.number,r.radix||t])}function kn(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\([\s\S]+)$/);if(t){r=t[1]}}if(r){return h(r)}throw new Error("Parse: invalid character")}function On(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=B(1)}else if(e==="-"){t=B(-1)}else if(e.match(gn)){t=B([e,i])}else if(e.match(bn)){var r=e.split("/");t=w({num:B([r[0],i]),denom:B([r[1],i])})}else if(e.match(an)){var n=Bn(e);if(a.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return B(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return B(Number.NEGATIVE_INFINITY)}return B(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(a.inexact){return g(t.valueOf())}return t}var a=En(e);i=a.radix||i;var r;var n=a.number.match(Dn);if(i!==10&&n){r=n}else{r=a.number.match(on[i])}var u,o;o=t(r[2]);if(r[1]){u=t(r[1])}else if(o instanceof g){u=g(0)}else{u=B(0)}if(o.cmp(0)===0&&o.__type__==="bigint"){return u}return m({im:o,re:u})}function Cn(e){return parseInt(e.toString(),10)===e}function Sn(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var a=t[3]&&t[3].length;if(i0&&(t.exact||!t.number.match(/\./))){return B(a).mul(o)}}}r=g(r);if(t.exact){return r.toRational()}return r}function In(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{var r=x(JSON.parse(e));r.freeze();return r}catch(e){var n=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(n))}}function Pn(e){if(e.match(/^\|.*\|$/)){e=e.replace(/(^\|)|(\|$)/g,"");var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\(.)/g,function(e,t){return r[t]||t})}return new V(e)}function Nn(e){if(Fo.hasOwnProperty(e)){return Fo[e]}if(e.match(/^"[\s\S]*"$/)){return In(e)}else if(e[0]==="#"){var t=e.match(tn);if(t){return new RegExp(t[1],t[2])}else if(e.match(_n)){return kn(e)}var r=e.match(/#\\(.+)/);if(r&&cn(r[1]).length===1){return kn(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(mn)){return An(e)}else if(e.match(an)){return Bn(e)}else if(e.match(yn)){return Fn(e)}else if(e.match(vn)){return On(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return Pn(e)}function Tn(e){return!(["(",")","[","]"].includes(e)||ri.names().includes(e))}function Ln(e){return Tn(e)&&!(e.match(tn)||e.match(/^"[\s\S]*"$/)||e.match(mn)||e.match(an)||e.match(vn)||e.match(yn)||e.match(_n)||["#t","#f","nil"].includes(e))}var Mn=/"(?:\\[\S\s]|[^"])*"?/g;function Rn(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function qn(){this.data=[]}qn.prototype.push=function(e){this.data.push(e)};qn.prototype.top=function(){return this.data[this.data.length-1]};qn.prototype.pop=function(){return this.data.pop()};qn.prototype.is_empty=function(){return!this.data.length};function Un(e){if(e instanceof x){e=e.valueOf()}var t=new o(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===co){break}r.push(n);t.skip()}return r}function zn(e){var t=e.token,r=he(e,Ar);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return U({token:t},r)}function Vn(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}Vn.prototype.toString=function(){return"#"};function $n(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof x){e=e.toString()}if(t){return Un(e)}else{var r=Un(e).map(function(e){if(e.token==="#\\ "||e.token=="#\\\n"){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return Kn(r)}}function Kn(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof V){if(e.is_gensym()){return e}e=e.valueOf()}if(Wn(e)){return V(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function Zn(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=Vo(e);n.fulfilled=true;n.pending=false;return e});s(this,"_promise",e,{hidden:true});if(d(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});s(this,"__promise__",e);this.then=false}Zn.prototype.then=function(e){return new Zn(this.valueOf().then(e))};Zn.prototype["catch"]=function(e){return new Zn(this.valueOf()["catch"](e))};Zn.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};Zn.prototype.toString=function(){if(this.__pending__){return Zn.pending_str}if(this.__rejected__){return Zn.rejected_str}return"#")};Zn.pending_str="#";Zn.rejected_str="#";function Xn(e){if(Array.isArray(e)){return Promise.all(ei(e)).then(ti)}return e}function ei(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Zn){t[r]=new po(n)}else{t[r]=n}}return t}function ti(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof po){t[r]=n.valueOf()}else{t[r]=n}}return t}var ri={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){try{return this.get(t).type}catch(e){console.log({name:t});console.log(e);return null}},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new V("quote-promise"),ri.LITERAL]];var si=oi.map(function(e){return e[0]});Object.freeze(si);Object.defineProperty(ri,"__builtins__",{writable:false,value:si});oi.forEach(function(e){var t=b(e,3),r=t[0],n=t[1],i=t[2];ri.append(r,n,i)});var o=function(){function m(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;ae(this,m);s(this,"__input__",e.replace(/\r/g,""));var a={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return a[r]},set:function e(t){a[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}ce(m,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return co}if(this._token){s(this,"__token__",this.token(true));return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);return this.token(t)}return co}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return co}for(var r=this._i;r=r){return co}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var a=i.match(/\n/g);if(a){this._line+=a.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return co}return h(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},n=r.prev_char,i=r["char"],a=r.next_char;var u=b(t,4),o=u[0],s=u[1],c=u[2],f=u[3];if(t.length!==5){throw new Error("Lexer: Invalid rule of length ".concat(t.length))}if(Ba(o)){if(o!==i){return false}}else if(!i.match(o)){return false}if(!hi(s,n)){return false}if(!hi(c,a)){return false}if(f!==this._state){return false}return true}},{key:"next_token",value:function e(){if(this._i>=this.__input__.length){return false}var t=true;e:for(var r=this._i,n=this.__input__.length;r2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var a=[];for(var u=0,o=t.length;u0&&arguments[0]!==undefined?arguments[0]:{},t=e.env,r=e.meta,n=r===void 0?false:r,i=e.formatter,a=i===void 0?zn:i;ae(this,u);s(this,"_formatter",a,{hidden:true});s(this,"__env__",t);s(this,"_meta",n,{hidden:true});s(this,"_refs",[],{hidden:true});s(this,"_state",{parentheses:0,fold_case:false},{hidden:true})}ce(u,[{key:"_with_syntax_scope",value:function e(t){var r=this;var n=bo(this.__env__);var i=n.get("stdin");this.__env__.set("lips",U(U({},Rs),{},{__parser__:this}));n.set("stdin",new to(this,this.__env__));var a=function e(){r.__env__.set("lips",Rs);n.set("stdin",i)};return D(t(),function(e){a();return e},a)}},{key:"parse",value:function e(t){if(t instanceof x){t=t.toString()}s(this,"__lexer__",new o(t))}},{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=ie(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===co)){t.next=4;break}return t.abrupt("return",co);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!Sa(r.token)){t.next=11;break}this.skip();if(r.token==="#!fold-case"){this._state.fold_case=true}else if(r.token==="#!no-fold-case"){this._state.fold_case=false}return t.abrupt("continue",0);case 11:if(!(r.token==="#;")){t.next=18;break}this.skip();if(!(this.__lexer__.peek()===co)){t.next=15;break}throw new Error("Lexer: syntax error eof found after comment");case 15:t.next=17;return this._read_object();case 17:return t.abrupt("continue",0);case 18:return t.abrupt("break",21);case 21:r=this._formatter(r);if(this._state.fold_case){r.token=Ki(r.token)}if(!this._meta){t.next=25;break}return t.abrupt("return",r);case 25:return t.abrupt("return",r.token);case 26:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=ie(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){return["(","["].includes(t)}},{key:"is_close",value:function e(t){return[")","]"].includes(t)}},{key:"read_list",value:function(){var e=ie(O.mark(function e(){var r,n,i,a,u,o;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=$,n=r;case 1:t.next=4;return this.peek();case 4:a=t.sent;if(!(a===co)){t.next=7;break}return t.abrupt("break",31);case 7:if(!this.is_close(a)){t.next=11;break}--this._state.parentheses;this.skip();return t.abrupt("break",31);case 11:if(!(a==="."&&!K(r))){t.next=19;break}this.skip();t.next=15;return this._read_object();case 15:n.cdr=t.sent;i=true;t.next=29;break;case 19:if(!i){t.next=23;break}throw new Error("Parser: syntax error more than one element after dot");case 23:t.next=25;return this._read_object();case 25:u=t.sent;o=new Y(u,$);if(K(r)){r=o}else{n.cdr=o}n=o;case 29:t.next=1;break;case 31:return t.abrupt("return",r);case 32:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=ie(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===co)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",Nn(r));case 6:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return k(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=ie(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof di){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",D(this._resolve_object(r),function(e){if(H(e)){e.mark_cycles()}return e}));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"balanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t,r){var n=this._state.parentheses;var i;if(n<0){i=new Error("Parser: unexpected parenthesis");i.__code__=[r.toString()+")"]}else{i=new Error("Parser: expected parenthesis but eof found");var a=new RegExp("\\){".concat(n,"}$"));i.__code__=[t.toString().replace(a,"")]}throw i}},{key:"_resolve_object",value:function(){var t=ie(O.mark(function e(r){var n=this;var i;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!Xi(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!H(r)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=ie(O.mark(function e(r){return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!H(r)){t.next=15;break}if(!(r.car instanceof di)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof di)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=ie(O.mark(function e(){var r=this;var n,i,a,u,o,s,c,f,l,h,_,p;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:n=t.sent;if(!(n===co)){t.next=5;break}return t.abrupt("return",n);case 5:if(!ni(n)){t.next=51;break}i=ri.get(n);a=ii(n);this.skip();s=ui(n);t.t0=this;t.next=13;return this.peek();case 13:t.t1=t.sent;c=t.t0.is_close.call(t.t0,t.t1);if(!s){t.next=19;break}t.t2=undefined;t.next=22;break;case 19:t.next=21;return this._read_object();case 21:t.t2=t.sent;case 22:f=t.t2;if(!(f===co)){t.next=25;break}throw new pi("Expecting expression eof found");case 25:if(a){t.next=32;break}o=this.__env__.get(i.symbol);if(!(typeof o==="function")){t.next=32;break}if(ai(n)){l=[f]}else if(K(f)){l=[]}else if(H(f)){l=f.to_array(false)}if(!(l||s)){t.next=31;break}return t.abrupt("return",this._with_syntax_scope(function(){return Go(o,s?[]:l,{env:r.__env__,dynamic_env:r.__env__,use_dynamic:false})}));case 31:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(i.symbol));case 32:if(!ai(n)){t.next=38;break}if(!c){t.next=35;break}throw new Error("Parse Error: expecting datum");case 35:u=new Y(i.symbol,new Y(f,$));t.next=39;break;case 38:u=new Y(i.symbol,f);case 39:if(!a){t.next=41;break}return t.abrupt("return",u);case 41:if(!(o instanceof J)){t.next=50;break}t.next=44;return this._with_syntax_scope(function(){return r.evaluate(u)});case 44:h=t.sent;if(!(H(h)||h instanceof V)){t.next=47;break}return t.abrupt("return",Y.fromArray([V("quote"),h]));case 47:return t.abrupt("return",h);case 50:throw new Error("Parse Error: invalid parser extension: "+i.symbol);case 51:_=this.match_datum_ref(n);if(!(_!==null)){t.next=57;break}this.skip();if(!this._refs[_]){t.next=56;break}return t.abrupt("return",new di(_,this._refs[_]));case 56:throw new Error("Parse Error: invalid datum label #".concat(_,"#"));case 57:p=this.match_datum_label(n);if(!(p!==null)){t.next=64;break}this.skip();this._refs[p]=this._read_object();return t.abrupt("return",this._refs[p]);case 64:if(!this.is_close(n)){t.next=69;break}--this._state.parentheses;this.skip();t.next=76;break;case 69:if(!this.is_open(n)){t.next=75;break}++this._state.parentheses;this.skip();return t.abrupt("return",this.read_list());case 75:return t.abrupt("return",this.read_value());case 76:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return u}();var pi=function(e){ee(t,e);function t(){ae(this,t);return Pr(this,t,arguments)}return ce(t)}(re(Error));_i.Unterminated=pi;var di=function(){function r(e,t){ae(this,r);this.name=e;this.data=t}ce(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function vi(e,t){return yi.apply(this,arguments)}function yi(){yi=ge(O.mark(function e(r,n){var i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!n){if(G){n=G.get("**interaction-environment**",{throwError:false})}else{n=Ao}}if(r instanceof _i){i=r}else{i=new _i({env:n});i.parse(r)}case 2:t.next=5;return ye(i.read_object());case 5:u=t.sent;if(!i.balanced()){i.ballancing_error(u,a)}if(!(u===co)){t.next=9;break}return t.abrupt("break",14);case 9:a=u;t.next=12;return u;case 12:t.next=2;break;case 14:case"end":return t.stop()}},e)}));return yi.apply(this,arguments)}function D(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(qa(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return mi(e,t,r)}if(Xi(e)){return gi(e,t,r)}return t(e)}function mi(t,r,e){if(t.find(qa)){return D(Xn(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function gi(t,e,r){var i=Object.keys(t);var n=[],a=[];var u=i.length;while(u--){var o=i[u];var s=t[o];n[u]=s;if(qa(s)){a.push(s)}}if(a.length){return D(Xn(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function s(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,a=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!a})}function bi(e){return wi.apply(this,arguments)}function wi(){wi=ie(O.mark(function e(r){var n,i,a,u,o,s,c;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:n=[];i=false;a=false;t.prev=3;o=qr(r);case 5:t.next=7;return o.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);a=true;u=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&o["return"]!=null)){t.next=24;break}t.next=24;return o["return"]();case 24:t.prev=24;if(!a){t.next=27;break}throw u;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}},e,null,[[3,15,19,29],[20,,24,28]])}));return wi.apply(this,arguments)}function Di(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(d(t)){return t}throw new Error("Invalid matcher")}function l(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=xi(r)}}if(e){t.__name__=e}else if(t.name&&!yu(t)){t.__name__=t.name}return t}function xi(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function Ei(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function Fi(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function Ai(e,t){return f(e,t)===t.length;function f(r,n){function e(e,t){var r=Tr(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var a=f(i,t);if(a!==-1){return a}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[a]===Symbol["for"]("symbol")&&!Ln(n[o])}function i(){var e=r[a+1];var t=n[o+1];if(e!==undefined&&t!==undefined){return f([e],[t])}}var a=0;var u={};for(var o=0;o0){continue}}else if(t()){return-1}}else if(r[a]instanceof Array){var c=f(r[a],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;a++;continue}else{return-1}a++}if(r.length!==a){return-1}return n.length}}function ki(e){this.__code__=e.replace(/\r/g,"")}ki.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*?-values|\*)?)$/],shift:{1:["&","#"]}}};ki.match=Ai;ki.prototype._options=function e(t){var r=ki.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var a=n.shift||{1:[]};return U(U(U({},r),t),{},{exceptions:{specials:[].concat(q(r.exceptions.specials),q(i)),shift:U(U({},a),{},{1:[].concat(q(r.exceptions.shift[1]),q(a[1]))})}})};ki.prototype.indent=function e(t){var r=Jn(this.__code__,true);return this._indent(r,t)};ki.exception_shift=function(a,e){function t(e){if(!e.length){return false}if(e.indexOf(a)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=Tr(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(a.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){n.offset=0}if(a.toString()===t.toString()&&us(a)){return n.offset+a[0].col}else if(a.length===1){return n.offset+a[0].col+1}else{var s=-1;if(u){var c=ki.exception_shift(u.token,n);if(c!==-1){s=c}}if(s===-1){s=ki.exception_shift(a[1].token,n)}if(s!==-1){return n.offset+a[0].col+s}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return n.offset+a[1].col}return n.offset+a[3].col}else if(a[0].line===a[1].line){return n.offset+n.indent+a[0].col}else{var f=a.slice(2);for(var l=0;l")};Oi.prototype.match=function(e){return e.match(this.pattern)};function Ci(){for(var e=arguments.length,t=new Array(e),r=0;r")};ki.Pattern=Ci;ki.Ahead=Oi;var Si=/^[[(]$/;var ji=/^[\])]$/;var Bi=/[^()[\]]/;var Ii=new Oi(/[^)\]]/);var Pi=Symbol["for"]("*");var Ni=new Ci([Si,Pi,ji],[Bi],"+");var Ti=new Ci([Si,Pi,ji],"+");var Li=new Ci([Symbol["for"]("symbol")],"?");var Mi=new Ci([Symbol["for"]("symbol")],"*");var Ri=[Si,Mi,ji];var qi=new Ci([Si,Symbol["for"]("symbol"),Pi,ji],"+");var Ui=Yi("syntax-rules");var zi=Yi("define","lambda","define-macro","syntax-rules");var Vi=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var $i=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function Yi(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!o[e]){o[e]=Ei(u,e)}});var s=Tr(i),c;try{for(s.s();!(c=s.n()).done;){var f=b(c.value,3),l=f[0],h=f[1],_=f[2];h=h.valueOf();var p=h>0?o[h]:u;var d=p.filter(function(e){return e.trim()&&!ni(e)});var v=r(p);var y=Ai(l,d);var m=n.slice(a).find(function(e){return e.trim()&&!ni(e)});if(y&&(_ instanceof Oi&&_.match(m)||!_)){var g=a-v;if(n[g]!=="\n"){if(!n[g].trim()){n[g]="\n"}else{n.splice(g,0,"\n");a++}}a+=v;continue e}}}catch(e){s.e(e)}finally{s.f()}}this.__code__=n.join("");return this};ki.prototype._spaces=function(e){return" ".repeat(e)};ki.prototype.format=function e(t){var r=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var n=Jn(r,true);var i=this._options(t);var a=0;var u=0;for(var o=0;o0){n=Math.floor(t()*r);r--;var i=[e[n],e[r]];e[r]=i[0];e[n]=i[1]}return e}function Wi(){}Wi.prototype.toString=function(){return"()"};Wi.prototype.valueOf=function(){return undefined};Wi.prototype.serialize=function(){return 0};Wi.prototype.to_object=function(){return{}};Wi.prototype.append=function(e){return new Y(e,$)};Wi.prototype.to_array=function(){return[]};var $=new Wi;function Y(e,t){if(typeof this!=="undefined"&&this.constructor!==Y||typeof this==="undefined"){return new Y(e,t)}this.car=e;this.cdr=t}function Qi(a,u){return function e(t){A(a,t,["pair","nil"]);if(K(t)){return[]}var r=[];var n=t;while(true){if(H(n)){if(n.have_cycles("cdr")){break}var i=n.car;if(u&&H(i)){i=this.get(a).call(this,i)}r.push(i);n=n.cdr}else if(K(n)){break}else{throw new Error("".concat(a,": can't convert improper list"))}}return r}}Y.prototype.flatten=function(){return Y.fromArray(Hi(this.to_array()))};Y.prototype.length=function(){var e=0;var t=this;while(true){if(!t||K(t)||!H(t)||t.have_cycles("cdr")){break}e++;t=t.cdr}return e};Y.match=function(e,t){if(e instanceof V){return V.is(e,t)}else if(H(e)){return Y.match(e.car,t)||Y.match(e.cdr,t)}else if(Array.isArray(e)){return e.some(function(e){return Y.match(e,t)})}else if(Xi(e)){return Object.values(e).some(function(e){return Y.match(e,t)})}return false};Y.prototype.find=function(e){return Y.match(this,e)};Y.prototype.clone=function(){var r=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(H(e)){if(n.has(e)){return n.get(e)}var t=new Y;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[su]=e[su];return t}return e}return i(this)};Y.prototype.last_pair=function(){var e=this;while(true){if(!H(e.cdr)){return e}if(e.have_cycles("cdr")){break}e=e.cdr}};Y.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(H(this.car)){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(H(this.cdr)){t=t.concat(this.cdr.to_array(e))}return t};Y.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(H(e)||r&&e instanceof Array&&e[uu]){return e}if(t===false){var n=$;for(var i=e.length;i--;){n=new Y(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=q(e)}var a=$;var u=e.length;while(u--){var o=e[u];if(o instanceof Array){o=Y.fromArray(o,t,r)}else if(typeof o==="string"){o=x(o)}else if(typeof o==="number"&&!Number.isNaN(o)){o=B(o)}a=new Y(o,a)}return a};Y.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(H(t)&&H(t.car)){var n=t.car;var i=n.car;if(i instanceof V){i=i.__name__}if(i instanceof x){i=i.valueOf()}var a=n.cdr;if(H(a)){a=a.to_object(e)}if(Ya(a)){if(!e){a=a.valueOf()}}r[i]=a;t=t.cdr}else{break}}return r};Y.fromPairs=function(e){return e.reduce(function(e,t){return new Y(new Y(new V(t[0]),t[1]),e)},$)};Y.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return Y.fromPairs(e)};Y.prototype.reduce=function(e){var t=this;var r=$;while(true){if(!K(t)){r=e(r,t.car);t=t.cdr}else{break}}return r};Y.prototype.reverse=function(){if(this.have_cycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=$;while(!K(e)){var r=e.cdr;e.cdr=t;t=e;e=r}return t};Y.prototype.transform=function(n){function i(e){if(H(e)){if(e.replace){delete e.replace;return e}var t=n(e.car);if(H(t)){t=i(t)}var r=n(e.cdr);if(H(r)){r=i(r)}return new Y(t,r)}return e}return i(this)};Y.prototype.map=function(e){if(typeof this.car!=="undefined"){return new Y(e(this.car),K(this.cdr)?$:this.cdr.map(e))}else{return $}};var Zi=new Map;function Xi(e){return e&&_(e)==="object"&&e.constructor===Object}var ea=Object.getOwnPropertyNames(Array.prototype);var ta=[];ea.forEach(function(e){ta.push(Array[e],Array.prototype[e])});function ra(e){e=Qa(e);return ta.includes(e)}function na(e){return d(e)&&(yu(e)||e.__doc__)}function ia(r){var e=r.constructor||Object;var n=Xi(r);var i=d(r[Symbol.asyncIterator])||d(r[Symbol.iterator]);var a;if(Zi.has(e)){a=Zi.get(e)}else{Zi.forEach(function(e,t){t=Qa(t);if(r instanceof t&&(t===Object&&n&&!i||t!==Object)){a=e}})}return a}var aa=new Map;[[true,"#t"],[false,"#f"],[null,"#null"],[undefined,"#void"]].forEach(function(e){var t=b(e,2),r=t[0],n=t[1];aa.set(r,n)});function ua(r){if(r&&_(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=ha(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_(t)==="object"&&t.constructor===Object){n[e]=ua(t)}else{n[e]=ha(t)}});return n}return r}function oa(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function sa(e,t){return e.hasOwnProperty(t)&&d(e.toString)}function ca(e){if(bu(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(d(t)&&yu(t)){if(e[cu]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(x.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_(n)==="symbol"){n=Gn(n)}if(typeof n==="string"){return"#")}}if(sa(e,"toString")){return e.toString()}else if(e.name&&!yu(e)){return"#")}else{return"#"}}var fa=new Map;[[Error,function(e){return e.message}],[Y,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.mark_cycles()}return e.toString.apply(e,[r].concat(q(i)))}],[h,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[x,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=b(e,2),r=t[0],n=t[1];fa.set(r,n)});var la=[V,J,vo,Gu,Wu,F,Zn];function ha(e,t,r){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(aa.has(e)){return aa.get(e)}if(Ia(e)){return"#"}if(e){var n=e.constructor;if(fa.has(n)){for(var i=arguments.length,a=new Array(i>3?i-3:0),u=3;u"}if(e===null){return"null"}if(d(e)){if(d(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}return ca(e)}if(_(e)==="object"){var f=e.constructor;if(!f){f=Object}var l;if(typeof f.__class__==="string"){l=f.__class__}else{var h=ia(e);if(h){if(d(h)){return h(e,t)}else{throw new Error("toString: Invalid repr value")}}l=f.name}if(d(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}if(Vo(e)==="instance"){if(yu(f)&&f.__name__){l=f.__name__.valueOf()}else if(!bu(f)){l="instance"}}if(za(e,Symbol.iterator)){if(l){return"#")}return"#"}if(za(e,Symbol.asyncIterator)){if(l){return"#")}return"#"}if(l!==""){return"#<"+l+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}Y.prototype.mark_cycles=function(){pa(this);return this};Y.prototype.have_cycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.have_cycles("car")||this.have_cycles("cdr")}return!!(this[su]&&this[su][e])};Y.prototype.is_cycle=function(){return _a(this)};function _a(e){if(!H(e)){return false}if(e.have_cycles()){return true}return _a(e.car,fn)||_a(e.cdr,fn)}function pa(e){var t=[];var i=[];var a=[];function u(e){if(!t.includes(e)){t.push(e)}}function o(e,t,r,n){if(H(r)){if(n.includes(r)){if(!a.includes(r)){a.push(r)}if(!e[su]){e[su]={}}e[su][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=$n(function e(t,r){if(H(t)){delete t[ou];delete t[su];u(t);r.push(t);var n=o(t,"car",t.car,r);var i=o(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new Vn(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(H(e[su][t])){var r=n.indexOf(e[su][t]);e[su][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return a.includes(e)});n.forEach(function(e,t){e[ou]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}Y.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[ou]){i.push(this[ou]+"(")}else if(!n){i.push("(")}var a;if(this[su]&&this[su].car){a=this[su].car}else{a=ha(this.car,e,true)}if(a!==undefined){i.push(a)}if(H(this.cdr)){if(this[su]&&this[su].cdr){i.push(" . ");i.push(this[su].cdr)}else{if(this.cdr[ou]){i.push(" . ")}else{i.push(" ")}var u=this.cdr.toString(e,{nested:true});i.push(u)}}else if(!K(this.cdr)){i=i.concat([" . ",ha(this.cdr,e,true)])}if(!n||this[ou]){i.push(")")}return i.join("")};Y.prototype.set=function(e,t){this[e]=t;if(H(t)){this.mark_cycles()}};Y.prototype.append=function(e){if(e instanceof Array){return this.append(Y.fromArray(e))}var t=this;if(t.car===undefined){if(H(e)){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(!K(e)){while(true){if(H(t)&&!K(t.cdr)){t=t.cdr}else{break}}t.cdr=e}return this};Y.prototype.serialize=function(){return[this.car,this.cdr]};Y.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(K(t)){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function da(e){return e<0?-e:e}function va(e,t){var r=Q(t),n=r[0],i=r.slice(1);while(i.length>0){var a=i,u=b(a,1),o=u[0];if(!e(n,o)){return false}var s=i;var c=Q(s);n=c[0];i=c.slice(1)}return true}function ya(e,t){if(d(e)){return d(t)&&Qa(e)===Qa(t)}else if(e instanceof B){if(!(t instanceof B)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return ya(B(e),B(t))}else if(e instanceof h){if(!(t instanceof h)){return false}return e.__char__===t.__char__}else{return e===t}}function ma(e,t){if(Vo(e)!==Vo(t)){return false}if(!ga(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof x){return e.valueOf()===t.valueOf()}return ya(e,t)}function ga(e){return e instanceof V||x.isString(e)||K(e)||e===null||e instanceof h||e instanceof B||e===true||e===false}var ba=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function J(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==J||typeof this==="undefined"){return new J(e,t)}A("Macro",e,"string",1);A("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=xi(r)}}this.__name__=e;this.__fn__=t}J.defmacro=function(e,t,r,n){var i=new J(e,t,r,n);i.__defmacro__=true;return i};J.prototype.invoke=function(e,t,r){var n=t.env,i=he(t,kr);var a=U(U({},i),{},{macro_expand:r});var u=this.__fn__.call(n,e,a,this.__name__);return u};J.prototype.toString=function(){return"#")};var wa="define-macro";var Da=-1e4;function xa(c){return function(){var r=ie(O.mark(function e(r,m){var a,g,n,i,u,b,w,D,x,E,F,A,o,k,s;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:s=function e(){s=ie(O.mark(function e(r,n,i){var a,u,o,s,c,f,l,h,_,p,d,v,y;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!(H(r)&&r.car instanceof V)){t.next=50;break}if(!r[uu]){t.next=3;break}return t.abrupt("return",r);case 3:a=r.car.valueOf();u=i.get(r.car,{throwError:false});o=b(r.car);s=o||w(u,r)||D(u);if(!(s&&H(r.cdr.car))){t.next=28;break}if(!o){t.next=15;break}g=E(r.cdr.car);t.next=12;return A(r.cdr.car,n);case 12:c=t.sent;t.next=17;break;case 15:g=x(r.cdr.car);c=r.cdr.car;case 17:t.t0=Y;t.t1=r.car;t.t2=Y;t.t3=c;t.next=23;return k(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!F(a,u)){t.next=50;break}f=u instanceof Ea?r:r.cdr;t.next=32;return u.invoke(f,U(U({},m),{},{env:i}),true);case 32:l=t.sent;if(!(u instanceof Ea)){t.next=41;break}h=l,_=h.expr,p=h.scope;if(!H(_)){t.next=40;break}if(!(n!==-1&&n<=1||n")}return"#"};var Fa=ce(function e(t){ae(this,e);s(this,"_syntax",t,{hidden:true});s(this._syntax,"_param",true,{hidden:true})});Ea.Parameter=Fa;function Aa(e,t,P,N){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var T={"...":{symbols:{},lists:[]},symbols:{}};var L=r.expansion,M=r.define;z(P);function R(t,e){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;z({code:e,pattern:t});if(ga(t)&&!(t instanceof V)){return ma(t,e)}if(t instanceof V&&P.includes(t.literal())){if(!V.is(e,t)){return false}var i=L.ref(t);return!i||i===M||i===G}if(Array.isArray(t)&&Array.isArray(e)){z("<<< a 1");if(t.length===0&&e.length===0){return true}if(V.is(t[1],N)){if(t[0]instanceof V){var a=t[0].valueOf();z("<<< a 2 "+n);if(n){var u=e.length-2;var o=u>0?e.slice(0,u):e;var s=Y.fromArray(o,false);if(!T["..."].symbols[a]){T["..."].symbols[a]=new Y(s,$)}else{T["..."].symbols[a].append(new Y(s,$))}}else{T["..."].symbols[a]=Y.fromArray(e,false)}}else if(Array.isArray(t[0])){z("<<< a 3");var c=q(r);if(!e.every(function(e){return R(t[0],e,c,true)})){return false}}if(t.length>2){var f=t.slice(2);return R(f,e.slice(-f.length),r,n)}return true}var l=R(t[0],e[0],r,n);z({first:l,pattern:t[0],code:e[0]});var h=R(t.slice(1),e.slice(1),r,n);z({first:l,rest:h});return l&&h}if(H(t)&&H(t.car)&&H(t.car.cdr)&&V.is(t.car.cdr.car,N)){z(">> 0");if(K(e)){z({pattern:t});if(t.car.car instanceof V){var _=t.car.car.valueOf();if(T["..."].symbols[_]){throw new Error("syntax: named ellipsis can only "+"appear onces")}T["..."].symbols[_]=e}}}if(H(t)&&H(t.cdr)&&V.is(t.cdr.car,N)){if(!K(t.cdr.cdr)){if(H(t.cdr.cdr)){var p=t.cdr.cdr.length();if(!H(e)){return false}var d=e.length();var v=e;while(d-1>p){v=v.cdr;d--}var y=v.cdr;v.cdr=$;if(!R(t.cdr.cdr,y,r,n)){return false}}}if(t.car instanceof V){var m=t.car.__name__;if(T["..."].symbols[m]&&!r.includes(m)&&!n){throw new Error("syntax: named ellipsis can only appear onces")}z(">> 1");if(K(e)){z(">> 2");if(n){z("NIL");T["..."].symbols[m]=$}else{z("NULL");T["..."].symbols[m]=null}}else if(H(e)&&(H(e.car)||K(e.car))){z(">> 3 "+n);if(n){if(T["..."].symbols[m]){var g=T["..."].symbols[m];if(K(g)){g=new Y($,new Y(e,$))}else{g=g.append(new Y(e,$))}T["..."].symbols[m]=g}else{T["..."].symbols[m]=new Y(e,$)}}else{z(">> 4");T["..."].symbols[m]=new Y(e,$)}}else{z(">> 6");if(H(e)){if(!H(e.cdr)&&!K(e.cdr)){z(">> 7 (b)");if(K(t.cdr.cdr)){return false}else if(!T["..."].symbols[m]){T["..."].symbols[m]=new Y(e.car,$);return R(t.cdr.cdr,e.cdr)}}var b=e.last_pair();if(!K(b.cdr)){if(K(t.cdr.cdr)){return false}else{var w=e.clone();w.last_pair().cdr=$;T["..."].symbols[m]=w;return R(t.cdr.cdr,b.cdr)}}z(">> 7 "+n);r.push(m);if(!T["..."].symbols[m]){T["..."].symbols[m]=new Y(e,$)}else{var D=T["..."].symbols[m];T["..."].symbols[m]=D.append(new Y(e,$))}z({IIIIII:T["..."].symbols[m]})}else if(t.car instanceof V&&H(t.cdr)&&V.is(t.cdr.car,N)){z(">> 8");T["..."].symbols[m]=null;return R(t.cdr.cdr,e)}else{z(">> 9");return false}}return true}else if(H(t.car)){var x=q(r);if(K(e)){z(">> 10");T["..."].lists.push($);return true}z(">> 11");var E=e;while(H(E)){if(!R(t.car,E.car,x,true)){return false}E=E.cdr}return true}if(Array.isArray(t.car)){var x=q(r);var F=e;while(H(F)){if(!R(t.car,F.car,x,true)){return false}F=F.cdr}return true}return false}if(t instanceof V){if(V.is(t,N)){throw new Error("syntax: invalid usage of ellipsis")}z(">> 12");var A=t.__name__;if(P.includes(A)){return true}if(n){var k,O;z(T["..."].symbols[A]);(O=(k=T["..."].symbols)[A])!==null&&O!==void 0?O:k[A]=[];T["..."].symbols[A].push(e)}else{T.symbols[A]=e}return true}if(H(t)&&H(e)){z(">> 13");z({a:13,code:e,pattern:t});if(K(e.cdr)){var C=t.car instanceof V&&t.cdr instanceof V;if(C){if(!R(t.car,e.car,r,n)){return false}z(">> 14");var S=t.cdr.valueOf();if(!(S in T.symbols)){T.symbols[S]=$}S=t.car.valueOf();if(!(S in T.symbols)){T.symbols[S]=e.car}return true}}z({pattern:t,code:e});if(H(t.cdr)&&H(t.cdr.cdr)&&t.cdr.car instanceof V&&V.is(t.cdr.cdr.car,N)&&H(t.cdr.cdr.cdr)&&!V.is(t.cdr.cdr.cdr.car,N)&&R(t.car,e.car,r,n)&&R(t.cdr.cdr.cdr,e.cdr,r,n)){var j=t.cdr.car.__name__;z({pattern:t,code:e,name:j});if(P.includes(j)){return true}T["..."].symbols[j]=null;return true}z("recur");z({pattern:t,code:e});var B=R(t.car,e.car,r,n);z({car:B,pattern:t.car,code:e.car});var I=R(t.cdr,e.cdr,r,n);z({car:B,cdr:I});if(B&&I){return true}}else if(K(t)&&(K(e)||e===undefined)){return true}else if(H(t.car)&&V.is(t.car.car,N)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(R(e,t)){return T}}function ka(e,i){function a(t){if(H(t)){if(!i.length){return t}var e=a(t.car);var r=a(t.cdr);return new Y(e,r)}else if(t instanceof V){var n=i.find(function(e){return e.gensym===t});if(n){return V(n.name)}return t}else{return t}}return a(e)}function Oa(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var B=e.bindings,t=e.expr,I=e.scope,u=e.symbols,f=e.names,P=e.ellipsis;var l={};function o(e){if(e instanceof V){return true}return["string","symbol"].includes(_(e))}function N(e){if(!o(e)){var t=Vo(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===P){throw new Error("syntax: internal error, ellipis not transformed")}var n=_(r);if(["string","symbol"].includes(n)){if(r in B.symbols){return B.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var a=i[0];if(a in B.symbols){return Y.fromArray([V("."),B.symbols[a]].concat(i.slice(1).map(function(e){return x(e)})))}}}if(u.includes(r)){return e}return s(r,e)}function s(e,t){if(!l[e]){var r=I.ref(e);if(_(e)==="symbol"&&!r){e=t.literal()}if(l[e]){return l[e]}var n=Qn(e);if(r){var i=I.get(e);I.set(n,i)}else{var a=I.get(e,{throwError:false});if(typeof a!=="undefined"){I.set(n,a)}}f.push({name:e,gensym:n});l[e]=n;if(typeof e==="string"&&e.match(/\./)){var u=e.split(".").filter(Boolean),o=Q(u),s=o[0],c=o.slice(1);if(l[s]){du(n,"__object__",[l[s]].concat(q(c)))}}}return l[e]}function T(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;z({bindings:t,expr:e});if(Array.isArray(e)&&!e.length){return e}if(e instanceof V){var a=e.valueOf();if(Wn(e)&&!t[a]);z("[t 1");if(t[a]){if(H(t[a])){var u=t[a],o=u.car,s=u.cdr;if(i){var c=o.car,f=o.cdr;if(!K(f)){n(a,new Y(f,$))}return c}if(!K(s)){n(a,s)}return o}else if(t[a]instanceof Array){n(a,t[a].slice(1));return t[a][0]}}return N(e)}var l=Array.isArray(e);if(H(e)||l){var h=l?e[0]:e.car;var _=l?e[1]:H(e.cdr)&&e.cdr.car;if(h instanceof V&&V.is(_,P)){l?e.slice(2):e.cdr.cdr;z("[t 2");var p=h.valueOf();var d=t[p];if(d===null){return}else if(d){z({name:p,binding:t[p]});if(H(d)){z("[t 2 Pair "+i);var v=d.car,y=d.cdr;var m=l?e.slice(2):e.cdr.cdr;if(i){if(!K(y)){z("|| next 1");n(p,y)}if(l&&m.length||!K(m)&&!l){var g=T(m,t,r,n);if(l){return v.concat(g)}else if(H(v)){return v.append(g)}else{z("UNKNOWN")}}return v}else if(H(v)){if(!K(v.cdr)){z("|| next 2");n(p,new Y(v.cdr,y))}return v.car}else if(K(y)){return v}else{var b=e.last_pair();if(b.cdr instanceof V){z("|| next 3");n(p,d.last_pair());return v}}}else if(d instanceof Array){z("[t 2 Array "+i);if(i){n(p,d.slice(1));return Y.fromArray(d)}else{var w=d.slice(1);if(w.length){n(p,w)}return d[0]}}else{return d}}}z("[t 3 recur ",e);var D=l?e.slice(1):e.cdr;var x=T(h,t,r,n);var E=T(D,t,r,n);z({head:x,rest:E});if(l){return[x].concat(E)}return new Y(x,E)}return e}function L(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,q(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return H(e)||K(e)||Array.isArray(e)&&e.length})}function M(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function R(i){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},t=e.disabled;z("traverse>> ",i);var a=Array.isArray(i);if(a&&i.length===0){return i}if(H(i)||a){var r=a?i[0]:i.car;var n,u;if(a){n=i[1];u=i.slice(2)}else if(H(i.cdr)){n=i.cdr.car;u=i.cdr.cdr}z({first:r,second:n,rest_second:u});if(!t&&H(r)&&V.is(r.car,P)){return new Y(r.cdr.car,R(i.cdr))}if(n&&V.is(n,P)&&!t){z(">> 1");var o=B["..."].symbols;var s=Object.values(o);if(s.length&&s.every(function(e){return e===null})){z(">>> 1 (a)");return R(u,{disabled:t})}var c=M(o);var f=r instanceof V&&V.is(u.car,P);if(H(r)||f){z(">>> 1 (b)");if(K(B["..."].lists[0])){if(!f){return R(u,{disabled:t})}z(u);return $}var l=r;if(f){z(">>> 1 (c)");l=new Y(r,new Y(n,$))}z(">> 2");var h;if(c.length){z(">> 2 (a)");var _=U({},o);h=a?[]:$;var p=function e(){z({bind:_});if(!L(_)){return 1}var n={};var t=function e(t,r){n[t]=r};var r=T(l,_,{nested:true},t);if(r!==undefined){if(f){if(a){if(Array.isArray(r)){var i;(i=h).push.apply(i,q(r))}else{z("ZONK {1}")}}else{if(K(h)){h=r}else{h=h.append(r)}}}else if(a){h.push(r)}else{h=new Y(r,h)}}_=n};while(true){if(p())break}if(!K(h)&&!f&&!a){h=h.reverse()}if(a){if(u){z({rest_second:u,expr:i});var d=R(u,{disabled:t});return h.concat(d)}return h}if(!K(i.cdr.cdr)&&!V.is(i.cdr.cdr.car,P)){var v=R(i.cdr.cdr,{disabled:t});return h.append(v)}return h}else{z(">> 3");var y=T(r,o,{nested:true});if(y){return new Y(y,$)}return $}}else if(r instanceof V){z(">> 4");if(V.is(u.car,P)){z(">> 4 (a)")}else{z(">> 4 (b)")}var m=r.__name__;var g=fe({},m,o[m]);z({bind:g});var b=o[m]===null;var w=a?[]:$;var D=function e(){if(!L(g,true)){z({bind:g});return 1}var n={};var t=function e(t,r){n[t]=r};var r=T(i,g,{nested:false},t);z({value:r});if(typeof r!=="undefined"){if(a){w.push(r)}else{w=new Y(r,w)}}g=n};while(true){if(D())break}if(!K(w)&&!a){w=w.reverse()}if(H(i.cdr)){if(H(i.cdr.cdr)||i.cdr.cdr instanceof V){var x=R(i.cdr.cdr,{disabled:t});z({node:x});if(b){return x}if(K(w)){w=x}else{w.append(x)}z({result:w,node:x})}}z("<<<< 2");return w}}var E=R(r,{disabled:t});var F;var A;if(r instanceof V){var k=I.get(r,{throwError:false});A=k instanceof J&&k.__name__==="syntax-rules"}if(A){if(i.cdr.car instanceof V){F=new Y(R(i.cdr.car,{disabled:t}),new Y(i.cdr.cdr.car,R(i.cdr.cdr.cdr,{disabled:t})))}else{F=new Y(i.cdr.car,R(i.cdr.cdr,{disabled:t}))}z("REST >>>> ",F)}else{F=R(i.cdr,{disabled:t})}z({a:true,car:ha(i.car),cdr:ha(i.cdr),head:ha(E),rest:ha(F)});return new Y(E,F)}if(i instanceof V){if(t&&V.is(i,P)){return i}var O=Object.keys(B["..."].symbols);var C=i.literal();if(O.includes(C)){var S="missing ellipsis symbol next to name `".concat(C,"'");throw new Error("syntax-rules: ".concat(S))}var j=N(i);if(typeof j!=="undefined"){return j}}return i}return R(t,{})}function Ca(e){return Ua(e)||K(e)||e===null}function K(e){return e===$}function d(e){return typeof e==="function"&&typeof e.bind==="function"}function Sa(e){return fi.includes(e)}function ja(e){return e===false||e===null}function Ba(e){return typeof e==="string"}function Ia(e){return e&&_(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}function Pa(e){return e instanceof ts}function Na(e){return e instanceof Xo}function Ta(e){return e instanceof Zo}function H(e){return e instanceof Y}function La(e){return e instanceof F}function Ma(e){return d(e)||Pa(e)||Ta(e)||Ra(e)}function Ra(e){return e instanceof J||e instanceof Fa}function qa(e){if(e instanceof Zn){return false}if(e instanceof Promise){return true}return!!e&&d(e.then)}function Ua(e){return typeof e==="undefined"}function za(e,t){if(Ja(e,t)||Ja(e.__proto__,t)){return d(e[t])}}function Va(e){if(!e){return false}if(_(e)!=="object"){return false}if(e.__instance__){e.__instance__=false;return e.__instance__}return false}function $a(e){var t=_(e);return["string","function"].includes(t)||_(e)==="symbol"||e instanceof Zn||e instanceof V||e instanceof B||e instanceof x||e instanceof RegExp}function Ya(e){return e instanceof B||e instanceof x||e instanceof h}function Ja(e,t){if(e===null){return false}return _(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function Ka(e){switch(_(e)){case"string":return x(e);case"bigint":return B(e);case"number":if(Number.isNaN(e)){return Eo}else{return B(e)}}return e}function Ha(r,n){var e=Object.getOwnPropertyNames(r);var t=Object.getOwnPropertySymbols(r);var i={};e.concat(t).forEach(function(e){var t=n(r[e]);i[e]=t});return i}function Ga(t){var e=[x,B,h].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(Ga)}if(t instanceof Zn){delete t.then}if(Xi(t)){return Ha(t,Ga)}return t}function Wa(e,t){if(H(e)){e.mark_cycles();return yo(e)}if(d(e)){if(t){return Za(e,t)}}return Ka(e)}function Qa(e){if(eu(e)){return e[au]}return e}function Za(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=Tr(n),a;try{for(i.s();!(a=i.n()).done;){var u=a.value;if(pu(u)){try{r[u]=e[u]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}du(r,"__fn__",e);du(r,"__context__",t);du(r,"__bound__",true);if(bu(e)){du(r,"__native__",true)}if(Xi(t)&&yu(e)){du(r,"__method__",true)}r.valueOf=function(){return e};return r}function Xa(e){return eu(e)&&e[Symbol["for"]("__context__")]===Object}function eu(e){return!!(d(e)&&e[au])}function tu(e){if(d(e)){var t=e[iu];if(t&&(t===Rs||t.constructor&&t.constructor.__class__)){return true}}return false}function ru(e){return e instanceof Gu||e instanceof Wu}function nu(e){if(d(e)){if(ru(e[iu])){return true}}return false}var iu=Symbol["for"]("__context__");var au=Symbol["for"]("__fn__");var uu=Symbol["for"]("__data__");var ou=Symbol["for"]("__ref__");var su=Symbol["for"]("__cycles__");var cu=Symbol["for"]("__class__");var fu=Symbol["for"]("__method__");var lu=Symbol["for"]("__prototype__");var hu=Symbol["for"]("__lambda__");var _u=["name","length","caller","callee","arguments","prototype"];function pu(e){return!_u.includes(e)}function du(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function vu(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function yu(e){return e&&e[hu]}function mu(e){return e&&e[fu]}function gu(e){return yu(e)&&!e[lu]&&!mu(e)&&!nu(e)}function bu(e){var t=Symbol["for"]("__native__");return d(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function wu(e){var w;switch(e){case Symbol["for"]("letrec"):w="letrec";break;case Symbol["for"]("let"):w="let";break;case Symbol["for"]("let*"):w="let*";break;default:throw new Error("Invalid let_macro value")}return J.defmacro(w,function(t,e){var f=e.dynamic_env;var l=e.error,r=e.macro_expand,h=e.use_dynamic;var _;if(t.car instanceof V){if(!(H(t.cdr.car)||K(t.cdr.car))){throw new Error("let require list of pairs")}var n;if(K(t.cdr.car)){_=$;n=$}else{n=t.cdr.car.map(function(e){return e.car});_=t.cdr.car.map(function(e){return e.cdr.car})}var i=Qn("args");return Y.fromArray([V("let"),[[i,Y(V("list"),_)]],[V("letrec"),[[t.car,Y(V("lambda"),Y(n,t.cdr.cdr))]],[V("apply"),t.car,i]]])}else if(r){return}var p=this;_=G.get("list->array")(t.car);var d=p.inherit(w);var v,y;if(w==="let*"){y=d}else if(w==="let"){v=[]}var m=0;function g(){var e=new Y(new V("begin"),t.cdr);return k(e,{env:d,dynamic_env:d,use_dynamic:h,error:l})}function b(e){if(e in d.__env__){throw new Error("Duplicated let variable ".concat(e))}}return function t(){var r=_[m++];f=w==="let*"?d:p;if(!r){if(v&&v.length){var e=v.map(function(e){return e.value});var n=e.filter(qa);if(n.length){return Xn(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=this;var a=this;var u=[];var o=e;while(H(o)){u.push(k(o.car,{env:i,dynamic_env:a,use_dynamic:r,error:n}));o=o.cdr}var s=u.filter(qa).length;if(s){return Xn(u).then(c.bind(this))}else{return c.call(this,u)}})}function xu(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),a=2;a1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=o){return u.apply(n,i)}else{return a}}}();return a.apply(void 0,arguments)}}function Bu(n,i){A("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(h.__names__[e]){t=e;e=h.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=h.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}h.__names__=sn;h.__rev_names__={};Object.keys(h.__names__).forEach(function(e){var t=h.__names__[e];h.__rev_names__[t]=e});h.prototype.toUpperCase=function(){return h(this.__char__.toUpperCase())};h.prototype.toLowerCase=function(){return h(this.__char__.toLowerCase())};h.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};h.prototype.valueOf=h.prototype.serialize=function(){return this.__char__};function x(e){if(typeof this!=="undefined"&&!(this instanceof x)||typeof this==="undefined"){return new x(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){A("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var Iu=["length","constructor"];var Pu=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!Iu.includes(e)});var Nu=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof B){return e}if(typeof this!=="undefined"&&!(this instanceof B)||typeof this==="undefined"){return new B(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=B.getType(e);if(B.types[r]){return B.types[r](e,t)}var n=e instanceof Array&&x.isString(e[0])&&B.isNumber(e[1]);if(e instanceof B){return B(e.value)}if(!B.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(Vo(e)))}if(e===null){e=0}var i;if(n){var a=e,u=b(a,2),o=u[0],s=u[1];if(o instanceof x){o=o.valueOf()}if(s instanceof B){s=s.valueOf()}var c=o.match(/^([+-])/);var f=false;if(c){o=o.replace(/^[+-]/,"");if(c[1]==="-"){f=true}}}if(Number.isNaN(e)){return g(e)}else if(n&&Number.isNaN(parseInt(o,s))){return Eo}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var l;switch(s){case 8:l="0o";break;case 16:l="0x";break;case 2:l="0b";break;case 10:l="";break}if(typeof l==="undefined"){var h=BigInt(s);i=q(o).map(function(e,t){return BigInt(parseInt(e,s))*Vu(h,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(l+o)}}else{i=BigInt(e)}if(f){i*=BigInt(-1)}}else{i=e}return E(i,true)}else if(typeof Hr!=="undefined"&&!(e instanceof Hr)){if(e instanceof Array){return E(T(Hr,q(e)))}return E(new Hr(e))}else if(n){this.constant(parseInt(o,s),"integer")}else{this.constant(e,"integer")}}B.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};B.types={float:function e(t){return new g(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!B.isComplex(t)){t={im:0,re:t}}return new m(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!B.isRational(t)){t={num:t,denom:1}}return new w(t,r)}};B.prototype.serialize=function(){return this.__value__};B.prototype.isNaN=function(){return Number.isNaN(this.__value__)};B.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};B.isFloat=function e(t){return t instanceof g||Number(t)===t&&t%1!==0};B.isNumber=function(e){return e instanceof B||B.isNative(e)||B.isBN(e)};B.isComplex=function(e){if(!e){return false}var t=e instanceof m||(B.isNumber(e.im)||B.isRational(e.im)||Number.isNaN(e.im))&&(B.isNumber(e.re)||B.isRational(e.re)||Number.isNaN(e.re));return t};B.isRational=function(e){if(!e){return false}return e instanceof w||B.isNumber(e.num)&&B.isNumber(e.denom)};B.isInteger=function(e){if(!(B.isNative(e)||e instanceof B)){return false}if(B.isFloat(e)){return false}if(B.isRational(e)){return false}if(B.isComplex(e)){return false}return true};B.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};B.isBigInteger=function(e){return e instanceof E||typeof e==="bigint"||B.isBN(e)};B.isBN=function(e){return typeof Hr!=="undefined"&&e instanceof Hr};B.getArgsType=function(e,t){if(e instanceof g||t instanceof g){return g}if(e instanceof E||t instanceof E){return E}return B};B.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>=2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};B.prototype.asType=function(e){var t=B.getType(this);return B.types[t]?B.types[t](e):B(e)};B.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof Hr!=="undefined"&&!(this.value instanceof Hr)};["floor","ceil","round"].forEach(function(e){B.prototype[e]=function(){if(this["float"]||B.isFloat(this.__value__)){return B(Math[e](this.__value__))}else{return B(Math[e](this.valueOf()))}}});B.prototype.valueOf=function(){if(B.isNative(this.__value__)){return Number(this.__value__)}else if(B.isBN(this.__value__)){return this.__value__.toNumber()}};var Ru=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[g(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[g(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&g(r.valueOf())]},integer:function e(t,r){return[t,r&&g(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&g(r.valueOf())]},complex:function e(t,r){return[{re:t,im:g(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function e(t,r){var n=B.coerce(t.__re__,r.__re__),i=b(n,2),a=i[0],u=i[1];var o=B.coerce(t.__im__,r.__im__),s=b(o,2),c=s[0],f=s[1];return[{im:c,re:a},{im:f,re:u}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[g(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:qu(t.__type__,r.__im__.__type__,0)[0],re:qu(t.__type__,r.__re__.__type__,t)[0]},{im:qu(t.__type__,r.__im__.__type__,r.__im__)[0],re:qu(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:qu(r,e.__im__.__type__,0,e.__im__)[1],re:qu(r,e.__re__.__type__,0,e.__re__)[1]},{im:qu(r,e.__im__.__type__,0,0)[1],re:qu(r,t.__type__,0,t)[1]}]}}}();function qu(e,t,r,n){return Ru[e][t](r,n)}B.coerce=function(e,t){var r=B.getType(e);var n=B.getType(t);if(!Ru[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!Ru[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=Ru[r][n](e,t);return i.map(function(e){return B(e,true)})};B.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof B)){throw new Error("LNumber: you can't coerce ".concat(Vo(e)))}if(typeof e==="number"){e=B(e)}return B.coerce(this,e)};B.getType=function(e){if(e instanceof B){return e.__type__}if(B.isFloat(e)){return"float"}if(B.isComplex(e)){return"complex"}if(B.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof Hr!=="undefined"&&!(e instanceof Hr)){return"bigint"}};B.prototype.isFloat=function(){return!!(B.isFloat(this.__value__)||this["float"])};var Uu={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var zu={};Object.keys(Uu).forEach(function(t){zu[Uu[t]]=t;B.prototype[t]=function(e){return this.op(Uu[t],e)}});B._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof m)||typeof this==="undefined"){return new m(e,t)}if(e instanceof m){return m({im:e.__im__,re:e.__re__})}if(B.isNumber(e)&&t){if(!t){return Number(e)}}else if(!B.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(ha(e));throw new Error(r)}var n=e.im instanceof B?e.im:B(e.im);var i=e.re instanceof B?e.re:B(e.re);this.constant(n,i)}m.prototype=Object.create(B.prototype);m.prototype.constructor=m;m.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};m.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};m.prototype.toRational=function(e){var t=this.__im__,r=this.__re__;if(B.isFloat(this.__im__)){t=g(this.__im__).toRational(e)}if(B.isFloat(this.__re__)){r=g(this.__re__).toRational(e)}return m({im:t,re:r})};m.prototype.pow=function(e){e.cmp(0);if(e===0){return B(1)}var t=B(Math.atan2(this.__im__.valueOf(),this.__re__.valueOf()));var r=B(this.modulus());if(B.isComplex(e)&&e.__im__.cmp(0)!==0){var n=e.mul(Math.log(r.valueOf())).add(m.i.mul(t).mul(e));if(!B.isComplex(n)){return g(Math.E).pow(n)}var i=g(Math.E).pow(n.__re__.valueOf());return m({re:i.mul(Math.cos(n.__im__.valueOf())),im:i.mul(Math.sin(n.__im__.valueOf()))})}var a=e.__re__.cmp(0)>0;e=e.__re__.valueOf();if(B.isInteger(e)&&a){var u=this;while(--e){u=u.mul(this)}return u}var o=r.pow(e);var s=t.mul(e);return m({re:o.mul(Math.cos(s)),im:o.mul(Math.sin(s))})};m.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};m.prototype.factor=function(){if(this.__im__ instanceof g||this.__im__ instanceof g){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof g){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof g){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};m.prototype.modulus=function(){return this.factor().sqrt()};m.prototype.conjugate=function(){return m({re:this.__re__,im:this.__im__.sub()})};m.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=g(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=g(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return m({im:r,re:t})};m.prototype.div=function(e){if(B.isNumber(e)&&!B.isComplex(e)){if(!(e instanceof B)){e=B(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return m({re:t,im:r})}else if(!B.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=b(n,2),a=i[0],u=i[1];var o=a.__im__.div(u.__im__);return o.coerce(u.__re__)[0]}var s=this.coerce(e),c=b(s,2),f=c[0],l=c[1];var h=l.factor();var _=l.conjugate();var p=f.mul(_);if(!B.isComplex(p)){return p.div(h)}var d=p.__re__.op("/",h);var v=p.__im__.op("/",h);return m({re:d,im:v})};m.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};m.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};m.prototype.complex_op=function(e,t,i){var a=this;var r=function e(t,r){var n=i(a.__re__,t,a.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return m(n,true)}return n};if(typeof t==="undefined"){return r()}if(B.isNumber(t)&&!B.isComplex(t)){if(!(t instanceof B)){t=B(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!B.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var u=t.__re__ instanceof B?t.__re__:this.__re__.asType(t.__re__);var o=t.__im__ instanceof B?t.__im__:this.__im__.asType(t.__im__);return r(u,o)};m._op={"+":"add","-":"sub","*":"mul","/":"div"};m.prototype._op=function(e,t){var r=m._op[e];return this[r](t)};m.prototype.cmp=function(e){var t=this.coerce(e),r=b(t,2),n=r[0],i=r[1];var a=n.__re__.coerce(i.__re__),u=b(a,2),o=u[0],s=u[1];var c=o.cmp(s);if(c!==0){return c}else{var f=n.__im__.coerce(i.__im__),l=b(f,2),h=l[0],_=l[1];return h.cmp(_)}};m.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};m.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[ha(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=ha(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function g(e){if(typeof this!=="undefined"&&!(this instanceof g)||typeof this==="undefined"){return new g(e)}if(!B.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof B){return g(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}g.prototype=Object.create(B.prototype);g.prototype.constructor=g;g.prototype.toString=function(e){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}e&&(e=e.valueOf());var t=this.__value__.toString(e);if(!t.match(/e[+-]?[0-9]+$/i)){var r=t.replace(/^-/,"");var n=this.__value__<0?"-":"";if(t.match(/^-?0\.0{3}/)){var i=r.match(/^[.0]+/g)[0].length-1;var a=r.replace(/^[.0]+/,"").replace(/^([0-9a-f])/i,"$1.");return"".concat(n).concat(a,"e-").concat(i.toString(e))}if(t.match(/^-?[0-9a-f]{7,}\.?/i)){var u=r.match(/^[0-9a-f]+/gi)[0].length-1;var o=r.replace(/\./,"").replace(/^([0-9a-f])/i,"$1.").replace(/0+$/,"").replace(/\.$/,".0");return"".concat(n).concat(o,"e+").concat(u.toString(e))}if(!B.isFloat(this.__value__)){var s=t+".0";return this._minus?"-"+s:s}}return t.replace(/^([0-9]+)e/,"$1.0e")};g.prototype._op=function(e,t){if(t instanceof B){t=t.__value__}var r=B._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return g(r(this.__value__,t))};g.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return Yu(this.__value__.valueOf())}return Ju(e.valueOf())(this.__value__.valueOf())};g.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=g(Math.sqrt(-e));return m({re:0,im:t})}return g(Math.sqrt(e))};g.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return g(e)};var Yu=Ju(1e-10);function Ju(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=Hu(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=Hu(r,n)}else if(t.cmp(0)<0){i=B(Hu(n.sub(),r.sub())).sub()}else{i=B(0)}if(B.isFloat(t)||B.isFloat(e)){return g(i)}return i}function Hu(e,t){var r=B(e).floor();var n=B(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=B(1).div(t.sub(n));var a=B(1).div(e.sub(r));return r.add(B(1).div(Hu(i,a)))}else{return r.add(B(1))}}function w(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof w)||typeof this==="undefined"){return new w(e,t)}if(!B.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof w){r=B(e.__num__);n=B(e.__denom__)}else{r=B(e.num);n=B(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return B(r.div(n))}}this.constant(r,n)}w.prototype=Object.create(B.prototype);w.prototype.constructor=w;w.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};w.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};w.prototype.pow=function(e){if(B.isRational(e)){return Vu(this.valueOf(),e.valueOf())}var t=e.cmp(0);if(t===0){return B(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return w({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};w.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof g||t instanceof g){return e.div(t)}return w({num:e,denom:t})};w.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return w({num:e,denom:t})};w.prototype.cmp=function(e){return B(this.valueOf(),true).cmp(e)};w.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof w){t=B(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof w){r=B(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};w.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return B._ops["/"](this.__num__.value,this.__denom__.value)}return g(this.__num__.valueOf()).div(this.__denom__.valueOf())};w.prototype.mul=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return w({num:t,denom:r})}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];return a.mul(u)};w.prototype.div=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return w({num:t,denom:r})}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];var o=a.div(u);return o};w.prototype._op=function(e,t){return this[zu[e]](t)};w.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(w({num:t,denom:r}))}if(!(e instanceof B)){e=B(e).sub()}else{e=e.sub()}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];return a.add(u)};w.prototype.add=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var a,u;if(t!==r){u=r.mul(n).add(i.mul(t));a=t.mul(r)}else{u=n.add(i);a=t}return w({num:u,denom:a})}if(B.isFloat(e)){return g(this.valueOf()).add(e)}var o=B.coerce(this,e),s=b(o,2),c=s[0],f=s[1];return c.add(f)};function E(e,t){if(typeof this!=="undefined"&&!(this instanceof E)||typeof this==="undefined"){return new E(e,t)}if(e instanceof E){return E(e.__value__,e._native)}if(!B.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}E.prototype=Object.create(B.prototype);E.prototype.constructor=E;E.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};E.prototype.serialize=function(){return this.__value__.toString()};E.prototype._op=function(e,t){if(typeof t==="undefined"){if(B.isBN(this.__value__)){e=E.bn_op[e];return E(this.__value__.clone()[e](),false)}return E(B._ops[e](this.__value__),true)}if(B.isBN(this.__value__)&&B.isBN(t.__value__)){e=E.bn_op[e];return E(this.__value__.clone()[e](t),false)}var r=B._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return B(r)}return w({num:this,denom:t})}return E(r,true)};E.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(B.isNative(this.__value__)){e=B(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(B.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return m({re:0,im:e})}return e};B.NaN=B(NaN);m.i=m({im:1,re:0});function Gu(e){var n=this;var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:G;if(typeof this!=="undefined"&&!(this instanceof Gu)||typeof this==="undefined"){return new Gu(e)}A("InputPort",e,"function");s(this,"__type__",so);var a;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return a},set:function e(t){A("InputPort::__parser__",t,"parser");a=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,ie(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=6;break}t.next=3;return n._read();case 3:r=t.sent;a=new _i({env:i});a.parse(r);case 6:return t.abrupt("return",n.__parser__);case 7:case"end":return t.stop()}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==co};this._make_defaults()}Gu.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!B.isInteger(t)){var r=B.getType(t);Lo("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};Gu.prototype._with_init_parser=function(o,s){var c=this;return ie(O.mark(function e(){var r,n,i,a,u=arguments;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return o.call(c);case 2:r=t.sent;for(n=u.length,i=new Array(n),a=0;a"};function Wu(e){if(typeof this!=="undefined"&&!(this instanceof Wu)||typeof this==="undefined"){return new Wu(e)}A("OutputPort",e,"function");s(this,"__type__",so);this.write=e}Wu.prototype.is_open=function(){return this._closed!==true};Wu.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};Wu.prototype.flush=function(){};Wu.prototype.toString=function(){return"#"};var Qu=function(e){ee(r,e);function r(e){var t;ae(this,r);t=Pr(this,r,[function(){var e;return(e=t)._write.apply(e,arguments)}]);A("BufferedOutputPort",e,"function");s(I(t),"_fn",e,{hidden:true});s(I(t),"_buffer",[],{hidden:true});return t}ce(r,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};Zu.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function Xu(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof Xu)||typeof this==="undefined"){return new Xu(e,t)}A("OutputFilePort",e,"string");s(this,"__filename__",e);s(this,"_fd",t.valueOf(),{hidden:true});s(this,"__type__",so);this.write=function(e){if(!x.isString(e)){e=ha(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}Xu.prototype=Object.create(Wu.prototype);Xu.prototype.constructor=Xu;Xu.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};Xu.prototype.internal=function(e){return Ao.get("**internal-env**").get(e)};Xu.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{s(n,"_fd",null,{hidden:true});Wu.prototype.close.call(n);t()}})})};Xu.prototype.toString=function(){return"#")};function eo(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:G;if(typeof this!=="undefined"&&!(this instanceof eo)||typeof this==="undefined"){return new eo(e)}A("InputStringPort",e,"string");e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!t.__parser__){t.__parser__=new _i({env:r});t.__parser__.parse(e)}return t.__parser__});s(this,"__type__",so);this._make_defaults()}eo.prototype.char_ready=function(){return true};eo.prototype=Object.create(Gu.prototype);eo.prototype.constructor=eo;eo.prototype.toString=function(){return"#"};function to(e){if(typeof this!=="undefined"&&!(this instanceof to)||typeof this==="undefined"){return new to(e)}this._with_parser=this._with_init_parser.bind(this,function(){return e});s(this,"__type__",so);this._make_defaults()}to.prototype.char_ready=function(){return true};to.prototype=Object.create(Gu.prototype);to.prototype.constructor=to;to.prototype.toString=function(){return"#"};function ro(e){if(typeof this!=="undefined"&&!(this instanceof ro)||typeof this==="undefined"){return new ro(e)}A("InputByteVectorPort",e,"uint8array");s(this,"__vector__",e);s(this,"__type__",oo);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){A("InputByteVectorPort::__index__",t,"number");if(t instanceof B){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}ro.prototype=Object.create(Gu.prototype);ro.prototype.constructor=ro;ro.prototype.toString=function(){return"#"};ro.prototype.close=function(){var t=this;s(this,"__vector__",$);var r=function e(){throw new Error("Input-binary-port: port is closed")};["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=r});this.u8_ready=this.char_ready=function(){return false}};ro.prototype.u8_ready=function(){return true};ro.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return co}return this.__vector__[this.__index__]};ro.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};ro.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};ro.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===co){return co}return this.__vector__.slice(this.__index__,e)};function no(){if(typeof this!=="undefined"&&!(this instanceof no)||typeof this==="undefined"){return new no}s(this,"__type__",oo);s(this,"_buffer",[],{hidden:true});this.write=function(e){A("write",e,["number","uint8array"]);if(B.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,q(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}no.prototype=Object.create(Wu.prototype);no.prototype.constructor=no;no.prototype.close=function(){Wu.prototype.close.call(this);s(this,"_buffer",null,{hidden:true})};no.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};no.prototype.write_u8=function(e){A("OutputByteVectorPort::write_u8",e,"number");this.write(e)};no.prototype.write_u8_vector=function(e){A("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};no.prototype.toString=function(){return"#"};no.prototype.valueOf=function(){return this.__buffer__};function io(e,t){if(typeof this!=="undefined"&&!(this instanceof io)||typeof this==="undefined"){return new io(e,t)}eo.call(this,e);A("InputFilePort",t,"string");s(this,"__filename__",t)}io.prototype=Object.create(eo.prototype);io.prototype.constructor=io;io.prototype.toString=function(){return"#")};function ao(e,t){if(typeof this!=="undefined"&&!(this instanceof ao)||typeof this==="undefined"){return new ao(e,t)}ro.call(this,e);A("InputBinaryFilePort",t,"string");s(this,"__filename__",t)}ao.prototype=Object.create(ro.prototype);ao.prototype.constructor=ao;ao.prototype.toString=function(){return"#")};function uo(e,t){var i=this;if(typeof this!=="undefined"&&!(this instanceof uo)||typeof this==="undefined"){return new uo(e,t)}A("OutputBinaryFilePort",e,"string");s(this,"__filename__",e);s(this,"_fd",t.valueOf(),{hidden:true});s(this,"__type__",oo);var a;this.write=function(e){A("write",e,["number","uint8array"]);var n;if(!a){a=i.internal("fs")}if(B.isNumber(e)){n=new Uint8Array([e.valueOf()])}else{n=new Uint8Array(Array.from(e))}return new Promise(function(t,r){a.write(i._fd,n,function(e){if(e){r(e)}else{t()}})})}}uo.prototype=Object.create(Xu.prototype);uo.prototype.constructor=uo;uo.prototype.write_u8=function(e){A("OutputByteVectorPort::write_u8",e,"number");this.write(e)};uo.prototype.write_u8_vector=function(e){A("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var oo=Symbol["for"]("binary");var so=Symbol["for"]("text");var co=new fo;function fo(){}fo.prototype.toString=function(){return"#"};function lo(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.stderr,i=r.stdin,a=r.stdout,u=r.command_line,o=u===void 0?null:u,s=he(r,Or);if(typeof this!=="undefined"&&!(this instanceof lo)||typeof this==="undefined"){return new lo(e,U({stdin:i,stdout:a,stderr:n,command_line:o},s))}if(typeof e==="undefined"){e="anonymous"}this.__env__=Ao.inherit(e,s);this.__parser__=new _i({env:this.__env__});this.__env__.set("parent.frame",l("parent.frame",function(){return t.__env__},G.__env__["parent.frame"].__doc__));var c="**interaction-environment-defaults**";this.set(c,oa(s).concat(c));var f=xo.inherit("internal-".concat(e));if(ru(i)){f.set("stdin",i)}if(ru(n)){f.set("stderr",n)}if(ru(a)){f.set("stdout",a)}f.set("command-line",o);ko(this.__env__,f)}lo.prototype.exec=function(){var t=ie(function(u){var o=this;var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return O.mark(function e(){var r,n,i,a;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=s.use_dynamic,n=r===void 0?false:r,i=s.dynamic_env,a=s.env;A("Interpreter::exec",u,["string","array"],1);A("Interpreter::exec",n,"boolean",2);if(!a){a=o.__env__}if(!i){i=a}G.set("**interaction-environment**",o.__env__);if(!Array.isArray(u)){t.next=10;break}return t.abrupt("return",ns(u,{env:a,dynamic_env:i,use_dynamic:n}));case 10:o.__parser__.parse(u);return t.abrupt("return",ns(o.__parser__,{env:a,dynamic_env:i,use_dynamic:n}));case 12:case"end":return t.stop()}},e)})()});return function(e){return t.apply(this,arguments)}}();lo.prototype.get=function(e){var t=this.__env__.get(e);if(d(t)){var r=new Xo({env:this.__env__});return t.bind(r)}return t};lo.prototype.set=function(e,t){return this.__env__.set(e,t)};lo.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function ho(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}ho.prototype=new Error;ho.prototype.constructor=ho;var _o=function(e){ee(t,e);function t(){ae(this,t);return Pr(this,t,arguments)}return ce(t)}(re(Error));function F(e,t,r){if(arguments.length===1){if(_(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}F.prototype.list=function(){return oa(this.__env__)};F.prototype.fs=function(){return this.get("**fs**")};F.prototype.unset=function(e){if(e instanceof V){e=e.valueOf()}if(e instanceof x){e=e.valueOf()}delete this.__env__[e]};F.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_(e)==="object"){t=e}if(!e||_(e)==="object"){e="child of "+(this.__name__||"unknown")}return new F(t||{},this,e)};F.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof V){e=e.__name__}if(e instanceof x){e=e.valueOf()}if(t){if(!r){t=xi(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};F.prototype.new_frame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",l("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!La(t)){return $}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},G.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};F.prototype._lookup=function(e){if(e instanceof V){e=e.__name__}if(e instanceof x){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return po(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};F.prototype.toString=function(){return"#"};F.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new F(r,this.__parent__,this.__name__)};F.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";A("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function po(e){if(typeof this!=="undefined"&&!(this instanceof po)||typeof this==="undefined"){return new po(e)}this.value=e}po.isUndefined=function(e){return e instanceof po&&typeof e.value==="undefined"};po.prototype.valueOf=function(){return this.value};function vo(e){if(!e.length){return}if(e.length===1){return e[0]}if(typeof this!=="undefined"&&!(this instanceof vo)||typeof this==="undefined"){return new vo(e)}this.__values__=e}vo.prototype.toString=function(){return this.__values__.map(function(e){return ha(e)}).join("\n")};vo.prototype.valueOf=function(){return this.__values__};F.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};A("Environment::get",e,["symbol","string"]);var r=t.throwError,n=r===void 0?true:r;var i=e;if(i instanceof V||i instanceof x){i=i.valueOf()}var a=this._lookup(i);if(a instanceof po){if(po.isUndefined(a)){return undefined}return Wa(a.valueOf())}var u;if(e instanceof V&&e[V.object]){u=e[V.object]}else if(typeof i==="string"){u=i.split(".").filter(Boolean)}if(u&&u.length>0){var o=u,s=Q(o),c=s[0],f=s.slice(1);a=this._lookup(c);if(f.length){try{if(a instanceof po){a=a.valueOf()}else{a=go(zr,c);if(d(a)){a=Qa(a)}}if(typeof a!=="undefined"){return go.apply(void 0,[a].concat(q(f)))}}catch(e){throw e}}else if(a instanceof po){return Wa(a.valueOf())}a=go(zr,i)}if(typeof a!=="undefined"){return a}if(n){throw new Error("Unbound variable `"+i.toString()+"'")}};F.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;A("Environment::set",e,["string","symbol"]);if(B.isNumber(t)){t=B(t)}if(e instanceof V){e=e.__name__}if(e instanceof x){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};F.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&Xi(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};F.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};F.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};F.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function yo(e){if(qa(e)){return e.then(yo)}if(H(e)||e instanceof V){e[uu]=true}return e}var mo=vi(Jn('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var go=l("get",function e(t){var r;for(var n=arguments.length,i=new Array(n>1?n-1:0),a=1;a0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=wo(this,"stdin")}Uo("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":l("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=wo(this,"stdin")}Uo("read-line",e,"input-port");return e.read_line()},"(read-line port)\n\n This function reads and returns the next line from the input\n port."),"read-char":l("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=wo(this,"stdin")}Uo("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:l("read",function(){var e=ie(function(){var i=this;var a=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;return O.mark(function e(){var r,n;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=i.env;if(a===null){n=wo(r,"stdin")}else{n=a}Uo("read",n,"input-port");return t.abrupt("return",n.read.call(r));case 4:case"end":return t.stop()}},e)})()});function t(){return e.apply(this,arguments)}return t}(),"(read [port])\n\n This function, if called with a port, it will parse the next\n item from the port. If called without an input, it will read\n a string from standard input (using the browser's prompt or\n a user defined input method) and parse it. This function can be\n used together with `eval` to evaluate code from port."),pprint:l("pprint",function e(t){if(H(t)){t=new Rs.Formatter(t.toString(true))["break"]().format();G.get("display").call(G,t)}else{G.get("write").call(G,t)}G.get("newline").call(G)},"(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."),print:l("print",function e(){var t=G.get("display");var r=G.get("newline");var n=this.use_dynamic;var i=G;var a=G;for(var u=arguments.length,o=new Array(u),s=0;s1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var o=0;var s=G.get("repr");t=t.replace(a,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[o++];if(t==="a"){return s(r)}else{return s(r,true)}}});u=t.match(/~([\S])/);if(u){throw new Error("format: Unrecognized escape sequence ".concat(u[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),display:l("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=wo(this,"stdout")}else{A("display",r,"output-port")}var n=t;if(!(r instanceof uo)){n=G.get("repr")(t)}r.write.call(G,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."),"display-error":l("display-error",function e(){var t=wo(this,"stderr");var r=G.get("repr");for(var n=arguments.length,i=new Array(n),a=0;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=he(t,Cr);var i=this;var u=this;var o;var s=U(U({},n),{},{env:this,dynamic_env:i,use_dynamic:r});var c=k(e.cdr.car,s);c=$o(c);function f(t,r,n){if(qa(t)){return t.then(function(e){return f(t,e,n)})}if(qa(r)){return r.then(function(e){return f(t,e,n)})}if(qa(n)){return n.then(function(e){return f(t,r,e)})}u.get("set-obj!").call(u,t,r,n);return n}if(H(e.car)&&V.is(e.car.car,".")){var l=e.car.cdr.car;var h=e.car.cdr.cdr.car;var _=k(l,s);var p=k(h,s);return f(_,p,c)}if(!(e.car instanceof V)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var d=e.car.valueOf();o=this.ref(e.car.__name__);return D(c,function(e){if(!o){var t=d.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=a.get(n,{throwError:false});if(i){f(i,r,e);return}}throw new Error("Unbound variable `"+d+"'")}o.set(d,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non empty slot and sets it."),"unset!":l(new J("set!",function(e){if(!(e.car instanceof V)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."),"set-car!":l("set-car!",function(e,t){A("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."),"set-cdr!":l("set-cdr!",function(e,t){A("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."),"empty?":l("empty?",function(e){return typeof e==="undefined"||K(e)},"(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."),gensym:l("gensym",Qn,"(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."),load:l("load",function e(o,t){A("load",o,"string");var s=this;if(s.__name__==="__frame__"){s=s.__parent__}if(!(t instanceof F)){if(s===G){t=s}else{t=this.get("**interaction-environment**")}}var c="**module-path**";var f=G.get(c,{throwError:false});o=o.valueOf();if(!o.match(/.[^.]+$/)){o+=".scm"}var r=o.match(/\.xcb$/);function l(e){if(r){e=js(e)}else{if(Vo(e)==="buffer"){e=e.toString()}e=e.replace(/^(#!.*)/,function(e,t){if(Sa(t)){return t}return""});if(e.match(/^\{/)){e=Es(e)}}return ns(e,{env:t})}function n(e){return zr.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}if(Io()){return new Promise(function(){var r=ie(O.mark(function e(r,n){var i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:i=Kr("path");if(!f){t.next=6;break}f=f.valueOf();o=i.join(f,o);t.next=12;break;case 6:a=s.get("command-line",{throwError:false});if(!a){t.next=11;break}t.next=10;return a();case 10:u=t.sent;case 11:if(u&&!K(u)){process.cwd();o=i.join(i.dirname(u.car.valueOf()),o)}case 12:G.set(c,i.dirname(o));Kr("fs").readFile(o,function(e,t){if(e){n(e);G.set(c,f)}else{try{l(t).then(function(){r();G.set(c,f)})["catch"](n)}catch(e){n(e)}}});case 14:case"end":return t.stop()}},e)}));return function(e,t){return r.apply(this,arguments)}}())}if(f){f=f.valueOf();o=f+"/"+o.replace(/^\.?\/?/,"")}return n(o).then(function(e){G.set(c,o.replace(/\/[^/]*$/,""));return l(e)}).then(function(){})["finally"](function(){G.set(c,f)})},"(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."),while:l(new J("while",function(e,t){var r=e.car;var n=U(U({},t),{},{env:this});var i=new Y(new V("begin"),e.cdr);return function t(){return D(k(r,n),function(e){if(e){return D(k(i,n),t)}})}()}),"(while cond body)\n\n Creates a loop, it executes cond and body until cond expression is false."),do:l(new J("do",function(){var r=ie(function(h,e){var _=this;var p=e.use_dynamic,d=e.error;return O.mark(function e(){var o,r,s,c,n,f,l,i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:o=_;r=o;s=o.inherit("do");c=h.car;n=h.cdr.car;f=h.cdr.cdr;if(!K(f)){f=new Y(V("begin"),f)}l={env:o,dynamic_env:r,use_dynamic:p,error:d};i=c;case 9:if(K(i)){t.next=20;break}a=i.car;t.t0=s;t.t1=a.car;t.next=15;return k(a.cdr.car,l);case 15:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);i=i.cdr;t.next=9;break;case 20:l={env:s,dynamic_env:r,error:d};u=O.mark(function e(){var r,n,i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(K(f)){t.next=3;break}t.next=3;return Rs.evaluate(f,l);case 3:r=c;n={};case 5:if(K(r)){t.next=15;break}i=r.car;if(K(i.cdr.cdr)){t.next=12;break}t.next=10;return k(i.cdr.cdr.car,l);case 10:a=t.sent;n[i.car.valueOf()]=a;case 12:r=r.cdr;t.next=5;break;case 15:u=Object.getOwnPropertySymbols(n);l.env=s=o.inherit("do");Object.keys(n).concat(u).forEach(function(e){s.set(e,n[e])});case 18:case"end":return t.stop()}},e)});case 22:t.next=24;return k(n.car,l);case 24:t.t3=t.sent;if(!(t.t3===false)){t.next=29;break}return t.delegateYield(u(),"t4",27);case 27:t.next=22;break;case 29:if(K(n.cdr)){t.next=33;break}t.next=32;return k(n.cdr.car,l);case 32:return t.abrupt("return",t.sent);case 33:case"end":return t.stop()}},e)})()});return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will\n evaluate and return the second expression after the loop exits."),if:l(new J("if",function(r,e){var t=e.error,n=e.use_dynamic;var i=this;var a=this;var u={env:a,dynamic_env:i,use_dynamic:n,error:t};var o=function e(t){if(ja(t)){return k(r.cdr.cdr.car,u)}else{return k(r.cdr.car,u)}};if(K(r)){throw new Error("too few expressions for `if`")}var s=k(r.car,u);return D(s,o)}),"(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."),"let-env":new J("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_env,n=e.use_dynamic,i=e.error;A("let-env",t,"pair");var a=k(t.car,{env:this,dynamic_env:r,error:i,use_dynamic:n});return D(a,function(e){A("let-env",e,"environment");return k(Y(V("begin"),t.cdr),{env:e,dynamic_env:r,error:i})})},"(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."),letrec:l(wu(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentially and the next value can access the\n previous values/names."),"letrec*":l(wu(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."),"let*":l(wu(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."),let:l(wu(Symbol["for"]("let")),"(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to names,\n and then evaluates the body in context of that environment. Values are evaluated\n sequentially but you can't access previous values/names when the next are\n evaluated. You can only get them in the body of the let expression. (If you want\n to define multiple variables and use them in each other's definitions, use\n `let*`.)"),"begin*":l(Du("begin*",function(e){return e.pop()}),"(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return\n the value of the last expression (i.e. it uses Promise.all())."),shuffle:l("shuffle",function(e){A("shuffle",e,["pair","nil","array"]);var t=G.get("random");if(K(e)){return $}if(Array.isArray(e)){return Gi(e.slice(),t)}var r=G.get("list->array")(e);r=Gi(r,t);return G.get("array->list")(r)},"(shuffle obj)\n\n Order items in vector or list in random order."),begin:l(new J("begin",function(e,t){var n=U(U({},t),{},{env:this});var i=G.get("list->array")(e);var a;return function t(){if(i.length){var e=i.shift();var r=k(e,n);return D(r,function(e){a=e;return t()})}else{return a}}()}),"(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."),ignore:new J("ignore",function(e,t){var r=U(U({},t),{},{env:this,dynamic_env:this});k(new Y(new V("begin"),e),r)},"(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It will discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":l(J.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=U({env:this},t);return D(k(e.car,r),function(e){if(d(e)){return e(new ts(null))}})}),"(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORTED BY LIPS RIGHT NOW"),parameterize:l(new J("parameterize",function(t,e){var i=e.dynamic_env;var a=i.inherit("parameterize").new_frame(null,{});var u=U(U({},e),{},{env:this});var o=t.car;if(!H(o)){var r=Vo(o);throw new Error("Invalid syntax for parameterize expecting pair got ".concat(r))}function s(){var e=new Y(new V("begin"),t.cdr);return k(e,U(U({},u),{},{dynamic_env:a}))}return function r(){var e=o.car;var n=e.car.valueOf();return D(k(e.cdr.car,u),function(e){var t=i.get(n,{throwError:false});if(!Ta(t)){throw new Error("Unknown parameter ".concat(n))}a.set(n,t.inherit(e));if(!Ca(o.cdr)){o=o.cdr;return r()}else{return s()}})}()}),"(parameterize ((name value) ...)\n\n Macro that change the dynamic variable created by make-parameter."),"make-parameter":l(new J("make-parameter",function(e,t){t.dynamic_env;var r=k(e.car,t);var n;if(H(e.cdr.car)){n=k(e.cdr.car,t)}return new Zo(r,n)}),"(make-parameter init converter)\n\n Function creates new dynamic variable that can be custimized with parameterize\n macro. The value should be assigned to a variable e.g.:\n\n (define radix (make-parameter 10))\n\n The result value is a procedure that return the value of dynamic variable."),"define-syntax-parameter":l(new J("define-syntax-parameter",function(e,t){var r=e.car;var n=this;if(!(r instanceof V)){throw new Error("define-syntax-parameter: invalid syntax expecting symbol got ".concat(Vo(r)))}var i=k(e.cdr.car,U({env:n},t));A("define-syntax-parameter",i,"syntax",2);i.__name__=r.valueOf();if(i.__name__ instanceof x){i.__name__=i.__name__.valueOf()}var a;if(H(e.cdr.cdr)&&x.isString(e.cdr.cdr.car)){a=e.cdr.cdr.car.valueOf()}n.set(e.car,new Fa(i),a,true)}),"(define-syntax-parameter name syntax [__doc__])\n\n Binds to the transformer obtained by evaluating .\n The transformer provides the default expansion for the syntax parameter,\n and in the absence of syntax-parameterize, is functionally equivalent to\n define-syntax."),"syntax-parameterize":l(new J("syntax-parameterize",function(e,t){var r=G.get("list->array")(e.car);var n=this.inherit("syntax-parameterize");while(r.length){var i=r.shift();if(!(H(i)||i.car instanceof V)){var a="invalid syntax for syntax-parameterize: ".concat(Zi(e,true));throw new Error("syntax-parameterize: ".concat(a))}var u=k(i.cdr.car,U(U({},t),{},{env:this}));var o=i.car;A("syntax-parameterize",u,["syntax"]);A("syntax-parameterize",o,"symbol");u.__name__=o.valueOf();if(u.__name__ instanceof x){u.__name__=u.__name__.valueOf()}var s=new Fa(u);if(o.is_gensym()){var c=o.literal();var f=this.get(c,{throwError:false});if(f instanceof Fa){n.set(c,s)}}n.set(o,s)}var l=new Y(new V("begin"),e.cdr);return k(l,U(U({},t),{},{env:n}))}),"(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),define:l(J.defmacro("define",function(r,e){var n=this;if(H(r.car)&&r.car.car instanceof V){var t=new Y(new V("define"),new Y(r.car.car,new Y(new Y(new V("lambda"),new Y(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}e.dynamic_env=this;e.env=n;var i=r.cdr.car;var a;if(H(i)){i=k(i,e);a=true}else if(i instanceof V){i=n.get(i)}A("define",r.car,"symbol");return D(i,function(e){if(n.__name__===Ea.__merge_env__){n=n.__parent__}if(a&&(d(e)&&yu(e)||e instanceof Ea||Ta(e))){e.__name__=r.car.valueOf();if(e.__name__ instanceof x){e.__name__=e.__name__.valueOf()}}var t;if(H(r.cdr.cdr)&&x.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`'),"set-obj!":l("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_(e);if(Ca(e)||i!=="object"&&i!=="function"){var a=Lo("set-obj!",Vo(e),["object","function"]);throw new Error(a)}A("set-obj!",t,["string","symbol","number"]);e=Qa(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(Ia(e)&&d(r)){e[t]=Qa(r);e[t][lu]=true}else if(d(r)||Ya(r)||K(r)){e[t]=r}else{e[t]=r&&!Ia(r)?r.valueOf():r}if(ea){var u=e[t];Object.defineProperty(e,t,U(U({},n),{},{value:u}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."),"null-environment":l("null-environment",function(){return G.inherit("null")},"(null-environment)\n\n Returns a clean environment with only the standard library."),values:l("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},y=e.use_dynamic,m=e.error;var g=this;var b;if(H(v.cdr)&&x.isString(v.cdr.car)&&!K(v.cdr.cdr)){b=v.cdr.car.valueOf()}function w(){var e=Na(this)?this:{dynamic_env:g},r=e.dynamic_env;var n=g.inherit("lambda");r=r.inherit("lambda");if(this&&!Na(this)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}n.set("this",this)}for(var t=arguments.length,i=new Array(t),a=0;a> SYNTAX");z(e);z(m);var n=w.inherit("syntax");var i=n;var a=this;if(a.__name__===Ea.__merge_env__){var u=Object.getOwnPropertySymbols(a.__env__);u.forEach(function(e){a.__parent__.set(e,a.__env__[e])});a=a.__parent__}var o={env:n,dynamic_env:i,use_dynamic:g,error:b};var s,c,f;if(m.car instanceof V){s=m.car;f=D(m.cdr.car);c=m.cdr.cdr}else{s="...";f=D(m.car);c=m.cdr}try{while(!K(c)){var l=c.car.car;var h=c.car.cdr.car;z("[[[ RULE");z(l);var _=Aa(l,e,f,s,{expansion:this,define:w});if(_){if(Wr()){console.log(JSON.stringify(ua(_),true,2));console.log("PATTERN: "+l.toString(true));console.log("MACRO: "+e.toString(true))}var p=[];var d=Oa({bindings:_,expr:h,symbols:f,scope:n,lex_scope:a,names:p,ellipsis:s});z("OUPUT>>> ",d);if(d){h=d}var v=a.merge(n,Ea.__merge_env__);if(r){return{expr:h,scope:v}}var y=k(h,U(U({},o),{},{env:v}));return ka(y,p)}c=c.cdr}}catch(e){e.message+="\nin macro:\n ".concat(m.toString(true));throw e}throw new Error("syntax-rules: no matching syntax in macro ".concat(e.toString(true)))},w);r.__code__=m;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."),quote:l(new J("quote",function(e){return yo(e.car)}),"(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."),"unquote-splicing":l("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the\n expression, the computed value must be a pair."),unquote:l("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."),quasiquote:J.defmacro("quasiquote",function(e,t){var o=t.use_dynamic,s=t.error;var c=this;var f=c;function a(e){return H(e)||Xi(e)||Array.isArray(e)}function l(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(H(e)){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(qa(n)||qa(i)){return Xn([n,i]).then(function(e){var t=b(e,2),r=t[0],n=t[1];return new Y(r,n)})}else{return new Y(n,i)}}return e}function u(e,t){if(H(e)){if(!K(t)){e.append(t)}}else{e=new Y(e,t)}return e}function r(e){return!!e.filter(function(e){return H(e)&&V.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function h(e,n,i){return e.reduce(function(e,t){if(!H(t)){e.push(t);return e}if(V.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(H(i.cdr)&&K(r[0]))){return r[0]}}r=r.map(function(e){if(d.has(e)){return e.clone()}else{d.add(e);return e}});var n=v(i.cdr,0,1);if(K(n)&&K(r[0])){return undefined}return D(n,function(e){if(K(r[0])){return e}if(r.length===1){return u(r[0],e)}var t=r.reduce(function(e,t){return u(e,t)});return u(t,e)})})}(i.car.cdr)}var d=new Set;function v(e,t,r){if(H(e)){if(H(e.car)){if(V.is(e.car.car,"unquote-splicing")){return p(e,t+1,r)}if(V.is(e.car.car,"unquote")){if(t+2===r&&H(e.car.cdr)&&H(e.car.cdr.car)&&V.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new Y(new Y(new V("unquote"),p(n,t+2,r)),$)}else if(H(e.car.cdr)&&!K(e.car.cdr.cdr)){if(H(e.car.cdr.car)){var i=[];return function t(r){if(K(r)){return Y.fromArray(i)}return D(k(r.car,{env:c,dynamic_env:f,use_dynamic:o,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(V.is(e.car,"quasiquote")){var a=v(e.cdr,t,r+1);return new Y(e.car,a)}if(V.is(e.car,"quote")){return new Y(e.car,v(e.cdr,t,r))}if(V.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(H(e.cdr)){if(!K(e.cdr.cdr)){if(H(e.cdr.car)){var u=[];return function t(r){if(K(r)){return Y.fromArray(u)}return D(k(r.car,{env:c,dynamic_env:f,use_dynamic:o,error:s}),function(e){u.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return k(e.cdr.car,{env:c,dynamic_env:f,error:s})}}else{return e.cdr}}return l(e,function(e){return v(e,t,r)})}else if(Xi(e)){return _(e,t,r)}else if(e instanceof Array){return h(e,t,r)}return e}function n(e){if(H(e)){delete e[uu];if(!e.have_cycles("car")){n(e.car)}if(!e.have_cycles("cdr")){n(e.cdr)}}}if(Xi(e.car)&&!r(Object.values(e.car))){return yo(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return yo(e.car)}if(H(e.car)&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return yo(e.car)}var i=v(e.car,0,1);return D(i,function(e){n(e);return yo(e)})},"(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special expressions (unquote\n x) abbreviated to ,x that will evaluate x and insert its value verbatim or\n (unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\n into the result. Best used with macros but it can be used outside."),clone:l("clone",function e(t){A("clone",t,"pair");return t.clone()},"(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),append:l("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return G.get("array->list")(r)}else if(Array.isArray(t)){return t.reverse()}else{throw new Error(Lo("reverse",Vo(t),"array or pair"))}},"(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."),nth:l("nth",function e(t,r){A("nth",t,"number");A("nth",r,["array","pair"]);if(H(r)){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function that returns a string by joining elements of the list using separator."),split:l("split",function e(t,r){A("split",t,["regex","string"]);A("split",r,"string");return G.get("array->list")(r.split(t))},"(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."),replace:l("replace",function e(t,r,n){A("replace",t,["regex","string"]);A("replace",r,["string","function"]);A("replace",n,"string");if(d(r)){var i=[];n.replace(t,function(){i.push(r.apply(void 0,arguments))});return D(i,function(e){return n.replace(t,function(){return e.shift()})})}return n.replace(t,r)},"(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a\n string or regex and replacement can be function or string. See Javascript\n String.replace()."),match:l("match",function e(t,r){A("match",t,["regex","string"]);A("match",r,"string");var n=r.match(t);return n?G.get("array->list")(n):false},"(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if\n no match."),search:l("search",function e(t,r){A("search",t,["regex","string"]);A("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."),repr:l("repr",function e(t,r){return ha(t,r)},"(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."),"escape-regex":l("escape-regex",function(e){A("escape-regex",e,"string");return Rn(e.valueOf())},"(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."),env:l("env",function e(e){e=e||this.env;var t=Object.keys(e.__env__).map(V);var r;if(t.length){r=Y.fromArray(t)}else{r=$}if(e.__parent__ instanceof F){return G.get("env").call(this,e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."),new:l("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:ri.LITERAL;A("set-special!",e,"string",1);A("set-special!",t,"symbol",2);ri.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors.'),get:go,".":go,unbind:l(Qa,"(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."),type:l(Vo,"(type object)\n\n Function that returns the type of an object as string."),debugger:l("debugger",function(){debugger},'(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the "debugger;" statement. If a debugger is not running this\n function does nothing.'),in:l("in",function(e,t){if(e instanceof V||e instanceof x||e instanceof B){e=e.valueOf()}return e in Ga(t)},'(in key value)\n\n Function that uses the Javascript "in" operator to check if key is\n a valid property in the value.'),"instance?":l("instance?",function(e){return Va(e)},"(instance? obj)\n\n Checks if object is an instance, created with a new operator"),instanceof:l("instanceof",function(e,t){return t instanceof Qa(e)},"(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."),"prototype?":l("prototype?",Ia,"(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."),"macro?":l("macro?",function(e){return e instanceof J},"(macro? expression)\n\n Predicate that tests if value is a macro."),"continuation?":l("continuation?",Pa,"(continuation? expression)\n\n Predicate that tests if value is a callable continuation."),"function?":l("function?",d,"(function? expression)\n\n Predicate that tests if value is a callable function."),"real?":l("real?",function(e){if(Vo(e)!=="number"){return false}if(e instanceof B){return e.isFloat()}return B.isFloat(e)},"(real? number)\n\n Predicate that tests if value is a real number (not complex)."),"number?":l("number?",function(e){return Number.isNaN(e)||B.isNumber(e)},"(number? expression)\n\n Predicate that tests if value is a number or NaN value."),"string?":l("string?",function(e){return x.isString(e)},"(string? expression)\n\n Predicate that tests if value is a string."),"pair?":l("pair?",H,"(pair? expression)\n\n Predicate that tests if value is a pair or list structure."),"regex?":l("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Predicate that tests if value is a regular expression."),"null?":l("null?",function(e){return Ca(e)},"(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or\n Javascript null)."),"boolean?":l("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."),"symbol?":l("symbol?",function(e){return e instanceof V},"(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."),"array?":l("array?",function(e){return e instanceof Array},"(array? expression)\n\n Predicate that tests if value is an array."),"object?":l("object?",function(e){return!K(e)&&e!==null&&!(e instanceof h)&&!(e instanceof RegExp)&&!(e instanceof x)&&!H(e)&&!(e instanceof B)&&_(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."),flatten:l("flatten",function e(t){A("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Returns a shallow list from tree structure (pairs)."),"vector-append":l("vector-append",function(){for(var e=arguments.length,t=new Array(e),r=0;rlist":l("array->list",function(e){A("array->list",e,"array");return Y.fromArray(e)},"(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."),"tree->array":l("tree->array",Qi("tree->array",true),"(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."),"list->array":l("list->array",Qi("list->array"),"(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."),apply:l("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,a));return t.apply(this,Ho(t,n))},"(apply fn list)\n\n Function that calls fn with the list of arguments."),length:l("length",function e(t){if(!t||K(t)){return 0}if(H(t)){return t.length()}if("length"in t){return t.length}},'(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a "length" property. Returns undefined if the\n length could not be found.'),"string->number":l("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;A("string->number",e,"string",1);A("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(bn)||e.match(yn)){return Fn(e,t)}else if(e.match(wn)||e.match(vn)){return On(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(gn)&&r||e.match(mn)){return An(e,t)}if(e.match(an)){return Bn(e)}}return false},"(string->number number [radix])\n\n Function that parses a string into a number."),try:l(new J("try",function(r,e){var l=this;var h=e.use_dynamic;e.error;return new Promise(function(t,o){var s,n;if(V.is(r.cdr.car.car,"catch")){s=r.cdr.car;if(H(r.cdr.cdr)&&V.is(r.cdr.cdr.car.car,"finally")){n=r.cdr.cdr.car}}else if(V.is(r.cdr.car.car,"finally")){n=r.cdr.car}if(!(n||s)){throw new Error("try: invalid syntax")}function c(e){t(e);throw new _o("[CATCH]")}var f=function e(t,r){r(t)};if(n){f=function e(t,r){f=o;i.error=function(e){throw e};D(k(new Y(new V("begin"),n.cdr),i),function(){r(t)})}}var i={env:l,use_dynamic:h,dynamic_env:l,error:function e(t){if(t instanceof _o){throw t}if(s){var r=l.inherit("try");var n=s.cdr.car.car;if(!(n instanceof V)){throw new Error("try: invalid syntax: catch require variable name")}r.set(n,t);var i;var a={env:r,use_dynamic:h,dynamic_env:l,error:function e(t){i=true;o(t);throw new _o("[CATCH]")}};var u=k(new Y(new V("begin"),s.cdr.cdr),a);D(u,function e(t){if(!i){f(t,c)}})}else{f(undefined,function(){o(t)})}}};var e=k(r.car,i);D(e,function(e){f(e,t)},i.error)})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thrown. If finally is provided it's always\n executed at the end."),raise:l("raise",function(e){throw e},"(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."),throw:l("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws a new exception."),find:l("find",function t(r,n){A("find",r,["regex","function"]);A("find",n,["pair","nil"]);if(Ca(n)){return $}var e=Di("find",r);return D(e(n.car),function(e){if(e&&!K(e)){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."),"for-each":l("for-each",function(e){var t;A("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),a=1;a3?n-3:0),a=3;a3?i-3:0),u=3;uarray")(r);var a=[];var u=Di("filter",t);return function t(r){function e(e){if(e&&!K(e)){a.push(n)}return t(++r)}if(r===i.length){return Y.fromArray(a)}var n=i[r];return D(u(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."),compose:l(Fu,"(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"),pipe:l(Eu,"(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"),curry:l(ju,"(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have partially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\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))"),gcd:l("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;no?a%=o:o%=a}a=da(s*r[u])/(a+o)}return B(a)},"(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."),"odd?":l("odd?",Ou(function(e){return B(e).isOdd()}),"(odd? number)\n\n Checks if number is odd."),"even?":l("even?",Ou(function(e){return B(e).isEven()}),"(even? number)\n\n Checks if number is even."),"*":l("*",Su(function(e,t){return B(e).mul(t)},B(1)),"(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."),"+":l("+",Su(function(e,t){return B(e).add(t)},B(0)),"(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."),"-":l("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":l(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,["bigint","float","rational"]);return va(function(e,t){return B(e).cmp(t)===1},t)},"(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."),"<":l("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":l(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,["bigint","float","rational"]);return va(function(e,t){return[0,1].includes(B(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."),"eq?":l("eq?",ya,"(eq? a b)\n\n Function that compares two values if they are identical."),or:l(new J("or",function(e,t){var i=t.use_dynamic,a=t.error;var u=G.get("list->array")(e);var o=this;var s=o;if(!u.length){return false}var c;return function t(){function e(e){c=e;if(!ja(c)){return c}else{return t()}}if(!u.length){if(!ja(c)){return c}else{return false}}else{var r=u.shift();var n=k(r,{env:o,dynamic_env:s,use_dynamic:i,error:a});return D(n,e)}}()}),"(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."),and:l(new J("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=G.get("list->array")(e);var a=this;var u=a;if(!i.length){return true}var o;var s={env:a,dynamic_env:u,use_dynamic:r,error:n};return function t(){function e(e){o=e;if(ja(o)){return o}else{return t()}}if(!i.length){if(!ja(o)){return o}else{return false}}else{var r=i.shift();return D(k(r,s),e)}}()}),"(and . expressions)\n\n Macro that evaluates each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."),"|":l("|",function(e,t){return B(e).or(t)},"(| a b)\n\n Function that calculates the bitwise or operation."),"&":l("&",function(e,t){return B(e).and(t)},"(& a b)\n\n Function that calculates the bitwise and operation."),"~":l("~",function(e){return B(e).neg()},"(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."),">>":l(">>",function(e,t){return B(e).shr(t)},"(>> a b)\n\n Function that right shifts the value a by value b bits."),"<<":l("<<",function(e,t){return B(e).shl(t)},"(<< a b)\n\n Function that left shifts the value a by value b bits."),not:l("not",function e(t){return!t},"(not object)\n\n Function that returns the Boolean negation of its argument.")},undefined,"global");var Ao=G.inherit("user-env");function ko(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error.");G.set("**interaction-environment**",e)}ko(Ao,xo);G.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr.");function Oo(e){Ao.get("**internal-env**").set("fs",e)}(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;G.set(r,l(r,function(e){A(r,e,"number");if(e instanceof B){return e[t]()}},"(".concat(r," number)\n\n Function that calculates the ").concat(r," of a number.")))})})();function Co(e){if(e.length===1){return e[0]}else{var t=[];var r=Co(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(d(r)){return"Invalid type: got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){var a=r[0].toLowerCase();r="a"+("aeiou".includes(a)?"n ":" ")+r[0]}else{r=new Intl.ListFormat("en",{style:"long",type:"disjunction"}).format(r)}}return"Expecting ".concat(r," got ").concat(t).concat(i)}function Mo(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;A(e,t,"number",n);var i=t.__type__;var a;if(H(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(Lo(e,i,r,n))}}function Ro(r,e,n){e.forEach(function(e,t){Mo(r,e,n,t+1)})}function qo(r,e,n){e.forEach(function(e,t){A(r,e,n,t+1)})}function Uo(e,t,r){A(e,t,r);if(t.__type__===oo){throw new Error(Lo(e,"binary-port","textual-port"))}}function A(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=Vo(t).toLowerCase();if(d(r)){if(!r(t)){throw new Error(Lo(e,i,r,n))}return}var a=false;if(H(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(Lo(e,i,r,n))}}function zo(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}Vo=zo(Vo);function Vo(e){var t=$r.get(e);if(t){return t}if(_(e)==="object"){for(var r=0,n=Object.entries(Vr);r2&&arguments[2]!==undefined?arguments[2]:{},n=r.env,i=r.dynamic_env,a=r.use_dynamic;var u=n===null||n===void 0?void 0:n.new_frame(e,t);var o=i===null||i===void 0?void 0:i.new_frame(e,t);var s=new Xo({env:u,use_dynamic:a,dynamic_env:o});return $o(e.apply(s,t))}function Wo(n,e){var t=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},i=t.env,a=t.dynamic_env,u=t.use_dynamic,r=t.error,o=r===void 0?function(){}:r;e=Yo(e,{env:i,dynamic_env:a,error:o,use_dynamic:u});return D(e,function(e){if(gu(n)){n=Qa(n)}e=Ho(n,e);var t=e.slice();var r=Go(n,t,{env:i,dynamic_env:a,use_dynamic:u});return D(r,function(e){if(H(e)){e.mark_cycles();return yo(e)}return Ka(e)},o)})}var Qo=new WeakMap;var Zo=function(){function n(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;ae(this,n);fe(this,"__value__",void 0);fe(this,"__fn__",void 0);Br(this,Qo,{writable:true,value:void 0});this.__value__=e;if(t){if(!d(t)){throw new Error("Section argument to Parameter need to be function "+"".concat(Vo(t)," given"))}this.__fn__=t}if(r){f(this,Qo,r)}}ce(n,[{key:"__name__",get:function e(){return t(this,Qo)},set:function e(t){f(this,Qo,t);if(this.__fn__){this.__fn__.__name__="fn-".concat(t)}}},{key:"invoke",value:function e(){if(d(this.__fn__)){return this.__fn__(this.__value__)}return this.__value__}},{key:"inherit",value:function e(t){return new n(t,this.__fn__,this.__name__)}}]);return n}();var Xo=function(){function t(e){ae(this,t);fe(this,"env",void 0);fe(this,"dynamic_env",void 0);fe(this,"use_dynamic",void 0);Object.assign(this,e)}ce(t,[{key:"__name__",get:function e(){return this.env.__name__}},{key:"__parent__",get:function e(){return this.env.__parent__}},{key:"get",value:function e(){var t;return(t=this.env).get.apply(t,arguments)}}]);return t}();function es(e,t){var r=e.get(t.__name__,{throwError:false});if(Ta(r)&&r!==t){return r}var n=Ao.get("**interaction-environment**");while(true){var i=e.get("parent.frame",{throwError:false});e=i(0);if(e===n){break}r=e.get(t.__name__,{throwError:false});if(Ta(r)&&r!==t){return r}}return t}var ts=function(){function t(e){ae(this,t);fe(this,"__value__",void 0);this.__value__=e}ce(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}}]);return t}();function k(o){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},s=e.env,c=e.dynamic_env,f=e.use_dynamic,t=e.error,l=t===void 0?Po:t,r=he(e,jr);return function(e){try{if(!La(c)){c=s===true?Ao:s||Ao}if(f){s=c}else if(s===true){s=Ao}else{s=s||G}var t={env:s,dynamic_env:c,use_dynamic:f,error:l};var r;if(Ca(o)){return o}if(o instanceof V){return s.get(o)}if(!H(o)){return o}var n=o.car;var e=o.cdr;if(H(n)){r=$o(k(n,t));if(qa(r)){return r.then(function(e){if(!Ma(e)){throw new Error(Vo(e)+" "+s.get("repr")(e)+" is not callable while evaluating "+o.toString())}return k(new Y(e,o.cdr),t)})}else if(!Ma(r)){throw new Error(Vo(r)+" "+s.get("repr")(r)+" is not callable while evaluating "+o.toString())}}if(n instanceof V){r=s.get(n)}else if(d(n)){r=n}var i;if(r instanceof Ea){i=Jo(r,o,t)}else if(r instanceof J){i=Ko(r,e,t)}else if(d(r)){i=Wo(r,e,t)}else if(r instanceof Fa){i=Jo(r._syntax,o,t)}else if(Ta(r)){var a=es(c,r);if(Ca(o.cdr)){i=a.invoke()}else{return D(k(o.cdr.car,t),function(e){a.__value__=e})}}else if(Pa(r)){i=r.invoke()}else if(H(o)){r=n&&n.toString();throw new Error("".concat(Vo(n)," ").concat(r," is not a function"))}else{return o}var u=s.get(Symbol["for"]("__promise__"),{throwError:false});if(u===true&&qa(i)){i=i.then(function(e){if(H(e)&&!r[uu]){return k(e,t)}return e});return new Zn(i)}return i}catch(e){l&&l.call(s,e,o)}}(r)}var rs=as(function(e){return e});var ns=as(function(e,t){return t});function is(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.dynamic_env,i=t.use_dynamic;return k(e,{env:r,dynamic_env:n,use_dynamic:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}if(!(t instanceof _o)){throw t}}})}function as(d){return function(){var t=ie(function(l){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},h=e.env,_=e.dynamic_env,p=e.use_dynamic;return O.mark(function e(){var r,n,i,a,u,o,s,c,f;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!La(_)){_=h===true?Ao:h||Ao}if(h===true){h=Ao}else{h=h||Ao}r=[];if(!H(l)){t.next=8;break}t.next=6;return is(l,{env:h,dynamic_env:_,use_dynamic:p});case 6:t.t0=t.sent;return t.abrupt("return",[t.t0]);case 8:n=Array.isArray(l)?l:vi(l);i=false;a=false;t.prev=11;o=qr(n);case 13:t.next=15;return o.next();case 15:if(!(i=!(s=t.sent).done)){t.next=31;break}c=s.value;t.next=19;return is(c,{env:h,dynamic_env:_,use_dynamic:p});case 19:f=t.sent;t.t1=r;t.t2=d;t.t3=c;t.next=25;return f;case 25:t.t4=t.sent;t.t5=(0,t.t2)(t.t3,t.t4);t.t1.push.call(t.t1,t.t5);case 28:i=false;t.next=13;break;case 31:t.next=37;break;case 33:t.prev=33;t.t6=t["catch"](11);a=true;u=t.t6;case 37:t.prev=37;t.prev=38;if(!(i&&o["return"]!=null)){t.next=42;break}t.next=42;return o["return"]();case 42:t.prev=42;if(!a){t.next=45;break}throw u;case 45:return t.finish(42);case 46:return t.finish(37);case 47:return t.abrupt("return",r);case 48:case"end":return t.stop()}},e,null,[[11,33,37,47],[38,,42,46]])})()});function e(e){return t.apply(this,arguments)}return e}()}function us(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){try{r=Jn(e)}catch(e){if(e instanceof pi){return false}throw e}}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var a=new qn;var u=Tr(r),o;try{for(u.s();!(o=u.n()).done;){var s=o.value;if(n.includes(s)){a.push(s)}else if(!a.is_empty()){var c=a.top();var f=t[c];if(s===f){a.pop()}else{throw new Error("Syntax error: missing closing ".concat(f))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){u.e(e)}finally{u.f()}return a.is_empty()}function os(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new zr.Worker(r.createObjectURL(n))}function ss(){return Rs.version.match(/^(\{\{VER\}\}|DEV)$/)}function cs(){if(Io()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var fs=cs();function ls(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(fs){e=fs.replace(/[^/]*$/,"std.xcb")}else if(ss()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(Rs.version,"/").concat(t)}}var r=G.get("load");return r.call(Ao,e,G)}function hs(e){this.url=e;var u=this.worker=os(function(){var u;var o;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!o){i("Worker RPC: LIPS not initialized, call init first");return}o.then(function(){var e=r.params[0];var t=r.params[1];u.exec(e,{use_dynamic:t}).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var a=r.params[0];if(typeof a!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(a,"/dist/lips.min.js"));u=new Rs.Interpreter("worker");o=ls(a);o.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var a=++n;return new Promise(function(n,i){u.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===a){if(r.error){i(r.error)}else{n(r.result)}u.removeEventListener("message",e)}});u.postMessage({type:"RPC",method:t,id:a,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e,t){var r=t.use_dynamic,n=r===void 0?false:r;return this.rpc("eval",[e,n])}}var _s={pair:function e(t){var r=b(t,2),n=r[0],i=r[1];return Y(n,i)},number:function e(t){if(x.isString(t)){return B([t,10])}return B(t)},regex:function e(t){var r=b(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return $},symbol:function e(t){if(x.isString(t)){return V(t)}else if(Array.isArray(t)){return V(Symbol["for"](t[0]))}},string:x,character:h};var ps=Object.keys(_s);var ds={};for(var vs=0,ys=Object.entries(ps);vs1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var a=0;t.forEach(function(e){i.set(e,a);a+=e.length});return i}else if(t.length){return t[0]}}function ks(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var Os=7;function Cs(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,Os));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function Ss(e){var t=ks();var r=Fs.encode(e);return As(t,xr(r,{magic:false}))}function js(e){var t=Cs(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=Er(e.slice(Os),{magic:false});return Fs.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function Bs(e){console.error(e.message||e);if(Array.isArray(e.code)){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function Is(){var u=["text/x-lips","text/x-scheme"];var o;function s(e){var t;return(t=e.getAttribute("data-bootstrap"))!==null&&t!==void 0?t:e.getAttribute("bootstrap")}function c(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(ns).then(t)["catch"](function(e){Bs(e);t()})}else{return ns(r.innerHTML).then(t)["catch"](function(e){Bs(e);t()})}})}function e(){return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function e(){var t=a.shift();if(!t){i()}else{var r=t.getAttribute("type");if(u.includes(r)){var n=s(t);if(!o&&typeof n==="string"){return ls(n).then(function(){return c(t)}).then(e)}else{return c(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+u.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(Ps){var t=Ps;var r=s(t);if(typeof r==="string"){return ls(r).then(function(){o=true;return e()})}}return e()}var Ps=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){Gr(window,Is)}var Ns=function(){var e=x("Mon, 27 May 2024 11:41:47 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var a="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return a}();s(Oi,"__class__","ahead");s(Y,"__class__","pair");s(Wi,"__class__","nil");s(Ci,"__class__","pattern");s(ki,"__class__","formatter");s(J,"__class__","macro");s(Ea,"__class__","syntax");s(Ea.Parameter,"__class__","syntax-parameter");s(F,"__class__","environment");s(Gu,"__class__","input-port");s(Wu,"__class__","output-port");s(Qu,"__class__","output-port");s(Zu,"__class__","output-string-port");s(eo,"__class__","input-string-port");s(io,"__class__","input-file-port");s(Xu,"__class__","output-file-port");s(ho,"__class__","lips-error");[B,m,w,g,E].forEach(function(e){s(e,"__class__","number")});s(h,"__class__","character");s(V,"__class__","symbol");s(x,"__class__","string");s(Zn,"__class__","promise");s(Zo,"__class__","parameter");var Ts="1.0.0-beta.19";var Ls="Mon, 27 May 2024 11:41:47 +0000";var Ms=Fu(bi,vi);var Rs={version:Ts,banner:Ns,date:Ls,exec:ns,parse:Ms,tokenize:Jn,evaluate:k,compile:rs,serialize:xs,unserialize:Es,serialize_bin:Ss,unserialize_bin:js,bootstrap:ls,Environment:F,env:Ao,Worker:hs,Interpreter:lo,balanced_parenthesis:us,balancedParenthesis:us,balanced:us,Macro:J,Syntax:Ea,Pair:Y,Values:vo,QuotedPromise:Zn,Error:ho,quote:yo,InputPort:Gu,OutputPort:Wu,BufferedOutputPort:Qu,InputFilePort:io,OutputFilePort:Xu,InputStringPort:eo,OutputStringPort:Zu,InputByteVectorPort:ro,OutputByteVectorPort:no,InputBinaryFilePort:ao,OutputBinaryFilePort:uo,set_fs:Oo,Formatter:ki,Parser:_i,Lexer:o,specials:ri,repr:Zi,nil:$,eof:co,LSymbol:V,LNumber:B,LFloat:g,LComplex:m,LRational:w,LBigInteger:E,LCharacter:h,LString:x,Parameter:Zo,rationalize:Ku};G.set("lips",Rs);e.BufferedOutputPort=Qu;e.Environment=F;e.Error=ho;e.Formatter=ki;e.InputBinaryFilePort=ao;e.InputByteVectorPort=ro;e.InputFilePort=io;e.InputPort=Gu;e.InputStringPort=eo;e.Interpreter=lo;e.LBigInteger=E;e.LCharacter=h;e.LComplex=m;e.LFloat=g;e.LNumber=B;e.LRational=w;e.LString=x;e.LSymbol=V;e.Lexer=o;e.Macro=J;e.OutputBinaryFilePort=uo;e.OutputByteVectorPort=no;e.OutputFilePort=Xu;e.OutputPort=Wu;e.OutputStringPort=Zu;e.Pair=Y;e.Parameter=Zo;e.Parser=_i;e.QuotedPromise=Zn;e.Syntax=Ea;e.Values=vo;e.Worker=hs;e._is_directive=Sa;e.balanced=us;e.balancedParenthesis=us;e.balanced_parenthesis=us;e.banner=Ns;e.bootstrap=ls;e.compile=rs;e.date=Ls;e.env=Ao;e.eof=co;e.evaluate=k;e.exec=ns;e.nil=$;e.parse=Ms;e.quote=yo;e.rationalize=Ku;e.repr=Zi;e.serialize=xs;e.serialize_bin=Ss;e.set_fs=Oo;e.specials=ri;e.tokenize=Jn;e.unserialize=Es;e.unserialize_bin=js;e.version=Ts}); \ No newline at end of file + */Object.defineProperty(or,"__esModule",{value:true});const sr=8,cr=6,fr=3,lr=(1<r-lr){t[i++]=e[n++];continue}f=(e[n]+13^e[n+1]-13^e[n+2])&_r-1;c=n-l[f]&hr;l[f]=n;a=n-c;if(a>=0&&a!=n&&e[n]==e[a]&&e[n+1]==e[a+1]&&e[n+2]==e[a+2]){t[u]|=o;for(s=fr;s>sr;t[i++]=c;n+=s}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function dr(e,t,r){t=t|0;var n=0,i=0,a=0,u=0,o=1<<(sr-1|0),s=0,c=0;while(n>(sr-cr|0))+fr|0;c=(e[n]<4){r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;s=s-4|0}while(s>0){r[i]=r[a];i=i+1|0;a=a+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function vr(){const e=new TextEncoder("utf-8");return e.encode(yr)}const yr="@lzjb";const mr=vr();function gr(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function br(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function Dr(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=pr(e,r);const i=br(e.length);const a=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){a.unshift(mr)}return gr(...a)}function xr(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,mr.length));if(s!==yr){throw new Error("Invalid magic value")}}const r=e?mr.length:0;const n=t[r];const i=r+1;const a=r+n+1;const u=wr(t.slice(i,a));t=t.slice(a);const o=new Uint8Array(u);dr(t,t.length,o);return o}var Er=or.pack=Dr;var Fr=or.unpack=xr;function Ar(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],a={},u=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:u,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var o in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),a[t]=a[t]?a[t]+","+r:r}),e(u())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(o,c.headers[o]);r.send(c.body||null)})}var kr=["token"],Or=["env"],Cr=["stderr","stdin","stdout","command_line"],Sr=["use_dynamic"],jr=["use_dynamic"],Br=["env","dynamic_env","use_dynamic","error"];function Ir(e,t,r){Pr(e,t);t.set(e,r)}function Pr(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}function Nr(e,t,r){return t=Y(t),$(e,Tr()?Reflect.construct(t,r||[],Y(e).constructor):t.apply(e,r))}function Tr(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(Tr=function e(){return!!t})()}function Lr(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=Mr(t))||e&&t&&typeof t.length==="number"){if(r)t=r;var n=0;var i=function e(){};return{s:i,n:function e(){if(n>=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a=true,u=false,o;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();a=t.done;return t},e:function e(t){u=true;o=t},f:function e(){try{if(!a&&r["return"]!=null)r["return"]()}finally{if(u)throw o}}}}function Mr(e,t){if(!e)return;if(typeof e==="string")return Rr(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Rr(e,t)}function Rr(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1?t-1:0),n=1;n0&&arguments[0]!==undefined?arguments[0]:null;var t=Co&&Co.get("DEBUG",{throwError:false});if(e===null){return t===true}return(t===null||t===void 0?void 0:t.valueOf())===e.valueOf()}function Zr(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function Xr(e,t){return"".concat(Zr(e),"[+-]?").concat(t,"+/").concat(t,"+")}function en(e,t){return"".concat(Zr(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function tn(e,t){return"".concat(Zr(e),"[+-]?").concat(t,"+")}var rn=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var nn="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var an="(?:#[ie])?(?:[+-]?(?:[0-9][0-9_]*/[0-9][0-9_]*|nan.0|inf.0|".concat(nn,"|[+-]?[0-9]+))?(?:").concat(nn,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var un=new RegExp("^(#[ie])?".concat(nn,"$"),"i");function on(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var sn=function(){var a={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=b(e,3),r=t[0],n=t[1],i=t[2];a[r]=on(n,i)});return a}();var cn={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function ln(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=Fn(e);var n=r.number.split("/");var i=w({num:B([n[0],r.radix||t]),denom:B([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function kn(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=Fn(e);if(r.inexact){return g(parseInt(r.number,r.radix||t))}return B([r.number,r.radix||t])}function On(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\([\s\S]+)$/);if(t){r=t[1]}}if(r){return h(r)}throw new Error("Parse: invalid character")}function Cn(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=B(1)}else if(e==="-"){t=B(-1)}else if(e.match(bn)){t=B([e,i])}else if(e.match(wn)){var r=e.split("/");t=w({num:B([r[0],i]),denom:B([r[1],i])})}else if(e.match(un)){var n=In(e);if(a.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return B(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return B(Number.NEGATIVE_INFINITY)}return B(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(a.inexact){return g(t.valueOf())}return t}var a=Fn(e);i=a.radix||i;var r;var n=a.number.match(xn);if(i!==10&&n){r=n}else{r=a.number.match(sn[i])}var u,o;o=t(r[2]);if(r[1]){u=t(r[1])}else if(o instanceof g){u=g(0)}else{u=B(0)}if(o.cmp(0)===0&&o.__type__==="bigint"){return u}return m({im:o,re:u})}function Sn(e){return parseInt(e.toString(),10)===e}function jn(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var a=t[3]&&t[3].length;if(i0&&(t.exact||!t.number.match(/\./))){return B(a).mul(o)}}}r=g(r);if(t.exact){return r.toRational()}return r}function Pn(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{var r=x(JSON.parse(e));r.freeze();return r}catch(e){var n=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(n))}}function Nn(e){e.match(/^name/);var t=/(^|.)\|/g;if(e.match(t)){e=e.split("|").filter(Boolean).reduce(function(e,t){var r="";if(t.match(/^\\+$/)){if(t.length>1){var n=Math.floor(t.length/2);r="\\".repeat(n)}if(t.length%2!==0){r+="|"}}else{r=t}return e+r});var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\([trn])/g,function(e,t){return r[t]})}return new ne(e)}function Tn(e){if(Oo.hasOwnProperty(e)){return Oo[e]}if(e.match(/^"[\s\S]*"$/)){return Pn(e)}else if(e[0]==="#"){var t=e.match(rn);if(t){return new RegExp(t[1],t[2])}else if(e.match(pn)){return On(e)}var r=e.match(/#\\(.+)/);if(r&&ln(r[1]).length===1){return On(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(gn)){return kn(e)}else if(e.match(un)){return In(e)}else if(e.match(mn)){return An(e)}else if(e.match(yn)){return Cn(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return Nn(e)}function Ln(e){return!(["(",")","[","]"].includes(e)||ii.names().includes(e))}function Mn(e){return Ln(e)&&!(e.match(rn)||e.match(/^"[\s\S]*"$/)||e.match(gn)||e.match(un)||e.match(yn)||e.match(mn)||e.match(pn)||["#t","#f","nil"].includes(e))}var Rn=/"(?:\\[\S\s]|[^"])*"?/g;function qn(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function Un(){this.data=[]}Un.prototype.push=function(e){this.data.push(e)};Un.prototype.top=function(){return this.data[this.data.length-1]};Un.prototype.pop=function(){return this.data.pop()};Un.prototype.is_empty=function(){return!this.data.length};function zn(e){if(e instanceof x){e=e.valueOf()}var t=new o(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===ho){break}r.push(n);t.skip()}return r}function Vn(e){var t=e.token,r=_e(e,kr);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return te({token:t},r)}function $n(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}$n.prototype.toString=function(){return"#"};function Yn(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof x){e=e.toString()}if(t){return zn(e)}else{var r=zn(e).map(function(e){if(e.token==="#\\ "||e.token=="#\\\n"){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return Wn(r)}}function Wn(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof ne){if(e.is_gensym()){return e}e=e.valueOf()}if(Qn(e)){return ne(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function Xn(e,t){var r=se.get("begin");var n=Zn("begin");e.forEach(function(e){e.set(n,r)});return new ae(n,t)}function ei(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=Ko(e);n.fulfilled=true;n.pending=false;return e});s(this,"_promise",e,{hidden:true});if(d(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});s(this,"__promise__",e);this.then=false}ei.prototype.then=function(e){return new ei(this.valueOf().then(e))};ei.prototype["catch"]=function(e){return new ei(this.valueOf()["catch"](e))};ei.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};ei.prototype.toString=function(){if(this.__pending__){return ei.pending_str}if(this.__rejected__){return ei.rejected_str}return"#")};ei.pending_str="#";ei.rejected_str="#";function ti(e){if(Array.isArray(e)){return Promise.all(ri(e)).then(ni)}return e}function ri(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof ei){t[r]=new mo(n)}else{t[r]=n}}return t}function ni(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof mo){t[r]=n.valueOf()}else{t[r]=n}}return t}var ii={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){try{return this.get(t).type}catch(e){console.log({name:t});console.log(e);return null}},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new ne("quote-promise"),ii.LITERAL]];var fi=ci.map(function(e){return e[0]});Object.freeze(fi);Object.defineProperty(ii,"__builtins__",{writable:false,value:fi});ci.forEach(function(e){var t=b(e,3),r=t[0],n=t[1],i=t[2];ii.append(r,n,i)});var o=function(){function m(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;Q(this,m);s(this,"__input__",e.replace(/\r/g,""));var a={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return a[r]},set:function e(t){a[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}fe(m,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return ho}if(this._token){s(this,"__token__",this.token(true));return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);if(!this.__token__){s(this,"__token__",this.token(true))}return this.token(t)}return ho}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return ho}for(var r=this._i;r=r){return ho}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var a=i.match(/\n/g);if(a){this._line+=a.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return ho}return h(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},n=r.prev_char,i=r["char"],a=r.next_char;var u=b(t,4),o=u[0],s=u[1],c=u[2],f=u[3];if(t.length!==5){throw new Error("Lexer: Invalid rule of length ".concat(t.length))}if(Pa(o)){if(o!==i){return false}}else if(!i.match(o)){return false}if(!pi(s,n)){return false}if(!pi(c,a)){return false}if(f!==this._state){return false}return true}},{key:"next_token",value:function e(){if(this._i>=this.__input__.length){return false}var t=true;e:for(var r=this._i,n=this.__input__.length;r2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var a=[];for(var u=0,o=t.length;u0&&arguments[0]!==undefined?arguments[0]:{},t=e.env,r=e.meta,n=r===void 0?false:r,i=e.formatter,a=i===void 0?Vn:i;Q(this,u);s(this,"_formatter",a,{hidden:true});s(this,"__env__",t);s(this,"_meta",n,{hidden:true});s(this,"_refs",[],{hidden:true});s(this,"_state",{parentheses:0,fold_case:false},{hidden:true})}fe(u,[{key:"_with_syntax_scope",value:function e(t){var r=xo(this.__env__);var n=r.get("stdin");se.set("lips",te(te({},Vs),{},{__parser__:this}));r.set("stdin",new io(this,this.__env__));var i=function e(){se.set("lips",Vs);r.set("stdin",n)};return D(t(),function(e){i();return e},i)}},{key:"parse",value:function e(t){if(t instanceof x){t=t.toString()}s(this,"__lexer__",new o(t))}},{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=H(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===ho)){t.next=4;break}return t.abrupt("return",ho);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!Ba(r.token)){t.next=11;break}this.skip();if(r.token==="#!fold-case"){this._state.fold_case=true}else if(r.token==="#!no-fold-case"){this._state.fold_case=false}return t.abrupt("continue",0);case 11:if(!(r.token==="#;")){t.next=18;break}this.skip();if(!(this.__lexer__.peek()===ho)){t.next=15;break}throw new Error("Lexer: syntax error eof found after comment");case 15:t.next=17;return this._read_object();case 17:return t.abrupt("continue",0);case 18:return t.abrupt("break",21);case 21:r=this._formatter(r);if(this._state.fold_case){r.token=Gi(r.token)}if(!this._meta){t.next=25;break}return t.abrupt("return",r);case 25:return t.abrupt("return",r.token);case 26:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=H(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){return["(","["].includes(t)}},{key:"is_close",value:function e(t){return[")","]"].includes(t)}},{key:"read_list",value:function(){var e=H(O.mark(function e(){var r,n,i,a,u,o;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=ie,n=r;case 1:t.next=4;return this.peek();case 4:a=t.sent;if(!(a===ho)){t.next=7;break}return t.abrupt("break",31);case 7:if(!this.is_close(a)){t.next=11;break}--this._state.parentheses;this.skip();return t.abrupt("break",31);case 11:if(!(a==="."&&!ue(r))){t.next=19;break}this.skip();t.next=15;return this._read_object();case 15:n.cdr=t.sent;i=true;t.next=29;break;case 19:if(!i){t.next=23;break}throw new Error("Parser: syntax error more than one element after dot");case 23:t.next=25;return this._read_object();case 25:u=t.sent;o=new ae(u,ie);if(ue(r)){r=o}else{n.cdr=o}n=o;case 29:t.next=1;break;case 31:return t.abrupt("return",r);case 32:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=H(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===ho)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",Tn(r));case 6:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return k(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=H(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof yi){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",D(this._resolve_object(r),function(e){if(oe(e)){e.mark_cycles()}return e}));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"balanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t,r){var n=this._state.parentheses;var i;if(n<0){i=new Error("Parser: unexpected parenthesis");i.__code__=[r.toString()+")"]}else{i=new Error("Parser: expected parenthesis but eof found");var a=new RegExp("\\){".concat(n,"}$"));i.__code__=[t.toString().replace(a,"")]}throw i}},{key:"_resolve_object",value:function(){var t=H(O.mark(function e(r){var n=this;var i;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!ta(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!oe(r)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=H(O.mark(function e(r){return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!oe(r)){t.next=15;break}if(!(r.car instanceof yi)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof yi)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=H(O.mark(function e(){var r=this;var n,i,a,u,o,s,c,f,l,h,_,p;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:n=t.sent;if(!(n===ho)){t.next=5;break}return t.abrupt("return",n);case 5:if(!ai(n)){t.next=51;break}i=ii.get(n);a=ui(n);this.skip();s=si(n);t.t0=this;t.next=13;return this.peek();case 13:t.t1=t.sent;c=t.t0.is_close.call(t.t0,t.t1);if(!s){t.next=19;break}t.t2=undefined;t.next=22;break;case 19:t.next=21;return this._read_object();case 21:t.t2=t.sent;case 22:f=t.t2;if(!(f===ho)){t.next=25;break}throw new vi("Expecting expression eof found");case 25:if(a){t.next=32;break}o=this.__env__.get(i.symbol);if(!(typeof o==="function")){t.next=32;break}if(oi(n)){l=[f]}else if(ue(f)){l=[]}else if(oe(f)){l=f.to_array(false)}if(!(l||s)){t.next=31;break}return t.abrupt("return",this._with_syntax_scope(function(){return Xo(o,s?[]:l,{env:r.__env__,dynamic_env:r.__env__,use_dynamic:false})}));case 31:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(i.symbol));case 32:if(!oi(n)){t.next=38;break}if(!c){t.next=35;break}throw new Error("Parse Error: expecting datum");case 35:u=new ae(i.symbol,new ae(f,ie));t.next=39;break;case 38:u=new ae(i.symbol,f);case 39:if(!a){t.next=41;break}return t.abrupt("return",u);case 41:if(!(o instanceof q)){t.next=50;break}t.next=44;return this._with_syntax_scope(function(){return r.evaluate(u)});case 44:h=t.sent;if(!(oe(h)||h instanceof ne)){t.next=47;break}return t.abrupt("return",ae.fromArray([ne("quote"),h]));case 47:return t.abrupt("return",h);case 50:throw new Error("Parse Error: invalid parser extension: "+i.symbol);case 51:_=this.match_datum_ref(n);if(!(_!==null)){t.next=57;break}this.skip();if(!this._refs[_]){t.next=56;break}return t.abrupt("return",new yi(_,this._refs[_]));case 56:throw new Error("Parse Error: invalid datum label #".concat(_,"#"));case 57:p=this.match_datum_label(n);if(!(p!==null)){t.next=64;break}this.skip();this._refs[p]=this._read_object();return t.abrupt("return",this._refs[p]);case 64:if(!this.is_close(n)){t.next=69;break}--this._state.parentheses;this.skip();t.next=76;break;case 69:if(!this.is_open(n)){t.next=75;break}++this._state.parentheses;this.skip();return t.abrupt("return",this.read_list());case 75:return t.abrupt("return",this.read_value());case 76:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return u}();var vi=function(e){J(t,e);function t(){Q(this,t);return Nr(this,t,arguments)}return fe(t)}(W(Error));di.Unterminated=vi;var yi=function(){function r(e,t){Q(this,r);this.name=e;this.data=t}fe(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function mi(e,t){return gi.apply(this,arguments)}function gi(){gi=be(O.mark(function e(r,n){var i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!n){if(se){n=se.get("**interaction-environment**",{throwError:false})}else{n=Co}}if(r instanceof di){i=r}else{i=new di({env:n});i.parse(r)}case 2:t.next=5;return me(i.read_object());case 5:u=t.sent;if(!i.balanced()){i.ballancing_error(u,a)}if(!(u===ho)){t.next=9;break}return t.abrupt("break",14);case 9:a=u;t.next=12;return u;case 12:t.next=2;break;case 14:case"end":return t.stop()}},e)}));return gi.apply(this,arguments)}function D(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(za(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return bi(e,t,r)}if(ta(e)){return wi(e,t,r)}return t(e)}function bi(t,r,e){if(t.find(za)){return D(ti(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function wi(t,e,r){var i=Object.keys(t);var n=[],a=[];var u=i.length;while(u--){var o=i[u];var s=t[o];n[u]=s;if(za(s)){a.push(s)}}if(a.length){return D(ti(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function s(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,a=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!a})}function Di(e){return xi.apply(this,arguments)}function xi(){xi=H(O.mark(function e(r){var n,i,a,u,o,s,c;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:n=[];i=false;a=false;t.prev=3;o=Ur(r);case 5:t.next=7;return o.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);a=true;u=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&o["return"]!=null)){t.next=24;break}t.next=24;return o["return"]();case 24:t.prev=24;if(!a){t.next=27;break}throw u;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}},e,null,[[3,15,19,29],[20,,24,28]])}));return xi.apply(this,arguments)}function Ei(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(d(t)){return t}throw new Error("Invalid matcher")}function l(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=Fi(r)}}if(e){t.__name__=e}else if(t.name&&!bu(t)){t.__name__=t.name}return t}function Fi(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function Ai(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function ki(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function Oi(e,t){return f(e,t)===t.length;function f(r,n){function e(e,t){var r=Lr(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var a=f(i,t);if(a!==-1){return a}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[a]===Symbol["for"]("symbol")&&!Mn(n[o])}function i(){var e=r[a+1];var t=n[o+1];if(e!==undefined&&t!==undefined){return f([e],[t])}}var a=0;var u={};for(var o=0;o0){continue}}else if(t()){return-1}}else if(r[a]instanceof Array){var c=f(r[a],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;a++;continue}else{return-1}a++}if(r.length!==a){return-1}return n.length}}function Ci(e){this.__code__=e.replace(/\r/g,"")}Ci.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*?-values|\*)?)$/],shift:{1:["&","#"]}}};Ci.match=Oi;Ci.prototype._options=function e(t){var r=Ci.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var a=n.shift||{1:[]};return te(te(te({},r),t),{},{exceptions:{specials:[].concat(ee(r.exceptions.specials),ee(i)),shift:te(te({},a),{},{1:[].concat(ee(r.exceptions.shift[1]),ee(a[1]))})}})};Ci.prototype.indent=function e(t){var r=Kn(this.__code__,true);return this._indent(r,t)};Ci.exception_shift=function(a,e){function t(e){if(!e.length){return false}if(e.indexOf(a)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=Lr(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(a.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){n.offset=0}if(a.toString()===t.toString()&&fs(a)){return n.offset+a[0].col}else if(a.length===1){return n.offset+a[0].col+1}else{var s=-1;if(u){var c=Ci.exception_shift(u.token,n);if(c!==-1){s=c}}if(s===-1){s=Ci.exception_shift(a[1].token,n)}if(s!==-1){return n.offset+a[0].col+s}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return n.offset+a[1].col}return n.offset+a[3].col}else if(a[0].line===a[1].line){return n.offset+n.indent+a[0].col}else{var f=a.slice(2);for(var l=0;l")};Si.prototype.match=function(e){return e.match(this.pattern)};function ji(){for(var e=arguments.length,t=new Array(e),r=0;r")};Ci.Pattern=ji;Ci.Ahead=Si;var Bi=/^[[(]$/;var Ii=/^[\])]$/;var Pi=/[^()[\]]/;var Ni=new Si(/[^)\]]/);var Ti=Symbol["for"]("*");var Li=new ji([Bi,Ti,Ii],[Pi],"+");var Mi=new ji([Bi,Ti,Ii],"+");var Ri=new ji([Symbol["for"]("symbol")],"?");var qi=new ji([Symbol["for"]("symbol")],"*");var Ui=[Bi,qi,Ii];var zi=new ji([Bi,Symbol["for"]("symbol"),Ti,Ii],"+");var Vi=Ki("syntax-rules");var $i=Ki("define","lambda","define-macro","syntax-rules");var Yi=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var Ji=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function Ki(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!o[e]){o[e]=Ai(u,e)}});var s=Lr(i),c;try{for(s.s();!(c=s.n()).done;){var f=b(c.value,3),l=f[0],h=f[1],_=f[2];h=h.valueOf();var p=h>0?o[h]:u;var d=p.filter(function(e){return e.trim()&&!ai(e)});var v=r(p);var y=Oi(l,d);var m=n.slice(a).find(function(e){return e.trim()&&!ai(e)});if(y&&(_ instanceof Si&&_.match(m)||!_)){var g=a-v;if(n[g]!=="\n"){if(!n[g].trim()){n[g]="\n"}else{n.splice(g,0,"\n");a++}}a+=v;continue e}}}catch(e){s.e(e)}finally{s.f()}}this.__code__=n.join("");return this};Ci.prototype._spaces=function(e){return" ".repeat(e)};Ci.prototype.format=function e(t){var r=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var n=Kn(r,true);var i=this._options(t);var a=0;var u=0;for(var o=0;o0){n=Math.floor(t()*r);r--;var i=[e[n],e[r]];e[r]=i[0];e[n]=i[1]}return e}function Zi(){}Zi.prototype.toString=function(){return"()"};Zi.prototype.valueOf=function(){return undefined};Zi.prototype.serialize=function(){return 0};Zi.prototype.to_object=function(){return{}};Zi.prototype.append=function(e){return new ae(e,ie)};Zi.prototype.to_array=function(){return[]};var ie=new Zi;function ae(e,t){if(typeof this!=="undefined"&&this.constructor!==ae||typeof this==="undefined"){return new ae(e,t)}this.car=e;this.cdr=t}function Xi(a,u){return function e(t){A(a,t,["pair","nil"]);if(ue(t)){return[]}var r=[];var n=t;while(true){if(oe(n)){if(n.have_cycles("cdr")){break}var i=n.car;if(u&&oe(i)){i=this.get(a).call(this,i)}r.push(i);n=n.cdr}else if(ue(n)){break}else{throw new Error("".concat(a,": can't convert improper list"))}}return r}}ae.prototype.flatten=function(){return ae.fromArray(Hi(this.to_array()))};ae.prototype.length=function(){var e=0;var t=this;while(true){if(!t||ue(t)||!oe(t)||t.have_cycles("cdr")){break}e++;t=t.cdr}return e};ae.match=function(e,t){if(e instanceof ne){return ne.is(e,t)}else if(oe(e)){return ae.match(e.car,t)||ae.match(e.cdr,t)}else if(Array.isArray(e)){return e.some(function(e){return ae.match(e,t)})}else if(ta(e)){return Object.values(e).some(function(e){return ae.match(e,t)})}return false};ae.prototype.find=function(e){return ae.match(this,e)};ae.prototype.clone=function(){var r=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(oe(e)){if(n.has(e)){return n.get(e)}var t=new ae;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[lu]=e[lu];return t}return e}return i(this)};ae.prototype.last_pair=function(){var e=this;while(true){if(!oe(e.cdr)){return e}if(e.have_cycles("cdr")){break}e=e.cdr}};ae.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(oe(this.car)){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(oe(this.cdr)){t=t.concat(this.cdr.to_array(e))}return t};ae.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(oe(e)||r&&e instanceof Array&&e[cu]){return e}if(t===false){var n=ie;for(var i=e.length;i--;){n=new ae(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=ee(e)}var a=ie;var u=e.length;while(u--){var o=e[u];if(o instanceof Array){o=ae.fromArray(o,t,r)}else if(typeof o==="string"){o=x(o)}else if(typeof o==="number"&&!Number.isNaN(o)){o=B(o)}a=new ae(o,a)}return a};ae.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(oe(t)&&oe(t.car)){var n=t.car;var i=n.car;if(i instanceof ne){i=i.__name__}if(i instanceof x){i=i.valueOf()}var a=n.cdr;if(oe(a)){a=a.to_object(e)}if(Wa(a)){if(!e){a=a.valueOf()}}r[i]=a;t=t.cdr}else{break}}return r};ae.fromPairs=function(e){return e.reduce(function(e,t){return new ae(new ae(new ne(t[0]),t[1]),e)},ie)};ae.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return ae.fromPairs(e)};ae.prototype.reduce=function(e){var t=this;var r=ie;while(true){if(!ue(t)){r=e(r,t.car);t=t.cdr}else{break}}return r};ae.prototype.reverse=function(){if(this.have_cycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=ie;while(!ue(e)){var r=e.cdr;e.cdr=t;t=e;e=r}return t};ae.prototype.transform=function(n){function i(e){if(oe(e)){if(e.replace){delete e.replace;return e}var t=n(e.car);if(oe(t)){t=i(t)}var r=n(e.cdr);if(oe(r)){r=i(r)}return new ae(t,r)}return e}return i(this)};ae.prototype.map=function(e){if(typeof this.car!=="undefined"){return new ae(e(this.car),ue(this.cdr)?ie:this.cdr.map(e))}else{return ie}};var ea=new Map;function ta(e){return e&&_(e)==="object"&&e.constructor===Object}var ra=Object.getOwnPropertyNames(Array.prototype);var na=[];ra.forEach(function(e){na.push(Array[e],Array.prototype[e])});function ia(e){e=eu(e);return na.includes(e)}function aa(e){return d(e)&&(bu(e)||e.__doc__)}function ua(e){var r=e.constructor||Object;var n=ta(e);var i=d(e[Symbol.asyncIterator])||d(e[Symbol.iterator]);var a;if(ea.has(r)){a=ea.get(r)}else{ea.forEach(function(e,t){t=eu(t);if(r===t&&(t===Object&&n&&!i||t!==Object)){a=e}})}return a}var oa=new Map;[[true,"#t"],[false,"#f"],[null,"#null"],[undefined,"#void"]].forEach(function(e){var t=b(e,2),r=t[0],n=t[1];oa.set(r,n)});function sa(r){if(r&&_(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=pa(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_(t)==="object"&&t.constructor===Object){n[e]=sa(t)}else{n[e]=pa(t)}});return n}return r}function ca(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function fa(e,t){return e.hasOwnProperty(t)&&d(e.toString)}function la(e){if(xu(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(d(t)&&bu(t)){if(e[hu]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(x.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_(n)==="symbol"){n=Hn(n)}if(typeof n==="string"){return"#")}}if(fa(e,"toString")){return e.toString()}else if(e.name&&!bu(e)){return"#")}else{return"#"}}var ha=new Map;[[Error,function(e){return e.message}],[ae,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.mark_cycles()}return e.toString.apply(e,[r].concat(ee(i)))}],[h,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[x,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=b(e,2),r=t[0],n=t[1];ha.set(r,n)});var _a=[ne,q,go,Zu,Xu,F,ei];function pa(e,t,r){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(oa.has(e)){return oa.get(e)}if(Na(e)){return"#"}if(e){var n=e.constructor;if(ha.has(n)){for(var i=arguments.length,a=new Array(i>3?i-3:0),u=3;u"}if(e===null){return"null"}if(d(e)){if(d(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}return la(e)}if(_(e)==="object"){var f=e.constructor;if(!f){f=Object}var l;if(typeof f.__class__==="string"){l=f.__class__}else{var h=ua(e);if(h){if(d(h)){return h(e,t)}else{throw new Error("toString: Invalid repr value")}}l=f.name}if(d(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}if(Ko(e)==="instance"){if(bu(f)&&f.__name__){l=f.__name__.valueOf();if(_(l)==="symbol"){l=l.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/,"$1")}}else if(!xu(f)){l="instance"}}if(Ya(e,Symbol.iterator)){if(l){return"#")}return"#"}if(Ya(e,Symbol.asyncIterator)){if(l){return"#")}return"#"}if(l!==""){return"#<"+l+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}ae.prototype.mark_cycles=function(){va(this);return this};ae.prototype.have_cycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.have_cycles("car")||this.have_cycles("cdr")}return!!(this[lu]&&this[lu][e])};ae.prototype.is_cycle=function(){return da(this)};function da(e){if(!oe(e)){return false}if(e.have_cycles()){return true}return da(e.car,fn)||da(e.cdr,fn)}function va(e){var t=[];var i=[];var a=[];function u(e){if(!t.includes(e)){t.push(e)}}function o(e,t,r,n){if(oe(r)){if(n.includes(r)){if(!a.includes(r)){a.push(r)}if(!e[lu]){e[lu]={}}e[lu][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=Yn(function e(t,r){if(oe(t)){delete t[fu];delete t[lu];u(t);r.push(t);var n=o(t,"car",t.car,r);var i=o(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new $n(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(oe(e[lu][t])){var r=n.indexOf(e[lu][t]);e[lu][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return a.includes(e)});n.forEach(function(e,t){e[fu]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}ae.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[fu]){i.push(this[fu]+"(")}else if(!n){i.push("(")}var a;if(this[lu]&&this[lu].car){a=this[lu].car}else{a=pa(this.car,e,true)}if(a!==undefined){i.push(a)}if(oe(this.cdr)){if(this[lu]&&this[lu].cdr){i.push(" . ");i.push(this[lu].cdr)}else{if(this.cdr[fu]){i.push(" . ")}else{i.push(" ")}var u=this.cdr.toString(e,{nested:true});i.push(u)}}else if(!ue(this.cdr)){i=i.concat([" . ",pa(this.cdr,e,true)])}if(!n||this[fu]){i.push(")")}return i.join("")};ae.prototype.set=function(e,t){this[e]=t;if(oe(t)){this.mark_cycles()}};ae.prototype.append=function(e){if(e instanceof Array){return this.append(ae.fromArray(e))}var t=this;if(t.car===undefined){if(oe(e)){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(!ue(e)){while(true){if(oe(t)&&!ue(t.cdr)){t=t.cdr}else{break}}t.cdr=e}return this};ae.prototype.serialize=function(){return[this.car,this.cdr]};ae.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(ue(t)){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function ya(e){return e<0?-e:e}function ma(e,t){var r=V(t),n=r[0],i=r.slice(1);while(i.length>0){var a=i,u=b(a,1),o=u[0];if(!e(n,o)){return false}var s=i;var c=V(s);n=c[0];i=c.slice(1)}return true}function ga(e,t){if(d(e)){return d(t)&&eu(e)===eu(t)}else if(e instanceof B){if(!(t instanceof B)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return ga(B(e),B(t))}else if(e instanceof h){if(!(t instanceof h)){return false}return e.__char__===t.__char__}else{return e===t}}function ba(e,t){if(Ko(e)!==Ko(t)){return false}if(!wa(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof x){return e.valueOf()===t.valueOf()}return ga(e,t)}function wa(e){return e instanceof ne||x.isString(e)||ue(e)||e===null||e instanceof h||e instanceof B||e===true||e===false}var Da=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function q(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==q||typeof this==="undefined"){return new q(e,t)}A("Macro",e,"string",1);A("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=Fi(r)}}this.__name__=e;this.__fn__=t}q.defmacro=function(e,t,r,n){var i=new q(e,t,r,n);i.__defmacro__=true;return i};q.prototype.invoke=function(e,t,r){var n=t.env,i=_e(t,Or);var a=te(te({},i),{},{macro_expand:r});var u=this.__fn__.call(n,e,a,this.__name__);return u};q.prototype.toString=function(){return"#")};var xa="define-macro";var Ea=-1e4;function Fa(c){return function(){var r=H(O.mark(function e(r,m){var a,g,n,i,u,b,w,D,x,E,F,A,o,k,s;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:s=function e(){s=H(O.mark(function e(r,n,i){var a,u,o,s,c,f,l,h,_,p,d,v,y;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!(oe(r)&&r.car instanceof ne)){t.next=50;break}if(!r[cu]){t.next=3;break}return t.abrupt("return",r);case 3:a=r.car.valueOf();u=i.get(r.car,{throwError:false});o=b(r.car);s=o||w(u,r)||D(u);if(!(s&&oe(r.cdr.car))){t.next=28;break}if(!o){t.next=15;break}g=E(r.cdr.car);t.next=12;return A(r.cdr.car,n);case 12:c=t.sent;t.next=17;break;case 15:g=x(r.cdr.car);c=r.cdr.car;case 17:t.t0=ae;t.t1=r.car;t.t2=ae;t.t3=c;t.next=23;return k(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!F(a,u)){t.next=50;break}f=u instanceof Aa?r:r.cdr;t.next=32;return u.invoke(f,te(te({},m),{},{env:i}),true);case 32:l=t.sent;if(!(u instanceof Aa)){t.next=41;break}h=l,_=h.expr,p=h.scope;if(!oe(_)){t.next=40;break}if(!(n!==-1&&n<=1||n")}return"#"};var ka=fe(function e(t){Q(this,e);s(this,"_syntax",t,{hidden:true});s(this._syntax,"_param",true,{hidden:true})});Aa.Parameter=ka;function Oa(e,t,W,G){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var H={"...":{symbols:{},lists:[]},symbols:{}};var Q=r.expansion,Z=r.define;re(W);function X(t,e){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var n=r.ellipsis,i=n===void 0?false:n,a=r.trailing,N=a===void 0?false:a,u=r.pattern_names,o=u===void 0?[]:u;re({code:e,pattern:t});if(wa(t)&&!(t instanceof ne)){return ba(t,e)}if(t instanceof ne){var s=t.literal();if(W.includes(s)){if(!ne.is(e,s)&&!ne.is(t,e)){return false}var c=Q.ref(s);return!c||c===Z||c===se}}if(Array.isArray(t)&&Array.isArray(e)){re("<<< a 1");if(t.length===0&&e.length===0){return true}if(ne.is(t[1],G)){if(t[0]instanceof ne){var f=t[0].valueOf();re("<<< a 2 "+i);if(i){var l=e.length-2;var T=l>0?e.slice(0,l):e;var h=ae.fromArray(T,false);if(!H["..."].symbols[f]){H["..."].symbols[f]=new ae(h,ie)}else{H["..."].symbols[f].append(new ae(h,ie))}}else{H["..."].symbols[f]=ae.fromArray(e,false)}}else if(Array.isArray(t[0])){re("<<< a 3");var L=ee(o);var M=te(te({},r),{},{pattern_names:L,ellipsis:true});if(!e.every(function(e){return X(t[0],e,M)})){return false}}if(t.length>2){var _=t.slice(2);return X(_,e.slice(-_.length),r)}return true}var p=X(t[0],e[0],r);re({first:p,pattern:t[0],code:e[0]});var d=X(t.slice(1),e.slice(1),r);re({first:p,rest:d});return p&&d}if(oe(t)&&oe(t.car)&&oe(t.car.cdr)&&ne.is(t.car.cdr.car,G)){re(">> 0");if(ue(e)){re({pattern:t});if(t.car.car instanceof ne){var v=t.car.car.valueOf();if(H["..."].symbols[v]){throw new Error("syntax: named ellipsis can only "+"appear onces")}H["..."].symbols[v]=e}}}if(oe(t)&&oe(t.cdr)&&ne.is(t.cdr.car,G)){re(">> 1 (a)");if(!ue(t.cdr.cdr)){if(oe(t.cdr.cdr)){re(">> 1 (b)");var R=t.cdr.cdr.length();var y=!ue(t.last_pair().cdr);if(!oe(e)){return false}var m=e.length();var g=e;var q=y?1:1;while(m-q>R){g=g.cdr;m--}var U=g.cdr;g.cdr=ie;var z=te(te({},r),{},{trailing:y});if(!X(t.cdr.cdr,U,z)){return false}}}if(t.car instanceof ne){var b=t.car.__name__;if(H["..."].symbols[b]&&!o.includes(b)&&!i){throw new Error("syntax: named ellipsis can only appear onces")}re(">> 1 (next)");if(ue(e)){re(">> 2");if(i){re("NIL");H["..."].symbols[b]=ie}else{re("NULL");H["..."].symbols[b]=null}}else if(oe(e)&&(oe(e.car)||ue(e.car))){re(">> 3 "+i);if(i){if(H["..."].symbols[b]){var w=H["..."].symbols[b];if(ue(w)){w=new ae(ie,new ae(e,ie))}else{w=w.append(new ae(e,ie))}H["..."].symbols[b]=w}else{H["..."].symbols[b]=new ae(e,ie)}}else{re(">> 4");H["..."].symbols[b]=new ae(e,ie)}}else{re(">> 6");if(oe(e)){re(">> 7 "+i);if(!oe(e.cdr)&&!ue(e.cdr)){re(">> 7 (b)");if(ue(t.cdr.cdr)){return false}else if(!H["..."].symbols[b]){H["..."].symbols[b]=new ae(e.car,ie);return X(t.cdr.cdr,e.cdr,r)}}var D=e.last_pair();re({last_pair:D});if(!ue(D.cdr)){re(">> 7 (c)");if(ue(t.cdr.cdr)){return false}else{re(">> 7 (d)");var x=e.clone();x.last_pair().cdr=ie;H["..."].symbols[b]=x;return X(t.cdr.cdr,D.cdr,r)}}o.push(b);if(!H["..."].symbols[b]){re(">> 7 (e)");H["..."].symbols[b]=new ae(e,ie)}else{re(">> 7 (f)");var V=H["..."].symbols[b];H["..."].symbols[b]=V.append(new ae(e,ie))}re({IIIIII:H["..."].symbols[b]})}else if(t.car instanceof ne&&oe(t.cdr)&&ne.is(t.cdr.car,G)){re(">> 8");H["..."].symbols[b]=null;return X(t.cdr.cdr,e,r)}else{re(">> 9");return false}}return true}else if(oe(t.car)){var E=ee(o);if(ue(e)){re(">> 10");H["..."].lists.push(ie);return true}re(">> 11");var F=e;var $=te(te({},r),{},{pattern_names:E,ellipsis:true});while(oe(F)){if(!X(t.car,F.car,$)){return false}F=F.cdr}return true}if(Array.isArray(t.car)){var E=ee(o);var A=e;var Y=te(te({},r),{},{pattern_names:E,ellipsis:true});while(oe(A)){if(!X(t.car,A.car,Y)){return false}A=A.cdr}return true}return false}if(t instanceof ne){if(ne.is(t,G)){throw new Error("syntax: invalid usage of ellipsis")}re(">> 12");var k=t.__name__;if(W.includes(k)){return true}if(i){var O,C;re(H["..."].symbols[k]);(C=(O=H["..."].symbols)[k])!==null&&C!==void 0?C:O[k]=[];H["..."].symbols[k].push(e)}else{H.symbols[k]=e}return true}if(oe(t)&&oe(e)){re(">> 13");re({a:13,code:e,pattern:t});var S=t.car instanceof ne&&t.cdr instanceof ne;if(N&&S){re(">> 13 (a)");if(!ue(e.cdr)){return false}var J=t.car.valueOf();var K=t.cdr.valueOf();H.symbols[J]=e.car;H.symbols[K]=ie;return true}if(ue(e.cdr)){re(">> 13 (b)");if(S){if(!X(t.car,e.car,r)){return false}re(">> 14");var j=t.cdr.valueOf();if(!(j in H.symbols)){H.symbols[j]=ie}j=t.car.valueOf();if(!(j in H.symbols)){H.symbols[j]=e.car}return true}}re({pattern:t,code:e});if(oe(t.cdr)&&oe(t.cdr.cdr)&&t.cdr.car instanceof ne&&ne.is(t.cdr.cdr.car,G)&&oe(t.cdr.cdr.cdr)&&!ne.is(t.cdr.cdr.cdr.car,G)&&X(t.car,e.car,r)&&X(t.cdr.cdr.cdr,e.cdr,te(te({},r),{},{trailing:true}))){var B=t.cdr.car.__name__;re({pattern:t,code:e,name:B});if(W.includes(B)){return true}H["..."].symbols[B]=null;return true}re("recur");re({pattern:t,code:e});var I=X(t.car,e.car,r);var P=X(t.cdr,e.cdr,r);re({$car_code:e.car,$car_pattern:t.car,car:I,$cdr_code:e.cdr,$cdr_pattern:t.cdr,cdr:P});if(I&&P){return true}}else if(ue(t)&&(ue(e)||e===undefined)){return true}else if(oe(t.car)&&ne.is(t.car.car,G)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(X(e,t)){return H}}function Ca(e,i){function a(t){if(oe(t)){if(!i.length){return t}var e=a(t.car);var r=a(t.cdr);return new ae(e,r)}else if(t instanceof ne){var n=i.find(function(e){return e.gensym===t});if(n){return ne(n.name)}return t}else{return t}}return a(e)}function Sa(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var B=e.bindings,t=e.expr,I=e.scope,u=e.symbols,f=e.names,P=e.ellipsis;var l={};function o(e){if(e instanceof ne){return true}return["string","symbol"].includes(_(e))}function N(e){if(!o(e)){var t=Ko(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===P){throw new Error("syntax: internal error, ellipis not transformed")}var n=_(r);if(["string","symbol"].includes(n)){if(r in B.symbols){return B.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var a=i[0];if(a in B.symbols){return ae.fromArray([ne("."),B.symbols[a]].concat(i.slice(1).map(function(e){return x(e)})))}}}if(u.includes(r)){return e}return s(r,e)}function s(e,t){if(!l[e]){var r=I.ref(e);if(_(e)==="symbol"&&!r){e=t.literal()}if(l[e]){return l[e]}var n=Zn(e);if(r){var i=I.get(e);I.set(n,i)}else{var a=I.get(e,{throwError:false});if(typeof a!=="undefined"){I.set(n,a)}}f.push({name:e,gensym:n});l[e]=n;if(typeof e==="string"&&e.match(/\./)){var u=e.split(".").filter(Boolean),o=V(u),s=o[0],c=o.slice(1);if(l[s]){mu(n,"__object__",[l[s]].concat(ee(c)))}}}return l[e]}function T(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;re({bindings:t,expr:e});if(Array.isArray(e)&&!e.length){return e}if(e instanceof ne){var a=e.valueOf();if(Qn(e)&&!t[a]);re("[t 1");if(t[a]){if(oe(t[a])){var u=t[a],o=u.car,s=u.cdr;if(i){var c=o.car,f=o.cdr;if(!ue(f)){n(a,new ae(f,ie))}return c}if(!ue(s)){n(a,s)}return o}else if(t[a]instanceof Array){n(a,t[a].slice(1));return t[a][0]}}return N(e)}var l=Array.isArray(e);if(oe(e)||l){var h=l?e[0]:e.car;var _=l?e[1]:oe(e.cdr)&&e.cdr.car;if(h instanceof ne&&ne.is(_,P)){l?e.slice(2):e.cdr.cdr;re("[t 2");var p=h.valueOf();var d=t[p];if(d===null){return}else if(p in t){re({name:p,binding:t[p]});if(oe(d)){re("[t 2 Pair "+i);var v=d.car,y=d.cdr;var m=l?e.slice(2):e.cdr.cdr;if(i){if(!ue(y)){re("|| next 1");n(p,y)}if(l&&m.length||!ue(m)&&!l){var g=T(m,t,r,n);if(l){return v.concat(g)}else if(oe(v)){return v.append(g)}else{re("UNKNOWN")}}return v}else if(oe(v)){if(!ue(v.cdr)){re("|| next 2");n(p,new ae(v.cdr,y))}return new mo(v.car)}else if(ue(y)){return v}else{var b=e.last_pair();if(b.cdr instanceof ne){re("|| next 3");n(p,d.last_pair());return v}}}else if(d instanceof Array){re("[t 2 Array "+i);if(i){n(p,d.slice(1));return ae.fromArray(d)}else{var w=d.slice(1);if(w.length){n(p,w)}return d[0]}}else{return d}}}re("[t 3 recur ",e);var D=l?e.slice(1):e.cdr;var x=T(h,t,r,n);var E=T(D,t,r,n);re({head:x,rest:E});if(l){return[x].concat(E)}return new ae(x,E)}return e}function L(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,ee(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return oe(e)||ue(e)||Array.isArray(e)&&e.length})}function M(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function R(i){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},t=e.disabled;re("traverse>> ",i);var a=Array.isArray(i);if(a&&i.length===0){return i}if(oe(i)||a){re(">> 0");var r=a?i[0]:i.car;var n,u;if(a){n=i[1];u=i.slice(2)}else if(oe(i.cdr)){n=i.cdr.car;u=i.cdr.cdr}re({first:r,second:n,rest_second:u});if(!t&&oe(r)&&ne.is(r.car,P)){return new ae(r.cdr.car,R(i.cdr))}if(n&&ne.is(n,P)&&!t){re(">> 1");var o=B["..."].symbols;var s=Object.values(o);if(s.length&&s.every(function(e){return e===null})){re(">>> 1 (a)");return R(u,{disabled:t})}var c=M(o);var f=r instanceof ne&&ne.is(u.car,P);if(oe(r)||f){re(">>> 1 (b)");if(ue(B["..."].lists[0])){if(!f){return R(u,{disabled:t})}re(u);return ie}var l=r;if(f){re(">>> 1 (c)");l=new ae(r,new ae(n,ie))}re(">> 2");var h;if(c.length){re(">> 2 (a)");var _=te({},o);h=a?[]:ie;var p=function e(){re({bind:_});if(!L(_)){return 1}var n={};var t=function e(t,r){n[t]=r};var r=T(l,_,{nested:true},t);if(r!==undefined){if(r instanceof mo){r.valueOf(),U("car")}if(f){if(a){if(Array.isArray(r)){var i;(i=h).push.apply(i,ee(r))}else{re("ZONK {1}")}}else{if(ue(h)){h=r}else{h=h.append(r)}}}else if(a){h.push(r)}else{h=new ae(r,h)}}_=n};while(true){if(p())break}if(!ue(h)&&!f&&!a){h=h.reverse()}if(a){if(u){re({rest_second:u,expr:i});var d=R(u,{disabled:t});return h.concat(d)}return h}if(!ue(i.cdr.cdr)&&!ne.is(i.cdr.cdr.car,P)){var v=R(i.cdr.cdr,{disabled:t});return h.append(v)}return h}else{re(">> 3");var y=T(r,o,{nested:true});if(y){if(y instanceof mo){y.valueOf(),U("car")}return new ae(y,ie)}return ie}}else if(r instanceof ne){re(">> 4");if(ne.is(u.car,P)){re(">> 4 (a)")}else{re(">> 4 (b)")}var m=r.__name__;var g=le({},m,o[m]);re({bind:g});var b=o[m]===null;var w=a?[]:ie;var D=function e(){if(!L(g,true)){re({bind:g});return 1}var n={};var t=function e(t,r){n[t]=r};var r=T(i,g,{nested:false},t);re({value:r});if(typeof r!=="undefined"){if(r instanceof mo){r=r.valueOf()}if(a){w.push(r)}else{w=new ae(r,w)}}g=n};while(true){if(D())break}if(!ue(w)&&!a){w=w.reverse()}if(oe(i.cdr)){if(oe(i.cdr.cdr)||i.cdr.cdr instanceof ne){var x=R(i.cdr.cdr,{disabled:t});re({node:x});if(b){return x}if(ue(w)){w=x}else{w.append(x)}re({result:w,node:x})}}re("<<<< 2");re({result:w});return w}}var E=R(r,{disabled:t});var F;var A;if(r instanceof ne){var k=I.get(r,{throwError:false});A=k instanceof q&&k.__name__==="syntax-rules"}if(A){if(i.cdr.car instanceof ne){F=new ae(R(i.cdr.car,{disabled:t}),new ae(i.cdr.cdr.car,R(i.cdr.cdr.cdr,{disabled:t})))}else{F=new ae(i.cdr.car,R(i.cdr.cdr,{disabled:t}))}re("REST >>>> ",F)}else{F=R(i.cdr,{disabled:t})}re({a:true,car:pa(i.car),cdr:pa(i.cdr),head:pa(E),rest:pa(F)});return new ae(E,F)}if(i instanceof ne){if(t&&ne.is(i,P)){return i}var O=Object.keys(B["..."].symbols);var C=i.literal();if(O.includes(C)){var S="missing ellipsis symbol next to name `".concat(C,"'");throw new Error("syntax-rules: ".concat(S))}var j=N(i);if(typeof j!=="undefined"){return j}}return i}return R(t,{})}function ja(e){return Va(e)||ue(e)||e===null}function ue(e){return e===ie}function d(e){return typeof e==="function"&&typeof e.bind==="function"}function Ba(e){return hi.includes(e)}function Ia(e){return e===false||e===null}function Pa(e){return typeof e==="string"}function Na(e){return e&&_(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}function Ta(e){return e instanceof as}function La(e){return e instanceof ns}function Ma(e){return e instanceof rs}function oe(e){return e instanceof ae}function Ra(e){return e instanceof F}function qa(e){return d(e)||Ta(e)||Ma(e)||Ua(e)}function Ua(e){return e instanceof q||e instanceof ka}function za(e){if(e instanceof ei){return false}if(e instanceof Promise){return true}return!!e&&d(e.then)}function Va(e){return typeof e==="undefined"}function $a(e){return Object.getPrototypeOf(e)}function Ya(e,t){if(Ga(e,t)||Ga($a(e),t)){return d(e[t])}}function Ja(e){if(!e){return false}if(_(e)!=="object"){return false}if(e.__instance__){e.__instance__=false;return e.__instance__}return false}function Ka(e){var t=_(e);return["string","function"].includes(t)||_(e)==="symbol"||e instanceof ei||e instanceof ne||e instanceof B||e instanceof x||e instanceof RegExp}function Wa(e){return e instanceof B||e instanceof x||e instanceof h}function Ga(e,t){if(e===null){return false}return _(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function Ha(e){switch(_(e)){case"string":return x(e);case"bigint":return B(e);case"number":if(Number.isNaN(e)){return ko}else{return B(e)}}return e}function Qa(r,n){var e=Object.getOwnPropertyNames(r);var t=Object.getOwnPropertySymbols(r);var i={};e.concat(t).forEach(function(e){var t=n(r[e]);i[e]=t});return i}function Za(t){var e=[x,B,h].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(Za)}if(t instanceof ei){delete t.then}if(ta(t)){return Qa(t,Za)}return t}function Xa(e,t){if(oe(e)){e.mark_cycles();return bo(e)}if(d(e)){if(t){return tu(e,t)}}return Ha(e)}function eu(e){if(nu(e)){return e[su]}return e}function tu(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=Lr(n),a;try{for(i.s();!(a=i.n()).done;){var u=a.value;if(yu(u)){try{r[u]=e[u]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}mu(r,"__fn__",e);mu(r,"__context__",t);mu(r,"__bound__",true);if(xu(e)){mu(r,"__native__",true)}if(ta(t)&&bu(e)){mu(r,"__method__",true)}r.valueOf=function(){return e};return r}function ru(e){return nu(e)&&e[Symbol["for"]("__context__")]===Object}function nu(e){return!!(d(e)&&e[su])}function iu(e){if(d(e)){var t=e[ou];if(t&&(t===Vs||t.constructor&&t.constructor.__class__)){return true}}return false}function au(e){return e instanceof Zu||e instanceof Xu}function uu(e){if(d(e)){if(au(e[ou])){return true}}return false}var ou=Symbol["for"]("__context__");var su=Symbol["for"]("__fn__");var cu=Symbol["for"]("__data__");var fu=Symbol["for"]("__ref__");var lu=Symbol["for"]("__cycles__");var hu=Symbol["for"]("__class__");var _u=Symbol["for"]("__method__");var pu=Symbol["for"]("__prototype__");var du=Symbol["for"]("__lambda__");var vu=["name","length","caller","callee","arguments","prototype"];function yu(e){return!vu.includes(e)}function mu(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function gu(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function bu(e){return e&&e[du]}function wu(e){return e&&e[_u]}function Du(e){return bu(e)&&!e[pu]&&!wu(e)&&!uu(e)}function xu(e){var t=Symbol["for"]("__native__");return d(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function Eu(e){var w;switch(e){case Symbol["for"]("letrec"):w="letrec";break;case Symbol["for"]("let"):w="let";break;case Symbol["for"]("let*"):w="let*";break;default:throw new Error("Invalid let_macro value")}return q.defmacro(w,function(t,e){var f=e.dynamic_env;var l=e.error,r=e.macro_expand,h=e.use_dynamic;var _;if(t.car instanceof ne){if(!(oe(t.cdr.car)||ue(t.cdr.car))){throw new Error("let require list of pairs")}var n;if(ue(t.cdr.car)){_=ie;n=ie}else{n=t.cdr.car.map(function(e){return e.car});_=t.cdr.car.map(function(e){return e.cdr.car})}return new ae(ae.fromArray([ne("letrec"),[[t.car,ae(ne("lambda"),ae(n,t.cdr.cdr))]],t.car]),_)}else if(r){return}var p=this;_=se.get("list->array")(t.car);var d=p.inherit(w);var v,y;if(w==="let*"){y=d}else if(w==="let"){v=[]}var m=0;function g(){var e=Xn([d],t.cdr);return k(e,{env:d,dynamic_env:d,use_dynamic:h,error:l})}function b(e){if(e in d.__env__){throw new Error("Duplicated let variable ".concat(e))}}return function t(){var r=_[m++];f=w==="let*"?d:p;if(!r){if(v&&v.length){var e=v.map(function(e){return e.value});var n=e.filter(za);if(n.length){return ti(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=this;var a=this;var u=[];var o=e;while(oe(o)){u.push(k(o.car,{env:i,dynamic_env:a,use_dynamic:r,error:n}));o=o.cdr}var s=u.filter(za).length;if(s){return ti(u).then(c.bind(this))}else{return c.call(this,u)}})}function Au(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),a=2;a1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=o){return u.apply(n,i)}else{return a}}}();return a.apply(void 0,arguments)}}function Nu(n,i){A("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(h.__names__[e]){t=e;e=h.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=h.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}h.__names__=cn;h.__rev_names__={};Object.keys(h.__names__).forEach(function(e){var t=h.__names__[e];h.__rev_names__[t]=e});h.prototype.toUpperCase=function(){return h(this.__char__.toUpperCase())};h.prototype.toLowerCase=function(){return h(this.__char__.toLowerCase())};h.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};h.prototype.valueOf=h.prototype.serialize=function(){return this.__char__};function x(e){if(typeof this!=="undefined"&&!(this instanceof x)||typeof this==="undefined"){return new x(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){A("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var Tu=["length","constructor"];var Lu=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!Tu.includes(e)});var Mu=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof B){return e}if(typeof this!=="undefined"&&!(this instanceof B)||typeof this==="undefined"){return new B(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=B.getType(e);if(B.types[r]){return B.types[r](e,t)}var n=e instanceof Array&&x.isString(e[0])&&B.isNumber(e[1]);if(e instanceof B){return B(e.value)}if(!B.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(Ko(e)))}if(e===null){e=0}var i;if(n){var a=e,u=b(a,2),o=u[0],s=u[1];if(o instanceof x){o=o.valueOf()}if(s instanceof B){s=s.valueOf()}var c=o.match(/^([+-])/);var f=false;if(c){o=o.replace(/^[+-]/,"");if(c[1]==="-"){f=true}}}if(Number.isNaN(e)){return g(e)}else if(n&&Number.isNaN(parseInt(o,s))){return ko}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var l;switch(s){case 8:l="0o";break;case 16:l="0x";break;case 2:l="0b";break;case 10:l="";break}if(typeof l==="undefined"){var h=BigInt(s);i=ee(o).map(function(e,t){return BigInt(parseInt(e,s))*Ju(h,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(l+o)}}else{i=BigInt(e)}if(f){i*=BigInt(-1)}}else{i=e}return E(i,true)}else if(typeof Gr!=="undefined"&&!(e instanceof Gr)){if(e instanceof Array){return E(T(Gr,ee(e)))}return E(new Gr(e))}else if(n){this.constant(parseInt(o,s),"integer")}else{this.constant(e,"integer")}}B.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};B.types={float:function e(t){return new g(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!B.isComplex(t)){t={im:0,re:t}}return new m(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!B.isRational(t)){t={num:t,denom:1}}return new w(t,r)}};B.prototype.serialize=function(){return this.__value__};B.prototype.isNaN=function(){return Number.isNaN(this.__value__)};B.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};B.isFloat=function e(t){return t instanceof g||Number(t)===t&&t%1!==0};B.isNumber=function(e){return e instanceof B||B.isNative(e)||B.isBN(e)};B.isComplex=function(e){if(!e){return false}var t=e instanceof m||(B.isNumber(e.im)||B.isRational(e.im)||Number.isNaN(e.im))&&(B.isNumber(e.re)||B.isRational(e.re)||Number.isNaN(e.re));return t};B.isRational=function(e){if(!e){return false}return e instanceof w||B.isNumber(e.num)&&B.isNumber(e.denom)};B.isInteger=function(e){if(!(B.isNative(e)||e instanceof B)){return false}if(B.isFloat(e)){return false}if(B.isRational(e)){return false}if(B.isComplex(e)){return false}return true};B.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};B.isBigInteger=function(e){return e instanceof E||typeof e==="bigint"||B.isBN(e)};B.isBN=function(e){return typeof Gr!=="undefined"&&e instanceof Gr};B.getArgsType=function(e,t){if(e instanceof g||t instanceof g){return g}if(e instanceof E||t instanceof E){return E}return B};B.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>=2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};B.prototype.asType=function(e){var t=B.getType(this);return B.types[t]?B.types[t](e):B(e)};B.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof Gr!=="undefined"&&!(this.value instanceof Gr)};["floor","ceil","round"].forEach(function(e){B.prototype[e]=function(){if(this["float"]||B.isFloat(this.__value__)){return B(Math[e](this.__value__))}else{return B(Math[e](this.valueOf()))}}});B.prototype.valueOf=function(){if(B.isNative(this.__value__)){return Number(this.__value__)}else if(B.isBN(this.__value__)){return this.__value__.toNumber()}};var zu=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[g(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[g(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&g(r.valueOf())]},integer:function e(t,r){return[t,r&&g(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&g(r.valueOf())]},complex:function e(t,r){return[{re:t,im:g(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function e(t,r){var n=B.coerce(t.__re__,r.__re__),i=b(n,2),a=i[0],u=i[1];var o=B.coerce(t.__im__,r.__im__),s=b(o,2),c=s[0],f=s[1];return[{im:c,re:a},{im:f,re:u}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[g(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:Vu(t.__type__,r.__im__.__type__,0)[0],re:Vu(t.__type__,r.__re__.__type__,t)[0]},{im:Vu(t.__type__,r.__im__.__type__,r.__im__)[0],re:Vu(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:Vu(r,e.__im__.__type__,0,e.__im__)[1],re:Vu(r,e.__re__.__type__,0,e.__re__)[1]},{im:Vu(r,e.__im__.__type__,0,0)[1],re:Vu(r,t.__type__,0,t)[1]}]}}}();function Vu(e,t,r,n){return zu[e][t](r,n)}B.coerce=function(e,t){var r=B.getType(e);var n=B.getType(t);if(!zu[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!zu[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=zu[r][n](e,t);return i.map(function(e){return B(e,true)})};B.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof B)){throw new Error("LNumber: you can't coerce ".concat(Ko(e)))}if(typeof e==="number"){e=B(e)}return B.coerce(this,e)};B.getType=function(e){if(e instanceof B){return e.__type__}if(B.isFloat(e)){return"float"}if(B.isComplex(e)){return"complex"}if(B.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof Gr!=="undefined"&&!(e instanceof Gr)){return"bigint"}};B.prototype.isFloat=function(){return!!(B.isFloat(this.__value__)||this["float"])};var $u={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var Yu={};Object.keys($u).forEach(function(t){Yu[$u[t]]=t;B.prototype[t]=function(e){return this.op($u[t],e)}});B._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof m)||typeof this==="undefined"){return new m(e,t)}if(e instanceof m){return m({im:e.__im__,re:e.__re__})}if(B.isNumber(e)&&t){if(!t){return Number(e)}}else if(!B.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(pa(e));throw new Error(r)}var n=e.im instanceof B?e.im:B(e.im);var i=e.re instanceof B?e.re:B(e.re);this.constant(n,i)}m.prototype=Object.create(B.prototype);m.prototype.constructor=m;m.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};m.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};m.prototype.toRational=function(e){var t=this.__im__,r=this.__re__;if(B.isFloat(this.__im__)){t=g(this.__im__).toRational(e)}if(B.isFloat(this.__re__)){r=g(this.__re__).toRational(e)}return m({im:t,re:r})};m.prototype.pow=function(e){e.cmp(0);if(e===0){return B(1)}var t=B(Math.atan2(this.__im__.valueOf(),this.__re__.valueOf()));var r=B(this.modulus());if(B.isComplex(e)&&e.__im__.cmp(0)!==0){var n=e.mul(Math.log(r.valueOf())).add(m.i.mul(t).mul(e));if(!B.isComplex(n)){return g(Math.E).pow(n)}var i=g(Math.E).pow(n.__re__.valueOf());return m({re:i.mul(Math.cos(n.__im__.valueOf())),im:i.mul(Math.sin(n.__im__.valueOf()))})}var a=e.__re__.cmp(0)>0;e=e.__re__.valueOf();if(B.isInteger(e)&&a){var u=this;while(--e){u=u.mul(this)}return u}var o=r.pow(e);var s=t.mul(e);return m({re:o.mul(Math.cos(s)),im:o.mul(Math.sin(s))})};m.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};m.prototype.factor=function(){if(this.__im__ instanceof g||this.__im__ instanceof g){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof g){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof g){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};m.prototype.modulus=function(){return this.factor().sqrt()};m.prototype.conjugate=function(){return m({re:this.__re__,im:this.__im__.sub()})};m.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=g(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=g(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return m({im:r,re:t})};m.prototype.div=function(e){if(B.isNumber(e)&&!B.isComplex(e)){if(!(e instanceof B)){e=B(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return m({re:t,im:r})}else if(!B.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=b(n,2),a=i[0],u=i[1];var o=a.__im__.div(u.__im__);return o.coerce(u.__re__)[0]}var s=this.coerce(e),c=b(s,2),f=c[0],l=c[1];var h=l.factor();var _=l.conjugate();var p=f.mul(_);if(!B.isComplex(p)){return p.div(h)}var d=p.__re__.op("/",h);var v=p.__im__.op("/",h);return m({re:d,im:v})};m.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};m.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};m.prototype.complex_op=function(e,t,i){var a=this;var r=function e(t,r){var n=i(a.__re__,t,a.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return m(n,true)}return n};if(typeof t==="undefined"){return r()}if(B.isNumber(t)&&!B.isComplex(t)){if(!(t instanceof B)){t=B(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!B.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var u=t.__re__ instanceof B?t.__re__:this.__re__.asType(t.__re__);var o=t.__im__ instanceof B?t.__im__:this.__im__.asType(t.__im__);return r(u,o)};m._op={"+":"add","-":"sub","*":"mul","/":"div"};m.prototype._op=function(e,t){var r=m._op[e];return this[r](t)};m.prototype.cmp=function(e){var t=this.coerce(e),r=b(t,2),n=r[0],i=r[1];var a=n.__re__.coerce(i.__re__),u=b(a,2),o=u[0],s=u[1];var c=o.cmp(s);if(c!==0){return c}else{var f=n.__im__.coerce(i.__im__),l=b(f,2),h=l[0],_=l[1];return h.cmp(_)}};m.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};m.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[pa(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=pa(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function g(e){if(typeof this!=="undefined"&&!(this instanceof g)||typeof this==="undefined"){return new g(e)}if(!B.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof B){return g(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}g.prototype=Object.create(B.prototype);g.prototype.constructor=g;g.prototype.toString=function(e){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}e&&(e=e.valueOf());var t=this.__value__.toString(e);if(!t.match(/e[+-]?[0-9]+$/i)){var r=t.replace(/^-/,"");var n=this.__value__<0?"-":"";if(t.match(/^-?0\.0{3}/)){var i=r.match(/^[.0]+/g)[0].length-1;var a=r.replace(/^[.0]+/,"").replace(/^([0-9a-f])/i,"$1.");return"".concat(n).concat(a,"e-").concat(i.toString(e))}if(t.match(/^-?[0-9a-f]{7,}\.?/i)){var u=r.match(/^[0-9a-f]+/gi)[0].length-1;var o=r.replace(/\./,"").replace(/^([0-9a-f])/i,"$1.").replace(/0+$/,"").replace(/\.$/,".0");return"".concat(n).concat(o,"e+").concat(u.toString(e))}if(!B.isFloat(this.__value__)){var s=t+".0";return this._minus?"-"+s:s}}return t.replace(/^([0-9]+)e/,"$1.0e")};g.prototype._op=function(e,t){if(t instanceof B){t=t.__value__}var r=B._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return g(r(this.__value__,t))};g.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return Wu(this.__value__.valueOf())}return Gu(e.valueOf())(this.__value__.valueOf())};g.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=g(Math.sqrt(-e));return m({re:0,im:t})}return g(Math.sqrt(e))};g.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return g(e)};var Wu=Gu(1e-10);function Gu(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=Qu(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=Qu(r,n)}else if(t.cmp(0)<0){i=B(Qu(n.sub(),r.sub())).sub()}else{i=B(0)}if(B.isFloat(t)||B.isFloat(e)){return g(i)}return i}function Qu(e,t){var r=B(e).floor();var n=B(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=B(1).div(t.sub(n));var a=B(1).div(e.sub(r));return r.add(B(1).div(Qu(i,a)))}else{return r.add(B(1))}}function w(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof w)||typeof this==="undefined"){return new w(e,t)}if(!B.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof w){r=B(e.__num__);n=B(e.__denom__)}else{r=B(e.num);n=B(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return B(r.div(n))}}this.constant(r,n)}w.prototype=Object.create(B.prototype);w.prototype.constructor=w;w.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};w.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};w.prototype.pow=function(e){if(B.isRational(e)){return Ju(this.valueOf(),e.valueOf())}var t=e.cmp(0);if(t===0){return B(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return w({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};w.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof g||t instanceof g){return e.div(t)}return w({num:e,denom:t})};w.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return w({num:e,denom:t})};w.prototype.cmp=function(e){return B(this.valueOf(),true).cmp(e)};w.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof w){t=B(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof w){r=B(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};w.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return B._ops["/"](this.__num__.value,this.__denom__.value)}return g(this.__num__.valueOf()).div(this.__denom__.valueOf())};w.prototype.mul=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return w({num:t,denom:r})}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];return a.mul(u)};w.prototype.div=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return w({num:t,denom:r})}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];var o=a.div(u);return o};w.prototype._op=function(e,t){return this[Yu[e]](t)};w.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(w({num:t,denom:r}))}if(!(e instanceof B)){e=B(e).sub()}else{e=e.sub()}var n=B.coerce(this,e),i=b(n,2),a=i[0],u=i[1];return a.add(u)};w.prototype.add=function(e){if(!(e instanceof B)){e=B(e)}if(B.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var a,u;if(t!==r){u=r.mul(n).add(i.mul(t));a=t.mul(r)}else{u=n.add(i);a=t}return w({num:u,denom:a})}if(B.isFloat(e)){return g(this.valueOf()).add(e)}var o=B.coerce(this,e),s=b(o,2),c=s[0],f=s[1];return c.add(f)};function E(e,t){if(typeof this!=="undefined"&&!(this instanceof E)||typeof this==="undefined"){return new E(e,t)}if(e instanceof E){return E(e.__value__,e._native)}if(!B.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}E.prototype=Object.create(B.prototype);E.prototype.constructor=E;E.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};E.prototype.serialize=function(){return this.__value__.toString()};E.prototype._op=function(e,t){if(typeof t==="undefined"){if(B.isBN(this.__value__)){e=E.bn_op[e];return E(this.__value__.clone()[e](),false)}return E(B._ops[e](this.__value__),true)}if(B.isBN(this.__value__)&&B.isBN(t.__value__)){e=E.bn_op[e];return E(this.__value__.clone()[e](t),false)}var r=B._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return B(r)}return w({num:this,denom:t})}return E(r,true)};E.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(B.isNative(this.__value__)){e=B(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(B.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return m({re:0,im:e})}return e};B.NaN=B(NaN);m.i=m({im:1,re:0});function Zu(e){var n=this;var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:se;if(typeof this!=="undefined"&&!(this instanceof Zu)||typeof this==="undefined"){return new Zu(e)}A("InputPort",e,"function");s(this,"__type__",lo);var a;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return a},set:function e(t){A("InputPort::__parser__",t,"parser");a=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,H(O.mark(function e(){var r;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=6;break}t.next=3;return n._read();case 3:r=t.sent;a=new di({env:i});a.parse(r);case 6:return t.abrupt("return",n.__parser__);case 7:case"end":return t.stop()}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==ho};this._make_defaults()}Zu.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!B.isInteger(t)){var r=B.getType(t);Uo("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};Zu.prototype._with_init_parser=function(o,s){var c=this;return H(O.mark(function e(){var r,n,i,a,u=arguments;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return o.call(c);case 2:r=t.sent;for(n=u.length,i=new Array(n),a=0;a"};function Xu(e){if(typeof this!=="undefined"&&!(this instanceof Xu)||typeof this==="undefined"){return new Xu(e)}A("OutputPort",e,"function");s(this,"__type__",lo);this.write=e}Xu.prototype.is_open=function(){return this._closed!==true};Xu.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};Xu.prototype.flush=function(){};Xu.prototype.toString=function(){return"#"};var eo=function(e){J(r,e);function r(e){var t;Q(this,r);t=Nr(this,r,[function(){var e;return(e=t)._write.apply(e,arguments)}]);A("BufferedOutputPort",e,"function");s(I(t),"_fn",e,{hidden:true});s(I(t),"_buffer",[],{hidden:true});return t}fe(r,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};to.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function ro(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof ro)||typeof this==="undefined"){return new ro(e,t)}A("OutputFilePort",e,"string");s(this,"__filename__",e);s(this,"_fd",t.valueOf(),{hidden:true});s(this,"__type__",lo);this.write=function(e){if(!x.isString(e)){e=pa(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}ro.prototype=Object.create(Xu.prototype);ro.prototype.constructor=ro;ro.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};ro.prototype.internal=function(e){return Co.get("**internal-env**").get(e)};ro.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{s(n,"_fd",null,{hidden:true});Xu.prototype.close.call(n);t()}})})};ro.prototype.toString=function(){return"#")};function no(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:se;if(typeof this!=="undefined"&&!(this instanceof no)||typeof this==="undefined"){return new no(e)}A("InputStringPort",e,"string");e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!t.__parser__){t.__parser__=new di({env:r});t.__parser__.parse(e)}return t.__parser__});s(this,"__type__",lo);this._make_defaults()}no.prototype.char_ready=function(){return true};no.prototype=Object.create(Zu.prototype);no.prototype.constructor=no;no.prototype.toString=function(){return"#"};function io(e){if(typeof this!=="undefined"&&!(this instanceof io)||typeof this==="undefined"){return new io(e)}this._with_parser=this._with_init_parser.bind(this,function(){return e});s(this,"__type__",lo);this._make_defaults()}io.prototype.char_ready=function(){return true};io.prototype=Object.create(Zu.prototype);io.prototype.constructor=io;io.prototype.toString=function(){return"#"};function ao(e){if(typeof this!=="undefined"&&!(this instanceof ao)||typeof this==="undefined"){return new ao(e)}A("InputByteVectorPort",e,"uint8array");s(this,"__vector__",e);s(this,"__type__",fo);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){A("InputByteVectorPort::__index__",t,"number");if(t instanceof B){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}ao.prototype=Object.create(Zu.prototype);ao.prototype.constructor=ao;ao.prototype.toString=function(){return"#"};ao.prototype.close=function(){var t=this;s(this,"__vector__",ie);var r=function e(){throw new Error("Input-binary-port: port is closed")};["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=r});this.u8_ready=this.char_ready=function(){return false}};ao.prototype.u8_ready=function(){return true};ao.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return ho}return this.__vector__[this.__index__]};ao.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};ao.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};ao.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===ho){return ho}return this.__vector__.slice(this.__index__,e)};function uo(){if(typeof this!=="undefined"&&!(this instanceof uo)||typeof this==="undefined"){return new uo}s(this,"__type__",fo);s(this,"_buffer",[],{hidden:true});this.write=function(e){A("write",e,["number","uint8array"]);if(B.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,ee(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}uo.prototype=Object.create(Xu.prototype);uo.prototype.constructor=uo;uo.prototype.close=function(){Xu.prototype.close.call(this);s(this,"_buffer",null,{hidden:true})};uo.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};uo.prototype.write_u8=function(e){A("OutputByteVectorPort::write_u8",e,"number");this.write(e)};uo.prototype.write_u8_vector=function(e){A("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};uo.prototype.toString=function(){return"#"};uo.prototype.valueOf=function(){return this.__buffer__};function oo(e,t){if(typeof this!=="undefined"&&!(this instanceof oo)||typeof this==="undefined"){return new oo(e,t)}no.call(this,e);A("InputFilePort",t,"string");s(this,"__filename__",t)}oo.prototype=Object.create(no.prototype);oo.prototype.constructor=oo;oo.prototype.toString=function(){return"#")};function so(e,t){if(typeof this!=="undefined"&&!(this instanceof so)||typeof this==="undefined"){return new so(e,t)}ao.call(this,e);A("InputBinaryFilePort",t,"string");s(this,"__filename__",t)}so.prototype=Object.create(ao.prototype);so.prototype.constructor=so;so.prototype.toString=function(){return"#")};function co(e,t){var i=this;if(typeof this!=="undefined"&&!(this instanceof co)||typeof this==="undefined"){return new co(e,t)}A("OutputBinaryFilePort",e,"string");s(this,"__filename__",e);s(this,"_fd",t.valueOf(),{hidden:true});s(this,"__type__",fo);var a;this.write=function(e){A("write",e,["number","uint8array"]);var n;if(!a){a=i.internal("fs")}if(B.isNumber(e)){n=new Uint8Array([e.valueOf()])}else{n=new Uint8Array(Array.from(e))}return new Promise(function(t,r){a.write(i._fd,n,function(e){if(e){r(e)}else{t()}})})}}co.prototype=Object.create(ro.prototype);co.prototype.constructor=co;co.prototype.write_u8=function(e){A("OutputByteVectorPort::write_u8",e,"number");this.write(e)};co.prototype.write_u8_vector=function(e){A("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var fo=Symbol["for"]("binary");var lo=Symbol["for"]("text");var ho=new _o;function _o(){}_o.prototype.toString=function(){return"#"};function po(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.stderr,i=r.stdin,a=r.stdout,u=r.command_line,o=u===void 0?null:u,s=_e(r,Cr);if(typeof this!=="undefined"&&!(this instanceof po)||typeof this==="undefined"){return new po(e,te({stdin:i,stdout:a,stderr:n,command_line:o},s))}if(typeof e==="undefined"){e="anonymous"}this.__env__=Co.inherit(e,s);this.__parser__=new di({env:this.__env__});this.__env__.set("parent.frame",l("parent.frame",function(){return t.__env__},se.__env__["parent.frame"].__doc__));var c="**interaction-environment-defaults**";this.set(c,ca(s).concat(c));var f=Ao.inherit("internal-".concat(e));if(au(i)){f.set("stdin",i)}if(au(n)){f.set("stderr",n)}if(au(a)){f.set("stdout",a)}f.set("command-line",o);So(this.__env__,f)}po.prototype.exec=function(){var t=H(function(u){var o=this;var s=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return O.mark(function e(){var r,n,i,a;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=s.use_dynamic,n=r===void 0?false:r,i=s.dynamic_env,a=s.env;A("Interpreter::exec",u,["string","array"],1);A("Interpreter::exec",n,"boolean",2);if(!a){a=o.__env__}if(!i){i=a}se.set("**interaction-environment**",o.__env__);if(!Array.isArray(u)){t.next=10;break}return t.abrupt("return",os(u,{env:a,dynamic_env:i,use_dynamic:n}));case 10:o.__parser__.parse(u);return t.abrupt("return",os(o.__parser__,{env:a,dynamic_env:i,use_dynamic:n}));case 12:case"end":return t.stop()}},e)})()});return function(e){return t.apply(this,arguments)}}();po.prototype.get=function(e){var t=this.__env__.get(e);if(d(t)){var r=new ns({env:this.__env__});return t.bind(r)}return t};po.prototype.set=function(e,t){return this.__env__.set(e,t)};po.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function vo(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}vo.prototype=new Error;vo.prototype.constructor=vo;var yo=function(e){J(t,e);function t(){Q(this,t);return Nr(this,t,arguments)}return fe(t)}(W(Error));function F(e,t,r){if(arguments.length===1){if(_(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}F.prototype.list=function(){return ca(this.__env__)};F.prototype.fs=function(){return this.get("**fs**")};F.prototype.unset=function(e){if(e instanceof ne){e=e.valueOf()}if(e instanceof x){e=e.valueOf()}delete this.__env__[e]};F.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_(e)==="object"){t=e}if(!e||_(e)==="object"){e="child of "+(this.__name__||"unknown")}return new F(t||{},this,e)};F.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof ne){e=e.__name__}if(e instanceof x){e=e.valueOf()}if(t){if(!r){t=Fi(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};F.prototype.new_frame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",l("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!Ra(t)){return ie}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},se.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};F.prototype._lookup=function(e){if(e instanceof ne){e=e.__name__}if(e instanceof x){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return mo(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};F.prototype.toString=function(){return"#"};F.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new F(r,this.__parent__,this.__name__)};F.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";A("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function mo(e){if(typeof this!=="undefined"&&!(this instanceof mo)||typeof this==="undefined"){return new mo(e)}this.value=e}mo.isUndefined=function(e){return e instanceof mo&&typeof e.value==="undefined"};mo.prototype.valueOf=function(){return this.value};function go(e){if(!e.length){return}if(e.length===1){return e[0]}if(typeof this!=="undefined"&&!(this instanceof go)||typeof this==="undefined"){return new go(e)}this.__values__=e}go.prototype.toString=function(){return this.__values__.map(function(e){return pa(e)}).join("\n")};go.prototype.valueOf=function(){return this.__values__};F.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};A("Environment::get",e,["symbol","string"]);var r=t.throwError,n=r===void 0?true:r;var i=e;if(i instanceof ne||i instanceof x){i=i.valueOf()}var a=this._lookup(i);if(a instanceof mo){if(mo.isUndefined(a)){return undefined}return Xa(a.valueOf())}var u;if(e instanceof ne&&e[ne.object]){u=e[ne.object]}else if(typeof i==="string"){u=i.split(".").filter(Boolean)}if(u&&u.length>0){var o=u,s=V(o),c=s[0],f=s.slice(1);a=this._lookup(c);if(f.length){try{if(a instanceof mo){a=a.valueOf()}else{a=Do(Vr,c);if(d(a)){a=eu(a)}}if(typeof a!=="undefined"){return Do.apply(void 0,[a].concat(ee(f)))}}catch(e){throw e}}else if(a instanceof mo){return Xa(a.valueOf())}a=Do(Vr,i)}if(typeof a!=="undefined"){return a}if(n){throw new Error("Unbound variable `"+i.toString()+"'")}};F.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;A("Environment::set",e,["string","symbol"]);if(B.isNumber(t)){t=B(t)}if(e instanceof ne){e=e.__name__}if(e instanceof x){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};F.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&ta(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};F.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};F.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};F.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function bo(e){if(za(e)){return e.then(bo)}if(oe(e)||e instanceof ne){e[cu]=true}return e}var wo=mi(Kn('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var Do=l("get",function e(t){var r;for(var n=arguments.length,i=new Array(n>1?n-1:0),a=1;a0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Eo(this,"stdin")}Yo("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":l("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Eo(this,"stdin")}Yo("read-line",e,"input-port");return e.read_line()},"(read-line port)\n\n This function reads and returns the next line from the input\n port."),"read-char":l("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Eo(this,"stdin")}Yo("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:l("read",function(){var e=H(function(){var i=this;var a=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;return O.mark(function e(){var r,n;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=i.env;if(a===null){n=Eo(r,"stdin")}else{n=a}Yo("read",n,"input-port");return t.abrupt("return",n.read.call(r));case 4:case"end":return t.stop()}},e)})()});function t(){return e.apply(this,arguments)}return t}(),"(read [port])\n\n This function, if called with a port, it will parse the next\n item from the port. If called without an input, it will read\n a string from standard input (using the browser's prompt or\n a user defined input method) and parse it. This function can be\n used together with `eval` to evaluate code from port."),pprint:l("pprint",function e(t){if(oe(t)){t=new Vs.Formatter(t.toString(true))["break"]().format();se.get("display").call(se,t)}else{se.get("write").call(se,t)}se.get("newline").call(se)},"(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."),print:l("print",function e(){var t=se.get("display");var r=se.get("newline");var n=this.use_dynamic;var i=se;var a=se;for(var u=arguments.length,o=new Array(u),s=0;s1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var o=0;var s=se.get("repr");t=t.replace(a,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[o++];if(t==="a"){return s(r)}else{return s(r,true)}}});u=t.match(/~([\S])/);if(u){throw new Error("format: Unrecognized escape sequence ".concat(u[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),newline:l("newline",function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var r=se.get("display");var n=this.use_dynamic;var i=se;var a=se;Xo(r,["\n",t],{env:i,dynamic_env:a,use_dynamic:n})},"(newline [port])\n\n Write newline character to standard output or given port"),display:l("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=Eo(this,"stdout")}else{A("display",r,"output-port")}var n=t;if(!(r instanceof co)){n=se.get("repr")(t)}r.write.call(se,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."),"display-error":l("display-error",function e(){var t=Eo(this,"stderr");var r=se.get("repr");for(var n=arguments.length,i=new Array(n),a=0;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=_e(t,Sr);var i=this;var u=this;var o;var s=te(te({},n),{},{env:this,dynamic_env:i,use_dynamic:r});var c=k(e.cdr.car,s);c=Wo(c);function f(t,r,n){if(za(t)){return t.then(function(e){return f(t,e,n)})}if(za(r)){return r.then(function(e){return f(t,e,n)})}if(za(n)){return n.then(function(e){return f(t,r,e)})}u.get("set-obj!").call(u,t,r,n);return n}if(oe(e.car)&&ne.is(e.car.car,".")){var l=e.car.cdr.car;var h=e.car.cdr.cdr.car;var _=k(l,s);var p=k(h,s);return f(_,p,c)}if(!(e.car instanceof ne)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var d=e.car.valueOf();o=this.ref(e.car.__name__);return D(c,function(e){if(!o){var t=d.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=a.get(n,{throwError:false});if(i){f(i,r,e);return}}throw new Error("Unbound variable `"+d+"'")}o.set(d,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non empty slot and sets it."),"unset!":l(new q("set!",function(e){if(!(e.car instanceof ne)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."),"set-car!":l("set-car!",function(e,t){A("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."),"set-cdr!":l("set-cdr!",function(e,t){A("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."),"empty?":l("empty?",function(e){return typeof e==="undefined"||ue(e)},"(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."),gensym:l("gensym",Zn,"(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."),load:l("load",function e(c,t){A("load",c,"string");var f=this;if(f.__name__==="__frame__"){f=f.__parent__}if(!(t instanceof F)){if(f===se){t=f}else{t=this.get("**interaction-environment**")}}var l="@lips";var h=c.startsWith(l);var _="**module-path**";var p=se.get(_,{throwError:false});c=c.valueOf();if(!c.match(/.[^.]+$/)){c+=".scm"}var r=c.match(/\.xcb$/);function d(e){if(r){e=Ns(e)}else{if(Ko(e)==="buffer"){e=e.toString()}e=e.replace(/^(#!.*)/,function(e,t){if(Ba(t)){return t}return""});if(e.match(/^\{/)){e=Os(e)}}return os(e,{env:t})}function n(e){return Vr.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}function v(){var e=se.get("__dirname");return e.replace(/[^/]+$/,"")}if(To()){return new Promise(function(){var r=H(O.mark(function e(r,n){var i,a,u,o,s;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.prev=0;t.next=3;return qo;case 3:i=Wr("path");a=Wr("fs");u=v();if(h){c=c.replace(l,u)}if(!p){t.next=12;break}p=p.valueOf();if(!c.startsWith("/")){c=i.join(p,c)}t.next=19;break;case 12:if(c.startsWith("/")){t.next=19;break}o=f.get("command-line",{throwError:false});if(!o){t.next=18;break}t.next=17;return o();case 17:s=t.sent;case 18:if(s&&!ue(s)){process.cwd();c=i.join(i.dirname(s.car.valueOf()),c)}case 19:se.set(_,i.dirname(c));a.readFile(c,function(e,t){if(e){n(e);se.set(_,p)}else{try{d(t).then(function(){r();se.set(_,p)})["catch"](n)}catch(e){n(e)}}});t.next=26;break;case 23:t.prev=23;t.t0=t["catch"](0);console.error(t.t0);case 26:case"end":return t.stop()}},e,null,[[0,23]])}));return function(e,t){return r.apply(this,arguments)}}())}if(h){var i,a;var u=(i=se.get("__dirname",{throwError:false}))!==null&&i!==void 0?i:ps;(a=u)!==null&&a!==void 0?a:u=ps;var o=u.replace(/dist\/?[^\/]*$/,"");c=c.replace(l,o)}if(p){p=p.valueOf();if(!c.startsWith("/")){c=p+"/"+c.replace(/^\.?\/?/,"")}}return n(c).then(function(e){se.set(_,c.replace(/\/[^/]*$/,""));return d(e)}).then(function(){})["finally"](function(){se.set(_,p)})},"(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."),while:l(new q("while",function(e,t){var r=e.car;var n=te(te({},t),{},{env:this});var i=new ae(new ne("begin"),e.cdr);return function t(){return D(k(r,n),function(e){if(e){return D(k(i,n),t)}})}()}),"(while cond body)\n\n Creates a loop, it executes cond and body until cond expression is false."),do:l(new q("do",function(){var r=H(function(h,e){var _=this;var p=e.use_dynamic,d=e.error;return O.mark(function e(){var o,r,s,c,n,f,l,i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:o=_;r=o;s=o.inherit("do");c=h.car;n=h.cdr.car;f=h.cdr.cdr;if(!ue(f)){f=new ae(ne("begin"),f)}l={env:o,dynamic_env:r,use_dynamic:p,error:d};i=c;case 9:if(ue(i)){t.next=20;break}a=i.car;t.t0=s;t.t1=a.car;t.next=15;return k(a.cdr.car,l);case 15:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);i=i.cdr;t.next=9;break;case 20:l={env:s,dynamic_env:r,error:d};u=O.mark(function e(){var r,n,i,a,u;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(ue(f)){t.next=3;break}t.next=3;return Vs.evaluate(f,l);case 3:r=c;n={};case 5:if(ue(r)){t.next=15;break}i=r.car;if(ue(i.cdr.cdr)){t.next=12;break}t.next=10;return k(i.cdr.cdr.car,l);case 10:a=t.sent;n[i.car.valueOf()]=a;case 12:r=r.cdr;t.next=5;break;case 15:u=Object.getOwnPropertySymbols(n);l.env=s=o.inherit("do");Object.keys(n).concat(u).forEach(function(e){s.set(e,n[e])});case 18:case"end":return t.stop()}},e)});case 22:t.next=24;return k(n.car,l);case 24:t.t3=t.sent;if(!(t.t3===false)){t.next=29;break}return t.delegateYield(u(),"t4",27);case 27:t.next=22;break;case 29:if(ue(n.cdr)){t.next=33;break}t.next=32;return k(n.cdr.car,l);case 32:return t.abrupt("return",t.sent);case 33:case"end":return t.stop()}},e)})()});return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will\n evaluate and return the second expression after the loop exits."),if:l(new q("if",function(r,e){var t=e.error,n=e.use_dynamic;var i=this;var a=this;var u={env:a,dynamic_env:i,use_dynamic:n,error:t};var o=function e(t){if(Ia(t)){return k(r.cdr.cdr.car,u)}else{return k(r.cdr.car,u)}};if(ue(r)){throw new Error("too few expressions for `if`")}var s=k(r.car,u);return D(s,o)}),"(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."),"let-env":new q("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_env,n=e.use_dynamic,i=e.error;A("let-env",t,"pair");var a=k(t.car,{env:this,dynamic_env:r,error:i,use_dynamic:n});return D(a,function(e){A("let-env",e,"environment");return k(ae(ne("begin"),t.cdr),{env:e,dynamic_env:r,error:i})})},"(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."),letrec:l(Eu(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentially and the next value can access the\n previous values/names."),"letrec*":l(Eu(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."),"let*":l(Eu(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."),let:l(Eu(Symbol["for"]("let")),"(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to names,\n and then evaluates the body in context of that environment. Values are evaluated\n sequentially but you can't access previous values/names when the next are\n evaluated. You can only get them in the body of the let expression. (If you want\n to define multiple variables and use them in each other's definitions, use\n `let*`.)"),"begin*":l(Fu("begin*",function(e){return e.pop()}),"(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return\n the value of the last expression (i.e. it uses Promise.all())."),shuffle:l("shuffle",function(e){A("shuffle",e,["pair","nil","array"]);var t=se.get("random");if(ue(e)){return ie}if(Array.isArray(e)){return Qi(e.slice(),t)}var r=se.get("list->array")(e);r=Qi(r,t);return se.get("array->list")(r)},"(shuffle obj)\n\n Order items in vector or list in random order."),begin:l(new q("begin",function(e,t){var n=te(te({},t),{},{env:this});var i=se.get("list->array")(e);var a;return function t(){if(i.length){var e=i.shift();var r=k(e,n);return D(r,function(e){a=e;return t()})}else{return a}}()}),"(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."),ignore:new q("ignore",function(e,t){var r=te(te({},t),{},{env:this,dynamic_env:this});k(new ae(new ne("begin"),e),r)},"(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It will discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":l(q.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=te({env:this},t);return D(k(e.car,r),function(e){if(d(e)){return e(new as(null))}})}),"(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORTED BY LIPS RIGHT NOW"),parameterize:l(new q("parameterize",function(t,e){var i=e.dynamic_env;var a=i.inherit("parameterize").new_frame(null,{});var u=te(te({},e),{},{env:this});var o=t.car;if(!oe(o)){var r=Ko(o);throw new Error("Invalid syntax for parameterize expecting pair got ".concat(r))}function s(){var e=new ae(new ne("begin"),t.cdr);return k(e,te(te({},u),{},{dynamic_env:a}))}return function r(){var e=o.car;var n=e.car.valueOf();return D(k(e.cdr.car,u),function(e){var t=i.get(n,{throwError:false});if(!Ma(t)){throw new Error("Unknown parameter ".concat(n))}a.set(n,t.inherit(e));if(!ja(o.cdr)){o=o.cdr;return r()}else{return s()}})}()}),"(parameterize ((name value) ...)\n\n Macro that change the dynamic variable created by make-parameter."),"make-parameter":l(new q("make-parameter",function(e,t){t.dynamic_env;var r=k(e.car,t);var n;if(oe(e.cdr.car)){n=k(e.cdr.car,t)}return new rs(r,n)}),"(make-parameter init converter)\n\n Function creates new dynamic variable that can be custimized with parameterize\n macro. The value should be assigned to a variable e.g.:\n\n (define radix (make-parameter 10))\n\n The result value is a procedure that return the value of dynamic variable."),"define-syntax-parameter":l(new q("define-syntax-parameter",function(e,t){var r=e.car;var n=this;if(!(r instanceof ne)){throw new Error("define-syntax-parameter: invalid syntax expecting symbol got ".concat(Ko(r)))}var i=k(e.cdr.car,te({env:n},t));A("define-syntax-parameter",i,"syntax",2);i.__name__=r.valueOf();if(i.__name__ instanceof x){i.__name__=i.__name__.valueOf()}var a;if(oe(e.cdr.cdr)&&x.isString(e.cdr.cdr.car)){a=e.cdr.cdr.car.valueOf()}n.set(e.car,new ka(i),a,true)}),"(define-syntax-parameter name syntax [__doc__])\n\n Binds to the transformer obtained by evaluating .\n The transformer provides the default expansion for the syntax parameter,\n and in the absence of syntax-parameterize, is functionally equivalent to\n define-syntax."),"syntax-parameterize":l(new q("syntax-parameterize",function(e,t){var r=se.get("list->array")(e.car);var n=this.inherit("syntax-parameterize");while(r.length){var i=r.shift();if(!(oe(i)||i.car instanceof ne)){var a="invalid syntax for syntax-parameterize: ".concat(ea(e,true));throw new Error("syntax-parameterize: ".concat(a))}var u=k(i.cdr.car,te(te({},t),{},{env:this}));var o=i.car;A("syntax-parameterize",u,["syntax"]);A("syntax-parameterize",o,"symbol");u.__name__=o.valueOf();if(u.__name__ instanceof x){u.__name__=u.__name__.valueOf()}var s=new ka(u);if(o.is_gensym()){var c=o.literal();var f=this.get(c,{throwError:false});if(f instanceof ka){n.set(c,s)}}n.set(o,s)}var l=Xn([n,t.dynamic_env],e.cdr);return k(l,te(te({},t),{},{env:n}))}),"(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),define:l(q.defmacro("define",function(r,e){var n=this;if(oe(r.car)&&r.car.car instanceof ne){var t=new ae(new ne("define"),new ae(r.car.car,new ae(new ae(new ne("lambda"),new ae(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}e.dynamic_env=this;e.env=n;var i=r.cdr.car;var a;if(oe(i)){i=k(i,e);a=true}else if(i instanceof ne){i=n.get(i)}A("define",r.car,"symbol");return D(i,function(e){if(n.__name__===Aa.__merge_env__){n=n.__parent__}if(a&&(d(e)&&bu(e)||e instanceof Aa||Ma(e))){e.__name__=r.car.valueOf();if(e.__name__ instanceof x){e.__name__=e.__name__.valueOf()}}var t;if(oe(r.cdr.cdr)&&x.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`'),"set-obj!":l("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_(e);if(ja(e)||i!=="object"&&i!=="function"){var a=Uo("set-obj!",Ko(e),["object","function"]);throw new Error(a)}A("set-obj!",t,["string","symbol","number"]);e=eu(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(Na(e)&&d(r)){e[t]=eu(r);e[t][pu]=true}else if(d(r)||Wa(r)||ue(r)){e[t]=r}else{e[t]=r&&!Na(r)?r.valueOf():r}if(ra){var u=e[t];Object.defineProperty(e,t,te(te({},n),{},{value:u}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."),"null-environment":l("null-environment",function(){return se.inherit("null")},"(null-environment)\n\n Returns a clean environment with only the standard library."),values:l("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},y=e.use_dynamic,m=e.error;var g=this;var b;if(oe(v.cdr)&&x.isString(v.cdr.car)&&!ue(v.cdr.cdr)){b=v.cdr.car.valueOf()}function w(){var e=La(this)?this:{dynamic_env:g},r=e.dynamic_env;var n=g.inherit("lambda");r=r.inherit("lambda");if(this&&!La(this)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}n.set("this",this)}for(var t=arguments.length,i=new Array(t),a=0;a> SYNTAX");re(e);re(m);var n=w.inherit("syntax");var i=n;var a=this;if(a.__name__===Aa.__merge_env__){var u=Object.getOwnPropertySymbols(a.__env__);u.forEach(function(e){a.__parent__.set(e,a.__env__[e])});a=a.__parent__}var o={env:n,dynamic_env:i,use_dynamic:g,error:b};var s,c,f;if(m.car instanceof ne){s=m.car;f=D(m.cdr.car);c=m.cdr.cdr}else{s="...";f=D(m.car);c=m.cdr}try{while(!ue(c)){var l=c.car.car;var h=c.car.cdr.car;re("[[[ RULE");re(l);var _=Oa(l,e,f,s,{expansion:this,define:w});if(_){if(Qr()){console.log(JSON.stringify(sa(_),true,2));console.log("PATTERN: "+l.toString(true));console.log("MACRO: "+e.toString(true))}var p=[];var d=Sa({bindings:_,expr:h,symbols:f,scope:n,lex_scope:a,names:p,ellipsis:s});re("OUPUT>>> ",d);if(d){h=d}var v=a.merge(n,Aa.__merge_env__);if(r){return{expr:h,scope:v}}var y=k(h,te(te({},o),{},{env:v}));return Ca(y,p)}c=c.cdr}}catch(e){e.message+="\nin macro:\n ".concat(m.toString(true));throw e}throw new Error("syntax-rules: no matching syntax in macro ".concat(e.toString(true)))},w);r.__code__=m;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."),quote:l(new q("quote",function(e){return bo(e.car)}),"(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."),"unquote-splicing":l("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the\n expression, the computed value must be a pair."),unquote:l("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."),quasiquote:q.defmacro("quasiquote",function(e,t){var o=t.use_dynamic,s=t.error;var c=this;var f=c;function a(e){return oe(e)||ta(e)||Array.isArray(e)}function l(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(oe(e)){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(za(n)||za(i)){return ti([n,i]).then(function(e){var t=b(e,2),r=t[0],n=t[1];return new ae(r,n)})}else{return new ae(n,i)}}return e}function u(e,t){if(oe(e)){if(!ue(t)){e.append(t)}}else{e=new ae(e,t)}return e}function r(e){return!!e.filter(function(e){return oe(e)&&ne.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function h(e,n,i){return e.reduce(function(e,t){if(!oe(t)){e.push(t);return e}if(ne.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(oe(i.cdr)&&ue(r[0]))){return r[0]}}r=r.map(function(e){if(d.has(e)){return e.clone()}else{d.add(e);return e}});var n=v(i.cdr,0,1);if(ue(n)&&ue(r[0])){return undefined}return D(n,function(e){if(ue(r[0])){return e}if(r.length===1){return u(r[0],e)}var t=r.reduce(function(e,t){return u(e,t)});return u(t,e)})})}(i.car.cdr)}var d=new Set;function v(e,t,r){if(oe(e)){if(oe(e.car)){if(ne.is(e.car.car,"unquote-splicing")){return p(e,t+1,r)}if(ne.is(e.car.car,"unquote")){if(t+2===r&&oe(e.car.cdr)&&oe(e.car.cdr.car)&&ne.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new ae(new ae(new ne("unquote"),p(n,t+2,r)),ie)}else if(oe(e.car.cdr)&&!ue(e.car.cdr.cdr)){if(oe(e.car.cdr.car)){var i=[];return function t(r){if(ue(r)){return ae.fromArray(i)}return D(k(r.car,{env:c,dynamic_env:f,use_dynamic:o,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(ne.is(e.car,"quasiquote")){var a=v(e.cdr,t,r+1);return new ae(e.car,a)}if(ne.is(e.car,"quote")){return new ae(e.car,v(e.cdr,t,r))}if(ne.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(oe(e.cdr)){if(!ue(e.cdr.cdr)){if(oe(e.cdr.car)){var u=[];return function t(r){if(ue(r)){return ae.fromArray(u)}return D(k(r.car,{env:c,dynamic_env:f,use_dynamic:o,error:s}),function(e){u.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return k(e.cdr.car,{env:c,dynamic_env:f,error:s})}}else{return e.cdr}}return l(e,function(e){return v(e,t,r)})}else if(ta(e)){return _(e,t,r)}else if(e instanceof Array){return h(e,t,r)}return e}function n(e){if(oe(e)){delete e[cu];if(!e.have_cycles("car")){n(e.car)}if(!e.have_cycles("cdr")){n(e.cdr)}}}if(ta(e.car)&&!r(Object.values(e.car))){return bo(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return bo(e.car)}if(oe(e.car)&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return bo(e.car)}var i=v(e.car,0,1);return D(i,function(e){n(e);return bo(e)})},"(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special expressions (unquote\n x) abbreviated to ,x that will evaluate x and insert its value verbatim or\n (unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\n into the result. Best used with macros but it can be used outside."),clone:l("clone",function e(t){A("clone",t,"pair");return t.clone()},"(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),append:l("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return se.get("array->list")(r)}else if(Array.isArray(t)){return t.reverse()}else{throw new Error(Uo("reverse",Ko(t),"array or pair"))}},"(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."),nth:l("nth",function e(t,r){A("nth",t,"number");A("nth",r,["array","pair"]);if(oe(r)){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function that returns a string by joining elements of the list using separator."),split:l("split",function e(t,r){A("split",t,["regex","string"]);A("split",r,"string");return se.get("array->list")(r.split(t))},"(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."),replace:l("replace",function e(t,r,n){A("replace",t,["regex","string"]);A("replace",r,["string","function"]);A("replace",n,"string");if(d(r)){var i=[];n.replace(t,function(){i.push(r.apply(void 0,arguments))});return D(i,function(e){return n.replace(t,function(){return e.shift()})})}return n.replace(t,r)},"(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a\n string or regex and replacement can be function or string. See Javascript\n String.replace()."),match:l("match",function e(t,r){A("match",t,["regex","string"]);A("match",r,"string");var n=r.match(t);return n?se.get("array->list")(n):false},"(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if\n no match."),search:l("search",function e(t,r){A("search",t,["regex","string"]);A("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."),repr:l("repr",function e(t,r){return pa(t,r)},"(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."),"escape-regex":l("escape-regex",function(e){A("escape-regex",e,"string");return qn(e.valueOf())},"(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."),env:l("env",function e(e){e=e||this.env;var t=Object.keys(e.__env__).map(ne);var r;if(t.length){r=ae.fromArray(t)}else{r=ie}if(e.__parent__ instanceof F){return se.get("env").call(this,e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."),new:l("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:ii.LITERAL;A("set-special!",e,"string",1);A("set-special!",t,"symbol",2);ii.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors.'),get:Do,".":Do,unbind:l(eu,"(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."),type:l(Ko,"(type object)\n\n Function that returns the type of an object as string."),debugger:l("debugger",function(){debugger},'(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the "debugger;" statement. If a debugger is not running this\n function does nothing.'),in:l("in",function(e,t){if(e instanceof ne||e instanceof x||e instanceof B){e=e.valueOf()}return e in Za(t)},'(in key value)\n\n Function that uses the Javascript "in" operator to check if key is\n a valid property in the value.'),"instance?":l("instance?",function(e){return Ja(e)},"(instance? obj)\n\n Checks if object is an instance, created with a new operator"),instanceof:l("instanceof",function(e,t){return t instanceof eu(e)},"(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."),"prototype?":l("prototype?",Na,"(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."),"macro?":l("macro?",function(e){return e instanceof q},"(macro? expression)\n\n Predicate that tests if value is a macro."),"continuation?":l("continuation?",Ta,"(continuation? expression)\n\n Predicate that tests if value is a callable continuation."),"function?":l("function?",d,"(function? expression)\n\n Predicate that tests if value is a callable function."),"real?":l("real?",function(e){if(Ko(e)!=="number"){return false}if(e instanceof B){return e.isFloat()}return B.isFloat(e)},"(real? number)\n\n Predicate that tests if value is a real number (not complex)."),"number?":l("number?",function(e){return Number.isNaN(e)||B.isNumber(e)},"(number? expression)\n\n Predicate that tests if value is a number or NaN value."),"string?":l("string?",function(e){return x.isString(e)},"(string? expression)\n\n Predicate that tests if value is a string."),"pair?":l("pair?",oe,"(pair? expression)\n\n Predicate that tests if value is a pair or list structure."),"regex?":l("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Predicate that tests if value is a regular expression."),"null?":l("null?",function(e){return ja(e)},"(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or\n Javascript null)."),"boolean?":l("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."),"symbol?":l("symbol?",function(e){return e instanceof ne},"(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."),"array?":l("array?",function(e){return e instanceof Array},"(array? expression)\n\n Predicate that tests if value is an array."),"object?":l("object?",function(e){return!ue(e)&&e!==null&&!(e instanceof h)&&!(e instanceof RegExp)&&!(e instanceof x)&&!oe(e)&&!(e instanceof B)&&_(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."),flatten:l("flatten",function e(t){A("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Returns a shallow list from tree structure (pairs)."),"vector-append":l("vector-append",function(){for(var e=arguments.length,t=new Array(e),r=0;rlist":l("array->list",function(e){A("array->list",e,"array");return ae.fromArray(e)},"(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."),"tree->array":l("tree->array",Xi("tree->array",true),"(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."),"list->array":l("list->array",Xi("list->array"),"(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."),apply:l("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,a));return t.apply(this,Zo(t,n))},"(apply fn list)\n\n Function that calls fn with the list of arguments."),length:l("length",function e(t){if(!t||ue(t)){return 0}if(oe(t)){return t.length()}if("length"in t){return t.length}},'(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a "length" property. Returns undefined if the\n length could not be found.'),"string->number":l("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;A("string->number",e,"string",1);A("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(wn)||e.match(mn)){return An(e,t)}else if(e.match(Dn)||e.match(yn)){return Cn(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(bn)&&r||e.match(gn)){return kn(e,t)}if(e.match(un)){return In(e)}}return false},"(string->number number [radix])\n\n Function that parses a string into a number."),try:l(new q("try",function(r,e){var l=this;var h=e.use_dynamic;e.error;return new Promise(function(t,o){var s,n;if(ne.is(r.cdr.car.car,"catch")){s=r.cdr.car;if(oe(r.cdr.cdr)&&ne.is(r.cdr.cdr.car.car,"finally")){n=r.cdr.cdr.car}}else if(ne.is(r.cdr.car.car,"finally")){n=r.cdr.car}if(!(n||s)){throw new Error("try: invalid syntax")}function c(e){t(e);throw new yo("[CATCH]")}var f=function e(t,r){r(t)};if(n){f=function e(t,r){f=o;i.error=function(e){throw e};D(k(new ae(new ne("begin"),n.cdr),i),function(){r(t)})}}var i={env:l,use_dynamic:h,dynamic_env:l,error:function e(t){if(t instanceof yo){throw t}if(s){var r=l.inherit("try");var n=s.cdr.car.car;if(!(n instanceof ne)){throw new Error("try: invalid syntax: catch require variable name")}r.set(n,t);var i;var a={env:r,use_dynamic:h,dynamic_env:l,error:function e(t){i=true;o(t);throw new yo("[CATCH]")}};var u=k(new ae(new ne("begin"),s.cdr.cdr),a);D(u,function e(t){if(!i){f(t,c)}})}else{f(undefined,function(){o(t)})}}};var e=k(r.car,i);D(e,function(e){f(e,t)},i.error)})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thrown. If finally is provided it's always\n executed at the end."),raise:l("raise",function(e){throw e},"(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."),throw:l("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws a new exception."),find:l("find",function t(r,n){A("find",r,["regex","function"]);A("find",n,["pair","nil"]);if(ja(n)){return ie}var e=Ei("find",r);return D(e(n.car),function(e){if(e&&!ue(e)){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."),"for-each":l("for-each",function(e){var t;A("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),a=1;a3?n-3:0),a=3;a3?i-3:0),u=3;uarray")(r);var a=[];var u=Ei("filter",t);return function t(r){function e(e){if(e&&!ue(e)){a.push(n)}return t(++r)}if(r===i.length){return ae.fromArray(a)}var n=i[r];return D(u(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."),compose:l(Ou,"(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"),pipe:l(ku,"(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"),curry:l(Pu,"(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have partially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\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))"),gcd:l("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;no?a%=o:o%=a}a=ya(s*r[u])/(a+o)}return B(a)},"(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."),"odd?":l("odd?",ju(function(e){return B(e).isOdd()}),"(odd? number)\n\n Checks if number is odd."),"even?":l("even?",ju(function(e){return B(e).isEven()}),"(even? number)\n\n Checks if number is even."),"*":l("*",Iu(function(e,t){return B(e).mul(t)},B(1)),"(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."),"+":l("+",Iu(function(e,t){return B(e).add(t)},B(0)),"(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."),"-":l("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":l(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,["bigint","float","rational"]);return ma(function(e,t){return B(e).cmp(t)===1},t)},"(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."),"<":l("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":l(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,["bigint","float","rational"]);return ma(function(e,t){return[0,1].includes(B(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."),"eq?":l("eq?",ga,"(eq? a b)\n\n Function that compares two values if they are identical."),or:l(new q("or",function(e,t){var i=t.use_dynamic,a=t.error;var u=se.get("list->array")(e);var o=this;var s=o;if(!u.length){return false}var c;return function t(){function e(e){c=e;if(!Ia(c)){return c}else{return t()}}if(!u.length){if(!Ia(c)){return c}else{return false}}else{var r=u.shift();var n=k(r,{env:o,dynamic_env:s,use_dynamic:i,error:a});return D(n,e)}}()}),"(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."),and:l(new q("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.use_dynamic,n=t.error;var i=se.get("list->array")(e);var a=this;var u=a;if(!i.length){return true}var o;var s={env:a,dynamic_env:u,use_dynamic:r,error:n};return function t(){function e(e){o=e;if(Ia(o)){return o}else{return t()}}if(!i.length){if(!Ia(o)){return o}else{return false}}else{var r=i.shift();return D(k(r,s),e)}}()}),"(and . expressions)\n\n Macro that evaluates each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."),"|":l("|",function(e,t){return B(e).or(t)},"(| a b)\n\n Function that calculates the bitwise or operation."),"&":l("&",function(e,t){return B(e).and(t)},"(& a b)\n\n Function that calculates the bitwise and operation."),"~":l("~",function(e){return B(e).neg()},"(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."),">>":l(">>",function(e,t){return B(e).shr(t)},"(>> a b)\n\n Function that right shifts the value a by value b bits."),"<<":l("<<",function(e,t){return B(e).shl(t)},"(<< a b)\n\n Function that left shifts the value a by value b bits."),not:l("not",function e(t){return!t},"(not object)\n\n Function that returns the Boolean negation of its argument.")},undefined,"global");var Co=se.inherit("user-env");function So(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error.");se.set("**interaction-environment**",e)}So(Co,Ao);se.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr.");function jo(e){Co.get("**internal-env**").set("fs",e)}(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;se.set(r,l(r,function(e){A(r,e,"number");if(e instanceof B){return e[t]()}},"(".concat(r," number)\n\n Function that calculates the ").concat(r," of a number.")))})})();function Bo(e){if(e.length===1){return e[0]}else{var t=[];var r=Bo(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(d(r)){return"Invalid type: got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){var a=r[0].toLowerCase();r="a"+("aeiou".includes(a)?"n ":" ")+r[0]}else{r=new Intl.ListFormat("en",{style:"long",type:"disjunction"}).format(r)}}return"Expecting ".concat(r," got ").concat(t).concat(i)}function zo(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;A(e,t,"number",n);var i=t.__type__;var a;if(oe(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(Uo(e,i,r,n))}}function Vo(r,e,n){e.forEach(function(e,t){zo(r,e,n,t+1)})}function $o(r,e,n){e.forEach(function(e,t){A(r,e,n,t+1)})}function Yo(e,t,r){A(e,t,r);if(t.__type__===fo){throw new Error(Uo(e,"binary-port","textual-port"))}}function A(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=Ko(t).toLowerCase();if(d(r)){if(!r(t)){throw new Error(Uo(e,i,r,n))}return}var a=false;if(oe(r)){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){a=true}}else{r=r.valueOf().toLowerCase()}if(!a&&i!==r){throw new Error(Uo(e,i,r,n))}}function Jo(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}Ko=Jo(Ko);function Ko(e){var t=Yr.get(e);if(t){return t}if(_(e)==="object"){for(var r=0,n=Object.entries($r);r2&&arguments[2]!==undefined?arguments[2]:{},n=r.env,i=r.dynamic_env,a=r.use_dynamic;var u=n===null||n===void 0?void 0:n.new_frame(e,t);var o=i===null||i===void 0?void 0:i.new_frame(e,t);var s=new ns({env:u,use_dynamic:a,dynamic_env:o});return Wo(e.apply(s,t))}function es(n,e){var t=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},i=t.env,a=t.dynamic_env,u=t.use_dynamic,r=t.error,o=r===void 0?function(){}:r;e=Go(e,{env:i,dynamic_env:a,error:o,use_dynamic:u});return D(e,function(e){if(Du(n)){n=eu(n)}e=Zo(n,e);var t=e.slice();var r=Xo(n,t,{env:i,dynamic_env:a,use_dynamic:u});return D(r,function(e){if(oe(e)){e.mark_cycles();return bo(e)}return Ha(e)},o)})}var ts=new WeakMap;var rs=function(){function n(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;Q(this,n);le(this,"__value__",void 0);le(this,"__fn__",void 0);Ir(this,ts,{writable:true,value:void 0});this.__value__=e;if(t){if(!d(t)){throw new Error("Section argument to Parameter need to be function "+"".concat(Ko(t)," given"))}this.__fn__=t}if(r){f(this,ts,r)}}fe(n,[{key:"__name__",get:function e(){return t(this,ts)},set:function e(t){f(this,ts,t);if(this.__fn__){this.__fn__.__name__="fn-".concat(t)}}},{key:"invoke",value:function e(){if(d(this.__fn__)){return this.__fn__(this.__value__)}return this.__value__}},{key:"inherit",value:function e(t){return new n(t,this.__fn__,this.__name__)}}]);return n}();var ns=function(){function t(e){Q(this,t);le(this,"env",void 0);le(this,"dynamic_env",void 0);le(this,"use_dynamic",void 0);Object.assign(this,e)}fe(t,[{key:"__name__",get:function e(){return this.env.__name__}},{key:"__parent__",get:function e(){return this.env.__parent__}},{key:"get",value:function e(){var t;return(t=this.env).get.apply(t,arguments)}}]);return t}();function is(e,t){var r=e.get(t.__name__,{throwError:false});if(Ma(r)&&r!==t){return r}var n=Co.get("**interaction-environment**");while(true){var i=e.get("parent.frame",{throwError:false});e=i(0);if(e===n){break}r=e.get(t.__name__,{throwError:false});if(Ma(r)&&r!==t){return r}}return t}var as=function(){function t(e){Q(this,t);le(this,"__value__",void 0);this.__value__=e}fe(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}}]);return t}();function k(o){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},s=e.env,c=e.dynamic_env,f=e.use_dynamic,t=e.error,l=t===void 0?Lo:t,r=_e(e,Br);return function(e){try{if(!Ra(c)){c=s===true?Co:s||Co}if(f){s=c}else if(s===true){s=Co}else{s=s||se}var t={env:s,dynamic_env:c,use_dynamic:f,error:l};var r;if(ja(o)){return o}if(o instanceof ne){return s.get(o)}if(!oe(o)){return o}var n=o.car;var e=o.cdr;if(oe(n)){r=Wo(k(n,t));if(za(r)){return r.then(function(e){if(!qa(e)){throw new Error(Ko(e)+" "+s.get("repr")(e)+" is not callable while evaluating "+o.toString())}return k(new ae(e,o.cdr),t)})}else if(!qa(r)){throw new Error(Ko(r)+" "+s.get("repr")(r)+" is not callable while evaluating "+o.toString())}}if(n instanceof ne){r=s.get(n)}else if(d(n)){r=n}var i;if(r instanceof Aa){i=Ho(r,o,t)}else if(r instanceof q){i=Qo(r,e,t)}else if(d(r)){i=es(r,e,t)}else if(r instanceof ka){i=Ho(r._syntax,o,t)}else if(Ma(r)){var a=is(c,r);if(ja(o.cdr)){i=a.invoke()}else{return D(k(o.cdr.car,t),function(e){a.__value__=e})}}else if(Ta(r)){i=r.invoke()}else if(oe(o)){r=n&&n.toString();throw new Error("".concat(Ko(n)," ").concat(r," is not a function"))}else{return o}var u=s.get(Symbol["for"]("__promise__"),{throwError:false});if(u===true&&za(i)){i=i.then(function(e){if(oe(e)&&!r[cu]){return k(e,t)}return e});return new ei(i)}return i}catch(e){l&&l.call(s,e,o)}}(r)}var us=cs(function(e){return e});var os=cs(function(e,t){return t});function ss(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.dynamic_env,i=t.use_dynamic;return k(e,{env:r,dynamic_env:n,use_dynamic:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}if(!(t instanceof yo)){throw t}}})}function cs(d){return function(){var t=H(function(l){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},h=e.env,_=e.dynamic_env,p=e.use_dynamic;return O.mark(function e(){var r,n,i,a,u,o,s,c,f;return O.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!Ra(_)){_=h===true?Co:h||Co}if(h===true){h=Co}else{h=h||Co}r=[];if(!oe(l)){t.next=8;break}t.next=6;return ss(l,{env:h,dynamic_env:_,use_dynamic:p});case 6:t.t0=t.sent;return t.abrupt("return",[t.t0]);case 8:n=Array.isArray(l)?l:mi(l);i=false;a=false;t.prev=11;o=Ur(n);case 13:t.next=15;return o.next();case 15:if(!(i=!(s=t.sent).done)){t.next=31;break}c=s.value;t.next=19;return ss(c,{env:h,dynamic_env:_,use_dynamic:p});case 19:f=t.sent;t.t1=r;t.t2=d;t.t3=c;t.next=25;return f;case 25:t.t4=t.sent;t.t5=(0,t.t2)(t.t3,t.t4);t.t1.push.call(t.t1,t.t5);case 28:i=false;t.next=13;break;case 31:t.next=37;break;case 33:t.prev=33;t.t6=t["catch"](11);a=true;u=t.t6;case 37:t.prev=37;t.prev=38;if(!(i&&o["return"]!=null)){t.next=42;break}t.next=42;return o["return"]();case 42:t.prev=42;if(!a){t.next=45;break}throw u;case 45:return t.finish(42);case 46:return t.finish(37);case 47:return t.abrupt("return",r);case 48:case"end":return t.stop()}},e,null,[[11,33,37,47],[38,,42,46]])})()});function e(e){return t.apply(this,arguments)}return e}()}function fs(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){try{r=Kn(e)}catch(e){if(e instanceof vi){return false}throw e}}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var a=new Un;var u=Lr(r),o;try{for(u.s();!(o=u.n()).done;){var s=o.value;if(n.includes(s)){a.push(s)}else if(!a.is_empty()){var c=a.top();var f=t[c];if(s===f){a.pop()}else{throw new Error("Syntax error: missing closing ".concat(f))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){u.e(e)}finally{u.f()}return a.is_empty()}function ls(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new Vr.Worker(r.createObjectURL(n))}function hs(){return Vs.version.match(/^(\{\{VER\}\}|DEV)$/)}function _s(){if(To()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var ps=_s();function ds(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(ps){e=ps.replace(/[^/]*$/,"std.xcb")}else if(hs()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(Vs.version,"/").concat(t)}}se.set("__dirname",e.replace(/[^/]+$/,""));var r=se.get("load");return r.call(Co,e,se)}function vs(e){this.url=e;var u=this.worker=ls(function(){var u;var o;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!o){i("Worker RPC: LIPS not initialized, call init first");return}o.then(function(){var e=r.params[0];var t=r.params[1];u.exec(e,{use_dynamic:t}).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var a=r.params[0];if(typeof a!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(a,"/dist/lips.min.js"));u=new Vs.Interpreter("worker");o=ds(a);o.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var a=++n;return new Promise(function(n,i){u.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===a){if(r.error){i(r.error)}else{n(r.result)}u.removeEventListener("message",e)}});u.postMessage({type:"RPC",method:t,id:a,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e,t){var r=t.use_dynamic,n=r===void 0?false:r;return this.rpc("eval",[e,n])}}var ys={pair:function e(t){var r=b(t,2),n=r[0],i=r[1];return ae(n,i)},number:function e(t){if(x.isString(t)){return B([t,10])}return B(t)},regex:function e(t){var r=b(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return ie},symbol:function e(t){if(x.isString(t)){return ne(t)}else if(Array.isArray(t)){return ne(Symbol["for"](t[0]))}},string:x,character:h};var ms=Object.keys(ys);var gs={};for(var bs=0,ws=Object.entries(ms);bs1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var a=0;t.forEach(function(e){i.set(e,a);a+=e.length});return i}else if(t.length){return t[0]}}function js(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var Bs=7;function Is(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,Bs));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function Ps(e){var t=js();var r=Cs.encode(e);return Ss(t,Er(r,{magic:false}))}function Ns(e){var t=Is(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=Fr(e.slice(Bs),{magic:false});return Cs.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function Ts(e){console.error(e.message||e);if(Array.isArray(e.code)){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function Ls(){var u=["text/x-lips","text/x-scheme"];var o;function s(e){var t;return(t=e.getAttribute("data-bootstrap"))!==null&&t!==void 0?t:e.getAttribute("bootstrap")}function c(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(os).then(t)["catch"](function(e){Ts(e);t()})}else{return os(r.innerHTML).then(t)["catch"](function(e){Ts(e);t()})}})}function e(){return new Promise(function(i){var a=Array.from(document.querySelectorAll("script"));return function e(){var t=a.shift();if(!t){i()}else{var r=t.getAttribute("type");if(u.includes(r)){var n=s(t);if(!o&&typeof n==="string"){return ds(n).then(function(){return c(t)}).then(e)}else{return c(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+u.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(Ms){var t=Ms;var r=s(t);if(typeof r==="string"){return ds(r).then(function(){o=true;return e()})}}return e()}var Ms=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){Hr(window,Ls)}var Rs=function(){var e=x("Fri, 08 Nov 2024 13:26:12 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var a="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return a}();s(Si,"__class__","ahead");s(ae,"__class__","pair");s(Zi,"__class__","nil");s(ji,"__class__","pattern");s(Ci,"__class__","formatter");s(q,"__class__","macro");s(Aa,"__class__","syntax");s(Aa.Parameter,"__class__","syntax-parameter");s(F,"__class__","environment");s(Zu,"__class__","input-port");s(Xu,"__class__","output-port");s(eo,"__class__","output-port");s(to,"__class__","output-string-port");s(no,"__class__","input-string-port");s(oo,"__class__","input-file-port");s(ro,"__class__","output-file-port");s(vo,"__class__","lips-error");[B,m,w,g,E].forEach(function(e){s(e,"__class__","number")});s(h,"__class__","character");s(ne,"__class__","symbol");s(x,"__class__","string");s(ei,"__class__","promise");s(rs,"__class__","parameter");var qs="DEV";var Us="Fri, 08 Nov 2024 13:26:12 +0000";var zs=Ou(Di,mi);var Vs={version:qs,banner:Rs,date:Us,exec:os,parse:zs,tokenize:Kn,evaluate:k,compile:us,serialize:ks,unserialize:Os,serialize_bin:Ps,unserialize_bin:Ns,bootstrap:ds,Environment:F,env:Co,Worker:vs,Interpreter:po,balanced_parenthesis:fs,balancedParenthesis:fs,balanced:fs,Macro:q,Syntax:Aa,Pair:ae,Values:go,QuotedPromise:ei,Error:vo,quote:bo,InputPort:Zu,OutputPort:Xu,BufferedOutputPort:eo,InputFilePort:oo,OutputFilePort:ro,InputStringPort:no,OutputStringPort:to,InputByteVectorPort:ao,OutputByteVectorPort:uo,InputBinaryFilePort:so,OutputBinaryFilePort:co,set_fs:jo,Formatter:Ci,Parser:di,Lexer:o,specials:ii,repr:ea,nil:ie,eof:ho,LSymbol:ne,LNumber:B,LFloat:g,LComplex:m,LRational:w,LBigInteger:E,LCharacter:h,LString:x,Parameter:rs,rationalize:Hu};se.set("lips",Vs);e.BufferedOutputPort=eo;e.Environment=F;e.Error=vo;e.Formatter=Ci;e.InputBinaryFilePort=so;e.InputByteVectorPort=ao;e.InputFilePort=oo;e.InputPort=Zu;e.InputStringPort=no;e.Interpreter=po;e.LBigInteger=E;e.LCharacter=h;e.LComplex=m;e.LFloat=g;e.LNumber=B;e.LRational=w;e.LString=x;e.LSymbol=ne;e.Lexer=o;e.Macro=q;e.OutputBinaryFilePort=co;e.OutputByteVectorPort=uo;e.OutputFilePort=ro;e.OutputPort=Xu;e.OutputStringPort=to;e.Pair=ae;e.Parameter=rs;e.Parser=di;e.QuotedPromise=ei;e.Syntax=Aa;e.Values=go;e.Worker=vs;e._is_directive=Ba;e.balanced=fs;e.balancedParenthesis=fs;e.balanced_parenthesis=fs;e.banner=Rs;e.bootstrap=ds;e.compile=us;e.date=Us;e.env=Co;e.eof=ho;e.evaluate=k;e.exec=os;e.nil=ie;e.parse=zs;e.quote=bo;e.rationalize=Hu;e.repr=ea;e.serialize=ks;e.serialize_bin=Ps;e.set_fs=jo;e.specials=ii;e.tokenize=Kn;e.unserialize=Os;e.unserialize_bin=Ns;e.version=qs}); \ No newline at end of file diff --git a/dist/std.min.scm b/dist/std.min.scm index bfe231c92..d2025d102 100644 --- a/dist/std.min.scm +++ b/dist/std.min.scm @@ -35,8 +35,9 @@ (define (native.number x) "(native.number obj)\u000A\u000AIf argument is a number it will convert it to a native number." (if (number? x) (value x) x)) (define (value obj) "(value obj)\u000A\u000AFunction that unwraps LNumbers and converts '() to #void." (if (eq? obj (quote ())) #void (if (number? obj) ((. obj "valueOf")) obj))) (define-macro (define-formatter-rule . patterns) "(rule-pattern pattern)\u000A\u000AAnaphoric macro for defining patterns for the formatter.\u000AWith Ahead, Pattern and * defined values." (let ((rules (gensym "rules"))) (quasiquote (let (((unquote rules) lips.Formatter.rules) (Ahead (lambda (pattern) (let ((Ahead (.. lips.Formatter.Ahead))) (new Ahead (if (string? pattern) (new RegExp pattern) pattern))))) (* (Symbol.for "*")) (Pattern (lambda (pattern flag) (new lips.Formatter.Pattern (list->array pattern) (if (null? flag) #void flag))))) (unquote-splicing (map (lambda (pattern) (quasiquote (--> (unquote rules) (push (tree->array (tree-map native.number (unquote-splicing pattern))))))) patterns)))))) -(define-macro (cond . list) "(cond (predicate? . body)\u000A (predicate? . body))\u000A\u000A(cond (predicate? => procedure)\u000A (predicate? => procedure))\u000A\u000AMacro for condition checks. For usage instead of nested ifs.\u000AYou can use predicate and any number of expressions. Or symbol =>\u000AFollowed by procedure that will be invoked with result\u000Aof the predicate." (if (pair? list) (let* ((item (car list)) (value (gensym)) (first (car item)) (fn (and (not (null? (cdr item))) (eq? (cadr item) (quote =>)))) (expression (if fn (caddr item) (cdr item))) (rest (cdr list))) (quasiquote (let (((unquote value) (unquote first))) (if (unquote value) (unquote (if fn (quasiquote ((unquote expression) (unquote value))) (quasiquote (begin (unquote-splicing expression))))) (unquote (if (and (pair? rest) (let ((x (caar rest))) (or (eq? x true) (and (symbol? x) (or (eq? x (quote else)) (eq? (--> (new lips.LString (x.literal)) (cmp "else")) 0)))))) (quasiquote (begin (unquote-splicing (cdar rest)))) (if (not (null? rest)) (quasiquote (cond (unquote-splicing rest)))))))))) (quote ()))) -(define (regex re . rest) "(regex re)\u000A\u000ACreates a new regular expression from string, to not break Emacs formatting." (typecheck "regex" re "string") (if (null? rest) (new RegExp re) (new RegExp re (car rest)))) +(define (%else-literal? obj) "(%else-literal? obj)\u000A\u000AChecks if object is symbol else." (and (symbol? obj) (or (eq? obj (quote else)) (eq? (--> (new lips.LString (obj.literal)) (cmp "else")) 0)))) +(define-macro (cond . list) "(cond (predicate? . body)\u000A (predicate? . body)\u000A (else . body))\u000A\u000A(cond (predicate? => procedure)\u000A (predicate? => procedure)\u000A (else . body))\u000A\u000AMacro for condition checks. For usage instead of nested ifs.\u000AYou can use predicate and any number of expressions. Or symbol =>\u000AFollowed by procedure that will be invoked with result\u000Aof the predicate." (if (pair? list) (let* ((item (car list)) (value (gensym)) (first (car item)) (fn (and (not (null? (cdr item))) (eq? (cadr item) (quote =>)))) (expression (if fn (caddr item) (cdr item))) (rest (cdr list))) (if (%else-literal? first) (quasiquote (begin (unquote-splicing expression))) (quasiquote (let (((unquote value) (unquote first))) (if (unquote value) (unquote (if fn (quasiquote ((unquote expression) (unquote value))) (quasiquote (begin (unquote-splicing expression))))) (unquote (if (not (null? rest)) (quasiquote (cond (unquote-splicing rest)))))))))) (quote ()))) +(define (regex re . rest) "(regex re)\u000A(regex re flags)\u000A\u000ACreates a new regular expression from string, to not break Emacs formatting." (typecheck "regex" re "string") (if (null? rest) (new RegExp re) (new RegExp re (car rest)))) (define (interaction-environment) "(interaction-environment)\u000A\u000AReturns the interaction environment equal to lips.env. This can be overwritten\u000Awhen creating new interpreter with lips.Interpreter." **interaction-environment**) (define (current-output-port) "(current-output-port)\u000A\u000AReturns the default stdout port." (let-env (interaction-environment) (--> **internal-env** (get (quote stdout))))) (define (current-error-port) "(current-output-port)\u000A\u000AReturns the default stderr port." (let-env (interaction-environment) (--> **internal-env** (get (quote stderr))))) @@ -50,11 +51,19 @@ (define (unset-repr! type) "(unset-repr! type)\u000A\u000ARemoves the string representation of the type, which should be constructor function,\u000Aadded by add-repr! function." (typecheck "unset-repr!" type "function") (ignore (--> lips.repr (delete type)))) (set-special! "&" (quote object-literal) lips.specials.SPLICE) (set-repr! Object (lambda (x q) (concat "&(" (--> (Object.getOwnPropertyNames x) (map (lambda (key) (let ((value (repr (. x key) q)) (key (repr (string->symbol key)))) (concat ":" key " " value)))) (join " ")) ")"))) +(set-special! "#\"" (quote %string-interpolation) lips.specials.SYMBOL) +(define (%read-interpolated . rest) "(%read-interpolated [port])\u000A\u000AFunction read from input port or stdin and return list of strings\u000Ainterleaved with expressions from interpolation ${...}" (let ((port (if (null? rest) (current-input-port) (car rest)))) (let loop ((part "") (result (vector)) (char (read-char port))) (cond ((and (char=? char #\$) (char=? (peek-char port) #\{)) (read-char) (let ((expr (read port))) (let ((next (peek-char port))) (if (char=? next #\}) (begin (read-char) (loop "" (vector-append result (vector part expr)) (read-char))) (error (string-append "Parse Error: expecting } got " (repr next))))))) ((char=? char #\\) (loop (string-append part (repr (read-char))) result (read-char))) ((char=? char #\") (vector->list (vector-append result (vector part)))) ((eof-object? char) (error "Parse Error: expecting character #eof found")) (else (loop (string-append part (repr char)) result (read-char))))))) +(define (%string-interpolation) "(%string-interpolation)\u000A\u000AString interpolation syntax-extension that read remainder of a string and return\u000ALISP scheme code that evaluate to the string." (let* ((lexer lips.__parser__.__lexer__) (token lexer.__token__) (offset (+ token.col 2)) (re (regex (string-append "\\u000A\\s{1," (repr offset) "}") "g"))) (quasiquote (string-append (unquote-splicing (map (lambda (expr) (if (string? expr) (begin (expr.replace re "\u000A")) (quasiquote (repr (unquote expr))))) (%read-interpolated))))))) (define (bound? x . rest) "(bound? x [env])\u000A\u000AFunction that check if the variable is defined in the given environment,\u000Aor interaction-environment if not specified." (let ((env (if (null? rest) (interaction-environment) (car rest)))) (try (begin (--> env (get x)) true) (catch (e) false)))) (define (environment-bound? env x) "(environment-bound? env symbol)\u000A\u000AChecks if symbol is a bound variable similar to bound?." (typecheck "environment-bound?" env "environment" 1) (typecheck "environment-bound?" x "symbol" 2) (bound? x env)) (define (qsort e predicate) "(qsort list predicate)\u000A\u000ASorts the list using the quick sort algorithm according to predicate." (if (or (null? e) (<= (length e) 1)) e (let loop ((left (quote ())) (right (quote ())) (pivot (car e)) (rest (cdr e))) (if (null? rest) (append (append (qsort left predicate) (list pivot)) (qsort right predicate)) (if (predicate (car rest) pivot) (loop (append left (list (car rest))) right pivot (cdr rest)) (loop left (append right (list (car rest))) pivot (cdr rest))))))) (define (sort list . rest) "(sort list [predicate])\u000A\u000ASorts the list using optional predicate function. If no comparison function\u000Ais given it will use <= and sort in increasing order." (let ((predicate (if (null? rest) <= (car rest)))) (typecheck "sort" list "pair") (typecheck "sort" predicate "function") (qsort list predicate))) -(define (every fn list) "(every fn list)\u000A\u000AFunction that calls fn on each item of the list, if every value returns true\u000Ait will return true otherwise it return false.\u000AAnalogous to Python all(map(fn, list))." (if (null? list) true (and (fn (car list)) (every fn (cdr list))))) +(define-macro (%any lists) (quasiquote (or (unquote-splicing lists)))) +(define (%any-null? lst) "(%any-null? lst)\u000A\u000AChecks if any of elements in the list is null." (if (null? lst) false (if (null? (car lst)) true (%any-null? (cdr lst))))) +(define (%some fn lists) "(%some fn lists)\u000A\u000Aversion of some without typechecking." (if (or (null? lists) (%any-null? lists)) false (if (apply fn (map car lists)) true (%some fn (map cdr lists))))) +(define (some fn . lists) "(some fn . lists)\u000A\u000AHigher-order function that calls fn on consecutive elements of the list of lists.\u000AIt stops and returns true when fn returns true. If none of the values give true,\u000Asome will return false. Analogous to Python any(map(fn, list))." (typecheck "some" fn "function") (typecheck-args (vector "pair" "nil") "some" lists) (%some fn lists)) +(define (%every fn lists) "(%every fn lists)\u000A\u000Aversion of every without typechecking." (if (or (null? lists) (%any-null? lists)) true (and (apply fn (map car lists)) (%every fn (map cdr lists))))) +(define (every fn . lists) "(every fn . lists)\u000A\u000AHigher-order function that calls fn on consecutive item of the list of lists,\u000Aif every call returns true it will return true otherwise it return false.\u000AAnalogous to Python all(map(fn, list))." (typecheck "every" fn "function") (typecheck-args (vector "pair" "nil") "every" lists) (%every fn lists)) (define-macro (promise . body) "(promise . body)\u000A\u000AAnaphoric macro that exposes resolve and reject functions from JS promise." (quasiquote (new Promise (lambda (resolve reject) (try (begin (unquote-splicing body)) (catch (e) (error e.message))))))) (define-macro (timer time . body) "(timer time . body)\u000A\u000AEvaluates body after delay, it returns the timer ID from setTimeout.\u000ATo clear the timer you can use native JS clearTimeout function." (quasiquote (setTimeout (lambda () (try (begin (unquote-splicing body)) (catch (e) (error (.. e.message))))) (unquote time)))) (define-macro (wait time . expr) "(wait time . expr)\u000A\u000AReturns a promise that will resolve with the expression after delay." (quasiquote (promise (timer (unquote time) (resolve (begin (unquote-splicing expr))))))) @@ -70,8 +79,8 @@ (define (%class-lambda expr) "(class-lambda expr)\u000A\u000AReturns a lambda expression where input expression lambda have `this` as first argument." (let ((args (gensym (quote args)))) (quasiquote (lambda (unquote args) (apply (unquote (cadr expr)) this (unquote args)))))) (define (%class-method-name expr) "(%class-method-name expr)\u000A\u000AHelper function that allows to use [Symbol.asyncIterator] inside method name." (if (pair? expr) (car expr) (list (quote quote) expr))) (define (constructor) "(constructor)\u000A\u000AFunction that is present in JavaScript environment. We define it in Scheme\u000Ato fix an issue with define-class. This function throw an error." (throw (new Error "Invalid call to constructor function"))) -(define-macro (define-class name parent . body) "(define-class name parent . body)\u000A\u000ADefines a class - JavaScript function constructor with prototype.\u000A\u000Ausage:\u000A\u000A (define-class Person Object\u000A (constructor (lambda (self name)\u000A (set-obj! self '_name name)))\u000A (hi (lambda (self)\u000A (display (string-append self._name \" says hi\"))\u000A (newline))))\u000A (define jack (new Person \"Jack\"))\u000A (jack.hi) ; prints \"Jack says hi\"" (let iter ((functions (quote ())) (constructor (quote ())) (lst body)) (if (null? lst) (quasiquote (begin (define (unquote name) (unquote (if (null? constructor) (quasiquote (lambda ())) (append (%class-lambda constructor) (list (quote this)))))) (set-obj! (unquote name) (Symbol.for "__class__") true) (unquote (if (not (null? parent)) (quasiquote (begin (set-obj! (unquote name) (quote prototype) (Object.create (. (unquote parent) (quote prototype)))) (set-obj! (. (unquote name) (quote prototype)) (quote constructor) (unquote name)))))) (set-obj! (unquote name) (quote __name__) (quote (unquote name))) (unquote-splicing (map (lambda (fn) (quasiquote (set-obj! (. (unquote name) (quote prototype)) (unquote (%class-method-name (car fn))) (unquote (%class-lambda fn))))) functions)))) (let ((item (car lst))) (if (eq? (car item) (quote constructor)) (iter functions item (cdr lst)) (iter (cons item functions) constructor (cdr lst))))))) -(define-syntax class (syntax-rules () ((_) (error "class: parent required")) ((_ parent body ...) (let () (define-class temp parent body ...) temp))) "(class body ...)\u000A\u000AAllows to create anonymous classes. See define-class for details.") +(define-macro (define-class name parent . body) "(define-class name parent . body)\u000A\u000ADefines a class - JavaScript function constructor with prototype.\u000Aparent needs to be class, constructor function, or #null\u000A\u000Ausage:\u000A\u000A (define-class Person Object\u000A (constructor (lambda (self name)\u000A (set-obj! self '_name name)))\u000A (hi (lambda (self)\u000A (display (string-append self._name \" says hi\"))\u000A (newline))))\u000A (define jack (new Person \"Jack\"))\u000A (jack.hi) ; prints \"Jack says hi\"" (let ((g:parent (gensym))) (let iter ((functions (quote ())) (constructor (quote ())) (lst body)) (if (null? lst) (quasiquote (begin (define (unquote name) (unquote (if (null? constructor) (quasiquote (lambda ())) (append (%class-lambda constructor) (list (quote this)))))) (set-obj! (unquote name) (Symbol.for "__class__") true) (let (((unquote g:parent) (unquote parent))) (if (not (null? (unquote g:parent))) (begin (set-obj! (unquote name) (quote prototype) (Object.create (. (unquote g:parent) (quote prototype)))) (set-obj! (. (unquote name) (quote prototype)) (quote constructor) (unquote name))))) (set-obj! (unquote name) (quote __name__) (quote (unquote name))) (unquote-splicing (map (lambda (fn) (quasiquote (set-obj! (. (unquote name) (quote prototype)) (unquote (%class-method-name (car fn))) (unquote (%class-lambda fn))))) functions)))) (let ((item (car lst))) (if (eq? (car item) (quote constructor)) (iter functions item (cdr lst)) (iter (cons item functions) constructor (cdr lst)))))))) +(define-syntax class (syntax-rules () ((_) (error "class: parent required")) ((_ parent-expr body ...) (let ((parent parent-expr)) (if (not (or (procedure? parent) (eq? parent #null))) (error "parent class need to be a function or #null")) (define-class temp parent body ...) (set-obj! temp "__name__" "anonymous") temp))) "(class body ...)\u000A\u000AAllows to create anonymous classes. See define-class for details.") (define (make-tags expr) "(make-tags expression)\u000A\u000AReturns a list structure of code with better syntax then raw LIPS" (quasiquote (h (unquote (let ((val (car expr))) (if (key? val) (key->string val) val))) (alist->object ((unquote (quote quasiquote)) (unquote (pair-map (lambda (car cdr) (quasiquote ((unquote (key->string car)) (unquote (quote unquote)) (unquote cdr)))) (cadr expr))))) (unquote (if (not (null? (cddr expr))) (if (and (pair? (caddr expr)) (let ((s (caaddr expr))) (and (symbol? s) (eq? s (quote list))))) (quasiquote (list->array (list (unquote-splicing (map make-tags (cdaddr expr)))))) (caddr expr))))))) (define (%sxml h expr) "(%sxml h expr)\u000A\u000AHelper function that renders the expression using create element function." (let* ((have-attrs (and (not (null? (cdr expr))) (pair? (cadr expr)) (eq? (caadr expr) (quote @)))) (attrs (if have-attrs (cdadr expr) (quote ()))) (rest (if have-attrs (cddr expr) (cdr expr)))) (quasiquote ((unquote h) (unquote (let* ((symbol (car expr)) (name (symbol->string symbol))) (if (char-lower-case? (car (string->list name))) name symbol))) (alist->object ((unquote (quote quasiquote)) (unquote (map (lambda (pair) (cons (symbol->string (car pair)) (list (quote unquote) (cadr pair)))) attrs)))) (unquote-splicing (if (null? rest) (quote ()) (let ((first (car rest))) (if (pair? first) (cond ((symbol=? (quote sxml-unquote) (car first)) (cdr first)) (else (map (lambda (expr) (%sxml h expr)) rest))) (list first))))))))) (set-special! "~" (quote sxml-unquote-mapper)) @@ -145,7 +154,7 @@ (define make-promise (lambda (proc) "(make-promise fn)\u000A\u000AFunction that creates a promise from a function." (typecheck "make-promise" proc "function") (let ((result-ready? #f) (result #f)) (let ((promise (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? #t) (set! result x) result))))))) (set-obj! promise (Symbol.for "promise") true) (set! promise.toString (lambda () (string-append "#"))) promise)))) (define-macro (delay expression) "(delay expression)\u000A\u000AWill create a promise from expression that can be forced with (force)." (quasiquote (make-promise (lambda () (unquote expression))))) (define (force promise) "(force promise)\u000A\u000AFunction that forces the promise and evaluates the delayed expression." (promise)) -(define (promise? obj) "(promise? obj)\u000A\u000AChecks if the value is a promise created with delay or make-promise." (string=? (type obj) "promise")) +(define (promise? obj) "(promise? obj)\u000A\u000AChecks if the value is a promise created with delay or make-promise." (and (string=? (type obj) "function") (. obj (Symbol.for "promise")))) (define (positive? x) "(positive? x)\u000A\u000AChecks if the number is larger then 0" (typecheck "positive?" x "number") (> x 0)) (define (negative? x) "(negative? x)\u000A\u000AChecks if the number is smaller then 0" (typecheck "negative?" x "number") (< x 0)) (define (zero? x) "(zero? x)\u000A\u000AChecks if the number is equal to 0" (typecheck "zero?" x "number") (= x 0)) @@ -238,7 +247,6 @@ (define (char-downcase char) "(char-downcase chr)\u000A\u000ACreate lowercase version of the character." (typecheck "char-upcase" char "character") (char.toLowerCase)) (define (char-upper-case? char) "(char-upper-case? char)\u000A\u000AChecks if character is upper case." (typecheck "char-upper-case?" char "character") (and (char-alphabetic? char) (char=? (char-upcase char) char))) (define (char-lower-case? char) "(char-upper-case? char)\u000A\u000AChecks if character is lower case." (typecheck "char-lower-case?" char "character") (and (char-alphabetic? char) (char=? (char-downcase char) char))) -(define (newline . rest) "(newline [port])\u000A\u000AWrite newline character to standard output or given port" (let ((port (if (null? rest) (current-output-port) (car rest)))) (display "\u000A" port))) (define (write obj . rest) "(write obj [port])\u000A\u000AWrite object to standard output or give port. For strings it will include\u000Awrap in quotes." (let ((port (if (null? rest) (current-output-port) (car rest)))) (if (binary-port? port) (display obj port) (display (repr obj true) port)))) (define (write-char char . rest) "(write-char char [port])\u000A\u000AWrite single character to given port using write function." (typecheck "write-char" char "character") (if (not (null? rest)) (typecheck "write-char" (car rest) "output-port")) (apply display (cons (char.valueOf) rest))) (define fold-right reduce) @@ -396,14 +404,14 @@ (define (read-string k . rest) "(read-string k)\u000A(read-string k port)\u000A\u000AReads the next k characters, or as many as are available\u000Abefore the end of file, from the textual input port into a\u000Anewly allocated string in left-to-right order and returns the\u000Astring. If no characters are available before the end of file,\u000Aan end-of-file object is returned." (typecheck "read-string" k "number") (let ((port (if (null? rest) (current-input-port) (car rest)))) (typecheck "read-string" port "input-port") (port.read_string k))) (define (list-copy obj) "(list-copy obj)\u000A\u000ACopy the object passed as argument but only if it's list. The car elements\u000Aof the list are not copied, they are passed as is." (typecheck "list-copy" obj #("pair" "nil")) (if (null? obj) obj (obj.clone false))) (define (list-set! l k obj) "(list-set! list n)\u000A\u000AReturns n-th element of a list." (set-car! (%nth-pair "list-set!" l k) obj)) -(define-macro (define-record-type name constructor pred . fields) "(define-record-type name constructor pred . fields)\u000A\u000AMacro for defining records. Example of usage:\u000A\u000A(define-record-type \u000A (kons x y)\u000A pare?\u000A (x kar set-kar!)\u000A (y kdr set-kdr!))\u000A\u000A(define p (kons 1 2))\u000A(print (kar p))\u000A;; ==> 1\u000A(set-kdr! p 3)\u000A(print (kdr p))\u000A;; ==> 3" (let ((obj-name (gensym (quote obj-name))) (value-name (gensym (quote value-name)))) (quasiquote (begin (define (unquote name) (class Object (constructor (lambda (self (unquote-splicing (cdr constructor))) (unquote-splicing (map (lambda (field) (let* ((name (symbol->string field)) (prop (string-append "self." name))) (quasiquote (set! (unquote (string->symbol prop)) (unquote field))))) (cdr constructor))))) (equal (lambda (self other) (if (instanceof (unquote name) other) (and (unquote-splicing (map (lambda (field) (let* ((name (symbol->string field)) (self-prop (string-append "self." name)) (other-prop (string-append "other." name))) (quasiquote (equal? (unquote (string->symbol self-prop)) (unquote (string->symbol other-prop))))))))) #f))) (typeOf (lambda (self) "record")) (toString (lambda (self) (string-append "#<" (unquote (symbol->string name)) ">"))))) (define (unquote constructor) (new (unquote name) (unquote-splicing (cdr constructor)))) (define ((unquote pred) obj) (instanceof (unquote name) obj)) (unquote-splicing (map (lambda (field) (let ((prop-name (car field)) (get (cadr field)) (set (if (null? (cddr field)) (quote ()) (caddr field)))) (quasiquote (begin (define ((unquote get) (unquote obj-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (. (unquote obj-name) (quote (unquote prop-name))))) (unquote (if (not (null? set)) (quasiquote (define ((unquote set) (unquote obj-name) (unquote value-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (set-obj! (unquote obj-name) (quote (unquote prop-name)) (unquote value-name))))))))))) fields)))))) +(define-macro (define-record-type name constructor pred . fields) "(define-record-type name constructor pred . fields)\u000A\u000AMacro for defining records. Example of usage:\u000A\u000A(define-record-type \u000A (kons x y)\u000A pare?\u000A (x kar set-kar!)\u000A (y kdr set-kdr!))\u000A\u000A(define p (kons 1 2))\u000A(print (kar p))\u000A;; ==> 1\u000A(set-kdr! p 3)\u000A(print (kdr p))\u000A;; ==> 3" (let ((obj-name (gensym (quote obj-name))) (value-name (gensym (quote value-name)))) (quasiquote (begin (define (unquote name) (class Object (constructor (lambda (self (unquote-splicing (cdr constructor))) (unquote-splicing (map (lambda (field) (let* ((name (symbol->string field)) (prop (string-append "self." name))) (quasiquote (set! (unquote (string->symbol prop)) (unquote field))))) (cdr constructor))))) (equal (lambda (self other) (if (instanceof (unquote name) other) (and (unquote-splicing (map (lambda (field) (let* ((name (symbol->string field)) (self-prop (string-append "self." name)) (other-prop (string-append "other." name))) (quasiquote (equal? (unquote (string->symbol self-prop)) (unquote (string->symbol other-prop))))))))) #f))) (typeOf (lambda (self) "record")) (toString (lambda (self) (string-append "#<" (unquote (symbol->string name)) ">"))))) (define (unquote constructor) (new (unquote name) (unquote-splicing (cdr constructor)))) (define ((unquote pred) obj) (instanceof (unquote name) obj)) (set-repr! (unquote name) (lambda () (string-append "#string (quote (unquote name))) ")>"))) (unquote-splicing (map (lambda (field) (let ((prop-name (car field)) (get (cadr field)) (set (if (null? (cddr field)) (quote ()) (caddr field)))) (quasiquote (begin (define ((unquote get) (unquote obj-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (. (unquote obj-name) (quote (unquote prop-name))))) (unquote (if (not (null? set)) (quasiquote (define ((unquote set) (unquote obj-name) (unquote value-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (set-obj! (unquote obj-name) (quote (unquote prop-name)) (unquote value-name))))))))))) fields)))))) (define (nan? x) "(nan? x)\u000A\u000AChecks if argument x is Not a Number (NaN) value." (and (number? x) (or (x.isNaN) (and (%number-type "complex" x) (or (nan? (real-part x)) (nan? (imag-part x))))))) (define (infinite? x) "(infinite? x)\u000A\u000AChecks if value is infinite." (or (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (number? x) (not (eq? x NaN)) (%number-type "complex" x) (or (infinite? (real-part x)) (infinite? (imag-part x)))))) (define (finite? x) "(finite? x)\u000A\u000AChecks if value is finite." (not (infinite? x))) (define-class %Library Object (constructor (lambda (self name) (set! self.__namespace__ &()) (set! self.__name__ name))) (append (lambda (self namespace env) (if (environment? (. self.__namespace__ namespace)) (throw (new Error (string-append "namespace " namespace " already exists in library " self.__name__))) (set-obj! self.__namespace__ namespace env)))) (env (lambda (self namespace) (let ((env (. self.__namespace__ namespace))) (if (not (environment? env)) (throw (new Error (string-append "namespace " namespace " sdon't exists"))) env)))) (get (lambda (self namespace name) (--> (self.env namespace) (get name)))) (set (lambda (self namespace name value) (--> (self.env namespace) (set name value)))) (toString (lambda (self) (string-append "#")))) (define (%import-name library namespace names) (quasiquote (begin (unquote-splicing (map (lambda (name) (quasiquote (define (unquote name) (--> (unquote library) (get (quote (unquote namespace)) (quote (unquote name))))))) names))))) (define-macro (import . specs) "(import (library namespace))\u000A(import (only (library namespace) name1 name2))\u000A\u000AMacro for importing names from library." (let ((parent (current-environment))) (quasiquote (begin (unquote-splicing (map (lambda (spec) (if (not (pair? spec)) (throw (new Error "import: invalid syntax")) (cond ((symbol=? (car spec) (quote only)) (let ((lib (caadr spec)) (namespace (caaddr spec))) (if (pair? (cadr spec)) (%import-name (unquote lib) (quote (unquote namespace)) (quote (unquote (caddr spec)))) (throw (new Error "import: invalid syntax"))))) (else (let* ((lib-name (car spec)) (lib (parent.get lib-name)) (namespace (cadr spec))) (%import-name lib-name namespace (env (lib.env namespace)))))))) specs)))))) -(define (new-library name namespace) "(new-library name)\u000A\u000ACreate new empty library object with empty namespace." (let* ((parent (. (current-environment) (quote __parent__))) (lib (let ((lib (--> parent (get name &(:throwError "false"))))) (if (null? lib) (new %Library name) lib))) (x (new lips.Environment (string-append "library-" (--> name (toLowerCase)) "-" (--> namespace (toLowerCase)))))) (lib.append namespace x) lib)) +(define (new-library name namespace) "(new-library name)\u000A\u000ACreate new empty library object with empty namespace." (let* ((parent (. (current-environment) (quote __parent__))) (lib (let ((lib (--> parent (get name &(:throwError #f))))) (if (null? lib) (new %Library name) lib))) (x (new lips.Environment (string-append "library-" (--> name (toLowerCase)) "-" (--> namespace (toLowerCase)))))) (lib.append namespace x) lib)) (define (%export module namespace specs) (quasiquote (begin (unquote-splicing (map (lambda (expr) (cond ((symbol? expr) (quasiquote (--> (unquote module) (set (quote (unquote namespace)) (quote (unquote expr)) (unquote expr))))) ((and (pair? expr) (symbol=? (car expr) (quote rename))) (quasiquote (--> (unquote module) (set (quote (unquote namespace)) (quote (unquote (cadr expr))) (unquote (caddr expr)))))))) specs))))) (define-macro (define-library spec . body) "(define-library (library (name namespace) . body)\u000A\u000AMacro for defining modules inside you can use define to create functions.\u000AAnd use export name to add that name to defined environment." (let ((parent (. (current-environment) (quote __parent__))) (module-var (gensym)) (namespace-var (gensym)) (name (car spec)) (namespace (cadr spec))) (quasiquote (let (((unquote module-var) (new-library (unquote (repr name)) (unquote (repr namespace)))) ((unquote namespace-var) (quote (unquote namespace)))) (define-macro (export . body) (%export (unquote module-var) (unquote namespace-var) body)) (unquote-splicing body) (--> (unquote parent) (set (quote (unquote name)) (unquote module-var))))))) (define-syntax guard (syntax-rules (catch aux =>) ((_ aux) (quote ())) ((_ aux (cond result) rest ...) (let ((it cond)) (if it result (guard aux rest ...)))) ((_ aux (cond => fn) rest ...) (let ((it cond)) (if it (fn it) (guard aux rest ...)))) ((_ aux (cond) rest ...) (let ((it cond)) (if it it (guard aux rest ...)))) ((_ (var cond1 cond2 ...) body ...) (try body ... (catch (var) (guard aux cond1 cond2 ...))))) "(guard (variable (cond)\u000A (cond => fn)\u000A (cond2 result))\u000A body)\u000A\u000AMacro that executes the body and when there is exception, triggered by\u000Araise it's saved in variable that can be tested by conditions.") diff --git a/dist/std.scm b/dist/std.scm index 93e10d43f..a491a29da 100644 --- a/dist/std.scm +++ b/dist/std.scm @@ -552,13 +552,25 @@ Helper macro used by cond.") +;; ----------------------------------------------------------------------------- +(define (%else-literal? obj) + "(%else-literal? obj) + + Checks if object is symbol else." + (and (symbol? obj) + (or (eq? obj 'else) + (eq? (--> (new lips.LString (obj.literal)) + (cmp "else")) 0)))) + ;; ----------------------------------------------------------------------------- (define-macro (cond . list) "(cond (predicate? . body) - (predicate? . body)) + (predicate? . body) + (else . body)) (cond (predicate? => procedure) - (predicate? => procedure)) + (predicate? => procedure) + (else . body)) Macro for condition checks. For usage instead of nested ifs. You can use predicate and any number of expressions. Or symbol => @@ -573,27 +585,23 @@ (caddr item) (cdr item))) (rest (cdr list))) - `(let ((,value ,first)) - (if ,value - ,(if fn - `(,expression ,value) - `(begin - ,@expression)) - ,(if (and (pair? rest) - (let ((x (caar rest))) - (or (eq? x true) - (and (symbol? x) - (or (eq? x 'else) - (eq? (--> (new lips.LString (x.literal)) (cmp "else")) 0)))))) - `(begin - ,@(cdar rest)) - (if (not (null? rest)) + (if (%else-literal? first) + `(begin + ,@expression) + `(let ((,value ,first)) + (if ,value + ,(if fn + `(,expression ,value) + `(begin + ,@expression)) + ,(if (not (null? rest)) `(cond ,@rest)))))) '())) ;; ----------------------------------------------------------------------------- (define (regex re . rest) "(regex re) + (regex re flags) Creates a new regular expression from string, to not break Emacs formatting." (typecheck "regex" re "string") @@ -732,6 +740,51 @@ (join " ")) ")"))) +;; ----------------------------------------------------------------------------- +(set-special! "#\"" '%string-interpolation lips.specials.SYMBOL) + +(define (%read-interpolated . rest) + "(%read-interpolated [port]) + + Function read from input port or stdin and return list of strings + interleaved with expressions from interpolation ${...}" + (let ((port (if (null? rest) (current-input-port) (car rest)))) + (let loop ((part "") (result (vector)) (char (read-char port))) + (cond ((and (char=? char #\$) + (char=? (peek-char port) #\{)) + (read-char) + (let ((expr (read port))) + (let ((next (peek-char port))) + (if (char=? next #\}) + (begin + (read-char) + (loop "" (vector-append result (vector part expr)) (read-char))) + (error (string-append "Parse Error: expecting } got " (repr next))))))) + ((char=? char #\\) + (loop (string-append part (repr (read-char))) result (read-char))) + ((char=? char #\") + (vector->list (vector-append result (vector part)))) + ((eof-object? char) + (error "Parse Error: expecting character #eof found")) + (else + (loop (string-append part (repr char)) result (read-char))))))) + +(define (%string-interpolation) + "(%string-interpolation) + + String interpolation syntax-extension that read remainder of a string and return + LISP scheme code that evaluate to the string." + (let* ((lexer lips.__parser__.__lexer__) + (token lexer.__token__) + (offset (+ token.col 2)) + (re (regex (string-append "\\n\\s{1," (repr offset) "}") "g"))) + `(string-append ,@(map (lambda (expr) + (if (string? expr) + (begin + (expr.replace re "\n")) + `(repr ,expr))) + (%read-interpolated))))) + ;; ----------------------------------------------------------------------------- (define (bound? x . rest) "(bound? x [env]) @@ -783,15 +836,62 @@ (qsort list predicate))) ;; ----------------------------------------------------------------------------- -(define (every fn list) - "(every fn list) +(define-macro (%any lists) + `(or ,@lists)) - Function that calls fn on each item of the list, if every value returns true - it will return true otherwise it return false. - Analogous to Python all(map(fn, list))." - (if (null? list) + +;; ----------------------------------------------------------------------------- +(define (%any-null? lst) + "(%any-null? lst) + + Checks if any of elements in the list is null." + (if (null? lst) + false + (if (null? (car lst)) + true + (%any-null? (cdr lst))))) + +;; ----------------------------------------------------------------------------- +(define (%some fn lists) + "(%some fn lists) + + version of some without typechecking." + (if (or (null? lists) (%any-null? lists)) + false + (if (apply fn (map car lists)) + true + (%some fn (map cdr lists))))) + +;; ----------------------------------------------------------------------------- +(define (some fn . lists) + "(some fn . lists) + + Higher-order function that calls fn on consecutive elements of the list of lists. + It stops and returns true when fn returns true. If none of the values give true, + some will return false. Analogous to Python any(map(fn, list))." + (typecheck "some" fn "function") + (typecheck-args (vector "pair" "nil") "some" lists) + (%some fn lists)) + +;; ----------------------------------------------------------------------------- +(define (%every fn lists) + "(%every fn lists) + + version of every without typechecking." + (if (or (null? lists) (%any-null? lists)) true - (and (fn (car list)) (every fn (cdr list))))) + (and (apply fn (map car lists)) (%every fn (map cdr lists))))) + +;; ----------------------------------------------------------------------------- +(define (every fn . lists) + "(every fn . lists) + + Higher-order function that calls fn on consecutive item of the list of lists, + if every call returns true it will return true otherwise it return false. + Analogous to Python all(map(fn, list))." + (typecheck "every" fn "function") + (typecheck-args (vector "pair" "nil") "every" lists) + (%every fn lists)) ;; ----------------------------------------------------------------------------- (define-macro (promise . body) @@ -936,6 +1036,7 @@ "(define-class name parent . body) Defines a class - JavaScript function constructor with prototype. + parent needs to be class, constructor function, or #null usage: @@ -947,40 +1048,45 @@ (newline)))) (define jack (new Person \"Jack\")) (jack.hi) ; prints \"Jack says hi\"" - (let iter ((functions '()) (constructor '()) (lst body)) - (if (null? lst) - `(begin - (define ,name ,(if (null? constructor) - `(lambda ()) - ;; we return this to solve issue when constructor - ;; return a promise - ;; ref: https://stackoverflow.com/a/50885340/387194 - (append (%class-lambda constructor) - (list 'this)))) - (set-obj! ,name (Symbol.for "__class__") true) - ,(if (not (null? parent)) - `(begin - (set-obj! ,name 'prototype (Object.create (. ,parent 'prototype))) - (set-obj! (. ,name 'prototype) 'constructor ,name))) - (set-obj! ,name '__name__ ',name) - ,@(map (lambda (fn) - `(set-obj! (. ,name 'prototype) - ,(%class-method-name (car fn)) - ,(%class-lambda fn))) - functions)) - (let ((item (car lst))) - (if (eq? (car item) 'constructor) - (iter functions item (cdr lst)) - (iter (cons item functions) constructor (cdr lst))))))) + (let ((g:parent (gensym))) + (let iter ((functions '()) (constructor '()) (lst body)) + (if (null? lst) + `(begin + (define ,name ,(if (null? constructor) + `(lambda ()) + ;; we return this to solve issue when constructor + ;; return a promise + ;; ref: https://stackoverflow.com/a/50885340/387194 + (append (%class-lambda constructor) + (list 'this)))) + (set-obj! ,name (Symbol.for "__class__") true) + (let ((,g:parent ,parent )) + (if (not (null? ,g:parent)) + (begin + (set-obj! ,name 'prototype (Object.create (. ,g:parent 'prototype))) + (set-obj! (. ,name 'prototype) 'constructor ,name)))) + (set-obj! ,name '__name__ ',name) + ,@(map (lambda (fn) + `(set-obj! (. ,name 'prototype) + ,(%class-method-name (car fn)) + ,(%class-lambda fn))) + functions)) + (let ((item (car lst))) + (if (eq? (car item) 'constructor) + (iter functions item (cdr lst)) + (iter (cons item functions) constructor (cdr lst)))))))) ;; ----------------------------------------------------------------------------- (define-syntax class (syntax-rules () ((_) (error "class: parent required")) - ((_ parent body ...) - (let () + ((_ parent-expr body ...) + (let ((parent parent-expr)) + (if (not (or (procedure? parent) (eq? parent #null))) + (error "parent class need to be a function or #null")) (define-class temp parent body ...) + (set-obj! temp "__name__" "anonymous") temp))) "(class body ...) @@ -1896,7 +2002,8 @@ "(promise? obj) Checks if the value is a promise created with delay or make-promise." - (string=? (type obj) "promise")) + (and (string=? (type obj) "function") + (. obj (Symbol.for "promise")))) ;; ----------------------------------------------------------------------------- (define (positive? x) @@ -2786,14 +2893,6 @@ (and (char-alphabetic? char) (char=? (char-downcase char) char))) -;; ----------------------------------------------------------------------------- -(define (newline . rest) - "(newline [port]) - - Write newline character to standard output or given port" - (let ((port (if (null? rest) (current-output-port) (car rest)))) - (display "\n" port))) - ;; ----------------------------------------------------------------------------- (define (write obj . rest) "(write obj [port]) @@ -4820,6 +4919,7 @@ (new ,name ,@(cdr constructor))) (define (,pred obj) (instanceof ,name obj)) + (set-repr! ,name (lambda () (string-append "#string ',name) ")>"))) ,@(map (lambda (field) (let ((prop-name (car field)) (get (cadr field)) @@ -4944,7 +5044,7 @@ Create new empty library object with empty namespace." (let* ((parent (. (current-environment) '__parent__)) - (lib (let ((lib (--> parent (get name &(:throwError false))))) + (lib (let ((lib (--> parent (get name &(:throwError #f))))) (if (null? lib) (new %Library name) lib))) diff --git a/dist/std.xcb b/dist/std.xcb index 833f5b28d..c7d95bbcd 100644 Binary files a/dist/std.xcb and b/dist/std.xcb differ diff --git a/docs/docs/lips/intro.md b/docs/docs/lips/intro.md index 339d1cbcf..98178ce72 100644 --- a/docs/docs/lips/intro.md +++ b/docs/docs/lips/intro.md @@ -1053,6 +1053,25 @@ $ lips -c file.xcb Will create `file.xcb` in same directory. For smaller files it make not have a difference when loading `.xcb` or `.scm` files. +<<<<<<< HEAD +**NOTE**: directives `#!fold-case` and `#!no-fold-case` work only inside the parser and they are +treated as comments, so you can't compile the code that have those directives. + +## loading SRFI + +In LIPS, you can use `(load)` with path absolute or relative to the directory of the executed LIPS +file. But you can use special syntax that indicate the root directory of the LIPS Scheme. + +```scheme +(load "@lips/lib/srfi/1.scm") +``` + +This will load the code from [SRFI-1](https://srfi.schemers.org/srfi-1/srfi-1.html) List +Library. You can use this syntax in Node based REPL (NPM executable). The same syntax should work +with the web. But note that the root directory reply on the path of the LIPS Scheme script file. So +you if you bundle the code with Webpack or Rollup, LIPS may not find the root URL and may not be +able to load the proper file. +======= **NOTE**: directives `#!fold-case` and `#!no-fold-case` work only inside the parser and they are treated as comments, so you can't compile the code that have those directives. @@ -1061,3 +1080,4 @@ as comments, so you can't compile the code that have those directives. LISP Scheme currently don't support [continuations](/docs/scheme-intro/continuations) and [Tail Call Optimization](/docs/scheme-intro/core#tail-call-optimization). But they are part of the roadmap for version 1.0. +>>>>>>> origin/master diff --git a/docs/reference.json b/docs/reference.json index 79884c92b..7e15473d0 100644 --- a/docs/reference.json +++ b/docs/reference.json @@ -1 +1 @@ -[{"name":"-","doc":"(- n1 n2 ...)\n(- n)\n\nSubtracts n2 and subsequent numbers from n1. If only one argument is passed\nit will negate the value."},{"name":"-->","doc":"Helper macro that simplifies calling methods on objects. It works with chaining\nusage: (--> ($ \"body\")\n (css \"color\" \"red\")\n (on \"click\" (lambda () (display \"click\"))))\n\n (--> document (querySelectorAll \"div\"))\n\n (--> (fetch \"https://jcubic.pl\")\n (text)\n (match #/([^<]+)<\\/title>/)\n 1)\n\n (--> document\n (querySelectorAll \".cmd-prompt\")\n 0\n 'innerHTML\n (replace #/<(\"[^\"]+\"|[^>])+>/g \"\"))\n\n (--> document.body\n (style.setProperty \"--color\" \"red\"))"},{"name":".","doc":"(. obj . args)\n(get obj . args)\n\nThis function uses an object as a base and keeps using arguments to get the\nproperty of JavaScript object. Arguments need to be a strings.\ne.g. `(. console \"log\")` if you use any function inside LIPS it\nwill be weakly bound (can be rebound), so you can call this log function\nwithout problem unlike in JavaScript when you use\n`var log = console.log`.\n`get` is an alias because . doesn't work everywhere, e.g. you can't\npass it as an argument."},{"name":"..","doc":"(.. foo.bar.baz)\n\nGets the value from a nested object where the argument is a period separated symbol."},{"name":"*","doc":"(* . numbers)\n\nMultiplies all numbers passed as arguments. If single value is passed\nit will return that value."},{"name":"**","doc":"(** a b)\n\nFunction that calculates number a to to the power of b."},{"name":"/","doc":"(/ n1 n2 ...)\n(/ n)\n\nDivides n1 by n2 and subsequent arguments one by one. If single argument\nis passed it will calculate (/ 1 n)."},{"name":"&","doc":"(& a b)\n\nFunction that calculates the bitwise and operation."},{"name":"+","doc":"(+ . numbers)\n\nSums all numbers passed as arguments. If single value is passed it will\nreturn that value."},{"name":"<","doc":"(< x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically increasing, i.e. x1 < x2 and x2 < x3 and so on."},{"name":"<<","doc":"(<< a b)\n\nFunction that left shifts the value a by value b bits."},{"name":"<=","doc":"(<= x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically nondecreasing, i.e. x1 <= x2 and x2 <= x3 and so on."},{"name":"=","doc":"(== x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nall equal."},{"name":"==","doc":"(== x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nall equal."},{"name":">","doc":"(> x1 x2 x3 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."},{"name":">=","doc":"(>= x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."},{"name":">>","doc":"(>> a b)\n\nFunction that right shifts the value a by value b bits."},{"name":"|","doc":"(| a b)\n\nFunction that calculates the bitwise or operation."},{"name":"~","doc":"(~ number)\n\nFunction that calculates the bitwise inverse (flip all the bits)."},{"name":"1-","doc":"(1- number)\n\nFunction that subtracts 1 from the number and return result."},{"name":"1+","doc":"(1+ number)\n\nFunction that adds 1 to the number and return result."},{"name":"abs","doc":"(abs number)\n\nFunction that returns the absolute value (magnitude) of number."},{"name":"alist->assign","doc":"(alist->assign alist . list-of-alists)\n\nFunction that works like Object.assign but for LIPS alists."},{"name":"alist->object","doc":"(alist->object alist)\n\nFunction that converts alist pairs to a JavaScript object."},{"name":"always","doc":"(always constant)\n\nHigher-order function that returns a new thunk that always returns\nthe given constant when called."},{"name":"and","doc":"(and . expressions)\n\nMacro that evaluates each expression in sequence and if any value returns false\nit will stop and return false. If each value returns true it will return the\nlast value. If it's called without arguments it will return true."},{"name":"angle","doc":"(angle x)\n\nReturns angle of the complex number in polar coordinate system."},{"name":"append","doc":"(append item ...)\n\nFunction that creates a new list with each argument appended end-to-end.\nIt will always return a new list and not modify its arguments."},{"name":"append!","doc":"(append! arg1 ...)\n\nDestructive version of append, it can modify the lists in place. It returns\na new list where each argument is appended to the end. It may modify\nlists added as arguments."},{"name":"apply","doc":"(apply fn list)\n\nFunction that calls fn with the list of arguments."},{"name":"apropos","doc":"(apropos name)\n\nSearch the current environment and display names that match the given name.\nname can be regex, string or symbol."},{"name":"array->list","doc":"(array->list array)\n\nFunction that converts a JavaScript array to a LIPS cons list."},{"name":"array?","doc":"(array? expression)\n\nPredicate that tests if value is an array."},{"name":"assoc","doc":"(assoc obj alist)\n\nReturns pair from alist that match given key using equal? check."},{"name":"assq","doc":"(assq obj alist)\n\nReturns pair from a list that matches given key using eq? check."},{"name":"assv","doc":"(assv obj alist)\n\nReturns pair from alist that match given key using eqv? check."},{"name":"atan","doc":"(atan z)\n(atan x y)\n\nFunction calculates arcus tangent of a complex number.\nIf two arguments are passed and they are not complex numbers\nit calculate Math.atan2 on those arguments."},{"name":"await","doc":"(await value)\n\nUnquotes a quoted promise so it can be automagically evaluated (resolved\nto its value)."},{"name":"begin","doc":"(begin . args)\n\nMacro that runs a list of expressions in order and returns the value\nof the last one. It can be used in places where you can only have a\nsingle expression, like (if)."},{"name":"begin*","doc":"(begin* . body)\n\nThis macro is a parallel version of begin. It evaluates each expression\nin the body and if it's a promise it will await it in parallel and return\nthe value of the last expression (i.e. it uses Promise.all())."},{"name":"binary","doc":"(binary fn)\n\nReturns a new function with arguments limited to two."},{"name":"binary-port?","doc":"(binary-port? port)\n\nFunction that tests if argument is binary port."},{"name":"boolean?","doc":"(boolean? x)\n\nReturns true if value is boolean."},{"name":"boolean=?","doc":"(boolean=? b1 b2 ...)\n\nChecks if all arguments are boolean and if they are the same."},{"name":"bound?","doc":"(bound? x [env])\n\nFunction that check if the variable is defined in the given environment,\nor interaction-environment if not specified."},{"name":"buffer->u8vector","doc":"(buffer->u8vector bin)\n\nCross platform function that can be used in both Node and browser.\nIt can be used together with %read-file or %read-binary-file to convert\nthe result ArrayBuffer or Buffer to u8vector."},{"name":"bytevector","doc":"(u8vector v1 v2 ...)\n\nCreate unsigned 8-bit integer vector (C unsigned char) from give arguments."},{"name":"bytevector-append","doc":"(bytevector-append v1 ...)\n\nCreate new bytevector u8vector that is created from joining each argument."},{"name":"bytevector-copy","doc":"(bytevector-copy v)\n(bytevector-copy v start)\n(bytevector-copy v start end)\n\nReturns a new vector from start to end. If no start and end is provided\nwhole vector is copied and returned."},{"name":"bytevector-copy!","doc":"(bytevector-copy! to at from)\n(bytevector-copy! to at from start)\n(bytevector-copy! to at from start end)\n\nCopies the bytes of bytevector from between start and end to bytevector to,\nstarting at at."},{"name":"bytevector-length","doc":"(u8vector-length v)\n\nreturn length of unsigned 8-bit integer vector (C unsigned char)."},{"name":"bytevector-u8-ref","doc":"(u8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"bytevector-u8-set!","doc":"(u8vector-set! vector k)\n\nFunction set value of unsigned 8-bit integer vector (C unsigned char) at index k.\nIf index is out of range it throw exception."},{"name":"bytevector?","doc":"(u8vector? x)\n\nReturns #t of argument is unsigned 8-bit integer vector (C unsigned char),\notherwise it return #f."},{"name":"caaaaar","doc":"(caaaaar arg)\n\nFunction that calculates (car (car (car (car (car arg)))))"},{"name":"caaaadr","doc":"(caaaadr arg)\n\nFunction that calculates (car (car (car (car (cdr arg)))))"},{"name":"caaaar","doc":"(caaaar arg)\n\nFunction that calculates (car (car (car (car arg))))"},{"name":"caaadar","doc":"(caaadar arg)\n\nFunction that calculates (car (car (car (cdr (car arg)))))"},{"name":"caaaddr","doc":"(caaaddr arg)\n\nFunction that calculates (car (car (car (cdr (cdr arg)))))"},{"name":"caaadr","doc":"(caaadr arg)\n\nFunction that calculates (car (car (car (cdr arg))))"},{"name":"caaar","doc":"(caaar arg)\n\nFunction that calculates (car (car (car arg)))"},{"name":"caadaar","doc":"(caadaar arg)\n\nFunction that calculates (car (car (cdr (car (car arg)))))"},{"name":"caadadr","doc":"(caadadr arg)\n\nFunction that calculates (car (car (cdr (car (cdr arg)))))"},{"name":"caadar","doc":"(caadar arg)\n\nFunction that calculates (car (car (cdr (car arg))))"},{"name":"caaddar","doc":"(caaddar arg)\n\nFunction that calculates (car (car (cdr (cdr (car arg)))))"},{"name":"caadddr","doc":"(caadddr arg)\n\nFunction that calculates (car (car (cdr (cdr (cdr arg)))))"},{"name":"caaddr","doc":"(caaddr arg)\n\nFunction that calculates (car (car (cdr (cdr arg))))"},{"name":"caadr","doc":"(caadr arg)\n\nFunction that calculates (car (car (cdr arg)))"},{"name":"caar","doc":"(caar arg)\n\nFunction that calculates (car (car arg))"},{"name":"cadaaar","doc":"(cadaaar arg)\n\nFunction that calculates (car (cdr (car (car (car arg)))))"},{"name":"cadaadr","doc":"(cadaadr arg)\n\nFunction that calculates (car (cdr (car (car (cdr arg)))))"},{"name":"cadaar","doc":"(cadaar arg)\n\nFunction that calculates (car (cdr (car (car arg))))"},{"name":"cadadar","doc":"(cadadar arg)\n\nFunction that calculates (car (cdr (car (cdr (car arg)))))"},{"name":"cadaddr","doc":"(cadaddr arg)\n\nFunction that calculates (car (cdr (car (cdr (cdr arg)))))"},{"name":"cadadr","doc":"(cadadr arg)\n\nFunction that calculates (car (cdr (car (cdr arg))))"},{"name":"cadar","doc":"(cadar arg)\n\nFunction that calculates (car (cdr (car arg)))"},{"name":"caddaar","doc":"(caddaar arg)\n\nFunction that calculates (car (cdr (cdr (car (car arg)))))"},{"name":"caddadr","doc":"(caddadr arg)\n\nFunction that calculates (car (cdr (cdr (car (cdr arg)))))"},{"name":"caddar","doc":"(caddar arg)\n\nFunction that calculates (car (cdr (cdr (car arg))))"},{"name":"cadddar","doc":"(cadddar arg)\n\nFunction that calculates (car (cdr (cdr (cdr (car arg)))))"},{"name":"caddddr","doc":"(caddddr arg)\n\nFunction that calculates (car (cdr (cdr (cdr (cdr arg)))))"},{"name":"cadddr","doc":"(cadddr arg)\n\nFunction that calculates (car (cdr (cdr (cdr arg))))"},{"name":"caddr","doc":"(caddr arg)\n\nFunction that calculates (car (cdr (cdr arg)))"},{"name":"cadr","doc":"(cadr arg)\n\nFunction that calculates (car (cdr arg))"},{"name":"call-with-current-continuation","doc":"(call/cc proc)\n\nCall-with-current-continuation.\n\nNOT SUPPORTED BY LIPS RIGHT NOW"},{"name":"call-with-input-file","doc":"(call-with-input-file filename proc)\n\nProcedure open file for reading, call user defined procedure with given port\nand then close the port. It return value that was returned by user proc\nand it close the port even if user proc throw exception."},{"name":"call-with-output-file","doc":"(call-with-output-file filename proc)\n\nProcedure open file for writing, call user defined procedure with port\nand then close the port. It return value that was returned by user proc\nand it close the port even if user proc throw exception."},{"name":"call-with-port","doc":"(call-with-port port proc)\n\nProc is executed with given port and after it returns, the port is closed."},{"name":"call-with-values","doc":"(call-with-values producer consumer)\n\nCalls the producer procedure with no arguments, then calls the\nconsumer procedure with the returned value as an argument -- unless\nthe returned value is a special Values object created by (values), if it is\nthe values are unpacked and the consumer is called with multiple arguments."},{"name":"call/cc","doc":"(call/cc proc)\n\nCall-with-current-continuation.\n\nNOT SUPPORTED BY LIPS RIGHT NOW"},{"name":"car","doc":"(car pair)\n\nThis function returns the car (item 1) of the list."},{"name":"cdaaaar","doc":"(cdaaaar arg)\n\nFunction that calculates (cdr (car (car (car (car arg)))))"},{"name":"cdaaadr","doc":"(cdaaadr arg)\n\nFunction that calculates (cdr (car (car (car (cdr arg)))))"},{"name":"cdaaar","doc":"(cdaaar arg)\n\nFunction that calculates (cdr (car (car (car arg))))"},{"name":"cdaadar","doc":"(cdaadar arg)\n\nFunction that calculates (cdr (car (car (cdr (car arg)))))"},{"name":"cdaaddr","doc":"(cdaaddr arg)\n\nFunction that calculates (cdr (car (car (cdr (cdr arg)))))"},{"name":"cdaadr","doc":"(cdaadr arg)\n\nFunction that calculates (cdr (car (car (cdr arg))))"},{"name":"cdaar","doc":"(cdaar arg)\n\nFunction that calculates (cdr (car (car arg)))"},{"name":"cdadaar","doc":"(cdadaar arg)\n\nFunction that calculates (cdr (car (cdr (car (car arg)))))"},{"name":"cdadadr","doc":"(cdadadr arg)\n\nFunction that calculates (cdr (car (cdr (car (cdr arg)))))"},{"name":"cdadar","doc":"(cdadar arg)\n\nFunction that calculates (cdr (car (cdr (car arg))))"},{"name":"cdaddar","doc":"(cdaddar arg)\n\nFunction that calculates (cdr (car (cdr (cdr (car arg)))))"},{"name":"cdadddr","doc":"(cdadddr arg)\n\nFunction that calculates (cdr (car (cdr (cdr (cdr arg)))))"},{"name":"cdaddr","doc":"(cdaddr arg)\n\nFunction that calculates (cdr (car (cdr (cdr arg))))"},{"name":"cdadr","doc":"(cdadr arg)\n\nFunction that calculates (cdr (car (cdr arg)))"},{"name":"cdar","doc":"(cdar arg)\n\nFunction that calculates (cdr (car arg))"},{"name":"cddaaar","doc":"(cddaaar arg)\n\nFunction that calculates (cdr (cdr (car (car (car arg)))))"},{"name":"cddaadr","doc":"(cddaadr arg)\n\nFunction that calculates (cdr (cdr (car (car (cdr arg)))))"},{"name":"cddaar","doc":"(cddaar arg)\n\nFunction that calculates (cdr (cdr (car (car arg))))"},{"name":"cddadar","doc":"(cddadar arg)\n\nFunction that calculates (cdr (cdr (car (cdr (car arg)))))"},{"name":"cddaddr","doc":"(cddaddr arg)\n\nFunction that calculates (cdr (cdr (car (cdr (cdr arg)))))"},{"name":"cddadr","doc":"(cddadr arg)\n\nFunction that calculates (cdr (cdr (car (cdr arg))))"},{"name":"cddar","doc":"(cddar arg)\n\nFunction that calculates (cdr (cdr (car arg)))"},{"name":"cdddaar","doc":"(cdddaar arg)\n\nFunction that calculates (cdr (cdr (cdr (car (car arg)))))"},{"name":"cdddadr","doc":"(cdddadr arg)\n\nFunction that calculates (cdr (cdr (cdr (car (cdr arg)))))"},{"name":"cdddar","doc":"(cdddar arg)\n\nFunction that calculates (cdr (cdr (cdr (car arg))))"},{"name":"cddddar","doc":"(cddddar arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr (car arg)))))"},{"name":"cdddddr","doc":"(cdddddr arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr (cdr arg)))))"},{"name":"cddddr","doc":"(cddddr arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr arg))))"},{"name":"cdddr","doc":"(cdddr arg)\n\nFunction that calculates (cdr (cdr (cdr arg)))"},{"name":"cddr","doc":"(cddr arg)\n\nFunction that calculates (cdr (cdr arg))"},{"name":"cdr","doc":"(cdr pair)\n\nThis function returns the cdr (all but first) of the list."},{"name":"ceiling","doc":"(ceiling number)\n\nFunction that calculates the ceiling of a number."},{"name":"char->integer","doc":"(char->integer chr)\n\nReturns the codepoint of Unicode character."},{"name":"char-alphabetic?","doc":"(char-alphabetic? chr)\n\nReturns true if character is leter of the ASCII alphabet."},{"name":"char-ci<?","doc":"(char-ci<? chr1 chr2)\n\nReturns true if characters are monotonically increasing case insensitive."},{"name":"char-ci<=?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-decreasing, case insensitive."},{"name":"char-ci=?","doc":"(char-ci=? chr1 chr2 ...)\n\nChecks if all characters are equal, case insensitive."},{"name":"char-ci>?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically decreasing case insensitive."},{"name":"char-ci>=?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-increasing, case insensitive."},{"name":"char-downcase","doc":"(char-downcase chr)\n\nCreate lowercase version of the character."},{"name":"char-foldcase","doc":"(char-foldcase char)\n\nReturns lowercase character using the Unicode simple case-folding algorithm."},{"name":"char-lower-case?","doc":"(char-upper-case? char)\n\nChecks if character is lower case."},{"name":"char-numeric?","doc":"(char-numeric? chr)\n\nReturns true if character is number."},{"name":"char-ready?","doc":"(char-ready?)\n(char-ready? port)\n\nChecks if characters is ready in input port. This is useful mostly\nfor interactive ports that return false if it would wait for user input.\nIt return false if port is closed."},{"name":"char-upcase","doc":"(char-upcase char)\n\nCreate uppercase version of the character."},{"name":"char-upper-case?","doc":"(char-upper-case? char)\n\nChecks if character is upper case."},{"name":"char-whitespace?","doc":"(char-whitespace? chr)\n\nReturns true if character is whitespace."},{"name":"char?","doc":"(char? obj)\n\nChecks if the object is a character."},{"name":"char<?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically increasing."},{"name":"char<=?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-decreasing."},{"name":"char=?","doc":"(char=? chr1 chr2 ...)\n\nChecks if all characters are equal."},{"name":"char>?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically decreasing."},{"name":"char>=?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-increasing."},{"name":"clone","doc":"(clone list)\n\nFunction that returns a clone of the list, that does not share any pairs with the\noriginal, so the clone can be safely mutated without affecting the original."},{"name":"close-input-port","doc":"(close-input-port port)\n\nProcedure close port that was opened with open-input-file. After that\nit no longer accept reading from that port."},{"name":"close-output-port","doc":"(close-output-port port)\n\nProcedure close port that was opened with open-output-file. After that\nit no longer accept write to that port."},{"name":"close-port","doc":"(close-port port)\n\nClose input or output port."},{"name":"command-line","doc":"(command-line)\n\nReturns the command line arguments, or an empty list if not running under Node.js."},{"name":"complement","doc":"(complement fn)\n\nHigher order function that returns the Boolean complement of the given function.\nIf the function fn for a given arguments return true the result function\nwill return false, if it would return false, the result function will return true."},{"name":"complex?","doc":"(complex? x)\n\nChecks if argument x is complex."},{"name":"compose","doc":"(compose . fns)\n\nHigher-order function that creates a new function that applies all functions\nfrom right to left and returns the last value. Reverse of pipe.\ne.g.:\n((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"},{"name":"concat","doc":"(concat . strings)\n\nFunction that creates a new string by joining its arguments."},{"name":"cond","doc":"(cond (predicate? . body)\n (predicate? . body))\n\n(cond (predicate? => procedure)\n (predicate? => procedure))\n\nMacro for condition checks. For usage instead of nested ifs.\nYou can use predicate and any number of expressions. Or symbol =>\nFollowed by procedure that will be invoked with result\nof the predicate."},{"name":"cons","doc":"(cons left right)\n\nThis function returns a new list with the first appended\nbefore the second. If the second is not a list cons will\nreturn a dotted pair."},{"name":"constructor","doc":"(constructor)\n\nFunction that is present in JavaScript environment. We define it in Scheme\nto fix an issue with define-class. This function throw an error."},{"name":"continuation?","doc":"(continuation? expression)\n\nPredicate that tests if value is a callable continuation."},{"name":"cos","doc":"(cos n)\n\nFunction that calculates cosine of a number."},{"name":"current-directory","doc":"(current-directory)\n\nReturns the current working directory, default is the path from where\nthe script was executed."},{"name":"current-environment","doc":"(current-environment)\n\nFunction that returns the current environment (they're first-class objects!)"},{"name":"current-error-port","doc":"(current-output-port)\n\nReturns the default stderr port."},{"name":"current-input-port","doc":"(current-input-port)\n\nReturns the default stdin port."},{"name":"current-jiffy","doc":"(current-jiffy)\n\nReturn current jiffy. In LIPS is jiffy since start of the process.\nYou can divide this value by (jiffies-per-second) to get seconds since\nstart of the process. And you can add %%start-jiffy to get jiffy since\nJanuary 1, 1970."},{"name":"current-output-port","doc":"(current-output-port)\n\nReturns the default stdout port."},{"name":"current-second","doc":"(current-second)\n\nFunctionn return exact integer of the seconds since January 1, 1970"},{"name":"curry","doc":"(curry fn . args)\n\nHigher-order function that creates a curried version of the function.\nThe result function will have partially applied arguments and it\nwill keep returning one-argument functions until all arguments are provided,\nthen it calls the original function with the accumulated arguments.\n\ne.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))"},{"name":"debugger","doc":"(debugger)\n\nFunction that triggers the JavaScript debugger (e.g. the browser devtools)\nusing the \"debugger;\" statement. If a debugger is not running this\nfunction does nothing."},{"name":"define","doc":"(define name expression)\n(define name expression \"doc string\")\n(define (function-name . args) . body)\n\nMacro for defining values. It can be used to define variables,\nor functions. If the first argument is list it will create a function\nwith name being first element of the list. This form expands to\n`(define function-name (lambda args body))`"},{"name":"define-class","doc":"(define-class name parent . body)\n\nDefines a class - JavaScript function constructor with prototype.\n\nusage:\n\n (define-class Person Object\n (constructor (lambda (self name)\n (set-obj! self '_name name)))\n (hi (lambda (self)\n (display (string-append self._name \" says hi\"))\n (newline))))\n (define jack (new Person \"Jack\"))\n (jack.hi) ; prints \"Jack says hi\""},{"name":"define-formatter-rule","doc":"(rule-pattern pattern)\n\nAnaphoric macro for defining patterns for the formatter.\nWith Ahead, Pattern and * defined values."},{"name":"define-global","doc":"(define-global var value)\n(define-global (name . args) body)\n\nDefines functions or variables in the global context, so they can be used\ninside let and get let variables in a closure. Useful for universal macros."},{"name":"define-library","doc":"(define-library (library (name namespace) . body)\n\nMacro for defining modules inside you can use define to create functions.\nAnd use export name to add that name to defined environment."},{"name":"define-macro","doc":"(define-macro (name . args) body)\n\nThe meta-macro, that creates new macros. If the return value is a list structure\nit will be evaluated where the macro is invoked from. You can use quasiquote `\nand unquote , and unquote-splicing ,@ inside to create an expression that will be\nevaluated at runtime. Macros works like this: if you pass any expression to a\nmacro the arguments will not be evaluated unless the macro's body explicitly\ncalls (eval) on it. Because of this a macro can manipulate the expression\n(arguments) as lists."},{"name":"define-record-type","doc":"(define-record-type name constructor pred . fields)\n\nMacro for defining records. Example of usage:\n\n(define-record-type <pare>\n (kons x y)\n pare?\n (x kar set-kar!)\n (y kdr set-kdr!))\n\n(define p (kons 1 2))\n(print (kar p))\n;; ==> 1\n(set-kdr! p 3)\n(print (kdr p))\n;; ==> 3"},{"name":"define-symbol-macro","doc":"(define-symbol-macro type (name . args) . body)\n\nCreates syntax extensions for evaluator similar to built-in , or `.\nIt's like an alias for a real macro. Similar to CL reader macros\nbut it receives already parsed code like normal macros. Type can be SPLICE\nor LITERAL symbols (see set-special!). ALL default symbol macros are literal."},{"name":"define-syntax","doc":"(define-syntax name expression [__doc__])\n\nDefines a new hygienic macro using syntax-rules with optional documentation."},{"name":"define-syntax-parameter","doc":"(define-syntax-parameter name syntax [__doc__])\n\nBinds <keyword> to the transformer obtained by evaluating <transformer spec>.\nThe transformer provides the default expansion for the syntax parameter,\nand in the absence of syntax-parameterize, is functionally equivalent to\ndefine-syntax."},{"name":"defmacro?","doc":"(defmacro? expression)\n\nChecks if object is a macro and it's expandable."},{"name":"degree->radians","doc":"(degree->radians x)\n\nConvert degrees to radians."},{"name":"delay","doc":"(delay expression)\n\nWill create a promise from expression that can be forced with (force)."},{"name":"delete-file","doc":"(delete-file filename)\n\nDeletes the file of given name."},{"name":"denominator","doc":"(denominator n)\n\nReturn denominator of rational or same number if one is not rational."},{"name":"digit-value","doc":"(digit-value chr)\n\nReturn digit number if character is numeral (as per char-numeric?)\nor #f otherwise."},{"name":"dir","doc":"(dir obj)\n\nReturns all props on the object including those in prototype chain."},{"name":"display","doc":"(display string [port])\n\nThis function outputs the string to the standard output or\nthe port if given. No newline."},{"name":"display-error","doc":"(display-error . args)\n\nDisplay an error message on stderr."},{"name":"do","doc":"(do ((<var> <init> <next>)) (test return) . body)\n\nIteration macro that evaluates the expression body in scope of the variables.\nOn each loop it changes the variables according to the <next> expression and runs\ntest to check if the loop should continue. If test is a single value, the macro\nwill return undefined. If the test is a pair of expressions the macro will\nevaluate and return the second expression after the loop exits."},{"name":"do-iterator","doc":"(do-iterator (var expr) (test result) body ...)\n\nIterates over iterators (e.g. created with JavaScript generator function)\nthat works with normal and async iterators. You can loop over an infinite\niterators and break the loop if you want, using expression like in do macro.\nLong synchronous iterators will block the main thread (you can't print\n1000 numbers from infinite iterators, because it will freeze the browser),\nbut if you use async iterators you can process the values as they are\ngenerated."},{"name":"drop","doc":"(take list n)\n\nReturns a list where first n elements are removed."},{"name":"dynamic-wind","doc":"(dynamic-wind before thunk after)\n\nAccepts 3 procedures/lambdas and executes before, then thunk, and\nalways after even if an error occurs in thunk."},{"name":"empty?","doc":"(empty? object)\n\nFunction that returns #t if value is nil (an empty list) or undefined."},{"name":"env","doc":"(env)\n(env obj)\n\nFunction that returns a list of names (functions, macros and variables)\nthat are bound in the current environment or one of its parents."},{"name":"environment-bound?","doc":"(environment-bound? env symbol)\n\nChecks if symbol is a bound variable similar to bound?."},{"name":"environment?","doc":"(environment? obj)\n\nChecks if object is a LIPS environment."},{"name":"eof-object","doc":"(eof-object)\n\nProcedure returns eof object that indicate end of the port"},{"name":"eof-object?","doc":"(eof-object? arg)\n\nChecks if value is eof object, returned from input string\nport when there are no more data to read."},{"name":"eq?","doc":"(eq? a b)\n\nFunction that compares two values if they are identical."},{"name":"equal?","doc":"(equal? a b)\n\nThe function checks if values are equal. If both are a pair or an array\nit compares their elements recursively. If pairs have cycles it compares\nthem with eq?"},{"name":"eqv?","doc":"(eqv? a b)\n\nFunction that compares the values. It returns true if they are the same, they\nneed to have the same type."},{"name":"error","doc":"(error message ...)\n\nFunction raises error with given message and arguments,\nwhich are called invariants."},{"name":"error-object-irritants","doc":"(error-object-irritants error-object)\n\nReturns a list of the irritants encapsulated by error-object."},{"name":"error-object-message","doc":"(error-object-message error-object)\n\nReturns the message encapsulated by error-object."},{"name":"error-object?","doc":"(error-object? obj)\n\nChecks if object is of Error object thrown by error function."},{"name":"escape-regex","doc":"(escape-regex string)\n\nFunction that returns a new string where all special operators used in regex,\nare escaped with backslashes so they can be used in the RegExp constructor\nto match a literal string."},{"name":"eval","doc":"(eval expr)\n(eval expr environment)\n\nFunction that evaluates LIPS Scheme code. If the second argument is provided\nit will be the environment that the code is evaluated in."},{"name":"even?","doc":"(even? number)\n\nChecks if number is even."},{"name":"every","doc":"(every fn list)\n\nFunction that calls fn on each item of the list, if every value returns true\nit will return true otherwise it return false.\nAnalogous to Python all(map(fn, list))."},{"name":"exact","doc":"(inexact->exact number)\n\nFunction that converts real number to exact rational number."},{"name":"exact->inexact","doc":"(exact->inexact n)\n\nConvert exact number to inexact."},{"name":"exact-integer?","doc":"(exact-integer? n)\n\nReturns #t if z is both exact and an integer; otherwise\nreturns #f."},{"name":"exact?","doc":"(exact? n)"},{"name":"exp","doc":"(exp n)\n\nFunction that calculates e raised to the power of n."},{"name":"expt","doc":"(** a b)\n\nFunction that calculates number a to to the power of b."},{"name":"f32vector","doc":"(f32vector v1 v2 ...)\n\nCreate 32-bit IEEE-754 floating point number vector (C float) from give arguments."},{"name":"f32vector-length","doc":"(f32vector-length v)\n\nreturn length of 32-bit IEEE-754 floating point number vector (C float)."},{"name":"f32vector-ref","doc":"(f32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"f32vector-set!","doc":"(f32vector-set! vector k)\n\nFunction set value of 32-bit IEEE-754 floating point number vector (C float) at index k.\nIf index is out of range it throw exception."},{"name":"f32vector?","doc":"(f32vector? x)\n\nReturns #t of argument is 32-bit IEEE-754 floating point number vector (C float),\notherwise it return #f."},{"name":"f64vector","doc":"(f64vector v1 v2 ...)\n\nCreate 64-bit IEEE-754 floating point number vector (C double) from give arguments."},{"name":"f64vector-length","doc":"(f64vector-length v)\n\nreturn length of 64-bit IEEE-754 floating point number vector (C double)."},{"name":"f64vector-ref","doc":"(f64vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"f64vector-set!","doc":"(f64vector-set! vector k)\n\nFunction set value of 64-bit IEEE-754 floating point number vector (C double) at index k.\nIf index is out of range it throw exception."},{"name":"f64vector?","doc":"(f64vector? x)\n\nReturns #t of argument is 64-bit IEEE-754 floating point number vector (C double),\notherwise it return #f."},{"name":"features","doc":"(features)\n\nFunction returns implemented features as a list."},{"name":"filter","doc":"(filter fn list)\n(filter regex list)\n\nHigher-order function that calls `fn` for each element of the list\nand return a new list for only those elements for which fn returns\na truthy value. If called with a regex it will create a matcher function."},{"name":"find","doc":"(find fn list)\n(find regex list)\n\nHigher-order function that finds the first value for which fn return true.\nIf called with a regex it will create a matcher function."},{"name":"finite?","doc":"(finite? x)\n\nChecks if value is finite."},{"name":"flatten","doc":"(flatten list)\n\nReturns a shallow list from tree structure (pairs)."},{"name":"flip","doc":"(flip fn)\n\nHigher-order function that returns a new function where the first two arguments\nare swapped.\n\nExample:\n\n (define first (curry (flip vector-ref) 0))\n (first #(1 2 3))\n ;; ==> 1"},{"name":"floor","doc":"(floor number)\n\nFunction that calculates the floor of a number."},{"name":"flush-output","doc":"(flush-output [port])\n\nIf output-port is buffered, this causes the contents of its buffer to be written to\nthe output device. Otherwise it has no effect. Returns an unspecified value."},{"name":"flush-output-port","doc":"(flush-output-port port)\n\nFunction do nothing, flush is not needed in LIPS in both NodeJS and Browser.\nThe function is added, so it don't throw exception when using R7RS code."},{"name":"fold","doc":"(fold fn init . lists)\n\nFunction fold is left-to-right reversal of reduce. It call `fn`\non each pair of elements of the list and returns a single value.\ne.g. it computes (fn 'a 'x (fn 'b 'y (fn 'c 'z 'foo)))\nfor: (fold fn 'foo '(a b c) '(x y z))"},{"name":"fold-left","doc":"(fold fn init . lists)\n\nFunction fold is left-to-right reversal of reduce. It call `fn`\non each pair of elements of the list and returns a single value.\ne.g. it computes (fn 'a 'x (fn 'b 'y (fn 'c 'z 'foo)))\nfor: (fold fn 'foo '(a b c) '(x y z))"},{"name":"fold-right","doc":"(reduce fn init list . lists)\n\nHigher-order function that takes each element of the list and calls\nthe fn with result of previous call or init and the next element\nof the list until each element is processed, and returns a single value\nas result of last call to `fn` function.\ne.g. it computes (fn 'c 'z (fn 'b 'y (fn 'a 'x 'foo)))\nfor: (reduce fn 'foo '(a b c) '(x y z))"},{"name":"for-each","doc":"(for-each fn . lists)\n\nHigher-order function that calls function `fn` on each\nvalue of the argument. If you provide more than one list\nit will take each value from each list and call `fn` function\nwith that many arguments as number of list arguments."},{"name":"force","doc":"(force promise)\n\nFunction that forces the promise and evaluates the delayed expression."},{"name":"format","doc":"(format string n1 n2 ...)\n\nThis function accepts a string template and replaces any\nescape sequences in its inputs:\n\n* ~a value as if printed with `display`\n* ~s value as if printed with `write`\n* ~% newline character\n* ~~ literal tilde '~'\n\nIf there are missing inputs or other escape characters it\nwill error."},{"name":"function?","doc":"(function? expression)\n\nPredicate that tests if value is a callable function."},{"name":"gcd","doc":"(gcd n1 n2 ...)\n\nFunction that returns the greatest common divisor of the arguments."},{"name":"gensym","doc":"(gensym)\n\nGenerates a unique symbol that is not bound anywhere,\nto use with macros as meta name."},{"name":"gensym-interal","doc":"(gensym-interal symbol)\n\nParser extension that creates a new quoted named gensym."},{"name":"gensym?","doc":"(gensym? value)\n\nReturns #t if value is a symbol created by gensym. It returns #f otherwise."},{"name":"get","doc":"(. obj . args)\n(get obj . args)\n\nThis function uses an object as a base and keeps using arguments to get the\nproperty of JavaScript object. Arguments need to be a strings.\ne.g. `(. console \"log\")` if you use any function inside LIPS it\nwill be weakly bound (can be rebound), so you can call this log function\nwithout problem unlike in JavaScript when you use\n`var log = console.log`.\n`get` is an alias because . doesn't work everywhere, e.g. you can't\npass it as an argument."},{"name":"get-environment-variable","doc":"(get-environment-variable name)\n\nReturns given environment variable. This function returns #void\nwhen called in the browser."},{"name":"get-environment-variables","doc":"(get-environment-variables)\n\nReturns all process environment variables as an alist. This function returns\nan empty list when called in the browser."},{"name":"get-output-bytevector","doc":"(get-output-string port)\n\nGets full string from string port. If nothing was wrote\nto given port it will return empty string."},{"name":"get-output-string","doc":"(get-output-string port)\n\nGets full string from string port. If nothing was wrote\nto given port it will return empty string."},{"name":"get-resource","doc":"(get-resource url)\n\nLoad JavaScript or CSS file in browser by adding script/link tag to head\nof the current document. When called from Node it allow it allows to load\nJavaScript files only."},{"name":"globalize","doc":"(globalize expr)\n\n Macro will get the value of the expression and add each method as function\n to global scope."},{"name":"help","doc":"(help object)\n\nThis macro returns documentation for a function or macro.\nYou can save the function or macro in a variable and use it\nhere. But getting help for a variable requires passing the\nvariable in a `quote`."},{"name":"http-get","doc":"(http-get url)\n\nNode.js function that sends a HTTP Request and returns a string or\nbinary Buffer object."},{"name":"identity","doc":"(identity n)\n\nNo-op function. It just returns its argument."},{"name":"if","doc":"(if cond true-expr false-expr)\n\nMacro that evaluates cond expression and if the value is true, it\nevaluates and returns true-expression, if not it evaluates and returns\nfalse-expression."},{"name":"ignore","doc":"(ignore . body)\n\nMacro that will evaluate the expression and swallow any promises that may\nbe created. It will discard any value that may be returned by the last body\nexpression. The code should have side effects and/or when it's promise\nit should resolve to undefined."},{"name":"imag-part","doc":"(imag-part n)\n\nReturn imaginary part of the complex number n."},{"name":"import","doc":"(import (library namespace))\n(import (only (library namespace) name1 name2))\n\nMacro for importing names from library."},{"name":"in","doc":"(in key value)\n\nFunction that uses the Javascript \"in\" operator to check if key is\na valid property in the value."},{"name":"include","doc":"(include file ...)\n\nLoad at least one file content and insert them into one,\nbody expression."},{"name":"indexed-db?","doc":"(indexed-db?)\n\nFunction that tests if IndexedDB is available."},{"name":"inexact","doc":"(exact->inexact n)\n\nConvert exact number to inexact."},{"name":"inexact->exact","doc":"(inexact->exact number)\n\nFunction that converts real number to exact rational number."},{"name":"inexact?","doc":"(inexact? n)"},{"name":"infinite?","doc":"(infinite? x)\n\nChecks if value is infinite."},{"name":"input-port-open?","doc":"(input-port-open? port)\n\nChecks if argument is input-port and if you can read from it."},{"name":"input-port?","doc":"(input-port? arg)\n\nReturns true if argument is input port."},{"name":"instance?","doc":"(instance? obj)\n\nChecks if object is an instance, created with a new operator"},{"name":"instanceof","doc":"(instanceof type obj)\n\nPredicate that tests if the obj is an instance of type."},{"name":"integer->char","doc":"(integer->char chr)\n\nFunction that converts number argument to character."},{"name":"integer?","doc":"(integer? x)\n\nChecks if the argument x is integer."},{"name":"interaction-environment","doc":"(interaction-environment)\n\nReturns the interaction environment equal to lips.env. This can be overwritten\nwhen creating new interpreter with lips.Interpreter."},{"name":"iterator->array","doc":"(iterator->array object)\n\nReturn array from JavaScript iterator object."},{"name":"iterator?","doc":"(iterator? x)\n\n Checks if value is JavaScript iterator object."},{"name":"join","doc":"(join separator list)\n\nFunction that returns a string by joining elements of the list using separator."},{"name":"key->string","doc":"(key->string symbol)\n\nIf symbol is a keyword it converts that to string and removes the colon."},{"name":"key?","doc":"(key? symbol)\n\nChecks if symbol is a keyword (has a colon as first character)."},{"name":"lambda","doc":"(lambda (a b) body)\n(lambda args body)\n(lambda (a b . rest) body)\n\nThe lambda macro creates a new anonymous function. If the first element of\nthe body is a string and there is more elements the string is used as the\ndocumentation string, that can be read using (help fn)."},{"name":"lcm","doc":"(lcm n1 n2 ...)\n\nFunction that returns the least common multiple of the arguments."},{"name":"length","doc":"(length expression)\n\nFunction that returns the length of the object. The object can be a LIPS\nlist or any object that has a \"length\" property. Returns undefined if the\nlength could not be found."},{"name":"let","doc":"(let ((a value-a) (b value-b) ...) . body)\n\nMacro that creates a new environment, then evaluates and assigns values to names,\nand then evaluates the body in context of that environment. Values are evaluated\nsequentially but you can't access previous values/names when the next are\nevaluated. You can only get them in the body of the let expression. (If you want\nto define multiple variables and use them in each other's definitions, use\n`let*`.)"},{"name":"let-env","doc":"(let-env env . body)\n\nSpecial macro that evaluates body in context of given environment\nobject."},{"name":"let-env-values","doc":"(let-env-values env ((name var)) . body)\n\nAdds mappings for variables var from specified env.\nit is similar to let-env but lexical scope is working with it."},{"name":"let-syntax","doc":"(let-syntax ((name fn) ...) . body)\n\n Works like a combination of let and define-syntax. It creates\n local macros and evaluates body in context of those macros.\n The macro to letrec-syntax is like letrec is to let."},{"name":"let*","doc":"(let* ((a value-a) (b value-b) ...) . body)\n\nMacro similar to `let`, but the subsequent bindings after the first\nare evaluated in the environment including the previous let variables,\nso you can define one variable, and use it in the next's definition."},{"name":"letrec","doc":"(letrec ((a value-a) (b value-b) ...) . body)\n\nMacro that creates a new environment, then evaluates and assigns values to\nnames and then evaluates the body in context of that environment.\nValues are evaluated sequentially and the next value can access the\nprevious values/names."},{"name":"letrec-syntax","doc":"(letrec-syntax ((name fn) ...) . body)\n\n Works like a combination of letrec and define-syntax. It creates\n local macros and evaluates the body in context of those macros."},{"name":"letrec*","doc":"(letrec* ((a value-a) (b value-b) ...) . body)\n\nSame as letrec but the order of execution of the binding is guaranteed,\nso you can use recursive code as well as referencing the previous binding.\n\nIn LIPS both letrec and letrec* behave the same."},{"name":"list","doc":"(list . args)\n\nFunction that creates a new list out of its arguments."},{"name":"list->array","doc":"(list->array list)\n\nFunction that converts a LIPS list into a JavaScript array."},{"name":"list->string","doc":"(list->string _list)\n\nReturns a string from a list of characters."},{"name":"list->vector","doc":"(list->array list)\n\nFunction that converts a LIPS list into a JavaScript array."},{"name":"list-copy","doc":"(list-copy obj)\n\nCopy the object passed as argument but only if it's list. The car elements\nof the list are not copied, they are passed as is."},{"name":"list-match?","doc":"(list-match? predicate list)\n\nChecks if consecutive elements of the list match the predicate function."},{"name":"list-ref","doc":"(list-ref list n)\n\nReturns n-th element of a list."},{"name":"list-set!","doc":"(list-set! list n)\n\nReturns n-th element of a list."},{"name":"list-tail","doc":"(list-tail list k)\n\nReturns the sublist of list obtained by omitting the first k elements."},{"name":"list?","doc":"(list? obj)\n\nPredicate that tests if value is a proper linked list structure.\nThe car of each pair can be any value. It returns false on cyclic lists.\""},{"name":"list*","doc":"(list* arg1 ...)\n\nParallel asynchronous version of list. Like begin* except all values\nare returned in a list."},{"name":"load","doc":"(load filename)\n(load filename environment)\n\nFetches the file (from disk or network) and evaluates its content as LIPS code.\nIf the second argument is provided and it's an environment the evaluation\nwill happen in that environment."},{"name":"log","doc":"(log z)\n(log z1 z2)\n\nFunction that calculates natural logarithm (base e) of z. Where the argument\ncan be any number (including complex negative and rational). If the value is 0\nit returns NaN. It two arguments are provided it will calculate logarithm\nof z1 with given base z2."},{"name":"macro?","doc":"(macro? expression)\n\nPredicate that tests if value is a macro."},{"name":"macroexpand","doc":"(macroexpand expr)\n\nMacro that expand all macros inside and return single expression as output."},{"name":"macroexpand-1","doc":"(macroexpand-1 expr)\n\nMacro similar to macroexpand but it expand macros only one level\nand return single expression as output."},{"name":"magnitude","doc":"(magnitude x)\n\nReturns magnitude of the complex number in polar coordinate system."},{"name":"make-bytevector","doc":"(make-u8vector k fill)\n\nAllocate new unsigned 8-bit integer vector (C unsigned char) of length k,\nwith optional initial values."},{"name":"make-f32vector","doc":"(make-f32vector k fill)\n\nAllocate new 32-bit IEEE-754 floating point number vector (C float) of length k,\nwith optional initial values."},{"name":"make-f64vector","doc":"(make-f64vector k fill)\n\nAllocate new 64-bit IEEE-754 floating point number vector (C double) of length k,\nwith optional initial values."},{"name":"make-parameter","doc":"(make-parameter init converter)\n\nFunction creates new dynamic variable that can be custimized with parameterize\nmacro. The value should be assigned to a variable e.g.:\n\n(define radix (make-parameter 10))\n\nThe result value is a procedure that return the value of dynamic variable."},{"name":"make-polar","doc":"(make-polar magnitude angle)\n\nCreate new complex number from polar parameters."},{"name":"make-promise","doc":"(make-promise fn)\n\nFunction that creates a promise from a function."},{"name":"make-rectangular","doc":"(make-rectangular im re)\n\nCreates a complex number from imaginary and real part (a+bi form)."},{"name":"make-s16vector","doc":"(make-s16vector k fill)\n\nAllocate new signed 16-bit integer vector (C short) of length k,\nwith optional initial values."},{"name":"make-s32vector","doc":"(make-s32vector k fill)\n\nAllocate new signed 32-bit integer vector (C unsigned int) of length k,\nwith optional initial values."},{"name":"make-s8vector","doc":"(make-s8vector k fill)\n\nAllocate new signed 8-bit integer vector (C signed char) of length k,\nwith optional initial values."},{"name":"make-string","doc":"(make-string k [char])\n\nReturns new string with k elements. If char is provided\nit's filled with that character."},{"name":"make-tags","doc":"(make-tags expression)\n\nReturns a list structure of code with better syntax then raw LIPS"},{"name":"make-u16vector","doc":"(make-u16vector k fill)\n\nAllocate new unsigned 16-bit integer vector (C unsigned short) of length k,\nwith optional initial values."},{"name":"make-u32vector","doc":"(make-u32vector k fill)\n\nAllocate new unsigned 32-bit integer vector (C int) of length k,\nwith optional initial values."},{"name":"make-u8vector","doc":"(make-u8vector k fill)\n\nAllocate new unsigned 8-bit integer vector (C unsigned char) of length k,\nwith optional initial values."},{"name":"make-vector","doc":"(make-vector n [fill])\n\nCreates a new vector with n empty elements. If fill is specified it will set\nall elements of the vector to that value."},{"name":"map","doc":"(map fn . lists)\n\nHigher-order function that calls function `fn` with each\nvalue of the list. If you provide more then one list as argument\nit will take each value from each list and call `fn` function\nwith that many argument as number of list arguments. The return\nvalues of the fn calls are accumulated in a result list and\nreturned by map."},{"name":"match","doc":"(match pattern string)\n\nFunction that returns a match object from JavaScript as a list or #f if\nno match."},{"name":"max","doc":"(max n1 n2 ...)\n\nReturns the maximum of its arguments."},{"name":"member","doc":"(member obj list)\n\nReturns first object in the list that match using equal? function."},{"name":"memq","doc":"(memq obj list)\n\nReturns first object in the list that match using eq? function."},{"name":"memv","doc":"(memv obj list)\n\nReturns first object in the list that match using eqv? function."},{"name":"min","doc":"(min n1 n2 ...)\n\nReturns the minimum of its arguments."},{"name":"modulo","doc":"(modulo a b)\n\nReturns modulo operation on its argumennts."},{"name":"n-ary","doc":"(n-ary n fn)\n\nReturns a new function that limits the number of arguments to n."},{"name":"nan?","doc":"(nan? x)\n\nChecks if argument x is Not a Number (NaN) value."},{"name":"native-symbol?","doc":"(native-symbol? object)\n\nChecks if value is JavaScript Symbol."},{"name":"native.number","doc":"(native.number obj)\n\nIf argument is a number it will convert it to a native number."},{"name":"negative?","doc":"(negative? x)\n\nChecks if the number is smaller then 0"},{"name":"new","doc":"(new obj . args)\n\nFunction that creates new JavaScript instance of an object."},{"name":"new-library","doc":"(new-library name)\n\nCreate new empty library object with empty namespace."},{"name":"newline","doc":"(newline [port])\n\nWrite newline character to standard output or given port"},{"name":"not","doc":"(not x)\n\nReturns true if value is false and false otherwise."},{"name":"nth","doc":"(nth index obj)\n\nFunction that returns the nth element of the list or array.\nIf used with a non-indexable value it will error."},{"name":"nth-pair","doc":"(nth-pair list n)\n\nReturns nth pair of a list."},{"name":"null-environment","doc":"(null-environment)\n\nReturns a clean environment with only the standard library."},{"name":"null?","doc":"(null? expression)\n\nPredicate that tests if value is null-ish (i.e. undefined, nil, or\nJavascript null)."},{"name":"number->string","doc":"(number->string x [radix])\n\nFunction that converts number to string with optional radix (number base)."},{"name":"number?","doc":"(number? expression)\n\nPredicate that tests if value is a number or NaN value."},{"name":"numerator","doc":"(numerator n)\n\nReturn numerator of rational or same number if n is not rational."},{"name":"object","doc":"(object :name value)\n\nCreates a JavaScript object using key like syntax."},{"name":"object->alist","doc":"(object->alist object)\n\nFunction that converts a JavaScript object to Alist"},{"name":"object-literal","doc":"(object-literal :name value)\n\nCreates a JavaScript object using key like syntax. This is similar,\nto object but all values are quoted. This macro is used by the & object literal."},{"name":"object?","doc":"(object? expression)\n\nPredicate that tests if value is an plain object (not another LIPS type)."},{"name":"odd?","doc":"(odd? number)\n\nChecks if number is odd."},{"name":"once","doc":"(once fn)\n\nHigher-order function that returns a new function, that only calls the original\non the first invocation, and immediately returns the first call's result again\non subsequent invocations."},{"name":"open-binary-input-file","doc":"(open-binary-input-file filename)\n\nReturns new Input Binary Port with given filename. In Browser\nuser need to provide global fs variable that is instance of FS interface."},{"name":"open-binary-output-file","doc":"(open-binary-output-file filename)\n\nOpens file and return port that can be used for writing. If file\nexists it will throw an Error."},{"name":"open-input-bytevector","doc":"(open-input-bytevector bytevector)\n\nCreate new input binary port with given bytevector"},{"name":"open-input-file","doc":"(open-input-file filename)\n\nReturns new Input Port with given filename. In Browser user need to\nprovide global fs variable that is instance of FS interface."},{"name":"open-input-string","doc":"(open-input-string string)\n\nCreates new string port as input that can be used to\nread S-exressions from this port using `read` function."},{"name":"open-output-bytevector","doc":"(open-output-bytevector)\n\nCreate new output port that can be used to write binary data.\nAfter done with the data the output buffer can be obtained by calling\n`get-output-bytevector` function."},{"name":"open-output-file","doc":"(open-output-file filename)\n\nFunction that opens file and return port that can be used for writing. If file\nexists it will throw an Error."},{"name":"open-output-string","doc":"(open-output-string)\n\nCreates new output port that can used to write string into\nand after finish get the whole string using `get-output-string`."},{"name":"or","doc":"(or . expressions)\n\nMacro that executes the values one by one and returns the first that is\na truthy value. If there are no expressions that evaluate to true it\nreturns false."},{"name":"output-port-open?","doc":"(output-port-open? port)\n\nChecks if argument is output-port and if you can write to it."},{"name":"output-port?","doc":"(output-port? arg)\n\nReturns true if argument is output port."},{"name":"pair-map","doc":"(pair-map fn list)\n\nFunction that calls fn argument for pairs in a list and returns a combined list\nwith values returned from function fn. It works likes map but take two items\nfrom the list each time."},{"name":"pair?","doc":"(pair? expression)\n\nPredicate that tests if value is a pair or list structure."},{"name":"parameterize","doc":"(parameterize ((name value) ...)\n\nMacro that change the dynamic variable created by make-parameter."},{"name":"parent.frame","doc":"(parent.frame)\n\nReturns the parent environment if called from inside a function.\nIf no parent frame can be found it returns nil."},{"name":"parent.frames","doc":"(parent.frames)\n\nReturns the list of environments from parent frames (lambda function calls)"},{"name":"peek-char","doc":"(peek-char port)\n\nThis function reads and returns a character from the string\nport, or, if there is no more data in the string port, it\nreturns an EOF."},{"name":"peek-u8","doc":"(peek-u8)\n(peek-u8 port)\n\nReturn next byte from input-binary port. If there are no more bytes\nit return eof object."},{"name":"pipe","doc":"(pipe . fns)\n\nHigher-order function that creates a new function that applies all functions\nfrom left to right and returns the last value. Reverse of compose.\ne.g.:\n((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"},{"name":"plain-object?","doc":"(plain-object? x)\n\nChecks if value is a plain JavaScript object created using the object macro."},{"name":"pluck","doc":"(pluck . strings)\n\nIf called with a single string it will return a function that when\ncalled with an object will return that key from the object.\nIf called with more then one string the returned function will\ncreate a new object by copying all properties from the given object."},{"name":"port?","doc":"(port? x)\n\nReturns true if the argument is an input or output port object."},{"name":"positive?","doc":"(positive? x)\n\nChecks if the number is larger then 0"},{"name":"pprint","doc":"(pprint expression)\n\nThis function will pretty print its input to stdout. If it is called\nwith a non-list, it will just call the print function on its\ninput."},{"name":"pretty-format","doc":"(pretty-format pair)\n\nReturns a pretty printed string from pair expression."},{"name":"print","doc":"(print . args)\n\nThis function converts each input into a string and prints\nthe result to the standard output (by default it's the\nconsole but it can be defined in user code). This function\ncalls `(newline)` after printing each input."},{"name":"procedure?","doc":"(procedure? expression)\n\nPredicate that tests if value is a callable function or continuation."},{"name":"promise","doc":"(promise . body)\n\nAnaphoric macro that exposes resolve and reject functions from JS promise."},{"name":"promise?","doc":"(promise? obj)\n\nChecks if the value is a promise created with delay or make-promise."},{"name":"promisify","doc":"(promisify fn)\n\nSimple function for adding promises to NodeJS two-callback based functions.\nFunction tested only with fs module."},{"name":"prototype?","doc":"(prototype? obj)\n\nPredicate that tests if value is a valid JavaScript prototype,\ni.e. calling (new) with it will not throw '<x> is not a constructor'."},{"name":"qsort","doc":"(qsort list predicate)\n\nSorts the list using the quick sort algorithm according to predicate."},{"name":"quasiquote","doc":"(quasiquote list)\n\nSimilar macro to `quote` but inside it you can use special expressions (unquote\nx) abbreviated to ,x that will evaluate x and insert its value verbatim or\n(unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\ninto the result. Best used with macros but it can be used outside."},{"name":"quote","doc":"(quote expression) or 'expression\n\nMacro that returns a single LIPS expression as data (it won't evaluate the\nargument). It will return a list if put in front of LIPS code.\nAnd if put in front of a symbol it will return the symbol itself, not the value\nbound to that name."},{"name":"quote-promise","doc":"(quote-promise expr) or '>expr\n\nMacro used to escape automati awaiting of the expression. It will be wrapped\nwith a JavaScript class that behaves like Promise but will not be automatically\nresolved by LIPS like normal promises are."},{"name":"quoted-symbol?","doc":"(quoted-symbol? code)\n\nHelper function that tests if value is a quoted symbol. To be used in macros\nthat pass literal code that is transformed by parser.\n\nusage:\n\n (define-macro (test x)\n (if (quoted-symbol? x)\n `',(cadr x)))\n\n (list 'hello (test 'world))"},{"name":"quotient","doc":"(quotient a b)\n\nReturn quotient from division as integer."},{"name":"radians->degree","doc":"(radians->degree x)\n\nConvert radians to degrees."},{"name":"raise","doc":"(raise obj)\n\nThrows the object verbatim (no wrapping an a new Error)."},{"name":"random","doc":"(random)\n(random seed)\n\nFunction that generates new random real number using Knuth algorithm."},{"name":"range","doc":"(range stop)\n(range start stop)\n(range start stop step)\n\nReturns a list of numbers from start to stop with optional step.\nIf start is not defined it starts from 0. If start is larger than stop\nthe step needs to be negative otherwise it will hang in an infinite loop."},{"name":"rational?","doc":"(rational? x)\n\nChecks if the value is rational."},{"name":"rationalize","doc":"(rationalize number tolerance)\n\nReturns simplest rational number approximation differing from number by no more\nthan the tolerance."},{"name":"read","doc":"(read [port])\n\nThis function, if called with a port, it will parse the next\nitem from the port. If called without an input, it will read\na string from standard input (using the browser's prompt or\na user defined input method) and parse it. This function can be\nused together with `eval` to evaluate code from port."},{"name":"read-all","doc":"(read-all)\n(read-all port)\n\nRead all S-Expressions from port and return them as a list"},{"name":"read-bytevector","doc":"(read-bytevector k)\n(read-bytevector k port)\n\nRead next n bytes from input-binary port. If there are no more bytes\nit returns eof object. If there are less then n bytes in port it\nreturn the only bytes that are available"},{"name":"read-bytevector!","doc":"(read-bytevector! bytevector)\n(read-bytevector! bytevector port)\n(read-bytevector! bytevector port start)\n(read-bytevector! bytevector port start end)\n\nReads next bytes from binary input port and write them into byte vector.\nif not start is specified it start to write into 0 position of the vector until\nthe end or end the vector if no end is specified."},{"name":"read-char","doc":"(read-char port)\n\nThis function reads and returns the next character from the\ninput port."},{"name":"read-line","doc":"(read-line port)\n\nThis function reads and returns the next line from the input\nport."},{"name":"read-string","doc":"(read-string k)\n(read-string k port)\n\nReads the next k characters, or as many as are available\nbefore the end of file, from the textual input port into a\nnewly allocated string in left-to-right order and returns the\nstring. If no characters are available before the end of file,\nan end-of-file object is returned."},{"name":"read-u8","doc":"(read-u8)\n(read-u8 port)\n\nRead next byte from input-binary port. If there are no more bytes\nit return eof object."},{"name":"real-part","doc":"(real-part n)\n\nReturn real part of the complex number n."},{"name":"real?","doc":"(real? x)\n\nChecks if the argument x is real."},{"name":"reduce","doc":"(reduce fn init list . lists)\n\nHigher-order function that takes each element of the list and calls\nthe fn with result of previous call or init and the next element\nof the list until each element is processed, and returns a single value\nas result of last call to `fn` function.\ne.g. it computes (fn 'c 'z (fn 'b 'y (fn 'a 'x 'foo)))\nfor: (reduce fn 'foo '(a b c) '(x y z))"},{"name":"regex","doc":"(regex re)\n\nCreates a new regular expression from string, to not break Emacs formatting."},{"name":"regex?","doc":"(regex? x)\n\nReturns true if value is a regular expression, or false otherwise."},{"name":"remainder","doc":"(% n1 n2)\n\nFunction returns the remainder of n1/n2 (modulo)."},{"name":"remainder__","doc":"(modulo a b)\n\nReturns remainder from division operation."},{"name":"replace","doc":"(replace pattern replacement string)\n\nFunction that changes pattern to replacement inside string. Pattern can be a\nstring or regex and replacement can be function or string. See Javascript\nString.replace()."},{"name":"repr","doc":"(repr obj)\n\nFunction that returns a LIPS code representation of the object as a string."},{"name":"require","doc":"(require module)\n\nFunction used inside Node.js to import a module."},{"name":"require.resolve","doc":"(require.resolve path)\n\nReturns the path relative to the current module.\n\nOnly available when LIPS is running under Node.js."},{"name":"reset","doc":"(reset)\n\nFunction resets the environment and removes all user defined variables."},{"name":"response->content","doc":"(response->text binary res)\n\nReads all text from a Node.js HTTP response object. If binary argument\nis true it will return Buffer object that can be converted to u8vector.\n\n***Warning:*** it may overflow the Javascript call stack when converting the\nwhole buffer to u8vector, because LIPS doesn't have TCO."},{"name":"reverse","doc":"(reverse list)\n\nFunction that reverses the list or array. If value is not a list\nor array it will error."},{"name":"round","doc":"(round number)\n\nFunction that calculates the round of a number."},{"name":"s16vector","doc":"(s16vector v1 v2 ...)\n\nCreate signed 16-bit integer vector (C short) from give arguments."},{"name":"s16vector-length","doc":"(s16vector-length v)\n\nreturn length of signed 16-bit integer vector (C short)."},{"name":"s16vector-ref","doc":"(s16vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s16vector-set!","doc":"(s16vector-set! vector k)\n\nFunction set value of signed 16-bit integer vector (C short) at index k.\nIf index is out of range it throw exception."},{"name":"s16vector?","doc":"(s16vector? x)\n\nReturns #t of argument is signed 16-bit integer vector (C short),\notherwise it return #f."},{"name":"s32vector","doc":"(s32vector v1 v2 ...)\n\nCreate signed 32-bit integer vector (C unsigned int) from give arguments."},{"name":"s32vector-length","doc":"(s32vector-length v)\n\nreturn length of signed 32-bit integer vector (C unsigned int)."},{"name":"s32vector-ref","doc":"(s32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s32vector-set!","doc":"(s32vector-set! vector k)\n\nFunction set value of signed 32-bit integer vector (C unsigned int) at index k.\nIf index is out of range it throw exception."},{"name":"s32vector?","doc":"(s32vector? x)\n\nReturns #t of argument is signed 32-bit integer vector (C unsigned int),\notherwise it return #f."},{"name":"s8vector","doc":"(s8vector v1 v2 ...)\n\nCreate signed 8-bit integer vector (C signed char) from give arguments."},{"name":"s8vector-length","doc":"(s8vector-length v)\n\nreturn length of signed 8-bit integer vector (C signed char)."},{"name":"s8vector-ref","doc":"(s8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s8vector-set!","doc":"(s8vector-set! vector k)\n\nFunction set value of signed 8-bit integer vector (C signed char) at index k.\nIf index is out of range it throw exception."},{"name":"s8vector?","doc":"(s8vector? x)\n\nReturns #t of argument is signed 8-bit integer vector (C signed char),\notherwise it return #f."},{"name":"scheme-report-environment","doc":"(scheme-report-environment version)\n\nReturns new Environment object for given Scheme Spec version.\nOnly argument 5 is supported that create environment for R5RS."},{"name":"search","doc":"(search pattern string)\n\nFunction that returns the first found index of the pattern inside a string."},{"name":"set-car!","doc":"(set-car! obj value)\n\nFunction that sets the car (first item) of the list/pair to specified value.\nThe old value is lost."},{"name":"set-cdr!","doc":"(set-cdr! obj value)\n\nFunction that sets the cdr (tail) of the list/pair to specified value.\nIt will destroy the list. The old tail is lost."},{"name":"set-current-directory!","doc":"(set-current-directory! string)\n\nChanges the current working directory to provided string."},{"name":"set-global!","doc":"(set-global! name)\n\nMacro to make the name a Javascript global variable (i.e. accessible on globalThis)."},{"name":"set-obj!","doc":"(set-obj! obj key value)\n(set-obj! obj key value props)\n\nFunction set a property of a JavaScript object. props should be a vector of pairs,\npassed to Object.defineProperty."},{"name":"set-repr!","doc":"(add-repr! type fn)\n\nFunction that adds the string representation to the type, which should be\na constructor function.\n\nFunction fn should have args (obj q) and it should return a string. obj\nis the value that need to be converted to a string. If the object is nested\nand you need to use `repr` recursively, it should pass the second parameter q\nto repr, so string will be quoted when it's true.\n\ne.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))"},{"name":"set-special!","doc":"(set-special! symbol name [type])\n\nAdd a special symbol to the list of transforming operators by the parser.\ne.g.: `(add-special! \"#\" 'x)` will allow to use `#(1 2 3)` and it will be\ntransformed into (x (1 2 3)) so you can write x macro that will process\nthe list. 3rd argument is optional, and it can be one of two values:\nlips.specials.LITERAL, which is the default behavior, or\nlips.specials.SPLICE which causes the value to be unpacked into the expression.\nThis can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\nby # that defines vectors."},{"name":"set!","doc":"(set! name value)\n\nMacro that can be used to set the value of the variable or slot (mutate it).\nset! searches the scope chain until it finds first non empty slot and sets it."},{"name":"shuffle","doc":"(shuffle obj)\n\nOrder items in vector or list in random order."},{"name":"sin","doc":"(sin n)\n\nFunction that calculates sine of a number."},{"name":"single","doc":"(single list)\n\nChecks if argument is list with one element."},{"name":"some","doc":"(some fn list)\n\nHigher-order function that calls fn on each element of the list.\nIt stops and returns true when fn returns true for a value.\nIf none of the values give true, some will return false.\nAnalogous to Python any(map(fn, list))."},{"name":"sort","doc":"(sort list [predicate])\n\nSorts the list using optional predicate function. If no comparison function\nis given it will use <= and sort in increasing order."},{"name":"split","doc":"(split separator string)\n\nFunction that creates a list by splitting string by separator which can\nbe a string or regular expression."},{"name":"sqrt","doc":"(sqrt number)\n\nFunction that returns the square root of the number."},{"name":"square","doc":"(square z)\n\nReturns the square of z. This is equivalent to (* z z)."},{"name":"string","doc":"(string chr1 chr2 ...)\n\nFunction that creates a new string from it's arguments. Each argument\nneeds to be a character object."},{"name":"string->list","doc":"(string->list string)\n\nReturns a list of characters created from string."},{"name":"string->number","doc":"(string->number number [radix])\n\nFunction that parses a string into a number."},{"name":"string->symbol","doc":"(string->symbol string)\n\nFunction that converts a string to a LIPS symbol."},{"name":"string->utf8","doc":"(string->utf8 string)\n(string->utf8 string start)\n(string->utf8 string start end)\n\nConverts string into u8 bytevector using utf8 encoding.\nThe start and end is the range of the input string for the conversion."},{"name":"string->vector","doc":"(string->list string)\n(string->list string start)\n(string->list string start end)\n\nFunction that copies given range of string to list. If no start is specified it use\nstart of the string, if no end is specified it convert to the end of the string."},{"name":"string-append","doc":"(concat . strings)\n\nFunction that creates a new string by joining its arguments."},{"name":"string-ci<?","doc":"(string-ci<? string1 string2 ...)\n\nReturns true if strings are monotonically increasing, ignoring the case."},{"name":"string-ci<=?","doc":"(string-ci<=? string1 string2 ...)\n\nReturns true if strings are monotonically non-decreasing, ignoring the case."},{"name":"string-ci=?","doc":"(string-ci=? string1 string2 ...)\n\nChecks if all strings are equal, ignoring the case."},{"name":"string-ci>?","doc":"(string-ci>? string1 string2 ...)\n\nReturns true if strings are monotonically decreasing, ignoring the case"},{"name":"string-ci>=?","doc":"(string-ci>=? string1 string2 ...)\n\nReturns true if strings are monotonically non-increasing, ignoring the case."},{"name":"string-copy","doc":"(string-copy x)\n\nCreates a new string based on given argument."},{"name":"string-downcase","doc":"(string-downcase string)\n\nFunction convert a string passed as argument to lower case."},{"name":"string-fill!","doc":"(string-fill! symbol char)\n\nFunction that destructively fills the string with given character."},{"name":"string-foldcase","doc":"(string-foldcase string)\n\nReturns lowercase string using the Unicode simple case-folding algorithm."},{"name":"string-for-each","doc":"(string-for-each fn string1 stringr2 ...)\n\nApplies a function fn to each element of the strings, similar string-map.\nBut the return value is #void."},{"name":"string-join","doc":"(join separator list)\n\nFunction that returns a string by joining elements of the list using separator."},{"name":"string-length","doc":"(string-length string)\n\nReturns the length of the string."},{"name":"string-map","doc":"(string-map fn string1 stringr2 ...)\n\nReturns new string from applying function fn to each element\nof the strings, similar to map for lists."},{"name":"string-ref","doc":"(string-ref string k)\n\nReturns character inside string at given zero-based index."},{"name":"string-set!","doc":"(string-set! string index char)\n\nReplaces character in string at a given index."},{"name":"string-split","doc":"(split separator string)\n\nFunction that creates a list by splitting string by separator which can\nbe a string or regular expression."},{"name":"string-upcase","doc":"(string-downcase string)\n\nFunction convert a string passed as argument to upper case."},{"name":"string?","doc":"(string? expression)\n\nPredicate that tests if value is a string."},{"name":"string<?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically increasing."},{"name":"string<=?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically non-decreasing."},{"name":"string=?","doc":"(string=? string1 string2 ...)\n\nChecks if all strings are equal."},{"name":"string>?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically decreasing."},{"name":"string>=?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically non-increasing."},{"name":"substring","doc":"(substring string start end)\n\nFunction that returns the slice of the string starting at start and ending\nwith end."},{"name":"sxml","doc":"(sxml expr)\n\nMacro for JSX like syntax but with SXML.\ne.g. usage:\n\n(sxml (div (@ (data-foo \"hello\")\n (id \"foo\"))\n (span \"hello\")\n (span \"world\")))\n;; ==> <div data-foo=\"hello\" id=\"foo\"><span>hello</span>\n;; ==> <span>world</span></div>"},{"name":"sxml-unquote","doc":"(sxml-unquote expression) or ~expression\n\nTreat expression as code and evaluate it inside sxml, similar to unquote\nwith quasiquote."},{"name":"symbol->string","doc":"(symbol->string symbol)\n\nFunction that converts a LIPS symbol to a string."},{"name":"symbol-append","doc":"(symbol-append s1 s2 ...)\n\nFunction that creates a new symbol from symbols passed as arguments."},{"name":"symbol?","doc":"(symbol? expression)\n\nPredicate that tests if value is a LIPS symbol."},{"name":"symbol=?","doc":"(symbol=? s1 s2 ...)\n\nChecks if each value is symbol and it's the same according to string=? predicate."},{"name":"syntax-parameterize","doc":"(syntax-parameterize (bindings) body)\n\nMacro work similar to let-syntax but the the bindnds will be exposed to the user.\nWith syntax-parameterize you can define anaphoric macros."},{"name":"syntax-rules","doc":"(syntax-rules () (pattern expression) ...)\n\nBase of hygienic macros, it will return a new syntax expander\nthat works like Lisp macros."},{"name":"take","doc":"(take list n)\n\nReturns n first values of the list."},{"name":"tan","doc":"(tan n)\n\nFunction that calculates tangent of a number."},{"name":"textual-port?","doc":"(textual-port? port)\n\nFunction that tests if argument is string port."},{"name":"throw","doc":"(throw string)\n\nThrows a new exception."},{"name":"timer","doc":"(timer time . body)\n\nEvaluates body after delay, it returns the timer ID from setTimeout.\nTo clear the timer you can use native JS clearTimeout function."},{"name":"tree->array","doc":"(tree->array list)\n\nFunction that converts a LIPS cons tree structure into a JavaScript array."},{"name":"tree-map","doc":"(tree-map fn tree)\n\nTree version of map. fn is invoked on every leaf."},{"name":"truncate","doc":"(truncate n)\n\nFunction that returns the integer part (floor) of a real number."},{"name":"try","doc":"(try expr (catch (e) code))\n(try expr (catch (e) code) (finally code))\n(try expr (finally code))\n\nMacro that executes expr and catches any exceptions thrown. If catch is provided\nit's executed when an error is thrown. If finally is provided it's always\nexecuted at the end."},{"name":"type","doc":"(type object)\n\nFunction that returns the type of an object as string."},{"name":"typecheck","doc":"(typecheck label value type [position])\n\nChecks the type of value and errors if the type is not one allowed. Type can be\nstring or list of strings. The position optional argument is used to create a\nproper error message for the nth argument of function calls."},{"name":"typecheck-args","doc":"(typecheck-args type label lst)\n\nFunction that makes sure that all items in list are of same type."},{"name":"typecheck-number","doc":"(typecheck-number label value type [position])\n\nFunction similar to typecheck but checks if the argument is a number\nand specific type of number e.g. complex."},{"name":"typed-array?","doc":"(typed-array? o)\n\nFunction that tests if the arguments is a JavaScript typed array (Scheme byte vector)."},{"name":"u16vector","doc":"(u16vector v1 v2 ...)\n\nCreate unsigned 16-bit integer vector (C unsigned short) from give arguments."},{"name":"u16vector-length","doc":"(u16vector-length v)\n\nreturn length of unsigned 16-bit integer vector (C unsigned short)."},{"name":"u16vector-ref","doc":"(u16vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u16vector-set!","doc":"(u16vector-set! vector k)\n\nFunction set value of unsigned 16-bit integer vector (C unsigned short) at index k.\nIf index is out of range it throw exception."},{"name":"u16vector?","doc":"(u16vector? x)\n\nReturns #t of argument is unsigned 16-bit integer vector (C unsigned short),\notherwise it return #f."},{"name":"u32vector","doc":"(u32vector v1 v2 ...)\n\nCreate unsigned 32-bit integer vector (C int) from give arguments."},{"name":"u32vector-length","doc":"(u32vector-length v)\n\nreturn length of unsigned 32-bit integer vector (C int)."},{"name":"u32vector-ref","doc":"(u32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u32vector-set!","doc":"(u32vector-set! vector k)\n\nFunction set value of unsigned 32-bit integer vector (C int) at index k.\nIf index is out of range it throw exception."},{"name":"u32vector?","doc":"(u32vector? x)\n\nReturns #t of argument is unsigned 32-bit integer vector (C int),\notherwise it return #f."},{"name":"u8-ready?","doc":"(u8-ready?)\n(u8-ready? port)\n\nReturns #t if a byte is ready on the binary input port and returns #f otherwise.\nIf u8-ready? returns #t then the next read-u8 operation on the given port is\nguaranteed not to hang. If the port is at end of file then u8-ready? returns #t."},{"name":"u8vector","doc":"(u8vector v1 v2 ...)\n\nCreate unsigned 8-bit integer vector (C unsigned char) from give arguments."},{"name":"u8vector-length","doc":"(u8vector-length v)\n\nreturn length of unsigned 8-bit integer vector (C unsigned char)."},{"name":"u8vector-ref","doc":"(u8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u8vector-set!","doc":"(u8vector-set! vector k)\n\nFunction set value of unsigned 8-bit integer vector (C unsigned char) at index k.\nIf index is out of range it throw exception."},{"name":"u8vector?","doc":"(u8vector? x)\n\nReturns #t of argument is unsigned 8-bit integer vector (C unsigned char),\notherwise it return #f."},{"name":"unary","doc":"(unary fn)\n\nReturns a new function with arguments limited to one."},{"name":"unbind","doc":"(unbind fn)\n\nFunction that removes the weak 'this' binding from a function so you\ncan get properties from the actual function object."},{"name":"unfold","doc":"(unfold fn init)\n\nReturns a list from the given function and init value. The function should\nreturn a pair where first is the item added to the list and second is next value\npassed to the function. If the function returns false it ends the loop."},{"name":"unquote","doc":"(unquote code) or ,code\n\nSpecial form used in the quasiquote macro. It evaluates the expression inside and\nsubstitutes the value into quasiquote's result."},{"name":"unquote-splicing","doc":"(unquote-splicing code) or ,@code\n\nSpecial form used in the quasiquote macro. It evaluates the expression inside and\nsplices the list into quasiquote's result. If it is not the last element of the\nexpression, the computed value must be a pair."},{"name":"unset-repr!","doc":"(unset-repr! type)\n\nRemoves the string representation of the type, which should be constructor function,\nadded by add-repr! function."},{"name":"unset-special!","doc":"(unset-special! name)\n\nFunction that removes a special symbol from parser added by `set-special!`,\nname must be a string."},{"name":"unset!","doc":"(unset! name)\n\nFunction to delete the specified name from environment.\nTrying to access the name afterwards will error."},{"name":"utf8->string","doc":"(utf8->string u8vector)\n(utf8->string u8vector start)\n(utf8->string u8vector start end)\n\nConverts u8 bytevector into string using utf8 encoding.\nThe start and end is the range of the input byte vector for the conversion."},{"name":"value","doc":"(value obj)\n\nFunction that unwraps LNumbers and converts '() to #void."},{"name":"values","doc":"(values a1 a2 ...)\n\nIf called with more then one element it will create a special\nValues object that can be used in the call-with-values function."},{"name":"values-ref","doc":"(values-ref values n)\n\nReturns n value of values object which is result of value function."},{"name":"vector","doc":"(vector 1 2 3 (+ 3 1)) or #(1 2 3 4)\n\nMacro for defining vectors (Javascript Arrays). Vector literals are\nautomatically quoted, so you can't use expressions inside them, only other\nliterals, like other vectors or objects."},{"name":"vector->list","doc":"(vector->list vector)\n(vector->list vector start)\n(vector->list vector start end)\n\nFunction that copies given range of vector to list. If no start is specified it use\nstart of the vector, if no end is specified it convert to the end of the vector."},{"name":"vector->string","doc":"(vector->string vector)\n(vector->string vector start)\n(vector->string vector start end)\n\nReturns new string created from vector of characters in given range.\nIf no start is given it create string from 0, if no end is given it return\nstring to the end."},{"name":"vector-append","doc":"(vector-append v1 v2 ...)\n\nReturns new vector by combining it's arguments that should be vectors."},{"name":"vector-copy","doc":"(vector-copy vector)\n(vector-copy vector start)\n(vector-copy vector start end)\n\nReturns a new vecotor that is a copy of given vector. If start\nis not provided it starts at 0, if end it's not provided it copy\ntil the end of the given vector."},{"name":"vector-copy!","doc":"(vector-copy to at from)\n(vector-copy to at from start)\n(vector-copy to at from start end)\n\nCopies the elements of vector from between start and end into\nvector to starting at `at`. If start is missing it start at 0 and if end\nis missing it copy til the end of the vector from. It throws an error\nif vector from don't fit into the destination `to`."},{"name":"vector-fill!","doc":"(vector-fill! vector fill)\n(vector-fill! vector fill start)\n(vector-fill! vector fill start end)\n\nFill vector with a given value in given range. If start is not given is start\nat 0. If end is not given it fill till the end if the vector."},{"name":"vector-for-each","doc":"(vector-for-each fn vector1 vector2 ...)\n\nInvokes every Returns new vector from applying function fn to each element\nof the vectors, similar to map for lists."},{"name":"vector-length","doc":"(vector-length vec)\n\nReturns length of the vector. It errors if the argument is not a vector."},{"name":"vector-map","doc":"(vector-map fn vector1 vector2 ...)\n\nReturns new vector from applying function fn to each element\nof the vectors, similar to map for lists."},{"name":"vector-ref","doc":"(vector-ref vec n)\n\nReturns nth element of the vector vec."},{"name":"vector-set!","doc":"(vector-set! vec n value)\n\nFunction that sets nth item of the vector to value."},{"name":"vector?","doc":"(vector? n)\n\nReturns true if value is vector and false if not."},{"name":"wait","doc":"(wait time . expr)\n\nReturns a promise that will resolve with the expression after delay."},{"name":"warn-quote","doc":"(warn-quote)\n\nSimple macro that throws an error, when you try to use ’ symbol as quote in code."},{"name":"while","doc":"(while cond body)\n\nCreates a loop, it executes cond and body until cond expression is false."},{"name":"with-exception-handler","doc":"(with-exception-handler handler thunk)\n\nProcedure call and return value of thunk function, if exception happen\nit call handler procedure."},{"name":"with-input-from-file","doc":"(with-input-from-file string thunk)\n\nProcedure open file and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and file port\nis closed."},{"name":"with-input-from-port","doc":"(with-input-from-port port thunk)\n\nProcedure use port and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and given port\nis closed."},{"name":"with-input-from-string","doc":"(with-input-from-string string thunk)\n\nProcedure open string and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and string port\nis closed."},{"name":"with-tags","doc":"(with-tags expression)\n\nvalutes LIPS shorter code for S-Expression equivalent of JSX.\ne.g.:\n\n(with-tags (:div (:class \"item\" :id \"item-1\")\n (list (:span () \"Random Item\")\n (:a (:onclick (lambda (e) (alert \"close\")))\n \"close\"))))\n\nAbove expression can be passed to function that renders JSX (like render\nin React, Preact) To get the string from the macro you can use vhtml\nlibrary from npm."},{"name":"write","doc":"(write obj [port])\n\nWrite object to standard output or give port. For strings it will include\nwrap in quotes."},{"name":"write-bytevector","doc":"(write-bytevector bytevector)\n(write-bytevector bytevector port)\n\nWrite byte vector into binary output port."},{"name":"write-char","doc":"(write-char string)\n(write-char string port)\n\nWrites the character char (not an external representation of the character)\nto the given textual output port and returns an unspecified value."},{"name":"write-string","doc":"(write-string string)\n(write-string string port)\n(write-string string port start)\n(write-string string port start end)\n\nWrites the characters of string from start to end in left-toright order\nto the textual output port."},{"name":"write-u8","doc":"(write-u8 byte)\n(write-u8 byte port)\n\nWrite byte into binary output port."},{"name":"Y","doc":"(Y f)\n\n _ __ __ _ _ _ _ __ __ _ _ _\n / \\ \\ / / / __ / ____ \\ / \\ \\ / / ____ \\ \\ \\\n+ \\ v / + \\ \\ + / ___| + + \\ v / / ___| + + +\n| \\ / | \\ \\ | | |__ | | \\ / | |__ | | |\n| | | | / \\ | | __| | | | | | __| | | |\n| | | | / /\\ \\ | | | | | | | | | | | |\n+ |_| + /_/ \\_\\ + |_| + + |_| |_| + + +\n \\_ \\_ \\_ _/ \\_ _/ _/ _/"},{"name":"zero?","doc":"(zero? x)\n\nChecks if the number is equal to 0"},{"name":"zip","doc":"(zip list1 list2 ...)\n\nReturn list where elements are taken from each list.\ne.g.:\n(zip '(1 2 3) '(2 3 4))\n;; ==> '((1 2) (2 3) (3 4))"}] +[{"name":"-","doc":"(- n1 n2 ...)\n(- n)\n\nSubtracts n2 and subsequent numbers from n1. If only one argument is passed\nit will negate the value."},{"name":"-->","doc":"Helper macro that simplifies calling methods on objects. It works with chaining\nusage: (--> ($ \"body\")\n (css \"color\" \"red\")\n (on \"click\" (lambda () (display \"click\"))))\n\n (--> document (querySelectorAll \"div\"))\n\n (--> (fetch \"https://jcubic.pl\")\n (text)\n (match #/<title>([^<]+)<\\/title>/)\n 1)\n\n (--> document\n (querySelectorAll \".cmd-prompt\")\n 0\n 'innerHTML\n (replace #/<(\"[^\"]+\"|[^>])+>/g \"\"))\n\n (--> document.body\n (style.setProperty \"--color\" \"red\"))"},{"name":".","doc":"(. obj . args)\n(get obj . args)\n\nThis function uses an object as a base and keeps using arguments to get the\nproperty of JavaScript object. Arguments need to be a strings.\ne.g. `(. console \"log\")` if you use any function inside LIPS it\nwill be weakly bound (can be rebound), so you can call this log function\nwithout problem unlike in JavaScript when you use\n`var log = console.log`.\n`get` is an alias because . doesn't work everywhere, e.g. you can't\npass it as an argument."},{"name":"..","doc":"(.. foo.bar.baz)\n\nGets the value from a nested object where the argument is a period separated symbol."},{"name":"*","doc":"(* . numbers)\n\nMultiplies all numbers passed as arguments. If single value is passed\nit will return that value."},{"name":"**","doc":"(** a b)\n\nFunction that calculates number a to to the power of b."},{"name":"/","doc":"(/ n1 n2 ...)\n(/ n)\n\nDivides n1 by n2 and subsequent arguments one by one. If single argument\nis passed it will calculate (/ 1 n)."},{"name":"&","doc":"(& a b)\n\nFunction that calculates the bitwise and operation."},{"name":"+","doc":"(+ . numbers)\n\nSums all numbers passed as arguments. If single value is passed it will\nreturn that value."},{"name":"<","doc":"(< x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically increasing, i.e. x1 < x2 and x2 < x3 and so on."},{"name":"<<","doc":"(<< a b)\n\nFunction that left shifts the value a by value b bits."},{"name":"<=","doc":"(<= x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically nondecreasing, i.e. x1 <= x2 and x2 <= x3 and so on."},{"name":"=","doc":"(== x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nall equal."},{"name":"==","doc":"(== x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nall equal."},{"name":">","doc":"(> x1 x2 x3 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."},{"name":">=","doc":"(>= x1 x2 ...)\n\nFunction that compares its numerical arguments and checks if they are\nmonotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."},{"name":">>","doc":"(>> a b)\n\nFunction that right shifts the value a by value b bits."},{"name":"|","doc":"(| a b)\n\nFunction that calculates the bitwise or operation."},{"name":"~","doc":"(~ number)\n\nFunction that calculates the bitwise inverse (flip all the bits)."},{"name":"1-","doc":"(1- number)\n\nFunction that subtracts 1 from the number and return result."},{"name":"1+","doc":"(1+ number)\n\nFunction that adds 1 to the number and return result."},{"name":"abs","doc":"(abs number)\n\nFunction that returns the absolute value (magnitude) of number."},{"name":"alist->assign","doc":"(alist->assign alist . list-of-alists)\n\nFunction that works like Object.assign but for LIPS alists."},{"name":"alist->object","doc":"(alist->object alist)\n\nFunction that converts alist pairs to a JavaScript object."},{"name":"always","doc":"(always constant)\n\nHigher-order function that returns a new thunk that always returns\nthe given constant when called."},{"name":"and","doc":"(and . expressions)\n\nMacro that evaluates each expression in sequence and if any value returns false\nit will stop and return false. If each value returns true it will return the\nlast value. If it's called without arguments it will return true."},{"name":"angle","doc":"(angle x)\n\nReturns angle of the complex number in polar coordinate system."},{"name":"append","doc":"(append item ...)\n\nFunction that creates a new list with each argument appended end-to-end.\nIt will always return a new list and not modify its arguments."},{"name":"append!","doc":"(append! arg1 ...)\n\nDestructive version of append, it can modify the lists in place. It returns\na new list where each argument is appended to the end. It may modify\nlists added as arguments."},{"name":"apply","doc":"(apply fn list)\n\nFunction that calls fn with the list of arguments."},{"name":"apropos","doc":"(apropos name)\n\nSearch the current environment and display names that match the given name.\nname can be regex, string or symbol."},{"name":"array->list","doc":"(array->list array)\n\nFunction that converts a JavaScript array to a LIPS cons list."},{"name":"array?","doc":"(array? expression)\n\nPredicate that tests if value is an array."},{"name":"assoc","doc":"(assoc obj alist)\n\nReturns pair from alist that match given key using equal? check."},{"name":"assq","doc":"(assq obj alist)\n\nReturns pair from a list that matches given key using eq? check."},{"name":"assv","doc":"(assv obj alist)\n\nReturns pair from alist that match given key using eqv? check."},{"name":"atan","doc":"(atan z)\n(atan x y)\n\nFunction calculates arcus tangent of a complex number.\nIf two arguments are passed and they are not complex numbers\nit calculate Math.atan2 on those arguments."},{"name":"await","doc":"(await value)\n\nUnquotes a quoted promise so it can be automagically evaluated (resolved\nto its value)."},{"name":"begin","doc":"(begin . args)\n\nMacro that runs a list of expressions in order and returns the value\nof the last one. It can be used in places where you can only have a\nsingle expression, like (if)."},{"name":"begin*","doc":"(begin* . body)\n\nThis macro is a parallel version of begin. It evaluates each expression\nin the body and if it's a promise it will await it in parallel and return\nthe value of the last expression (i.e. it uses Promise.all())."},{"name":"binary","doc":"(binary fn)\n\nReturns a new function with arguments limited to two."},{"name":"binary-port?","doc":"(binary-port? port)\n\nFunction that tests if argument is binary port."},{"name":"boolean?","doc":"(boolean? x)\n\nReturns true if value is boolean."},{"name":"boolean=?","doc":"(boolean=? b1 b2 ...)\n\nChecks if all arguments are boolean and if they are the same."},{"name":"bound?","doc":"(bound? x [env])\n\nFunction that check if the variable is defined in the given environment,\nor interaction-environment if not specified."},{"name":"buffer->u8vector","doc":"(buffer->u8vector bin)\n\nCross platform function that can be used in both Node and browser.\nIt can be used together with %read-file or %read-binary-file to convert\nthe result ArrayBuffer or Buffer to u8vector."},{"name":"bytevector","doc":"(u8vector v1 v2 ...)\n\nCreate unsigned 8-bit integer vector (C unsigned char) from give arguments."},{"name":"bytevector-append","doc":"(bytevector-append v1 ...)\n\nCreate new bytevector u8vector that is created from joining each argument."},{"name":"bytevector-copy","doc":"(bytevector-copy v)\n(bytevector-copy v start)\n(bytevector-copy v start end)\n\nReturns a new vector from start to end. If no start and end is provided\nwhole vector is copied and returned."},{"name":"bytevector-copy!","doc":"(bytevector-copy! to at from)\n(bytevector-copy! to at from start)\n(bytevector-copy! to at from start end)\n\nCopies the bytes of bytevector from between start and end to bytevector to,\nstarting at at."},{"name":"bytevector-length","doc":"(u8vector-length v)\n\nreturn length of unsigned 8-bit integer vector (C unsigned char)."},{"name":"bytevector-u8-ref","doc":"(u8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"bytevector-u8-set!","doc":"(u8vector-set! vector k)\n\nFunction set value of unsigned 8-bit integer vector (C unsigned char) at index k.\nIf index is out of range it throw exception."},{"name":"bytevector?","doc":"(u8vector? x)\n\nReturns #t of argument is unsigned 8-bit integer vector (C unsigned char),\notherwise it return #f."},{"name":"caaaaar","doc":"(caaaaar arg)\n\nFunction that calculates (car (car (car (car (car arg)))))"},{"name":"caaaadr","doc":"(caaaadr arg)\n\nFunction that calculates (car (car (car (car (cdr arg)))))"},{"name":"caaaar","doc":"(caaaar arg)\n\nFunction that calculates (car (car (car (car arg))))"},{"name":"caaadar","doc":"(caaadar arg)\n\nFunction that calculates (car (car (car (cdr (car arg)))))"},{"name":"caaaddr","doc":"(caaaddr arg)\n\nFunction that calculates (car (car (car (cdr (cdr arg)))))"},{"name":"caaadr","doc":"(caaadr arg)\n\nFunction that calculates (car (car (car (cdr arg))))"},{"name":"caaar","doc":"(caaar arg)\n\nFunction that calculates (car (car (car arg)))"},{"name":"caadaar","doc":"(caadaar arg)\n\nFunction that calculates (car (car (cdr (car (car arg)))))"},{"name":"caadadr","doc":"(caadadr arg)\n\nFunction that calculates (car (car (cdr (car (cdr arg)))))"},{"name":"caadar","doc":"(caadar arg)\n\nFunction that calculates (car (car (cdr (car arg))))"},{"name":"caaddar","doc":"(caaddar arg)\n\nFunction that calculates (car (car (cdr (cdr (car arg)))))"},{"name":"caadddr","doc":"(caadddr arg)\n\nFunction that calculates (car (car (cdr (cdr (cdr arg)))))"},{"name":"caaddr","doc":"(caaddr arg)\n\nFunction that calculates (car (car (cdr (cdr arg))))"},{"name":"caadr","doc":"(caadr arg)\n\nFunction that calculates (car (car (cdr arg)))"},{"name":"caar","doc":"(caar arg)\n\nFunction that calculates (car (car arg))"},{"name":"cadaaar","doc":"(cadaaar arg)\n\nFunction that calculates (car (cdr (car (car (car arg)))))"},{"name":"cadaadr","doc":"(cadaadr arg)\n\nFunction that calculates (car (cdr (car (car (cdr arg)))))"},{"name":"cadaar","doc":"(cadaar arg)\n\nFunction that calculates (car (cdr (car (car arg))))"},{"name":"cadadar","doc":"(cadadar arg)\n\nFunction that calculates (car (cdr (car (cdr (car arg)))))"},{"name":"cadaddr","doc":"(cadaddr arg)\n\nFunction that calculates (car (cdr (car (cdr (cdr arg)))))"},{"name":"cadadr","doc":"(cadadr arg)\n\nFunction that calculates (car (cdr (car (cdr arg))))"},{"name":"cadar","doc":"(cadar arg)\n\nFunction that calculates (car (cdr (car arg)))"},{"name":"caddaar","doc":"(caddaar arg)\n\nFunction that calculates (car (cdr (cdr (car (car arg)))))"},{"name":"caddadr","doc":"(caddadr arg)\n\nFunction that calculates (car (cdr (cdr (car (cdr arg)))))"},{"name":"caddar","doc":"(caddar arg)\n\nFunction that calculates (car (cdr (cdr (car arg))))"},{"name":"cadddar","doc":"(cadddar arg)\n\nFunction that calculates (car (cdr (cdr (cdr (car arg)))))"},{"name":"caddddr","doc":"(caddddr arg)\n\nFunction that calculates (car (cdr (cdr (cdr (cdr arg)))))"},{"name":"cadddr","doc":"(cadddr arg)\n\nFunction that calculates (car (cdr (cdr (cdr arg))))"},{"name":"caddr","doc":"(caddr arg)\n\nFunction that calculates (car (cdr (cdr arg)))"},{"name":"cadr","doc":"(cadr arg)\n\nFunction that calculates (car (cdr arg))"},{"name":"call-with-current-continuation","doc":"(call/cc proc)\n\nCall-with-current-continuation.\n\nNOT SUPPORTED BY LIPS RIGHT NOW"},{"name":"call-with-input-file","doc":"(call-with-input-file filename proc)\n\nProcedure open file for reading, call user defined procedure with given port\nand then close the port. It return value that was returned by user proc\nand it close the port even if user proc throw exception."},{"name":"call-with-output-file","doc":"(call-with-output-file filename proc)\n\nProcedure open file for writing, call user defined procedure with port\nand then close the port. It return value that was returned by user proc\nand it close the port even if user proc throw exception."},{"name":"call-with-port","doc":"(call-with-port port proc)\n\nProc is executed with given port and after it returns, the port is closed."},{"name":"call-with-values","doc":"(call-with-values producer consumer)\n\nCalls the producer procedure with no arguments, then calls the\nconsumer procedure with the returned value as an argument -- unless\nthe returned value is a special Values object created by (values), if it is\nthe values are unpacked and the consumer is called with multiple arguments."},{"name":"call/cc","doc":"(call/cc proc)\n\nCall-with-current-continuation.\n\nNOT SUPPORTED BY LIPS RIGHT NOW"},{"name":"car","doc":"(car pair)\n\nThis function returns the car (item 1) of the list."},{"name":"cdaaaar","doc":"(cdaaaar arg)\n\nFunction that calculates (cdr (car (car (car (car arg)))))"},{"name":"cdaaadr","doc":"(cdaaadr arg)\n\nFunction that calculates (cdr (car (car (car (cdr arg)))))"},{"name":"cdaaar","doc":"(cdaaar arg)\n\nFunction that calculates (cdr (car (car (car arg))))"},{"name":"cdaadar","doc":"(cdaadar arg)\n\nFunction that calculates (cdr (car (car (cdr (car arg)))))"},{"name":"cdaaddr","doc":"(cdaaddr arg)\n\nFunction that calculates (cdr (car (car (cdr (cdr arg)))))"},{"name":"cdaadr","doc":"(cdaadr arg)\n\nFunction that calculates (cdr (car (car (cdr arg))))"},{"name":"cdaar","doc":"(cdaar arg)\n\nFunction that calculates (cdr (car (car arg)))"},{"name":"cdadaar","doc":"(cdadaar arg)\n\nFunction that calculates (cdr (car (cdr (car (car arg)))))"},{"name":"cdadadr","doc":"(cdadadr arg)\n\nFunction that calculates (cdr (car (cdr (car (cdr arg)))))"},{"name":"cdadar","doc":"(cdadar arg)\n\nFunction that calculates (cdr (car (cdr (car arg))))"},{"name":"cdaddar","doc":"(cdaddar arg)\n\nFunction that calculates (cdr (car (cdr (cdr (car arg)))))"},{"name":"cdadddr","doc":"(cdadddr arg)\n\nFunction that calculates (cdr (car (cdr (cdr (cdr arg)))))"},{"name":"cdaddr","doc":"(cdaddr arg)\n\nFunction that calculates (cdr (car (cdr (cdr arg))))"},{"name":"cdadr","doc":"(cdadr arg)\n\nFunction that calculates (cdr (car (cdr arg)))"},{"name":"cdar","doc":"(cdar arg)\n\nFunction that calculates (cdr (car arg))"},{"name":"cddaaar","doc":"(cddaaar arg)\n\nFunction that calculates (cdr (cdr (car (car (car arg)))))"},{"name":"cddaadr","doc":"(cddaadr arg)\n\nFunction that calculates (cdr (cdr (car (car (cdr arg)))))"},{"name":"cddaar","doc":"(cddaar arg)\n\nFunction that calculates (cdr (cdr (car (car arg))))"},{"name":"cddadar","doc":"(cddadar arg)\n\nFunction that calculates (cdr (cdr (car (cdr (car arg)))))"},{"name":"cddaddr","doc":"(cddaddr arg)\n\nFunction that calculates (cdr (cdr (car (cdr (cdr arg)))))"},{"name":"cddadr","doc":"(cddadr arg)\n\nFunction that calculates (cdr (cdr (car (cdr arg))))"},{"name":"cddar","doc":"(cddar arg)\n\nFunction that calculates (cdr (cdr (car arg)))"},{"name":"cdddaar","doc":"(cdddaar arg)\n\nFunction that calculates (cdr (cdr (cdr (car (car arg)))))"},{"name":"cdddadr","doc":"(cdddadr arg)\n\nFunction that calculates (cdr (cdr (cdr (car (cdr arg)))))"},{"name":"cdddar","doc":"(cdddar arg)\n\nFunction that calculates (cdr (cdr (cdr (car arg))))"},{"name":"cddddar","doc":"(cddddar arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr (car arg)))))"},{"name":"cdddddr","doc":"(cdddddr arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr (cdr arg)))))"},{"name":"cddddr","doc":"(cddddr arg)\n\nFunction that calculates (cdr (cdr (cdr (cdr arg))))"},{"name":"cdddr","doc":"(cdddr arg)\n\nFunction that calculates (cdr (cdr (cdr arg)))"},{"name":"cddr","doc":"(cddr arg)\n\nFunction that calculates (cdr (cdr arg))"},{"name":"cdr","doc":"(cdr pair)\n\nThis function returns the cdr (all but first) of the list."},{"name":"ceiling","doc":"(ceiling number)\n\nFunction that calculates the ceiling of a number."},{"name":"char->integer","doc":"(char->integer chr)\n\nReturns the codepoint of Unicode character."},{"name":"char-alphabetic?","doc":"(char-alphabetic? chr)\n\nReturns true if character is leter of the ASCII alphabet."},{"name":"char-ci<?","doc":"(char-ci<? chr1 chr2)\n\nReturns true if characters are monotonically increasing case insensitive."},{"name":"char-ci<=?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-decreasing, case insensitive."},{"name":"char-ci=?","doc":"(char-ci=? chr1 chr2 ...)\n\nChecks if all characters are equal, case insensitive."},{"name":"char-ci>?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically decreasing case insensitive."},{"name":"char-ci>=?","doc":"(char-ci<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-increasing, case insensitive."},{"name":"char-downcase","doc":"(char-downcase chr)\n\nCreate lowercase version of the character."},{"name":"char-foldcase","doc":"(char-foldcase char)\n\nReturns lowercase character using the Unicode simple case-folding algorithm."},{"name":"char-lower-case?","doc":"(char-upper-case? char)\n\nChecks if character is lower case."},{"name":"char-numeric?","doc":"(char-numeric? chr)\n\nReturns true if character is number."},{"name":"char-ready?","doc":"(char-ready?)\n(char-ready? port)\n\nChecks if characters is ready in input port. This is useful mostly\nfor interactive ports that return false if it would wait for user input.\nIt return false if port is closed."},{"name":"char-upcase","doc":"(char-upcase char)\n\nCreate uppercase version of the character."},{"name":"char-upper-case?","doc":"(char-upper-case? char)\n\nChecks if character is upper case."},{"name":"char-whitespace?","doc":"(char-whitespace? chr)\n\nReturns true if character is whitespace."},{"name":"char?","doc":"(char? obj)\n\nChecks if the object is a character."},{"name":"char<?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically increasing."},{"name":"char<=?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-decreasing."},{"name":"char=?","doc":"(char=? chr1 chr2 ...)\n\nChecks if all characters are equal."},{"name":"char>?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically decreasing."},{"name":"char>=?","doc":"(char<? chr1 chr2 ...)\n\nReturns true if characters are monotonically non-increasing."},{"name":"clone","doc":"(clone list)\n\nFunction that returns a clone of the list, that does not share any pairs with the\noriginal, so the clone can be safely mutated without affecting the original."},{"name":"close-input-port","doc":"(close-input-port port)\n\nProcedure close port that was opened with open-input-file. After that\nit no longer accept reading from that port."},{"name":"close-output-port","doc":"(close-output-port port)\n\nProcedure close port that was opened with open-output-file. After that\nit no longer accept write to that port."},{"name":"close-port","doc":"(close-port port)\n\nClose input or output port."},{"name":"command-line","doc":"(command-line)\n\nReturns the command line arguments, or an empty list if not running under Node.js."},{"name":"complement","doc":"(complement fn)\n\nHigher order function that returns the Boolean complement of the given function.\nIf the function fn for a given arguments return true the result function\nwill return false, if it would return false, the result function will return true."},{"name":"complex?","doc":"(complex? x)\n\nChecks if argument x is complex."},{"name":"compose","doc":"(compose . fns)\n\nHigher-order function that creates a new function that applies all functions\nfrom right to left and returns the last value. Reverse of pipe.\ne.g.:\n((compose (curry + 2) (curry * 3)) 10) ==> (+ 2 (* 3 10)) ==> 32"},{"name":"concat","doc":"(concat . strings)\n\nFunction that creates a new string by joining its arguments."},{"name":"cond","doc":"(cond (predicate? . body)\n (predicate? . body)\n (else . body))\n\n(cond (predicate? => procedure)\n (predicate? => procedure)\n (else . body))\n\nMacro for condition checks. For usage instead of nested ifs.\nYou can use predicate and any number of expressions. Or symbol =>\nFollowed by procedure that will be invoked with result\nof the predicate."},{"name":"cons","doc":"(cons left right)\n\nThis function returns a new list with the first appended\nbefore the second. If the second is not a list cons will\nreturn a dotted pair."},{"name":"constructor","doc":"(constructor)\n\nFunction that is present in JavaScript environment. We define it in Scheme\nto fix an issue with define-class. This function throw an error."},{"name":"continuation?","doc":"(continuation? expression)\n\nPredicate that tests if value is a callable continuation."},{"name":"cos","doc":"(cos n)\n\nFunction that calculates cosine of a number."},{"name":"current-directory","doc":"(current-directory)\n\nReturns the current working directory, default is the path from where\nthe script was executed."},{"name":"current-environment","doc":"(current-environment)\n\nFunction that returns the current environment (they're first-class objects!)"},{"name":"current-error-port","doc":"(current-output-port)\n\nReturns the default stderr port."},{"name":"current-input-port","doc":"(current-input-port)\n\nReturns the default stdin port."},{"name":"current-jiffy","doc":"(current-jiffy)\n\nReturn current jiffy. In LIPS is jiffy since start of the process.\nYou can divide this value by (jiffies-per-second) to get seconds since\nstart of the process. And you can add %%start-jiffy to get jiffy since\nJanuary 1, 1970."},{"name":"current-output-port","doc":"(current-output-port)\n\nReturns the default stdout port."},{"name":"current-second","doc":"(current-second)\n\nFunctionn return exact integer of the seconds since January 1, 1970"},{"name":"curry","doc":"(curry fn . args)\n\nHigher-order function that creates a curried version of the function.\nThe result function will have partially applied arguments and it\nwill keep returning one-argument functions until all arguments are provided,\nthen it calls the original function with the accumulated arguments.\n\ne.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))"},{"name":"debugger","doc":"(debugger)\n\nFunction that triggers the JavaScript debugger (e.g. the browser devtools)\nusing the \"debugger;\" statement. If a debugger is not running this\nfunction does nothing."},{"name":"define","doc":"(define name expression)\n(define name expression \"doc string\")\n(define (function-name . args) . body)\n\nMacro for defining values. It can be used to define variables,\nor functions. If the first argument is list it will create a function\nwith name being first element of the list. This form expands to\n`(define function-name (lambda args body))`"},{"name":"define-class","doc":"(define-class name parent . body)\n\nDefines a class - JavaScript function constructor with prototype.\nparent needs to be class, constructor function, or #null\n\nusage:\n\n (define-class Person Object\n (constructor (lambda (self name)\n (set-obj! self '_name name)))\n (hi (lambda (self)\n (display (string-append self._name \" says hi\"))\n (newline))))\n (define jack (new Person \"Jack\"))\n (jack.hi) ; prints \"Jack says hi\""},{"name":"define-formatter-rule","doc":"(rule-pattern pattern)\n\nAnaphoric macro for defining patterns for the formatter.\nWith Ahead, Pattern and * defined values."},{"name":"define-global","doc":"(define-global var value)\n(define-global (name . args) body)\n\nDefines functions or variables in the global context, so they can be used\ninside let and get let variables in a closure. Useful for universal macros."},{"name":"define-library","doc":"(define-library (library (name namespace) . body)\n\nMacro for defining modules inside you can use define to create functions.\nAnd use export name to add that name to defined environment."},{"name":"define-macro","doc":"(define-macro (name . args) body)\n\nThe meta-macro, that creates new macros. If the return value is a list structure\nit will be evaluated where the macro is invoked from. You can use quasiquote `\nand unquote , and unquote-splicing ,@ inside to create an expression that will be\nevaluated at runtime. Macros works like this: if you pass any expression to a\nmacro the arguments will not be evaluated unless the macro's body explicitly\ncalls (eval) on it. Because of this a macro can manipulate the expression\n(arguments) as lists."},{"name":"define-record-type","doc":"(define-record-type name constructor pred . fields)\n\nMacro for defining records. Example of usage:\n\n(define-record-type <pare>\n (kons x y)\n pare?\n (x kar set-kar!)\n (y kdr set-kdr!))\n\n(define p (kons 1 2))\n(print (kar p))\n;; ==> 1\n(set-kdr! p 3)\n(print (kdr p))\n;; ==> 3"},{"name":"define-symbol-macro","doc":"(define-symbol-macro type (name . args) . body)\n\nCreates syntax extensions for evaluator similar to built-in , or `.\nIt's like an alias for a real macro. Similar to CL reader macros\nbut it receives already parsed code like normal macros. Type can be SPLICE\nor LITERAL symbols (see set-special!). ALL default symbol macros are literal."},{"name":"define-syntax","doc":"(define-syntax name expression [__doc__])\n\nDefines a new hygienic macro using syntax-rules with optional documentation."},{"name":"define-syntax-parameter","doc":"(define-syntax-parameter name syntax [__doc__])\n\nBinds <keyword> to the transformer obtained by evaluating <transformer spec>.\nThe transformer provides the default expansion for the syntax parameter,\nand in the absence of syntax-parameterize, is functionally equivalent to\ndefine-syntax."},{"name":"defmacro?","doc":"(defmacro? expression)\n\nChecks if object is a macro and it's expandable."},{"name":"degree->radians","doc":"(degree->radians x)\n\nConvert degrees to radians."},{"name":"delay","doc":"(delay expression)\n\nWill create a promise from expression that can be forced with (force)."},{"name":"delete-file","doc":"(delete-file filename)\n\nDeletes the file of given name."},{"name":"denominator","doc":"(denominator n)\n\nReturn denominator of rational or same number if one is not rational."},{"name":"digit-value","doc":"(digit-value chr)\n\nReturn digit number if character is numeral (as per char-numeric?)\nor #f otherwise."},{"name":"dir","doc":"(dir obj)\n\nReturns all props on the object including those in prototype chain."},{"name":"display","doc":"(display string [port])\n\nThis function outputs the string to the standard output or\nthe port if given. No newline."},{"name":"display-error","doc":"(display-error . args)\n\nDisplay an error message on stderr."},{"name":"do","doc":"(do ((<var> <init> <next>)) (test return) . body)\n\nIteration macro that evaluates the expression body in scope of the variables.\nOn each loop it changes the variables according to the <next> expression and runs\ntest to check if the loop should continue. If test is a single value, the macro\nwill return undefined. If the test is a pair of expressions the macro will\nevaluate and return the second expression after the loop exits."},{"name":"do-iterator","doc":"(do-iterator (var expr) (test result) body ...)\n\nIterates over iterators (e.g. created with JavaScript generator function)\nthat works with normal and async iterators. You can loop over an infinite\niterators and break the loop if you want, using expression like in do macro.\nLong synchronous iterators will block the main thread (you can't print\n1000 numbers from infinite iterators, because it will freeze the browser),\nbut if you use async iterators you can process the values as they are\ngenerated."},{"name":"drop","doc":"(take list n)\n\nReturns a list where first n elements are removed."},{"name":"dynamic-wind","doc":"(dynamic-wind before thunk after)\n\nAccepts 3 procedures/lambdas and executes before, then thunk, and\nalways after even if an error occurs in thunk."},{"name":"empty?","doc":"(empty? object)\n\nFunction that returns #t if value is nil (an empty list) or undefined."},{"name":"env","doc":"(env)\n(env obj)\n\nFunction that returns a list of names (functions, macros and variables)\nthat are bound in the current environment or one of its parents."},{"name":"environment-bound?","doc":"(environment-bound? env symbol)\n\nChecks if symbol is a bound variable similar to bound?."},{"name":"environment?","doc":"(environment? obj)\n\nChecks if object is a LIPS environment."},{"name":"eof-object","doc":"(eof-object)\n\nProcedure returns eof object that indicate end of the port"},{"name":"eof-object?","doc":"(eof-object? arg)\n\nChecks if value is eof object, returned from input string\nport when there are no more data to read."},{"name":"eq?","doc":"(eq? a b)\n\nFunction that compares two values if they are identical."},{"name":"equal?","doc":"(equal? a b)\n\nThe function checks if values are equal. If both are a pair or an array\nit compares their elements recursively. If pairs have cycles it compares\nthem with eq?"},{"name":"eqv?","doc":"(eqv? a b)\n\nFunction that compares the values. It returns true if they are the same, they\nneed to have the same type."},{"name":"error","doc":"(error message ...)\n\nFunction raises error with given message and arguments,\nwhich are called invariants."},{"name":"error-object-irritants","doc":"(error-object-irritants error-object)\n\nReturns a list of the irritants encapsulated by error-object."},{"name":"error-object-message","doc":"(error-object-message error-object)\n\nReturns the message encapsulated by error-object."},{"name":"error-object?","doc":"(error-object? obj)\n\nChecks if object is of Error object thrown by error function."},{"name":"escape-regex","doc":"(escape-regex string)\n\nFunction that returns a new string where all special operators used in regex,\nare escaped with backslashes so they can be used in the RegExp constructor\nto match a literal string."},{"name":"eval","doc":"(eval expr)\n(eval expr environment)\n\nFunction that evaluates LIPS Scheme code. If the second argument is provided\nit will be the environment that the code is evaluated in."},{"name":"even?","doc":"(even? number)\n\nChecks if number is even."},{"name":"every","doc":"(every fn . lists)\n\nHigher-order function that calls fn on consecutive item of the list of lists,\nif every call returns true it will return true otherwise it return false.\nAnalogous to Python all(map(fn, list))."},{"name":"exact","doc":"(inexact->exact number)\n\nFunction that converts real number to exact rational number."},{"name":"exact->inexact","doc":"(exact->inexact n)\n\nConvert exact number to inexact."},{"name":"exact-integer?","doc":"(exact-integer? n)\n\nReturns #t if z is both exact and an integer; otherwise\nreturns #f."},{"name":"exact?","doc":"(exact? n)"},{"name":"exp","doc":"(exp n)\n\nFunction that calculates e raised to the power of n."},{"name":"expt","doc":"(** a b)\n\nFunction that calculates number a to to the power of b."},{"name":"f32vector","doc":"(f32vector v1 v2 ...)\n\nCreate 32-bit IEEE-754 floating point number vector (C float) from give arguments."},{"name":"f32vector-length","doc":"(f32vector-length v)\n\nreturn length of 32-bit IEEE-754 floating point number vector (C float)."},{"name":"f32vector-ref","doc":"(f32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"f32vector-set!","doc":"(f32vector-set! vector k)\n\nFunction set value of 32-bit IEEE-754 floating point number vector (C float) at index k.\nIf index is out of range it throw exception."},{"name":"f32vector?","doc":"(f32vector? x)\n\nReturns #t of argument is 32-bit IEEE-754 floating point number vector (C float),\notherwise it return #f."},{"name":"f64vector","doc":"(f64vector v1 v2 ...)\n\nCreate 64-bit IEEE-754 floating point number vector (C double) from give arguments."},{"name":"f64vector-length","doc":"(f64vector-length v)\n\nreturn length of 64-bit IEEE-754 floating point number vector (C double)."},{"name":"f64vector-ref","doc":"(f64vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"f64vector-set!","doc":"(f64vector-set! vector k)\n\nFunction set value of 64-bit IEEE-754 floating point number vector (C double) at index k.\nIf index is out of range it throw exception."},{"name":"f64vector?","doc":"(f64vector? x)\n\nReturns #t of argument is 64-bit IEEE-754 floating point number vector (C double),\notherwise it return #f."},{"name":"features","doc":"(features)\n\nFunction returns implemented features as a list."},{"name":"filter","doc":"(filter fn list)\n(filter regex list)\n\nHigher-order function that calls `fn` for each element of the list\nand return a new list for only those elements for which fn returns\na truthy value. If called with a regex it will create a matcher function."},{"name":"find","doc":"(find fn list)\n(find regex list)\n\nHigher-order function that finds the first value for which fn return true.\nIf called with a regex it will create a matcher function."},{"name":"finite?","doc":"(finite? x)\n\nChecks if value is finite."},{"name":"flatten","doc":"(flatten list)\n\nReturns a shallow list from tree structure (pairs)."},{"name":"flip","doc":"(flip fn)\n\nHigher-order function that returns a new function where the first two arguments\nare swapped.\n\nExample:\n\n (define first (curry (flip vector-ref) 0))\n (first #(1 2 3))\n ;; ==> 1"},{"name":"floor","doc":"(floor number)\n\nFunction that calculates the floor of a number."},{"name":"flush-output","doc":"(flush-output [port])\n\nIf output-port is buffered, this causes the contents of its buffer to be written to\nthe output device. Otherwise it has no effect. Returns an unspecified value."},{"name":"flush-output-port","doc":"(flush-output-port port)\n\nFunction do nothing, flush is not needed in LIPS in both NodeJS and Browser.\nThe function is added, so it don't throw exception when using R7RS code."},{"name":"fold","doc":"(fold fn init . lists)\n\nFunction fold is left-to-right reversal of reduce. It call `fn`\non each pair of elements of the list and returns a single value.\ne.g. it computes (fn 'a 'x (fn 'b 'y (fn 'c 'z 'foo)))\nfor: (fold fn 'foo '(a b c) '(x y z))"},{"name":"fold-left","doc":"(fold fn init . lists)\n\nFunction fold is left-to-right reversal of reduce. It call `fn`\non each pair of elements of the list and returns a single value.\ne.g. it computes (fn 'a 'x (fn 'b 'y (fn 'c 'z 'foo)))\nfor: (fold fn 'foo '(a b c) '(x y z))"},{"name":"fold-right","doc":"(reduce fn init list . lists)\n\nHigher-order function that takes each element of the list and calls\nthe fn with result of previous call or init and the next element\nof the list until each element is processed, and returns a single value\nas result of last call to `fn` function.\ne.g. it computes (fn 'c 'z (fn 'b 'y (fn 'a 'x 'foo)))\nfor: (reduce fn 'foo '(a b c) '(x y z))"},{"name":"for-each","doc":"(for-each fn . lists)\n\nHigher-order function that calls function `fn` on each\nvalue of the argument. If you provide more than one list\nit will take each value from each list and call `fn` function\nwith that many arguments as number of list arguments."},{"name":"force","doc":"(force promise)\n\nFunction that forces the promise and evaluates the delayed expression."},{"name":"format","doc":"(format string n1 n2 ...)\n\nThis function accepts a string template and replaces any\nescape sequences in its inputs:\n\n* ~a value as if printed with `display`\n* ~s value as if printed with `write`\n* ~% newline character\n* ~~ literal tilde '~'\n\nIf there are missing inputs or other escape characters it\nwill error."},{"name":"function?","doc":"(function? expression)\n\nPredicate that tests if value is a callable function."},{"name":"gcd","doc":"(gcd n1 n2 ...)\n\nFunction that returns the greatest common divisor of the arguments."},{"name":"gensym","doc":"(gensym)\n\nGenerates a unique symbol that is not bound anywhere,\nto use with macros as meta name."},{"name":"gensym-interal","doc":"(gensym-interal symbol)\n\nParser extension that creates a new quoted named gensym."},{"name":"gensym?","doc":"(gensym? value)\n\nReturns #t if value is a symbol created by gensym. It returns #f otherwise."},{"name":"get","doc":"(. obj . args)\n(get obj . args)\n\nThis function uses an object as a base and keeps using arguments to get the\nproperty of JavaScript object. Arguments need to be a strings.\ne.g. `(. console \"log\")` if you use any function inside LIPS it\nwill be weakly bound (can be rebound), so you can call this log function\nwithout problem unlike in JavaScript when you use\n`var log = console.log`.\n`get` is an alias because . doesn't work everywhere, e.g. you can't\npass it as an argument."},{"name":"get-environment-variable","doc":"(get-environment-variable name)\n\nReturns given environment variable. This function returns #void\nwhen called in the browser."},{"name":"get-environment-variables","doc":"(get-environment-variables)\n\nReturns all process environment variables as an alist. This function returns\nan empty list when called in the browser."},{"name":"get-output-bytevector","doc":"(get-output-string port)\n\nGets full string from string port. If nothing was wrote\nto given port it will return empty string."},{"name":"get-output-string","doc":"(get-output-string port)\n\nGets full string from string port. If nothing was wrote\nto given port it will return empty string."},{"name":"get-resource","doc":"(get-resource url)\n\nLoad JavaScript or CSS file in browser by adding script/link tag to head\nof the current document. When called from Node it allow it allows to load\nJavaScript files only."},{"name":"globalize","doc":"(globalize expr)\n\n Macro will get the value of the expression and add each method as function\n to global scope."},{"name":"help","doc":"(help object)\n\nThis macro returns documentation for a function or macro.\nYou can save the function or macro in a variable and use it\nhere. But getting help for a variable requires passing the\nvariable in a `quote`."},{"name":"http-get","doc":"(http-get url)\n\nNode.js function that sends a HTTP Request and returns a string or\nbinary Buffer object."},{"name":"identity","doc":"(identity n)\n\nNo-op function. It just returns its argument."},{"name":"if","doc":"(if cond true-expr false-expr)\n\nMacro that evaluates cond expression and if the value is true, it\nevaluates and returns true-expression, if not it evaluates and returns\nfalse-expression."},{"name":"ignore","doc":"(ignore . body)\n\nMacro that will evaluate the expression and swallow any promises that may\nbe created. It will discard any value that may be returned by the last body\nexpression. The code should have side effects and/or when it's promise\nit should resolve to undefined."},{"name":"imag-part","doc":"(imag-part n)\n\nReturn imaginary part of the complex number n."},{"name":"import","doc":"(import (library namespace))\n(import (only (library namespace) name1 name2))\n\nMacro for importing names from library."},{"name":"in","doc":"(in key value)\n\nFunction that uses the Javascript \"in\" operator to check if key is\na valid property in the value."},{"name":"include","doc":"(include file ...)\n\nLoad at least one file content and insert them into one,\nbody expression."},{"name":"indexed-db?","doc":"(indexed-db?)\n\nFunction that tests if IndexedDB is available."},{"name":"inexact","doc":"(exact->inexact n)\n\nConvert exact number to inexact."},{"name":"inexact->exact","doc":"(inexact->exact number)\n\nFunction that converts real number to exact rational number."},{"name":"inexact?","doc":"(inexact? n)"},{"name":"infinite?","doc":"(infinite? x)\n\nChecks if value is infinite."},{"name":"input-port-open?","doc":"(input-port-open? port)\n\nChecks if argument is input-port and if you can read from it."},{"name":"input-port?","doc":"(input-port? arg)\n\nReturns true if argument is input port."},{"name":"instance?","doc":"(instance? obj)\n\nChecks if object is an instance, created with a new operator"},{"name":"instanceof","doc":"(instanceof type obj)\n\nPredicate that tests if the obj is an instance of type."},{"name":"integer->char","doc":"(integer->char chr)\n\nFunction that converts number argument to character."},{"name":"integer?","doc":"(integer? x)\n\nChecks if the argument x is integer."},{"name":"interaction-environment","doc":"(interaction-environment)\n\nReturns the interaction environment equal to lips.env. This can be overwritten\nwhen creating new interpreter with lips.Interpreter."},{"name":"iterator->array","doc":"(iterator->array object)\n\nReturn array from JavaScript iterator object."},{"name":"iterator?","doc":"(iterator? x)\n\n Checks if value is JavaScript iterator object."},{"name":"join","doc":"(join separator list)\n\nFunction that returns a string by joining elements of the list using separator."},{"name":"key->string","doc":"(key->string symbol)\n\nIf symbol is a keyword it converts that to string and removes the colon."},{"name":"key?","doc":"(key? symbol)\n\nChecks if symbol is a keyword (has a colon as first character)."},{"name":"lambda","doc":"(lambda (a b) body)\n(lambda args body)\n(lambda (a b . rest) body)\n\nThe lambda macro creates a new anonymous function. If the first element of\nthe body is a string and there is more elements the string is used as the\ndocumentation string, that can be read using (help fn)."},{"name":"lcm","doc":"(lcm n1 n2 ...)\n\nFunction that returns the least common multiple of the arguments."},{"name":"length","doc":"(length expression)\n\nFunction that returns the length of the object. The object can be a LIPS\nlist or any object that has a \"length\" property. Returns undefined if the\nlength could not be found."},{"name":"let","doc":"(let ((a value-a) (b value-b) ...) . body)\n\nMacro that creates a new environment, then evaluates and assigns values to names,\nand then evaluates the body in context of that environment. Values are evaluated\nsequentially but you can't access previous values/names when the next are\nevaluated. You can only get them in the body of the let expression. (If you want\nto define multiple variables and use them in each other's definitions, use\n`let*`.)"},{"name":"let-env","doc":"(let-env env . body)\n\nSpecial macro that evaluates body in context of given environment\nobject."},{"name":"let-env-values","doc":"(let-env-values env ((name var)) . body)\n\nAdds mappings for variables var from specified env.\nit is similar to let-env but lexical scope is working with it."},{"name":"let-syntax","doc":"(let-syntax ((name fn) ...) . body)\n\n Works like a combination of let and define-syntax. It creates\n local macros and evaluates body in context of those macros.\n The macro to letrec-syntax is like letrec is to let."},{"name":"let*","doc":"(let* ((a value-a) (b value-b) ...) . body)\n\nMacro similar to `let`, but the subsequent bindings after the first\nare evaluated in the environment including the previous let variables,\nso you can define one variable, and use it in the next's definition."},{"name":"letrec","doc":"(letrec ((a value-a) (b value-b) ...) . body)\n\nMacro that creates a new environment, then evaluates and assigns values to\nnames and then evaluates the body in context of that environment.\nValues are evaluated sequentially and the next value can access the\nprevious values/names."},{"name":"letrec-syntax","doc":"(letrec-syntax ((name fn) ...) . body)\n\n Works like a combination of letrec and define-syntax. It creates\n local macros and evaluates the body in context of those macros."},{"name":"letrec*","doc":"(letrec* ((a value-a) (b value-b) ...) . body)\n\nSame as letrec but the order of execution of the binding is guaranteed,\nso you can use recursive code as well as referencing the previous binding.\n\nIn LIPS both letrec and letrec* behave the same."},{"name":"list","doc":"(list . args)\n\nFunction that creates a new list out of its arguments."},{"name":"list->array","doc":"(list->array list)\n\nFunction that converts a LIPS list into a JavaScript array."},{"name":"list->string","doc":"(list->string _list)\n\nReturns a string from a list of characters."},{"name":"list->vector","doc":"(list->array list)\n\nFunction that converts a LIPS list into a JavaScript array."},{"name":"list-copy","doc":"(list-copy obj)\n\nCopy the object passed as argument but only if it's list. The car elements\nof the list are not copied, they are passed as is."},{"name":"list-match?","doc":"(list-match? predicate list)\n\nChecks if consecutive elements of the list match the predicate function."},{"name":"list-ref","doc":"(list-ref list n)\n\nReturns n-th element of a list."},{"name":"list-set!","doc":"(list-set! list n)\n\nReturns n-th element of a list."},{"name":"list-tail","doc":"(list-tail list k)\n\nReturns the sublist of list obtained by omitting the first k elements."},{"name":"list?","doc":"(list? obj)\n\nPredicate that tests if value is a proper linked list structure.\nThe car of each pair can be any value. It returns false on cyclic lists.\""},{"name":"list*","doc":"(list* arg1 ...)\n\nParallel asynchronous version of list. Like begin* except all values\nare returned in a list."},{"name":"load","doc":"(load filename)\n(load filename environment)\n\nFetches the file (from disk or network) and evaluates its content as LIPS code.\nIf the second argument is provided and it's an environment the evaluation\nwill happen in that environment."},{"name":"log","doc":"(log z)\n(log z1 z2)\n\nFunction that calculates natural logarithm (base e) of z. Where the argument\ncan be any number (including complex negative and rational). If the value is 0\nit returns NaN. It two arguments are provided it will calculate logarithm\nof z1 with given base z2."},{"name":"macro?","doc":"(macro? expression)\n\nPredicate that tests if value is a macro."},{"name":"macroexpand","doc":"(macroexpand expr)\n\nMacro that expand all macros inside and return single expression as output."},{"name":"macroexpand-1","doc":"(macroexpand-1 expr)\n\nMacro similar to macroexpand but it expand macros only one level\nand return single expression as output."},{"name":"magnitude","doc":"(magnitude x)\n\nReturns magnitude of the complex number in polar coordinate system."},{"name":"make-bytevector","doc":"(make-u8vector k fill)\n\nAllocate new unsigned 8-bit integer vector (C unsigned char) of length k,\nwith optional initial values."},{"name":"make-f32vector","doc":"(make-f32vector k fill)\n\nAllocate new 32-bit IEEE-754 floating point number vector (C float) of length k,\nwith optional initial values."},{"name":"make-f64vector","doc":"(make-f64vector k fill)\n\nAllocate new 64-bit IEEE-754 floating point number vector (C double) of length k,\nwith optional initial values."},{"name":"make-parameter","doc":"(make-parameter init converter)\n\nFunction creates new dynamic variable that can be custimized with parameterize\nmacro. The value should be assigned to a variable e.g.:\n\n(define radix (make-parameter 10))\n\nThe result value is a procedure that return the value of dynamic variable."},{"name":"make-polar","doc":"(make-polar magnitude angle)\n\nCreate new complex number from polar parameters."},{"name":"make-promise","doc":"(make-promise fn)\n\nFunction that creates a promise from a function."},{"name":"make-rectangular","doc":"(make-rectangular im re)\n\nCreates a complex number from imaginary and real part (a+bi form)."},{"name":"make-s16vector","doc":"(make-s16vector k fill)\n\nAllocate new signed 16-bit integer vector (C short) of length k,\nwith optional initial values."},{"name":"make-s32vector","doc":"(make-s32vector k fill)\n\nAllocate new signed 32-bit integer vector (C unsigned int) of length k,\nwith optional initial values."},{"name":"make-s8vector","doc":"(make-s8vector k fill)\n\nAllocate new signed 8-bit integer vector (C signed char) of length k,\nwith optional initial values."},{"name":"make-string","doc":"(make-string k [char])\n\nReturns new string with k elements. If char is provided\nit's filled with that character."},{"name":"make-tags","doc":"(make-tags expression)\n\nReturns a list structure of code with better syntax then raw LIPS"},{"name":"make-u16vector","doc":"(make-u16vector k fill)\n\nAllocate new unsigned 16-bit integer vector (C unsigned short) of length k,\nwith optional initial values."},{"name":"make-u32vector","doc":"(make-u32vector k fill)\n\nAllocate new unsigned 32-bit integer vector (C int) of length k,\nwith optional initial values."},{"name":"make-u8vector","doc":"(make-u8vector k fill)\n\nAllocate new unsigned 8-bit integer vector (C unsigned char) of length k,\nwith optional initial values."},{"name":"make-vector","doc":"(make-vector n [fill])\n\nCreates a new vector with n empty elements. If fill is specified it will set\nall elements of the vector to that value."},{"name":"map","doc":"(map fn . lists)\n\nHigher-order function that calls function `fn` with each\nvalue of the list. If you provide more then one list as argument\nit will take each value from each list and call `fn` function\nwith that many argument as number of list arguments. The return\nvalues of the fn calls are accumulated in a result list and\nreturned by map."},{"name":"match","doc":"(match pattern string)\n\nFunction that returns a match object from JavaScript as a list or #f if\nno match."},{"name":"max","doc":"(max n1 n2 ...)\n\nReturns the maximum of its arguments."},{"name":"member","doc":"(member obj list)\n\nReturns first object in the list that match using equal? function."},{"name":"memq","doc":"(memq obj list)\n\nReturns first object in the list that match using eq? function."},{"name":"memv","doc":"(memv obj list)\n\nReturns first object in the list that match using eqv? function."},{"name":"min","doc":"(min n1 n2 ...)\n\nReturns the minimum of its arguments."},{"name":"modulo","doc":"(modulo a b)\n\nReturns modulo operation on its argumennts."},{"name":"n-ary","doc":"(n-ary n fn)\n\nReturns a new function that limits the number of arguments to n."},{"name":"nan?","doc":"(nan? x)\n\nChecks if argument x is Not a Number (NaN) value."},{"name":"native-symbol?","doc":"(native-symbol? object)\n\nChecks if value is JavaScript Symbol."},{"name":"native.number","doc":"(native.number obj)\n\nIf argument is a number it will convert it to a native number."},{"name":"negative?","doc":"(negative? x)\n\nChecks if the number is smaller then 0"},{"name":"new","doc":"(new obj . args)\n\nFunction that creates new JavaScript instance of an object."},{"name":"new-library","doc":"(new-library name)\n\nCreate new empty library object with empty namespace."},{"name":"newline","doc":"(newline [port])\n\nWrite newline character to standard output or given port"},{"name":"not","doc":"(not x)\n\nReturns true if value is false and false otherwise."},{"name":"nth","doc":"(nth index obj)\n\nFunction that returns the nth element of the list or array.\nIf used with a non-indexable value it will error."},{"name":"nth-pair","doc":"(nth-pair list n)\n\nReturns nth pair of a list."},{"name":"null-environment","doc":"(null-environment)\n\nReturns a clean environment with only the standard library."},{"name":"null?","doc":"(null? expression)\n\nPredicate that tests if value is null-ish (i.e. undefined, nil, or\nJavascript null)."},{"name":"number->string","doc":"(number->string x [radix])\n\nFunction that converts number to string with optional radix (number base)."},{"name":"number?","doc":"(number? expression)\n\nPredicate that tests if value is a number or NaN value."},{"name":"numerator","doc":"(numerator n)\n\nReturn numerator of rational or same number if n is not rational."},{"name":"object","doc":"(object :name value)\n\nCreates a JavaScript object using key like syntax."},{"name":"object->alist","doc":"(object->alist object)\n\nFunction that converts a JavaScript object to Alist"},{"name":"object-literal","doc":"(object-literal :name value)\n\nCreates a JavaScript object using key like syntax. This is similar,\nto object but all values are quoted. This macro is used by the & object literal."},{"name":"object?","doc":"(object? expression)\n\nPredicate that tests if value is an plain object (not another LIPS type)."},{"name":"odd?","doc":"(odd? number)\n\nChecks if number is odd."},{"name":"once","doc":"(once fn)\n\nHigher-order function that returns a new function, that only calls the original\non the first invocation, and immediately returns the first call's result again\non subsequent invocations."},{"name":"open-binary-input-file","doc":"(open-binary-input-file filename)\n\nReturns new Input Binary Port with given filename. In Browser\nuser need to provide global fs variable that is instance of FS interface."},{"name":"open-binary-output-file","doc":"(open-binary-output-file filename)\n\nOpens file and return port that can be used for writing. If file\nexists it will throw an Error."},{"name":"open-input-bytevector","doc":"(open-input-bytevector bytevector)\n\nCreate new input binary port with given bytevector"},{"name":"open-input-file","doc":"(open-input-file filename)\n\nReturns new Input Port with given filename. In Browser user need to\nprovide global fs variable that is instance of FS interface."},{"name":"open-input-string","doc":"(open-input-string string)\n\nCreates new string port as input that can be used to\nread S-exressions from this port using `read` function."},{"name":"open-output-bytevector","doc":"(open-output-bytevector)\n\nCreate new output port that can be used to write binary data.\nAfter done with the data the output buffer can be obtained by calling\n`get-output-bytevector` function."},{"name":"open-output-file","doc":"(open-output-file filename)\n\nFunction that opens file and return port that can be used for writing. If file\nexists it will throw an Error."},{"name":"open-output-string","doc":"(open-output-string)\n\nCreates new output port that can used to write string into\nand after finish get the whole string using `get-output-string`."},{"name":"or","doc":"(or . expressions)\n\nMacro that executes the values one by one and returns the first that is\na truthy value. If there are no expressions that evaluate to true it\nreturns false."},{"name":"output-port-open?","doc":"(output-port-open? port)\n\nChecks if argument is output-port and if you can write to it."},{"name":"output-port?","doc":"(output-port? arg)\n\nReturns true if argument is output port."},{"name":"pair-map","doc":"(pair-map fn list)\n\nFunction that calls fn argument for pairs in a list and returns a combined list\nwith values returned from function fn. It works likes map but take two items\nfrom the list each time."},{"name":"pair?","doc":"(pair? expression)\n\nPredicate that tests if value is a pair or list structure."},{"name":"parameterize","doc":"(parameterize ((name value) ...)\n\nMacro that change the dynamic variable created by make-parameter."},{"name":"parent.frame","doc":"(parent.frame)\n\nReturns the parent environment if called from inside a function.\nIf no parent frame can be found it returns nil."},{"name":"parent.frames","doc":"(parent.frames)\n\nReturns the list of environments from parent frames (lambda function calls)"},{"name":"peek-char","doc":"(peek-char port)\n\nThis function reads and returns a character from the string\nport, or, if there is no more data in the string port, it\nreturns an EOF."},{"name":"peek-u8","doc":"(peek-u8)\n(peek-u8 port)\n\nReturn next byte from input-binary port. If there are no more bytes\nit return eof object."},{"name":"pipe","doc":"(pipe . fns)\n\nHigher-order function that creates a new function that applies all functions\nfrom left to right and returns the last value. Reverse of compose.\ne.g.:\n((pipe (curry + 2) (curry * 3)) 10) ==> (* 3 (+ 2 10)) ==> 36"},{"name":"plain-object?","doc":"(plain-object? x)\n\nChecks if value is a plain JavaScript object created using the object macro."},{"name":"pluck","doc":"(pluck . strings)\n\nIf called with a single string it will return a function that when\ncalled with an object will return that key from the object.\nIf called with more then one string the returned function will\ncreate a new object by copying all properties from the given object."},{"name":"port?","doc":"(port? x)\n\nReturns true if the argument is an input or output port object."},{"name":"positive?","doc":"(positive? x)\n\nChecks if the number is larger then 0"},{"name":"pprint","doc":"(pprint expression)\n\nThis function will pretty print its input to stdout. If it is called\nwith a non-list, it will just call the print function on its\ninput."},{"name":"pretty-format","doc":"(pretty-format pair)\n\nReturns a pretty printed string from pair expression."},{"name":"print","doc":"(print . args)\n\nThis function converts each input into a string and prints\nthe result to the standard output (by default it's the\nconsole but it can be defined in user code). This function\ncalls `(newline)` after printing each input."},{"name":"procedure?","doc":"(procedure? expression)\n\nPredicate that tests if value is a callable function or continuation."},{"name":"promise","doc":"(promise . body)\n\nAnaphoric macro that exposes resolve and reject functions from JS promise."},{"name":"promise?","doc":"(promise? obj)\n\nChecks if the value is a promise created with delay or make-promise."},{"name":"promisify","doc":"(promisify fn)\n\nSimple function for adding promises to NodeJS two-callback based functions.\nFunction tested only with fs module."},{"name":"prototype?","doc":"(prototype? obj)\n\nPredicate that tests if value is a valid JavaScript prototype,\ni.e. calling (new) with it will not throw '<x> is not a constructor'."},{"name":"qsort","doc":"(qsort list predicate)\n\nSorts the list using the quick sort algorithm according to predicate."},{"name":"quasiquote","doc":"(quasiquote list)\n\nSimilar macro to `quote` but inside it you can use special expressions (unquote\nx) abbreviated to ,x that will evaluate x and insert its value verbatim or\n(unquote-splicing x) abbreviated to ,@x that will evaluate x and splice the value\ninto the result. Best used with macros but it can be used outside."},{"name":"quote","doc":"(quote expression) or 'expression\n\nMacro that returns a single LIPS expression as data (it won't evaluate the\nargument). It will return a list if put in front of LIPS code.\nAnd if put in front of a symbol it will return the symbol itself, not the value\nbound to that name."},{"name":"quote-promise","doc":"(quote-promise expr) or '>expr\n\nMacro used to escape automati awaiting of the expression. It will be wrapped\nwith a JavaScript class that behaves like Promise but will not be automatically\nresolved by LIPS like normal promises are."},{"name":"quoted-symbol?","doc":"(quoted-symbol? code)\n\nHelper function that tests if value is a quoted symbol. To be used in macros\nthat pass literal code that is transformed by parser.\n\nusage:\n\n (define-macro (test x)\n (if (quoted-symbol? x)\n `',(cadr x)))\n\n (list 'hello (test 'world))"},{"name":"quotient","doc":"(quotient a b)\n\nReturn quotient from division as integer."},{"name":"radians->degree","doc":"(radians->degree x)\n\nConvert radians to degrees."},{"name":"raise","doc":"(raise obj)\n\nThrows the object verbatim (no wrapping an a new Error)."},{"name":"random","doc":"(random)\n(random seed)\n\nFunction that generates new random real number using Knuth algorithm."},{"name":"range","doc":"(range stop)\n(range start stop)\n(range start stop step)\n\nReturns a list of numbers from start to stop with optional step.\nIf start is not defined it starts from 0. If start is larger than stop\nthe step needs to be negative otherwise it will hang in an infinite loop."},{"name":"rational?","doc":"(rational? x)\n\nChecks if the value is rational."},{"name":"rationalize","doc":"(rationalize number tolerance)\n\nReturns simplest rational number approximation differing from number by no more\nthan the tolerance."},{"name":"read","doc":"(read [port])\n\nThis function, if called with a port, it will parse the next\nitem from the port. If called without an input, it will read\na string from standard input (using the browser's prompt or\na user defined input method) and parse it. This function can be\nused together with `eval` to evaluate code from port."},{"name":"read-all","doc":"(read-all)\n(read-all port)\n\nRead all S-Expressions from port and return them as a list"},{"name":"read-bytevector","doc":"(read-bytevector k)\n(read-bytevector k port)\n\nRead next n bytes from input-binary port. If there are no more bytes\nit returns eof object. If there are less then n bytes in port it\nreturn the only bytes that are available"},{"name":"read-bytevector!","doc":"(read-bytevector! bytevector)\n(read-bytevector! bytevector port)\n(read-bytevector! bytevector port start)\n(read-bytevector! bytevector port start end)\n\nReads next bytes from binary input port and write them into byte vector.\nif not start is specified it start to write into 0 position of the vector until\nthe end or end the vector if no end is specified."},{"name":"read-char","doc":"(read-char port)\n\nThis function reads and returns the next character from the\ninput port."},{"name":"read-line","doc":"(read-line port)\n\nThis function reads and returns the next line from the input\nport."},{"name":"read-string","doc":"(read-string k)\n(read-string k port)\n\nReads the next k characters, or as many as are available\nbefore the end of file, from the textual input port into a\nnewly allocated string in left-to-right order and returns the\nstring. If no characters are available before the end of file,\nan end-of-file object is returned."},{"name":"read-u8","doc":"(read-u8)\n(read-u8 port)\n\nRead next byte from input-binary port. If there are no more bytes\nit return eof object."},{"name":"real-part","doc":"(real-part n)\n\nReturn real part of the complex number n."},{"name":"real?","doc":"(real? x)\n\nChecks if the argument x is real."},{"name":"reduce","doc":"(reduce fn init list . lists)\n\nHigher-order function that takes each element of the list and calls\nthe fn with result of previous call or init and the next element\nof the list until each element is processed, and returns a single value\nas result of last call to `fn` function.\ne.g. it computes (fn 'c 'z (fn 'b 'y (fn 'a 'x 'foo)))\nfor: (reduce fn 'foo '(a b c) '(x y z))"},{"name":"regex","doc":"(regex re)\n(regex re flags)\n\nCreates a new regular expression from string, to not break Emacs formatting."},{"name":"regex?","doc":"(regex? x)\n\nReturns true if value is a regular expression, or false otherwise."},{"name":"remainder","doc":"(% n1 n2)\n\nFunction returns the remainder of n1/n2 (modulo)."},{"name":"remainder__","doc":"(modulo a b)\n\nReturns remainder from division operation."},{"name":"replace","doc":"(replace pattern replacement string)\n\nFunction that changes pattern to replacement inside string. Pattern can be a\nstring or regex and replacement can be function or string. See Javascript\nString.replace()."},{"name":"repr","doc":"(repr obj)\n\nFunction that returns a LIPS code representation of the object as a string."},{"name":"require","doc":"(require module)\n\nFunction used inside Node.js to import a module."},{"name":"require.resolve","doc":"(require.resolve path)\n\nReturns the path relative to the current module.\n\nOnly available when LIPS is running under Node.js."},{"name":"reset","doc":"(reset)\n\nFunction resets the environment and removes all user defined variables."},{"name":"response->content","doc":"(response->text binary res)\n\nReads all text from a Node.js HTTP response object. If binary argument\nis true it will return Buffer object that can be converted to u8vector.\n\n***Warning:*** it may overflow the Javascript call stack when converting the\nwhole buffer to u8vector, because LIPS doesn't have TCO."},{"name":"reverse","doc":"(reverse list)\n\nFunction that reverses the list or array. If value is not a list\nor array it will error."},{"name":"round","doc":"(round number)\n\nFunction that calculates the round of a number."},{"name":"s16vector","doc":"(s16vector v1 v2 ...)\n\nCreate signed 16-bit integer vector (C short) from give arguments."},{"name":"s16vector-length","doc":"(s16vector-length v)\n\nreturn length of signed 16-bit integer vector (C short)."},{"name":"s16vector-ref","doc":"(s16vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s16vector-set!","doc":"(s16vector-set! vector k)\n\nFunction set value of signed 16-bit integer vector (C short) at index k.\nIf index is out of range it throw exception."},{"name":"s16vector?","doc":"(s16vector? x)\n\nReturns #t of argument is signed 16-bit integer vector (C short),\notherwise it return #f."},{"name":"s32vector","doc":"(s32vector v1 v2 ...)\n\nCreate signed 32-bit integer vector (C unsigned int) from give arguments."},{"name":"s32vector-length","doc":"(s32vector-length v)\n\nreturn length of signed 32-bit integer vector (C unsigned int)."},{"name":"s32vector-ref","doc":"(s32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s32vector-set!","doc":"(s32vector-set! vector k)\n\nFunction set value of signed 32-bit integer vector (C unsigned int) at index k.\nIf index is out of range it throw exception."},{"name":"s32vector?","doc":"(s32vector? x)\n\nReturns #t of argument is signed 32-bit integer vector (C unsigned int),\notherwise it return #f."},{"name":"s8vector","doc":"(s8vector v1 v2 ...)\n\nCreate signed 8-bit integer vector (C signed char) from give arguments."},{"name":"s8vector-length","doc":"(s8vector-length v)\n\nreturn length of signed 8-bit integer vector (C signed char)."},{"name":"s8vector-ref","doc":"(s8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"s8vector-set!","doc":"(s8vector-set! vector k)\n\nFunction set value of signed 8-bit integer vector (C signed char) at index k.\nIf index is out of range it throw exception."},{"name":"s8vector?","doc":"(s8vector? x)\n\nReturns #t of argument is signed 8-bit integer vector (C signed char),\notherwise it return #f."},{"name":"scheme-report-environment","doc":"(scheme-report-environment version)\n\nReturns new Environment object for given Scheme Spec version.\nOnly argument 5 is supported that create environment for R5RS."},{"name":"search","doc":"(search pattern string)\n\nFunction that returns the first found index of the pattern inside a string."},{"name":"set-car!","doc":"(set-car! obj value)\n\nFunction that sets the car (first item) of the list/pair to specified value.\nThe old value is lost."},{"name":"set-cdr!","doc":"(set-cdr! obj value)\n\nFunction that sets the cdr (tail) of the list/pair to specified value.\nIt will destroy the list. The old tail is lost."},{"name":"set-current-directory!","doc":"(set-current-directory! string)\n\nChanges the current working directory to provided string."},{"name":"set-global!","doc":"(set-global! name)\n\nMacro to make the name a Javascript global variable (i.e. accessible on globalThis)."},{"name":"set-obj!","doc":"(set-obj! obj key value)\n(set-obj! obj key value props)\n\nFunction set a property of a JavaScript object. props should be a vector of pairs,\npassed to Object.defineProperty."},{"name":"set-repr!","doc":"(add-repr! type fn)\n\nFunction that adds the string representation to the type, which should be\na constructor function.\n\nFunction fn should have args (obj q) and it should return a string. obj\nis the value that need to be converted to a string. If the object is nested\nand you need to use `repr` recursively, it should pass the second parameter q\nto repr, so string will be quoted when it's true.\n\ne.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))"},{"name":"set-special!","doc":"(set-special! symbol name [type])\n\nAdd a special symbol to the list of transforming operators by the parser.\ne.g.: `(add-special! \"#\" 'x)` will allow to use `#(1 2 3)` and it will be\ntransformed into (x (1 2 3)) so you can write x macro that will process\nthe list. 3rd argument is optional, and it can be one of two values:\nlips.specials.LITERAL, which is the default behavior, or\nlips.specials.SPLICE which causes the value to be unpacked into the expression.\nThis can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\nby # that defines vectors."},{"name":"set!","doc":"(set! name value)\n\nMacro that can be used to set the value of the variable or slot (mutate it).\nset! searches the scope chain until it finds first non empty slot and sets it."},{"name":"shuffle","doc":"(shuffle obj)\n\nOrder items in vector or list in random order."},{"name":"sin","doc":"(sin n)\n\nFunction that calculates sine of a number."},{"name":"single","doc":"(single list)\n\nChecks if argument is list with one element."},{"name":"some","doc":"(some fn . lists)\n\nHigher-order function that calls fn on consecutive elements of the list of lists.\nIt stops and returns true when fn returns true. If none of the values give true,\nsome will return false. Analogous to Python any(map(fn, list))."},{"name":"sort","doc":"(sort list [predicate])\n\nSorts the list using optional predicate function. If no comparison function\nis given it will use <= and sort in increasing order."},{"name":"split","doc":"(split separator string)\n\nFunction that creates a list by splitting string by separator which can\nbe a string or regular expression."},{"name":"sqrt","doc":"(sqrt number)\n\nFunction that returns the square root of the number."},{"name":"square","doc":"(square z)\n\nReturns the square of z. This is equivalent to (* z z)."},{"name":"string","doc":"(string chr1 chr2 ...)\n\nFunction that creates a new string from it's arguments. Each argument\nneeds to be a character object."},{"name":"string->list","doc":"(string->list string)\n\nReturns a list of characters created from string."},{"name":"string->number","doc":"(string->number number [radix])\n\nFunction that parses a string into a number."},{"name":"string->symbol","doc":"(string->symbol string)\n\nFunction that converts a string to a LIPS symbol."},{"name":"string->utf8","doc":"(string->utf8 string)\n(string->utf8 string start)\n(string->utf8 string start end)\n\nConverts string into u8 bytevector using utf8 encoding.\nThe start and end is the range of the input string for the conversion."},{"name":"string->vector","doc":"(string->list string)\n(string->list string start)\n(string->list string start end)\n\nFunction that copies given range of string to list. If no start is specified it use\nstart of the string, if no end is specified it convert to the end of the string."},{"name":"string-append","doc":"(concat . strings)\n\nFunction that creates a new string by joining its arguments."},{"name":"string-ci<?","doc":"(string-ci<? string1 string2 ...)\n\nReturns true if strings are monotonically increasing, ignoring the case."},{"name":"string-ci<=?","doc":"(string-ci<=? string1 string2 ...)\n\nReturns true if strings are monotonically non-decreasing, ignoring the case."},{"name":"string-ci=?","doc":"(string-ci=? string1 string2 ...)\n\nChecks if all strings are equal, ignoring the case."},{"name":"string-ci>?","doc":"(string-ci>? string1 string2 ...)\n\nReturns true if strings are monotonically decreasing, ignoring the case"},{"name":"string-ci>=?","doc":"(string-ci>=? string1 string2 ...)\n\nReturns true if strings are monotonically non-increasing, ignoring the case."},{"name":"string-copy","doc":"(string-copy x)\n\nCreates a new string based on given argument."},{"name":"string-downcase","doc":"(string-downcase string)\n\nFunction convert a string passed as argument to lower case."},{"name":"string-fill!","doc":"(string-fill! symbol char)\n\nFunction that destructively fills the string with given character."},{"name":"string-foldcase","doc":"(string-foldcase string)\n\nReturns lowercase string using the Unicode simple case-folding algorithm."},{"name":"string-for-each","doc":"(string-for-each fn string1 stringr2 ...)\n\nApplies a function fn to each element of the strings, similar string-map.\nBut the return value is #void."},{"name":"string-join","doc":"(join separator list)\n\nFunction that returns a string by joining elements of the list using separator."},{"name":"string-length","doc":"(string-length string)\n\nReturns the length of the string."},{"name":"string-map","doc":"(string-map fn string1 stringr2 ...)\n\nReturns new string from applying function fn to each element\nof the strings, similar to map for lists."},{"name":"string-ref","doc":"(string-ref string k)\n\nReturns character inside string at given zero-based index."},{"name":"string-set!","doc":"(string-set! string index char)\n\nReplaces character in string at a given index."},{"name":"string-split","doc":"(split separator string)\n\nFunction that creates a list by splitting string by separator which can\nbe a string or regular expression."},{"name":"string-upcase","doc":"(string-downcase string)\n\nFunction convert a string passed as argument to upper case."},{"name":"string?","doc":"(string? expression)\n\nPredicate that tests if value is a string."},{"name":"string<?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically increasing."},{"name":"string<=?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically non-decreasing."},{"name":"string=?","doc":"(string=? string1 string2 ...)\n\nChecks if all strings are equal."},{"name":"string>?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically decreasing."},{"name":"string>=?","doc":"(string<? string1 string2 ...)\n\nReturns true if strings are monotonically non-increasing."},{"name":"substring","doc":"(substring string start end)\n\nFunction that returns the slice of the string starting at start and ending\nwith end."},{"name":"sxml","doc":"(sxml expr)\n\nMacro for JSX like syntax but with SXML.\ne.g. usage:\n\n(sxml (div (@ (data-foo \"hello\")\n (id \"foo\"))\n (span \"hello\")\n (span \"world\")))\n;; ==> <div data-foo=\"hello\" id=\"foo\"><span>hello</span>\n;; ==> <span>world</span></div>"},{"name":"sxml-unquote","doc":"(sxml-unquote expression) or ~expression\n\nTreat expression as code and evaluate it inside sxml, similar to unquote\nwith quasiquote."},{"name":"symbol->string","doc":"(symbol->string symbol)\n\nFunction that converts a LIPS symbol to a string."},{"name":"symbol-append","doc":"(symbol-append s1 s2 ...)\n\nFunction that creates a new symbol from symbols passed as arguments."},{"name":"symbol?","doc":"(symbol? expression)\n\nPredicate that tests if value is a LIPS symbol."},{"name":"symbol=?","doc":"(symbol=? s1 s2 ...)\n\nChecks if each value is symbol and it's the same according to string=? predicate."},{"name":"syntax-parameterize","doc":"(syntax-parameterize (bindings) body)\n\nMacro work similar to let-syntax but the the bindnds will be exposed to the user.\nWith syntax-parameterize you can define anaphoric macros."},{"name":"syntax-rules","doc":"(syntax-rules () (pattern expression) ...)\n\nBase of hygienic macros, it will return a new syntax expander\nthat works like Lisp macros."},{"name":"take","doc":"(take list n)\n\nReturns n first values of the list."},{"name":"tan","doc":"(tan n)\n\nFunction that calculates tangent of a number."},{"name":"textual-port?","doc":"(textual-port? port)\n\nFunction that tests if argument is string port."},{"name":"throw","doc":"(throw string)\n\nThrows a new exception."},{"name":"timer","doc":"(timer time . body)\n\nEvaluates body after delay, it returns the timer ID from setTimeout.\nTo clear the timer you can use native JS clearTimeout function."},{"name":"tree->array","doc":"(tree->array list)\n\nFunction that converts a LIPS cons tree structure into a JavaScript array."},{"name":"tree-map","doc":"(tree-map fn tree)\n\nTree version of map. fn is invoked on every leaf."},{"name":"truncate","doc":"(truncate n)\n\nFunction that returns the integer part (floor) of a real number."},{"name":"try","doc":"(try expr (catch (e) code))\n(try expr (catch (e) code) (finally code))\n(try expr (finally code))\n\nMacro that executes expr and catches any exceptions thrown. If catch is provided\nit's executed when an error is thrown. If finally is provided it's always\nexecuted at the end."},{"name":"type","doc":"(type object)\n\nFunction that returns the type of an object as string."},{"name":"typecheck","doc":"(typecheck label value type [position])\n\nChecks the type of value and errors if the type is not one allowed. Type can be\nstring or list of strings. The position optional argument is used to create a\nproper error message for the nth argument of function calls."},{"name":"typecheck-args","doc":"(typecheck-args type label lst)\n\nFunction that makes sure that all items in list are of same type."},{"name":"typecheck-number","doc":"(typecheck-number label value type [position])\n\nFunction similar to typecheck but checks if the argument is a number\nand specific type of number e.g. complex."},{"name":"typed-array?","doc":"(typed-array? o)\n\nFunction that tests if the arguments is a JavaScript typed array (Scheme byte vector)."},{"name":"u16vector","doc":"(u16vector v1 v2 ...)\n\nCreate unsigned 16-bit integer vector (C unsigned short) from give arguments."},{"name":"u16vector-length","doc":"(u16vector-length v)\n\nreturn length of unsigned 16-bit integer vector (C unsigned short)."},{"name":"u16vector-ref","doc":"(u16vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u16vector-set!","doc":"(u16vector-set! vector k)\n\nFunction set value of unsigned 16-bit integer vector (C unsigned short) at index k.\nIf index is out of range it throw exception."},{"name":"u16vector?","doc":"(u16vector? x)\n\nReturns #t of argument is unsigned 16-bit integer vector (C unsigned short),\notherwise it return #f."},{"name":"u32vector","doc":"(u32vector v1 v2 ...)\n\nCreate unsigned 32-bit integer vector (C int) from give arguments."},{"name":"u32vector-length","doc":"(u32vector-length v)\n\nreturn length of unsigned 32-bit integer vector (C int)."},{"name":"u32vector-ref","doc":"(u32vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u32vector-set!","doc":"(u32vector-set! vector k)\n\nFunction set value of unsigned 32-bit integer vector (C int) at index k.\nIf index is out of range it throw exception."},{"name":"u32vector?","doc":"(u32vector? x)\n\nReturns #t of argument is unsigned 32-bit integer vector (C int),\notherwise it return #f."},{"name":"u8-ready?","doc":"(u8-ready?)\n(u8-ready? port)\n\nReturns #t if a byte is ready on the binary input port and returns #f otherwise.\nIf u8-ready? returns #t then the next read-u8 operation on the given port is\nguaranteed not to hang. If the port is at end of file then u8-ready? returns #t."},{"name":"u8vector","doc":"(u8vector v1 v2 ...)\n\nCreate unsigned 8-bit integer vector (C unsigned char) from give arguments."},{"name":"u8vector-length","doc":"(u8vector-length v)\n\nreturn length of unsigned 8-bit integer vector (C unsigned char)."},{"name":"u8vector-ref","doc":"(u8vector-ref vector k)\n\nReturns value from vector at index k.\nIf index is out of range it throw exception."},{"name":"u8vector-set!","doc":"(u8vector-set! vector k)\n\nFunction set value of unsigned 8-bit integer vector (C unsigned char) at index k.\nIf index is out of range it throw exception."},{"name":"u8vector?","doc":"(u8vector? x)\n\nReturns #t of argument is unsigned 8-bit integer vector (C unsigned char),\notherwise it return #f."},{"name":"unary","doc":"(unary fn)\n\nReturns a new function with arguments limited to one."},{"name":"unbind","doc":"(unbind fn)\n\nFunction that removes the weak 'this' binding from a function so you\ncan get properties from the actual function object."},{"name":"unfold","doc":"(unfold fn init)\n\nReturns a list from the given function and init value. The function should\nreturn a pair where first is the item added to the list and second is next value\npassed to the function. If the function returns false it ends the loop."},{"name":"unquote","doc":"(unquote code) or ,code\n\nSpecial form used in the quasiquote macro. It evaluates the expression inside and\nsubstitutes the value into quasiquote's result."},{"name":"unquote-splicing","doc":"(unquote-splicing code) or ,@code\n\nSpecial form used in the quasiquote macro. It evaluates the expression inside and\nsplices the list into quasiquote's result. If it is not the last element of the\nexpression, the computed value must be a pair."},{"name":"unset-repr!","doc":"(unset-repr! type)\n\nRemoves the string representation of the type, which should be constructor function,\nadded by add-repr! function."},{"name":"unset-special!","doc":"(unset-special! name)\n\nFunction that removes a special symbol from parser added by `set-special!`,\nname must be a string."},{"name":"unset!","doc":"(unset! name)\n\nFunction to delete the specified name from environment.\nTrying to access the name afterwards will error."},{"name":"utf8->string","doc":"(utf8->string u8vector)\n(utf8->string u8vector start)\n(utf8->string u8vector start end)\n\nConverts u8 bytevector into string using utf8 encoding.\nThe start and end is the range of the input byte vector for the conversion."},{"name":"value","doc":"(value obj)\n\nFunction that unwraps LNumbers and converts '() to #void."},{"name":"values","doc":"(values a1 a2 ...)\n\nIf called with more then one element it will create a special\nValues object that can be used in the call-with-values function."},{"name":"values-ref","doc":"(values-ref values n)\n\nReturns n value of values object which is result of value function."},{"name":"vector","doc":"(vector 1 2 3 (+ 3 1)) or #(1 2 3 4)\n\nMacro for defining vectors (Javascript Arrays). Vector literals are\nautomatically quoted, so you can't use expressions inside them, only other\nliterals, like other vectors or objects."},{"name":"vector->list","doc":"(vector->list vector)\n(vector->list vector start)\n(vector->list vector start end)\n\nFunction that copies given range of vector to list. If no start is specified it use\nstart of the vector, if no end is specified it convert to the end of the vector."},{"name":"vector->string","doc":"(vector->string vector)\n(vector->string vector start)\n(vector->string vector start end)\n\nReturns new string created from vector of characters in given range.\nIf no start is given it create string from 0, if no end is given it return\nstring to the end."},{"name":"vector-append","doc":"(vector-append v1 v2 ...)\n\nReturns new vector by combining it's arguments that should be vectors."},{"name":"vector-copy","doc":"(vector-copy vector)\n(vector-copy vector start)\n(vector-copy vector start end)\n\nReturns a new vecotor that is a copy of given vector. If start\nis not provided it starts at 0, if end it's not provided it copy\ntil the end of the given vector."},{"name":"vector-copy!","doc":"(vector-copy to at from)\n(vector-copy to at from start)\n(vector-copy to at from start end)\n\nCopies the elements of vector from between start and end into\nvector to starting at `at`. If start is missing it start at 0 and if end\nis missing it copy til the end of the vector from. It throws an error\nif vector from don't fit into the destination `to`."},{"name":"vector-fill!","doc":"(vector-fill! vector fill)\n(vector-fill! vector fill start)\n(vector-fill! vector fill start end)\n\nFill vector with a given value in given range. If start is not given is start\nat 0. If end is not given it fill till the end if the vector."},{"name":"vector-for-each","doc":"(vector-for-each fn vector1 vector2 ...)\n\nInvokes every Returns new vector from applying function fn to each element\nof the vectors, similar to map for lists."},{"name":"vector-length","doc":"(vector-length vec)\n\nReturns length of the vector. It errors if the argument is not a vector."},{"name":"vector-map","doc":"(vector-map fn vector1 vector2 ...)\n\nReturns new vector from applying function fn to each element\nof the vectors, similar to map for lists."},{"name":"vector-ref","doc":"(vector-ref vec n)\n\nReturns nth element of the vector vec."},{"name":"vector-set!","doc":"(vector-set! vec n value)\n\nFunction that sets nth item of the vector to value."},{"name":"vector?","doc":"(vector? n)\n\nReturns true if value is vector and false if not."},{"name":"wait","doc":"(wait time . expr)\n\nReturns a promise that will resolve with the expression after delay."},{"name":"warn-quote","doc":"(warn-quote)\n\nSimple macro that throws an error, when you try to use ’ symbol as quote in code."},{"name":"while","doc":"(while cond body)\n\nCreates a loop, it executes cond and body until cond expression is false."},{"name":"with-exception-handler","doc":"(with-exception-handler handler thunk)\n\nProcedure call and return value of thunk function, if exception happen\nit call handler procedure."},{"name":"with-input-from-file","doc":"(with-input-from-file string thunk)\n\nProcedure open file and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and file port\nis closed."},{"name":"with-input-from-port","doc":"(with-input-from-port port thunk)\n\nProcedure use port and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and given port\nis closed."},{"name":"with-input-from-string","doc":"(with-input-from-string string thunk)\n\nProcedure open string and make it current-input-port then thunk is executed.\nAfter thunk is executed current-input-port is restored and string port\nis closed."},{"name":"with-tags","doc":"(with-tags expression)\n\nvalutes LIPS shorter code for S-Expression equivalent of JSX.\ne.g.:\n\n(with-tags (:div (:class \"item\" :id \"item-1\")\n (list (:span () \"Random Item\")\n (:a (:onclick (lambda (e) (alert \"close\")))\n \"close\"))))\n\nAbove expression can be passed to function that renders JSX (like render\nin React, Preact) To get the string from the macro you can use vhtml\nlibrary from npm."},{"name":"write","doc":"(write obj [port])\n\nWrite object to standard output or give port. For strings it will include\nwrap in quotes."},{"name":"write-bytevector","doc":"(write-bytevector bytevector)\n(write-bytevector bytevector port)\n\nWrite byte vector into binary output port."},{"name":"write-char","doc":"(write-char string)\n(write-char string port)\n\nWrites the character char (not an external representation of the character)\nto the given textual output port and returns an unspecified value."},{"name":"write-string","doc":"(write-string string)\n(write-string string port)\n(write-string string port start)\n(write-string string port start end)\n\nWrites the characters of string from start to end in left-toright order\nto the textual output port."},{"name":"write-u8","doc":"(write-u8 byte)\n(write-u8 byte port)\n\nWrite byte into binary output port."},{"name":"Y","doc":"(Y f)\n\n _ __ __ _ _ _ _ __ __ _ _ _\n / \\ \\ / / / __ / ____ \\ / \\ \\ / / ____ \\ \\ \\\n+ \\ v / + \\ \\ + / ___| + + \\ v / / ___| + + +\n| \\ / | \\ \\ | | |__ | | \\ / | |__ | | |\n| | | | / \\ | | __| | | | | | __| | | |\n| | | | / /\\ \\ | | | | | | | | | | | |\n+ |_| + /_/ \\_\\ + |_| + + |_| |_| + + +\n \\_ \\_ \\_ _/ \\_ _/ _/ _/"},{"name":"zero?","doc":"(zero? x)\n\nChecks if the number is equal to 0"},{"name":"zip","doc":"(zip list1 list2 ...)\n\nReturn list where elements are taken from each list.\ne.g.:\n(zip '(1 2 3) '(2 3 4))\n;; ==> '((1 2) (2 3) (3 4))"}] diff --git a/lib/R5RS.scm b/lib/R5RS.scm index d4d5169c6..edecb078b 100755 --- a/lib/R5RS.scm +++ b/lib/R5RS.scm @@ -225,7 +225,8 @@ "(promise? obj) Checks if the value is a promise created with delay or make-promise." - (string=? (type obj) "promise")) + (and (string=? (type obj) "function") + (. obj (Symbol.for "promise")))) ;; ----------------------------------------------------------------------------- (define (positive? x) @@ -1115,14 +1116,6 @@ (and (char-alphabetic? char) (char=? (char-downcase char) char))) -;; ----------------------------------------------------------------------------- -(define (newline . rest) - "(newline [port]) - - Write newline character to standard output or given port" - (let ((port (if (null? rest) (current-output-port) (car rest)))) - (display "\n" port))) - ;; ----------------------------------------------------------------------------- (define (write obj . rest) "(write obj [port]) diff --git a/lib/R7RS.scm b/lib/R7RS.scm index 61bfe7feb..bbc35e869 100755 --- a/lib/R7RS.scm +++ b/lib/R7RS.scm @@ -1426,6 +1426,7 @@ (new ,name ,@(cdr constructor))) (define (,pred obj) (instanceof ,name obj)) + (set-repr! ,name (lambda () (string-append "#<record(" (symbol->string ',name) ")>"))) ,@(map (lambda (field) (let ((prop-name (car field)) (get (cadr field)) @@ -1550,7 +1551,7 @@ Create new empty library object with empty namespace." (let* ((parent (. (current-environment) '__parent__)) - (lib (let ((lib (--> parent (get name &(:throwError false))))) + (lib (let ((lib (--> parent (get name &(:throwError #f))))) (if (null? lib) (new %Library name) lib))) diff --git a/lib/bootstrap.scm b/lib/bootstrap.scm index 48ce86757..7f2b3f234 100755 --- a/lib/bootstrap.scm +++ b/lib/bootstrap.scm @@ -552,13 +552,25 @@ Helper macro used by cond.") +;; ----------------------------------------------------------------------------- +(define (%else-literal? obj) + "(%else-literal? obj) + + Checks if object is symbol else." + (and (symbol? obj) + (or (eq? obj 'else) + (eq? (--> (new lips.LString (obj.literal)) + (cmp "else")) 0)))) + ;; ----------------------------------------------------------------------------- (define-macro (cond . list) "(cond (predicate? . body) - (predicate? . body)) + (predicate? . body) + (else . body)) (cond (predicate? => procedure) - (predicate? => procedure)) + (predicate? => procedure) + (else . body)) Macro for condition checks. For usage instead of nested ifs. You can use predicate and any number of expressions. Or symbol => @@ -573,27 +585,23 @@ (caddr item) (cdr item))) (rest (cdr list))) - `(let ((,value ,first)) - (if ,value - ,(if fn - `(,expression ,value) - `(begin - ,@expression)) - ,(if (and (pair? rest) - (let ((x (caar rest))) - (or (eq? x true) - (and (symbol? x) - (or (eq? x 'else) - (eq? (--> (new lips.LString (x.literal)) (cmp "else")) 0)))))) - `(begin - ,@(cdar rest)) - (if (not (null? rest)) + (if (%else-literal? first) + `(begin + ,@expression) + `(let ((,value ,first)) + (if ,value + ,(if fn + `(,expression ,value) + `(begin + ,@expression)) + ,(if (not (null? rest)) `(cond ,@rest)))))) '())) ;; ----------------------------------------------------------------------------- (define (regex re . rest) "(regex re) + (regex re flags) Creates a new regular expression from string, to not break Emacs formatting." (typecheck "regex" re "string") @@ -732,6 +740,51 @@ (join " ")) ")"))) +;; ----------------------------------------------------------------------------- +(set-special! "#\"" '%string-interpolation lips.specials.SYMBOL) + +(define (%read-interpolated . rest) + "(%read-interpolated [port]) + + Function read from input port or stdin and return list of strings + interleaved with expressions from interpolation ${...}" + (let ((port (if (null? rest) (current-input-port) (car rest)))) + (let loop ((part "") (result (vector)) (char (read-char port))) + (cond ((and (char=? char #\$) + (char=? (peek-char port) #\{)) + (read-char) + (let ((expr (read port))) + (let ((next (peek-char port))) + (if (char=? next #\}) + (begin + (read-char) + (loop "" (vector-append result (vector part expr)) (read-char))) + (error (string-append "Parse Error: expecting } got " (repr next))))))) + ((char=? char #\\) + (loop (string-append part (repr (read-char))) result (read-char))) + ((char=? char #\") + (vector->list (vector-append result (vector part)))) + ((eof-object? char) + (error "Parse Error: expecting character #eof found")) + (else + (loop (string-append part (repr char)) result (read-char))))))) + +(define (%string-interpolation) + "(%string-interpolation) + + String interpolation syntax-extension that read remainder of a string and return + LISP scheme code that evaluate to the string." + (let* ((lexer lips.__parser__.__lexer__) + (token lexer.__token__) + (offset (+ token.col 2)) + (re (regex (string-append "\\n\\s{1," (repr offset) "}") "g"))) + `(string-append ,@(map (lambda (expr) + (if (string? expr) + (begin + (expr.replace re "\n")) + `(repr ,expr))) + (%read-interpolated))))) + ;; ----------------------------------------------------------------------------- (define (bound? x . rest) "(bound? x [env]) @@ -783,15 +836,62 @@ (qsort list predicate))) ;; ----------------------------------------------------------------------------- -(define (every fn list) - "(every fn list) +(define-macro (%any lists) + `(or ,@lists)) - Function that calls fn on each item of the list, if every value returns true - it will return true otherwise it return false. - Analogous to Python all(map(fn, list))." - (if (null? list) + +;; ----------------------------------------------------------------------------- +(define (%any-null? lst) + "(%any-null? lst) + + Checks if any of elements in the list is null." + (if (null? lst) + false + (if (null? (car lst)) + true + (%any-null? (cdr lst))))) + +;; ----------------------------------------------------------------------------- +(define (%some fn lists) + "(%some fn lists) + + version of some without typechecking." + (if (or (null? lists) (%any-null? lists)) + false + (if (apply fn (map car lists)) + true + (%some fn (map cdr lists))))) + +;; ----------------------------------------------------------------------------- +(define (some fn . lists) + "(some fn . lists) + + Higher-order function that calls fn on consecutive elements of the list of lists. + It stops and returns true when fn returns true. If none of the values give true, + some will return false. Analogous to Python any(map(fn, list))." + (typecheck "some" fn "function") + (typecheck-args (vector "pair" "nil") "some" lists) + (%some fn lists)) + +;; ----------------------------------------------------------------------------- +(define (%every fn lists) + "(%every fn lists) + + version of every without typechecking." + (if (or (null? lists) (%any-null? lists)) true - (and (fn (car list)) (every fn (cdr list))))) + (and (apply fn (map car lists)) (%every fn (map cdr lists))))) + +;; ----------------------------------------------------------------------------- +(define (every fn . lists) + "(every fn . lists) + + Higher-order function that calls fn on consecutive item of the list of lists, + if every call returns true it will return true otherwise it return false. + Analogous to Python all(map(fn, list))." + (typecheck "every" fn "function") + (typecheck-args (vector "pair" "nil") "every" lists) + (%every fn lists)) ;; ----------------------------------------------------------------------------- (define-macro (promise . body) @@ -936,6 +1036,7 @@ "(define-class name parent . body) Defines a class - JavaScript function constructor with prototype. + parent needs to be class, constructor function, or #null usage: @@ -947,40 +1048,45 @@ (newline)))) (define jack (new Person \"Jack\")) (jack.hi) ; prints \"Jack says hi\"" - (let iter ((functions '()) (constructor '()) (lst body)) - (if (null? lst) - `(begin - (define ,name ,(if (null? constructor) - `(lambda ()) - ;; we return this to solve issue when constructor - ;; return a promise - ;; ref: https://stackoverflow.com/a/50885340/387194 - (append (%class-lambda constructor) - (list 'this)))) - (set-obj! ,name (Symbol.for "__class__") true) - ,(if (not (null? parent)) - `(begin - (set-obj! ,name 'prototype (Object.create (. ,parent 'prototype))) - (set-obj! (. ,name 'prototype) 'constructor ,name))) - (set-obj! ,name '__name__ ',name) - ,@(map (lambda (fn) - `(set-obj! (. ,name 'prototype) - ,(%class-method-name (car fn)) - ,(%class-lambda fn))) - functions)) - (let ((item (car lst))) - (if (eq? (car item) 'constructor) - (iter functions item (cdr lst)) - (iter (cons item functions) constructor (cdr lst))))))) + (let ((g:parent (gensym))) + (let iter ((functions '()) (constructor '()) (lst body)) + (if (null? lst) + `(begin + (define ,name ,(if (null? constructor) + `(lambda ()) + ;; we return this to solve issue when constructor + ;; return a promise + ;; ref: https://stackoverflow.com/a/50885340/387194 + (append (%class-lambda constructor) + (list 'this)))) + (set-obj! ,name (Symbol.for "__class__") true) + (let ((,g:parent ,parent )) + (if (not (null? ,g:parent)) + (begin + (set-obj! ,name 'prototype (Object.create (. ,g:parent 'prototype))) + (set-obj! (. ,name 'prototype) 'constructor ,name)))) + (set-obj! ,name '__name__ ',name) + ,@(map (lambda (fn) + `(set-obj! (. ,name 'prototype) + ,(%class-method-name (car fn)) + ,(%class-lambda fn))) + functions)) + (let ((item (car lst))) + (if (eq? (car item) 'constructor) + (iter functions item (cdr lst)) + (iter (cons item functions) constructor (cdr lst)))))))) ;; ----------------------------------------------------------------------------- (define-syntax class (syntax-rules () ((_) (error "class: parent required")) - ((_ parent body ...) - (let () + ((_ parent-expr body ...) + (let ((parent parent-expr)) + (if (not (or (procedure? parent) (eq? parent #null))) + (error "parent class need to be a function or #null")) (define-class temp parent body ...) + (set-obj! temp "__name__" "anonymous") temp))) "(class <parent> body ...) diff --git a/lib/js/prism.js b/lib/js/prism.js index 642a0a5ee..beb9177d3 100755 --- a/lib/js/prism.js +++ b/lib/js/prism.js @@ -24,6 +24,31 @@ Prism.languages.insertBefore('scheme', 'string', { greedy: true } }); +// modification of PrismJS JavaScript string interpolation +Prism.languages.insertBefore('scheme', 'string', { + 'template-string': { + pattern: /#"(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\"])*"/, + greedy: true, + inside: { + 'template-punctuation': { + pattern: /^#"|"$/, + alias: 'string' + }, + 'interpolation': { + pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/, + lookbehind: true, + inside: { + 'interpolation-punctuation': { + pattern: /^\$\{|\}$/, + alias: 'punctuation' + }, + rest: Prism.languages.scheme + } + }, + 'string': /[\s\S]+/ + } + } +}); // properties of object literals Prism.languages.insertBefore('scheme', 'string', { variable: { diff --git a/lib/srfi/239.scm b/lib/srfi/239.scm new file mode 100644 index 000000000..e775766da --- /dev/null +++ b/lib/srfi/239.scm @@ -0,0 +1,102 @@ +;; Copyright (C) Robby Zambito (2023). All Rights Reserved. +;; Copyright (C) Marc Nieper-Wißkirchen (2022). All Rights Reserved. + +;; Permission is hereby granted, free of charge, to any person +;; obtaining a copy of this software and associated documentation +;; files (the "Software"), to deal in the Software without +;; restriction, including without limitation the rights to use, copy, +;; modify, merge, publish, distribute, sublicense, and/or sell copies +;; of the Software, and to permit persons to whom the Software is +;; furnished to do so, subject to the following conditions: + +;; The above copyright notice and this permission notice shall be +;; included in all copies or substantial portions of the Software. + +;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +;; SOFTWARE. + +(define-syntax duplicate-clause + (syntax-rules () + ((_ c) (syntax-error "duplicate clause in list-case" c)))) + +(define-syntax list-case + (syntax-rules () + ((list-case expr clauses ...) + (letrec-syntax + ((make-clauses + (syntax-rules ::: (_ pair null dotted matched) + ((make-clauses obj p n d) + (error "list-case: no matching clause" obj)) + + ;; pair clauses + ((make-clauses obj (matched pair) n d ((_ . _) body1 ::: body2) remaining :::) + (duplicate-clause '(_ . _))) + + ((make-clauses obj pair n d ((_ . _) body1 ::: body2) remaining :::) + (if (pair? obj) + (begin body1 ::: body2) + (make-clauses obj (matched pair) n d remaining :::))) + + ((make-clauses obj (matched pair) n d ((head . _) body1 ::: body2) remaining :::) + (duplicate-clause '(head . _))) + + ((make-clauses obj pair n d ((head . _) body1 ::: body2) remaining :::) + (if (pair? obj) + (let ((head (car obj))) + body1 ::: body2) + (make-clauses obj (matched pair) n d remaining :::))) + + ((make-clauses obj (matched pair) n d ((_ . tail) body1 ::: body2) remaining :::) + (duplicate-clause '(_ . tail))) + + ((make-clauses obj pair n d ((_ . tail) body1 ::: body2) remaining :::) + (if (pair? obj) + (let ((tail (cdr obj))) + body1 ::: body2) + (make-clauses obj (matched pair) n d remaining :::))) + + ((make-clauses obj (matched pair) n d ((head . tail) body1 ::: body2) remaining :::) + (duplicate-clause '(head . tail))) + + ((make-clauses obj pair n d ((head . tail) body1 ::: body2) remaining :::) + (if (pair? obj) + (let ((head (car obj)) (tail (cdr obj))) + body1 ::: body2) + (make-clauses obj (matched pair) n d remaining :::))) + + ;; null clauses + ((make-clauses obj p (matched null) d (() body1 ::: body2) remaining :::) + (duplicate-clause '())) + + ((make-clauses obj p null d (() body1 ::: body2) remaining :::) + (if (null? obj) + (begin body1 ::: body2) + (make-clauses obj p (matched null) d remaining :::))) + + ;; dotted clauses + ((make-clauses obj p n (matched dotted) (_ body1 ::: body2) remaining :::) + (duplicate-clause '_)) + + ((make-clauses obj p n dotted (_ body1 ::: body2) remaining :::) + (if (and (not (null? obj)) + (not (pair? obj))) + (begin body1 ::: body2) + (make-clauses obj p n (matched dotted) remaining :::))) + + ((make-clauses obj p n (matched dotted) (x body1 ::: body2) remaining :::) + (duplicate-clause 'x)) + + ((make-clauses obj p n dotted (x body1 ::: body2) remaining :::) + (if (and (not (null? obj)) + (not (pair? obj))) + (let ((x obj)) + body1 ::: body2) + (make-clauses obj p n (matched dotted) remaining :::)))))) + (let ((obj expr)) ;only evaluate expr once + (make-clauses obj pair null dotted clauses ...)))))) diff --git a/package.json b/package.json index ed2ea5954..4f33671fb 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,8 @@ "main": "dist/lips.min.js", "module": "dist/lips.esm.min.js", "exports": { - "import": "dist/lips.esm.min.js", - "require": "dist/lips.cjs" + "import": "./dist/lips.esm.min.js", + "require": "./dist/lips.cjs" }, "unpkg": "dist/lips.min.js", "scripts": { diff --git a/src/lips.js b/src/lips.js index 6b7b0a34a..41df537b3 100644 --- a/src/lips.js +++ b/src/lips.js @@ -117,21 +117,19 @@ function contentLoaded(win, fn) { } } // ------------------------------------------------------------------------- -/* eslint-disable */ /* c8 ignore next 13 */ function log(x, ...args) { - if (is_debug()) { - if (is_plain_object(x)) { - console.log(map_object(x, function(value) { - return toString(value, true); - })); - } else { - console.log(toString(x, true), ...args.map(item => { - return toString(item, true); - })); - } + if (is_plain_object(x) && is_debug(args[0])) { + console.log(map_object(x, function(value) { + return toString(value, true); + })); + } else if (is_debug()) { + console.log(toString(x, true), ...args.map(item => { + return toString(item, true); + })); } } +/* eslint-enable */ // ---------------------------------------------------------------------- /* c8 ignore next */ function is_debug(n = null) { @@ -506,17 +504,34 @@ function parse_string(string) { } // ---------------------------------------------------------------------- function parse_symbol(arg) { - if (arg.match(/^\|.*\|$/)) { - arg = arg.replace(/(^\|)|(\|$)/g, ''); - var chars = { + const debug = arg.match(/^name/); + const re = /(^|.)\|/g; + if (arg.match(re)) { + // handle escaped bar and escaped slash + arg = arg.split('|').filter(Boolean).reduce((acc, str) => { + let result = ''; + if (str.match(/^\\+$/)) { + if (str.length > 1) { + const count = Math.floor(str.length / 2); + result = '\\'.repeat(count); + } + if (str.length % 2 !== 0) { + result += '|'; + } + } else { + result = str; + } + return acc + result; + }); + const chars = { t: '\t', r: '\r', n: '\n' }; arg = arg.replace(/\\(x[^;]+);/g, function(_, chr) { return String.fromCharCode(parseInt('0' + chr, 16)); - }).replace(/\\(.)/g, function(_, chr) { - return chars[chr] || chr; + }).replace(/\\([trn])/g, function(_, chr) { + return chars[chr]; }); } return new LSymbol(arg); @@ -818,6 +833,18 @@ const gensym = (function() { return with_props(count, Symbol(`#:g${count}`)); }; })(); +// ---------------------------------------------------------------------- +// :: helper function that make symbols in names array hygienic +// ---------------------------------------------------------------------- +function hygienic_begin(envs, expr) { + const begin = global_env.get('begin'); + const g_begin = gensym('begin'); + envs.forEach(env => { + env.set(g_begin, begin); + }); + return new Pair(g_begin, expr); +} + // ---------------------------------------------------------------------- // Class used to escape promises: feature #54 // ---------------------------------------------------------------------- @@ -1083,6 +1110,11 @@ class Lexer { var found = this.next_token(); if (found) { this._token = this.__input__.substring(this._i, this._next); + if (!this.__token__) { + // handle case when accessing __token__ from the syntax extension + // (e.g. string interpolation) as the first expression in a REPL + read_only(this, '__token__', this.token(true)); + } return this.token(meta); } return eof; @@ -1289,6 +1321,8 @@ Lexer.regex_class = Symbol.for('regex_class'); Lexer.character = Symbol.for('character'); Lexer.bracket = Symbol.for('bracket'); Lexer.b_symbol = Symbol.for('b_symbol'); +Lexer.b_symbol_ex = Symbol.for('b_symbol_ex'); + Lexer.b_comment = Symbol.for('b_comment'); Lexer.i_comment = Symbol.for('i_comment'); Lexer.l_datum = Symbol.for('l_datum'); @@ -1356,7 +1390,9 @@ Lexer._rules = [ // block symbols [/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], - [/\|/, null, Lexer.boundary, Lexer.b_symbol, null] + [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], + [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], + [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null] ]; // ---------------------------------------------------------------------- Lexer._brackets = [ @@ -1463,10 +1499,10 @@ class Parser { // to read data from the parser stream #150 const internal = get_internal(this.__env__); const stdin = internal.get('stdin'); - this.__env__.set('lips', { ...lips, __parser__: this }); + global_env.set('lips', { ...lips, __parser__: this }); internal.set('stdin', new ParserInputPort(this, this.__env__)); const cleanup = () => { - this.__env__.set('lips', lips); + global_env.set('lips', lips); internal.set('stdin', stdin); } return unpromise(fn(), (result) => { @@ -2311,8 +2347,8 @@ function keywords_re(...args) { // line breaking rules Formatter.rules = [ [[sexp], 0, not_close], - [[p_o, keywords_re('begin', 'cond-expand')], 1], - [[p_o, let_re, symbol, p_o, let_value, p_e], 1], + [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], + [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], @@ -2325,7 +2361,7 @@ Formatter.rules = [ [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], - [[p_o, keywords_re('if'), not_p, glob], 1], + [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], @@ -3181,7 +3217,7 @@ Pair.prototype.map = function(fn) { return nil; } }; -var repr = new Map(); +const repr = new Map(); // ---------------------------------------------------------------------- function is_plain_object(object) { return object && typeof object === 'object' && object.constructor === Object; @@ -3203,11 +3239,11 @@ function is_lips_function(x) { } // ---------------------------------------------------------------------- function user_repr(obj) { - var constructor = obj.constructor || Object; - var plain_object = is_plain_object(obj); + const constructor = obj.constructor || Object; + const plain_object = is_plain_object(obj); var iterator = is_function(obj[Symbol.asyncIterator]) || is_function(obj[Symbol.iterator]); - var fn; + let fn; if (repr.has(constructor)) { fn = repr.get(constructor); } else { @@ -3216,7 +3252,7 @@ function user_repr(obj) { // if key is Object it should only work for plain_object // because otherwise it will match every object // we don't use instanceof so it don't work for subclasses - if (obj instanceof key && + if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) { fn = value; } @@ -3418,6 +3454,9 @@ function toString(obj, quote, skip_cycles, ...pair_args) { if (type(obj) === 'instance') { if (is_lambda(constructor) && constructor.__name__) { name = constructor.__name__.valueOf(); + if (typeof name === 'symbol') { + name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1'); + } } else if (!is_native_function(constructor)) { name = 'instance'; } @@ -4040,7 +4079,7 @@ Syntax.Parameter = SyntaxParameter; // :: TODO detect cycles // ---------------------------------------------------------------------- function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { - var bindings = { + const bindings = { '...': { symbols: { }, // symbols ellipsis (x ...) lists: [ ] @@ -4054,7 +4093,8 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { // duplicated ellipsis symbol log(symbols); /* eslint-disable complexity */ - function traverse(pattern, code, pattern_names = [], ellipsis = false) { + function traverse(pattern, code, state = {}) { + const { ellipsis = false, trailing = false, pattern_names = [] } = state; log({ code, pattern @@ -4062,13 +4102,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { if (is_atom(pattern) && !(pattern instanceof LSymbol)) { return same_atom(pattern, code); } - if (pattern instanceof LSymbol && - symbols.includes(pattern.literal())) { // TODO: literal() may be SLOW - if (!LSymbol.is(code, pattern)) { - return false; + if (pattern instanceof LSymbol) { + const literal = pattern.literal(); // TODO: literal() may be SLOW + if (symbols.includes(literal)) { + if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) { + return false; + } + const ref = expansion.ref(literal); + return !ref || ref === define || ref === global_env; } - const ref = expansion.ref(pattern); - return !ref || ref === define || ref === global_env; } if (Array.isArray(pattern) && Array.isArray(code)) { log('<<< a 1'); @@ -4095,19 +4137,20 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { log('<<< a 3'); const names = [...pattern_names]; let node = code; - if (!code.every(node => traverse(pattern[0], node, names, true))) { + const new_state = { ...state, pattern_names: names, ellipsis: true }; + if (!code.every(node => traverse(pattern[0], node, new_state))) { return false; } } if (pattern.length > 2) { const pat = pattern.slice(2); - return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis); + return traverse(pat, code.slice(-pat.length), state); } return true; } - const first = traverse(pattern[0], code[0], pattern_names, ellipsis); + const first = traverse(pattern[0], code[0], state); log({first, pattern: pattern[0], code: code[0]}); - const rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis); + const rest = traverse(pattern.slice(1), code.slice(1), state); log({first, rest}); return first && rest; } @@ -4132,23 +4175,28 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) { + log('>> 1 (a)'); // pattern (... ???) - SRFI-46 if (!is_nil(pattern.cdr.cdr)) { if (is_pair(pattern.cdr.cdr)) { + log('>> 1 (b)'); // if we have (x ... a b) we need to remove two from the end const list_len = pattern.cdr.cdr.length(); + const improper_list = !is_nil(pattern.last_pair().cdr); if (!is_pair(code)) { return false; } let code_len = code.length(); let list = code; - while (code_len - 1 > list_len) { + const trailing = improper_list ? 1 : 1; + while (code_len - trailing > list_len) { list = list.cdr; code_len--; } const rest = list.cdr; list.cdr = nil; - if (!traverse(pattern.cdr.cdr, rest, pattern_names, ellipsis)) { + const new_sate = { ...state, trailing: improper_list }; + if (!traverse(pattern.cdr.cdr, rest, new_sate)) { return false; } } @@ -4159,7 +4207,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { !pattern_names.includes(name) && !ellipsis) { throw new Error('syntax: named ellipsis can only appear onces'); } - log('>> 1'); + log('>> 1 (next)'); if (is_nil(code)) { log('>> 2'); if (ellipsis) { @@ -4190,6 +4238,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { } else { log('>> 6'); if (is_pair(code)) { + log('>> 7 ' + ellipsis); // cons (a . b) => (var ... . x) if (!is_pair(code.cdr) && !is_nil(code.cdr)) { log('>> 7 (b)'); @@ -4197,31 +4246,35 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { return false; } else if (!bindings['...'].symbols[name]) { bindings['...'].symbols[name] = new Pair(code.car, nil); - return traverse(pattern.cdr.cdr, code.cdr); + return traverse(pattern.cdr.cdr, code.cdr, state); } } // code as improper list const last_pair = code.last_pair(); + log({ last_pair }); if (!is_nil(last_pair.cdr)) { + log('>> 7 (c)') if (is_nil(pattern.cdr.cdr)) { // case (a ...) for (a b . x) return false; } else { + log('>> 7 (d)'); // case (a ... . b) for (a b . x) const copy = code.clone(); copy.last_pair().cdr = nil; bindings['...'].symbols[name] = copy; - return traverse(pattern.cdr.cdr, last_pair.cdr); + return traverse(pattern.cdr.cdr, last_pair.cdr, state); } } - log('>> 7 ' + ellipsis); pattern_names.push(name); if (!bindings['...'].symbols[name]) { + log('>> 7 (e)'); bindings['...'].symbols[name] = new Pair( code, nil ); } else { + log('>> 7 (f)'); const node = bindings['...'].symbols[name]; bindings['...'].symbols[name] = node.append( new Pair( @@ -4237,7 +4290,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { // empty ellipsis with rest (a b ... . d) #290 log('>> 8'); bindings['...'].symbols[name] = null; - return traverse(pattern.cdr.cdr, code); + return traverse(pattern.cdr.cdr, code, state); } else { log('>> 9'); return false; @@ -4254,8 +4307,9 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { } log('>> 11'); let node = code; + const new_state = { ...state, pattern_names: names, ellipsis: true }; while (is_pair(node)) { - if (!traverse(pattern.car, node.car, names, true)) { + if (!traverse(pattern.car, node.car, new_state)) { return false; } node = node.cdr; @@ -4264,8 +4318,9 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { } if (Array.isArray(pattern.car) ) { var names = [...pattern_names]; let node = code; + const new_state = { ...state, pattern_names: names, ellipsis: true }; while (is_pair(node)) { - if (!traverse(pattern.car, node.car, names, true)) { + if (!traverse(pattern.car, node.car, new_state)) { return false; } node = node.cdr; @@ -4299,16 +4354,30 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { code, pattern }); + const rest_pattern = pattern.car instanceof LSymbol && + pattern.cdr instanceof LSymbol; + if (trailing && rest_pattern) { + log('>> 13 (a)'); + // handle (x ... y . z) + if (!is_nil(code.cdr)) { + return false; + } + const car = pattern.car.valueOf(); + const cdr = pattern.cdr.valueOf(); + bindings.symbols[car] = code.car; + bindings.symbols[cdr] = nil; + return true; + //return is_pair(code.cdr) && code.cdr.length() > 1; + } if (is_nil(code.cdr)) { + log('>> 13 (b)'); // 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) { // fix for SRFI-26 in recursive call of (b) ==> (<> . x) // where <> is symbol - if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) { + if (!traverse(pattern.car, code.car, state)) { return false; } log('>> 14'); @@ -4328,14 +4397,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { code }); // case (x y) ===> (var0 var1 ... warn) where var1 match nil + // trailing: true start processing of (var ... x . y) if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && - traverse(pattern.car, code.car, pattern_names, ellipsis) && - traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) { + traverse(pattern.car, code.car, state) && + traverse(pattern.cdr.cdr.cdr, code.cdr, {...state, trailing: true })) { const name = pattern.cdr.car.__name__; log({ pattern, @@ -4353,10 +4423,16 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol, scope = {}) { pattern, code }); - const car = traverse(pattern.car, code.car, pattern_names, ellipsis); - log({car, pattern: pattern.car, code: code.car}); - const cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis); - log({ car, cdr }); + const car = traverse(pattern.car, code.car, state); + const cdr = traverse(pattern.cdr, code.cdr, state); + log({ + $car_code: code.car, + $car_pattern: pattern.car, + car, + $cdr_code: code.cdr, + $cdr_pattern: pattern.cdr, + cdr + }); if (car && cdr) { return true; } @@ -4539,7 +4615,7 @@ function transform_syntax(options = {}) { const item = bindings[name]; if (item === null) { return; - } else if (item) { + } else if (name in bindings) { log({ name, binding: bindings[name] }); if (is_pair(item)) { log('[t 2 Pair ' + nested); @@ -4566,7 +4642,8 @@ function transform_syntax(options = {}) { log('|| next 2'); next(name, new Pair(car.cdr, cdr)); } - return car.car; + // wrap with Value to handle undefined + return new Value(car.car); } else if (is_nil(cdr)) { return car; } else { @@ -4633,6 +4710,7 @@ function transform_syntax(options = {}) { return expr; } if (is_pair(expr) || is_array) { + log('>> 0'); const first = is_array ? expr[0] : expr.car; let second, rest_second; if (is_array) { @@ -4719,6 +4797,9 @@ function transform_syntax(options = {}) { // undefined can be null caused by null binding // on empty ellipsis if (car !== undefined) { + if (car instanceof Value) { + car = car.valueOf(); + } if (is_spread) { if (is_array) { if (Array.isArray(car)) { @@ -4768,6 +4849,9 @@ function transform_syntax(options = {}) { nested: true }); if (car) { + if (car instanceof Value) { + car = car.valueOf(); + } return new Pair( car, nil @@ -4798,7 +4882,7 @@ function transform_syntax(options = {}) { const next = (key, value) => { new_bind[key] = value; }; - const value = transform_ellipsis_expr( + let value = transform_ellipsis_expr( expr, bind, { nested: false }, @@ -4806,6 +4890,9 @@ function transform_syntax(options = {}) { ); log({ value }); if (typeof value !== 'undefined') { + if (value instanceof Value) { + value = value.valueOf(); + } if (is_array) { result.push(value); } else { @@ -4840,6 +4927,7 @@ function transform_syntax(options = {}) { } } log('<<<< 2'); + log({ result }); return result; } } @@ -4979,8 +5067,12 @@ function is_undef(value) { return typeof value === 'undefined'; } // ------------------------------------------------------------------------- +function get_proto(obj) { + return Object.getPrototypeOf(obj); +} +// ------------------------------------------------------------------------- function is_iterator(obj, symbol) { - if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) { + if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) { return is_function(obj[symbol]); } } @@ -5271,16 +5363,14 @@ function let_macro(symbol) { params = code.cdr.car.map(pair => pair.car); args = code.cdr.car.map(pair => pair.cdr.car); } - const args_name = gensym('args'); - return Pair.fromArray([ - LSymbol('let'), - [[args_name, Pair(LSymbol('list'), args)]], - [LSymbol('letrec'), - [[code.car, Pair( - LSymbol('lambda'), - Pair(params, code.cdr.cdr))]], - [LSymbol('apply'), code.car, args_name]] - ]); + return new Pair( + Pair.fromArray([ + LSymbol('letrec'), + [[code.car, Pair( + LSymbol('lambda'), + Pair(params, code.cdr.cdr))]], + code.car]), + args); } else if (macro_expand) { // Macro.defmacro are special macros that should return lips code // here we use evaluate, so we need to check special flag set by @@ -5298,7 +5388,7 @@ function let_macro(symbol) { } var i = 0; function exec() { - var output = new Pair(new LSymbol('begin'), code.cdr); + var output = hygienic_begin([env], code.cdr); return evaluate(output, { env, dynamic_env: env, @@ -8024,6 +8114,16 @@ var global_env = new Environment({ If there are missing inputs or other escape characters it will error.`), // ------------------------------------------------------------------ + newline: doc('newline', function newline(port = null) { + const display = global_env.get('display'); + const { use_dynamic } = this; + const env = global_env; + const dynamic_env = global_env; + call_function(display, ['\n', port], { env, dynamic_env, use_dynamic }); + }, `(newline [port]) + + Write newline character to standard output or given port`), + // ------------------------------------------------------------------ display: doc('display', function display(arg, port = null) { if (port === null) { port = internal(this, 'stdout'); @@ -8045,7 +8145,7 @@ var global_env = new Environment({ const repr = global_env.get('repr'); const value = args.map(repr).join(' '); port.write.call(global_env, value); - global_env.get('newline')(port); + global_env.get('newline').call(this, port); }, `(display-error . args) Display an error message on stderr.`), @@ -8244,6 +8344,8 @@ var global_env = new Environment({ env = this.get('**interaction-environment**'); } } + const package_name = '@lips'; + const has_package = file.startsWith(package_name); // TODO: move **module-path** to internal env const PATH = '**module-path**'; var module_path = global_env.get(PATH, { throwError: false }); @@ -8281,45 +8383,69 @@ var global_env = new Environment({ return code; }); } + function get_root_dir() { + const __dirname = global_env.get('__dirname'); + return __dirname.replace(/[^/]+$/, ''); + } if (is_node()) { return new Promise(async (resolve, reject) => { - const path = nodeRequire('path'); - let cwd; - if (module_path) { - module_path = module_path.valueOf(); - file = path.join(module_path, file); - } else { - const cmd = g_env.get('command-line', { throwError: false }); - let args; - if (cmd) { - args = await cmd(); - } - if (args && !is_nil(args)) { - cwd = process.cwd(); - file = path.join(path.dirname(args.car.valueOf()), file); + try { + await node_ready; + const path = nodeRequire('path'); + const fs = nodeRequire('fs'); + let cwd; + const root_dir = get_root_dir(); + if (has_package) { + file = file.replace(package_name, root_dir); } - } - global_env.set(PATH, path.dirname(file)); - nodeRequire('fs').readFile(file, function(err, data) { - if (err) { - reject(err); - global_env.set(PATH, module_path); - } else { - try { - run(data).then(() => { - resolve(); - global_env.set(PATH, module_path); - }).catch(reject); - } catch (e) { - reject(e); + if (module_path) { + module_path = module_path.valueOf(); + if (!file.startsWith('/')) { + file = path.join(module_path, file); + } + } else if (!file.startsWith('/')) { + const cmd = g_env.get('command-line', { throwError: false }); + let args; + if (cmd) { + args = await cmd(); + } + if (args && !is_nil(args)) { + cwd = process.cwd(); + file = path.join(path.dirname(args.car.valueOf()), file); } } - }); + global_env.set(PATH, path.dirname(file)); + fs.readFile(file, function(err, data) { + if (err) { + reject(err); + global_env.set(PATH, module_path); + } else { + try { + run(data).then(() => { + resolve(); + global_env.set(PATH, module_path); + }).catch(reject); + } catch (e) { + reject(e); + } + } + }); + } catch(e) { + console.error(e); + } }); } + if (has_package) { + let path = global_env.get('__dirname', { throwError: false }) ?? current_script; + path ??= current_script; + const root = path.replace(/dist\/?[^\/]*$/, ''); + file = file.replace(package_name, root); + } if (module_path) { module_path = module_path.valueOf(); - file = module_path + '/' + file.replace(/^\.?\/?/, ''); + if (!file.startsWith('/')) { + file = module_path + '/' + file.replace(/^\.?\/?/, ''); + } } return fetch(file).then(code => { global_env.set(PATH, file.replace(/\/[^/]*$/, '')); @@ -8653,8 +8779,10 @@ var global_env = new Environment({ } env.set(name, parameter); } - const body = new Pair(new LSymbol('begin'), code.cdr); - return evaluate(body, { ...eval_args, env }); + const expr = hygienic_begin([ + env, eval_args.dynamic_env + ], code.cdr); + return evaluate(expr, { ...eval_args, env }); }), `(syntax-parameterize (bindings) body) Macro work similar to let-syntax but the the bindnds will be exposed to the user. @@ -8798,19 +8926,13 @@ var global_env = new Environment({ // ------------------------------------------------------------------ 'eval': doc('eval', function(code, env) { env = env || this.get('interaction-environment').call(this); - return evaluate(code, { - env, - dynamic_env: env, - error: e => { - var error = global_env.get('display-error'); - error.call(this, e.message); - if (e.code) { - var stack = e.code.map((line, i) => { - return `[${i + 1}]: ${line}`; - }).join('\n'); - error.call(this, stack); - } - } + return new Promise((resolve, reject) => { + const result = evaluate(code, { + env, + dynamic_env: env, + error: reject + }); + resolve(result); }); }, `(eval expr) (eval expr environment) @@ -8881,7 +9003,7 @@ var global_env = new Environment({ } } var rest = __doc__ ? code.cdr.cdr : code.cdr; - var output = new Pair(new LSymbol('begin'), rest); + var output = hygienic_begin([env, dynamic_env], rest); const eval_args = { env, dynamic_env, @@ -9242,12 +9364,16 @@ var global_env = new Environment({ // ----------------------------------------------------------------- function unquote_splice(pair, unquote_cnt, max_unq) { if (unquote_cnt < max_unq) { + let cdr = nil; + if (!is_nil(pair.cdr)) { + cdr = recur(pair.cdr, unquote_cnt - 1, max_unq); + } return new Pair( new Pair( pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq) ), - nil + cdr ); } var lists = []; @@ -10147,23 +10273,6 @@ var global_env = new Environment({ Predicate that tests if value is a proper linked list structure. The car of each pair can be any value. It returns false on cyclic lists."`), // ------------------------------------------------------------------ - some: doc('some', function some(fn, list) { - typecheck('some', fn, 'function'); - typecheck('some', list, ['pair', 'nil']); - if (is_null(list)) { - return false; - } else { - return unpromise(fn(list.car), (value) => { - return value || some(fn, list.cdr); - }); - } - }, `(some fn list) - - Higher-order function that calls fn on each element of the list. - It stops and returns true when fn returns true for a value. - If none of the values give true, some will return false. - Analogous to Python any(map(fn, list)).`), - // ------------------------------------------------------------------ fold: doc('fold', fold('fold', function(fold, fn, init, ...lists) { typecheck('fold', fn, 'function'); lists.forEach((arg, i) => { @@ -10756,17 +10865,21 @@ async function node_specific() { }); } // ------------------------------------------------------------------------- -/* c8 ignore next 11 */ +/* c8 ignore next 15 */ +let node_ready; // Scheme load function need to wait for node_specific if (is_node()) { - node_specific(); -} else if (typeof window !== 'undefined' && window === root) { - global_env.set('window', window); - global_env.set('global', undefined); - global_env.set('self', window); -} else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { - global_env.set('self', self); - global_env.set('window', undefined); - global_env.set('global', undefined); + node_ready = node_specific(); +} else { + node_ready = Promise.resolve(); + if (typeof window !== 'undefined' && window === root) { + global_env.set('window', window); + global_env.set('global', undefined); + global_env.set('self', window); + } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') { + global_env.set('self', self); + global_env.set('window', undefined); + global_env.set('global', undefined); + } } // ------------------------------------------------------------------------- function typeErrorMessage(fn, got, expected, position = null) { @@ -11337,7 +11450,7 @@ function exec_collect(collect_callback) { dynamic_env = env === true ? user_env : env || user_env; } if (env === true) { - env = user_env; + env = user_env; } else { env = env || user_env; } @@ -11456,6 +11569,7 @@ function bootstrap(url = '') { url = `https://cdn.jsdelivr.net/npm/@jcubic/lips@${lips.version}/${std}`; } } + global_env.set('__dirname', url.replace(/[^/]+$/, '')); var load = global_env.get('load'); return load.call(user_env, url, global_env); } diff --git a/templates/Makefile b/templates/Makefile index 8981a35a1..3a70f9a6b 100755 --- a/templates/Makefile +++ b/templates/Makefile @@ -11,6 +11,7 @@ COMMIT=`git rev-parse HEAD` URL=`git config --get remote.origin.url` UNICODE_ALL=https://unicode.org/Public/UNIDATA/UnicodeData.txt UNICODE_FOLD=https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt +WORK_TREE=`git worktree list | cut -f1 -d' ' | grep -v "\`pwd\`$$" | xargs -I{} basename {} | tr $$'\n' ',' | sed 's/,$$//'` MAKE=make GIT=git @@ -131,7 +132,7 @@ coverage: $(NPM) run coverage codespell: - $(CODESPELL) -S 'package-lock.json,node_modules,build,coverage' + @$(CODESPELL) -S $(WORK_TREE) lint: - $(ESLINT) src/lips.js lib/js/bookmark.js + $(ESLINT) src/lips.js lib/js/bookmark.js bin/lips.js diff --git a/templates/README.md b/templates/README.md index 25f7df4c1..34b381542 100644 --- a/templates/README.md +++ b/templates/README.md @@ -260,8 +260,16 @@ This can happen with React/Preact and when the component returns a Promise. Some | Custom macro transformers | [SRFI-147](https://srfi.schemers.org/srfi-147/) | | Version flag | [SRFI-176](https://srfi.schemers.org/srfi-176/) | | Command line | [SRFI-193](https://srfi.schemers.org/srfi-193/) | +| Mixing groups of definitions with expressions within bodies | [SRFI-251](https://srfi.schemers.org/srfi-251/) | -### require `(load "./lib/srfi/<number>.scm")` +### require manual loading + +You can load the SRFI with special syntax that start with `@lips` +which points to root LIPS directory: + +```scheme +(load "@lips/lib/srfi/<number>.scm") +``` They should be loaded as R7RS libraries in final 1.0.0 version @@ -278,8 +286,9 @@ They should be loaded as R7RS libraries in final 1.0.0 version | Multiple-value boxes | [SRFI-195](https://srfi.schemers.org/srfi-195) | | Procedures and Syntax for Multiple Values | [SRFI-210](https://srfi.schemers.org/srfi-210/) | | Evaluating expressions in an unspecified order | [SRFI-236](https://srfi.schemers.org/srfi-236) | +| Destructuring Lists | [SRFI 239](https://srfi.schemers.org/srfi-239/) | -in Web (e.g. in Web REPL) you can use URL: +in Web (e.g. in Web REPL) you can also use full URL: ```scheme (load "https://cdn.jsdelivr.net/npm/@jcubic/lips@beta/lib/srfi/<NUMBER>.scm") @@ -364,6 +373,8 @@ I would also love to see if you use the library, I may even share the links of p Special thanks to [Lassi Kortela](https://github.com/lassik) for helping with Scheme code. +Thanks for [Algolia DocSearch](https://docsearch.algolia.com/) for providing free search on LIPS website. + ## License Released under [MIT](http://opensource.org/licenses/MIT) license<br/> diff --git a/tests/continuations.scm b/tests/continuations.scm index c24caddae..187897710 100644 --- a/tests/continuations.scm +++ b/tests/continuations.scm @@ -82,6 +82,25 @@ (t.is result '("Hello <0>"))))) +(test.failing "continuations: scope mutation" + (lambda (t) + (define counter '()) + + (define (make-counter n) + (let ((m (call/cc + (lambda (cont) + (begin + (set! counter cont) + 0))))) + (begin + (set! n (+ n 1)) + (+ m n)))) + + (t.is (make-counter 0) 1) + (t.is (counter 0) 2) + (t.is (counter 0) 3))) + + (test.failing "continuations: coroutine generator" (lambda (t) (define (make-coroutine-generator proc) diff --git a/tests/core.scm b/tests/core.scm index 258842628..6e56fa179 100644 --- a/tests/core.scm +++ b/tests/core.scm @@ -146,9 +146,13 @@ (t.is '|\n| (string->symbol "\n")) (t.is '|\t\t| (string->symbol "\t\t")) (t.is '|\r| (string->symbol "\r")) - (t.is '|\s| 's) + (t.is '|\s| '\s) (t.is '|\x3BB;| 'λ) - (t.is '|\x9;\x9;| '|\t\t|))) + (t.is '|\x9;\x9;| '|\t\t|) + ;; found in + ;; https://docs.scheme.org/surveys/reader-vertical-bar-concatenated-with-number/ + (t.is (lips.tokenize "|1|aaa |a|b|c| |foo bar|") + #("|1|aaa" "|a|b|c|" "|foo bar|")))) (test "core: dot comma" (lambda (t) @@ -747,6 +751,11 @@ (lambda (t) (t.is (replace #/foo/ (lambda () (Promise.resolve "lips")) "foo bar") "lips bar"))) +(test "core: should throw proper error" + (lambda (t) + (t.is (try (eval '(+ x x)) (catch (e) e.message)) + "Unbound variable `x'"))) + ;; TODO ;; begin* ;; set-obj! throws with null or boolean diff --git a/tests/parser.scm b/tests/parser.scm index f0f4dcf29..ed826d4f6 100644 --- a/tests/parser.scm +++ b/tests/parser.scm @@ -267,6 +267,11 @@ (lambda (t) (t.is (to.throw (lips.parse "#f10")) #t))) +(test "parser: escape symbols" + (lambda (t) + (t.is (map symbol->string '(|name| name|| name|\|| name|\\|xxx name|\\\\| name|\\|)) + '("name" "name" "name|" "name\\xxx" "name\\\\" "name\\")))) + (test "lexer: should create tokens for simple list" (lambda (t) (t.is (lips.tokenize "(foo bar baz)") diff --git a/tests/quotation.scm b/tests/quotation.scm index fe36c8919..ce1fe5c21 100644 --- a/tests/quotation.scm +++ b/tests/quotation.scm @@ -338,3 +338,13 @@ (lambda (t) (let ((result `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))))) (t.is result '((foo 7) . cons))))) + +(test "quasiquote: should process list after double unquote-splicing (#362)" + (lambda (t) + (let ((x '(1 2 3)) + (y '(11 22 33)) + (l '(x y))) + (t.is ``(,@,@l ,@,@l) + '(quasiquote ((unquote-splicing x y) (unquote-splicing x y)))) + (t.is (eval ``(foo ,@,@l ,@,@l bar) (current-environment)) + '(foo 1 2 3 11 22 33 1 2 3 11 22 33 bar))))) diff --git a/tests/snapshots/test.js.md b/tests/snapshots/test.js.md index b53509320..6c9f52672 100644 --- a/tests/snapshots/test.js.md +++ b/tests/snapshots/test.js.md @@ -4,6 +4,3543 @@ The actual snapshot is saved in `test.js.snap`. Generated by [AVA](https://avajs.dev). +## syntax: ellipsis maps into #void + +> Snapshot 1 + + Pair { + car: LSymbol { + Symbol(#:let) + --- + __name__: Symbol(#:let), + }, + cdr: Pair { + car: Pair { + car: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + }, + cdr: Pair { + car: Pair { + car: LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + cdr: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + cdr: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + }, + --- + Pair { + car: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + }, + Pair { + car: LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + cdr: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + }, + [Symbol.for(__data__)]: true, + --- + LSymbol { + Symbol(#:let) + --- + __name__: Symbol(#:let), + }, + Pair { + car: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + cdr: Pair { + car: Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + cdr: Pair { + car: LSymbol { + 'alist' + --- + __name__: 'alist', + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + --- + LSymbol { + 'assoc' + --- + __name__: 'assoc', + }, + Pair { + car: LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + cdr: Pair { + car: LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + cdr: Nil { + undefined + }, + --- + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + --- + LSymbol { + 'quote' + --- + __name__: 'quote', + [Symbol.for(__data__)]: true, + }, + LSymbol { + 'bar' + --- + __name__: 'bar', + [Symbol.for(__data__)]: true, + }, + }, + LSymbol { + 'alist' + --- + __name__: 'alist', + }, + }, + }, + }, + Pair { + car: LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + cdr: Pair { + car: LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + cdr: Pair { + car: Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + cdr: Nil { + undefined + }, + --- + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + --- + LSymbol { + Symbol(#:if) + --- + __name__: Symbol(#:if), + }, + LSymbol { + Symbol(#:tmp) + --- + __name__: Symbol(#:tmp), + }, + Pair { + car: LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + cdr: Pair { + car: undefined, + cdr: Nil { + undefined + }, + --- + undefined, + }, + --- + LSymbol { + Symbol(#:begin) + --- + __name__: Symbol(#:begin), + }, + undefined, + }, + }, + } + +## std: should render SXML string + +> Snapshot 1 + + '<div data-foo="hello" id="foo"><button id="btn1">me</button><button id="btn2">me</button></div>' + +## std: string interpolation + +> Snapshot 1 + + `this is string " 30 hello "hello"␊ + world␊ + x␊ + x` + ## formatter: let+if+begin > Snapshot 1 @@ -24237,9 +27774,3 @@ Generated by [AVA](https://avajs.dev). `, }, ] - -## std: should render SXML string - -> Snapshot 1 - - '<div data-foo="hello" id="foo"><button id="btn1">me</button><button id="btn2">me</button></div>' diff --git a/tests/snapshots/test.js.snap b/tests/snapshots/test.js.snap index b7a219d6a..bbbe4c443 100644 Binary files a/tests/snapshots/test.js.snap and b/tests/snapshots/test.js.snap differ diff --git a/tests/std.scm b/tests/std.scm index 7530aa84c..705b8e59f 100644 --- a/tests/std.scm +++ b/tests/std.scm @@ -342,3 +342,20 @@ `&(:done #f :value ,(/ 1 i)))))))) (t.is (iterator->array obj) #(1 1/2 1/3 1/4 1/5)) (t.is (Array.from (iterator->array obj)) #(1 0.5 0.3333333333333333 0.25 0.2))))) + +(test "std: string interpolation" + (lambda (t) + (let ((x 10) (y 20)) + (t.snapshot #"this is string \" ${(+ x y)} hello ${(repr "hello" #t)} + world + x + x")))) + +(test "std: cond" + (lambda (t) + (t.is (cond (else 10)) 10) + (t.is (cond ((zero? 0) 10) (else 20)) 10) + (t.is (cond ((zero? 10) 10) (else 20)) 20) + (t.is (let ((alist '((a . 10) (b . 20) (c . 30)))) + (cond ((assoc 'b alist) => cdr) (else #f))) + 20))) diff --git a/tests/syntax.scm b/tests/syntax.scm index 2bd286136..4423c3ee3 100644 --- a/tests/syntax.scm +++ b/tests/syntax.scm @@ -1579,3 +1579,64 @@ (t.is (alist foo 10 bar 20 baz 30) '((foo . 10) (bar . 20) (baz . 30))))) + +(test "syntax: nested syntax rules (SRFI-239 case)" + (lambda (t) + (define-syntax foo + (syntax-rules () + ((foo expr clauses ...) + (let-syntax ((clause + (syntax-rules ::: (_ pair null doted matched) + ((clause obj pair n d ((_ . _) body1 ::: body2) remaining :::) + (if (pair? obj) + (begin body1 ::: body2)))))) + (let ((obj expr)) + (clause obj pair null doted clauses ...)))))) + + (t.is (foo '(1 2) ((_ . _) 'pair)) 'pair))) + +(test "syntax: ellipsis maps into #void" + (lambda (t) + (define-syntax when + (syntax-rules () + ((_ test body ...) + (let ((tmp test)) + (if tmp + (begin + body ...)))))) + + (t.snapshot (macroexpand (when (assoc 'bar alist) #void))))) + +(test "syntax: let and syntax-parameterize hygiene #356" + (lambda (t) + (define-syntax-parameter it (syntax-rules () ((_) (syntax-error "Use outside aif")))) + + (define-syntax awhen + (syntax-rules () + ((_ test body ...) + (let ((tmp test)) + (syntax-parameterize + ((it (syntax-rules () + ((__) tmp)))) + (if tmp + (begin + body ...))))))) + + (t.is (let ((alist '((foo . "lorem") (bar . "ipsum") (baz . "dolor"))) + (begin (lambda () (throw 'ZONK)))) + (awhen (assoc 'bar alist) "msg")) + "msg"))) + +(test "syntax: improper pattern" + (lambda (t) + (define-syntax f + (syntax-rules () + ((f a ... x . y) + (let ((output (vector))) + (begin + (begin + (output.push (list a x y))) ...) + output)))) + + (t.is (f 10 20 30 'a 'b) + #((10 b ()) (20 b ()) (30 b ()) (a b ()))))) diff --git a/tests/test.js b/tests/test.js index aa09af98a..cf2cbb8e5 100644 --- a/tests/test.js +++ b/tests/test.js @@ -37,8 +37,8 @@ get_files().then(filenames => { })).then(async function (files) { await exec(` (let-env lips.env.__parent__ - (load "./dist/std.xcb") - (load "./tests/helpers/helpers.scm")) + (load "@lips/dist/std.xcb") + (load "@lips/tests/helpers/helpers.scm")) (define test (require "ava")) `); return exec(files.join('\n\n'));