|
1 | 1 | try {
|
2 |
| - var { hanzi2num, hanzi2numstr, num2hanzi, bool2hanzi } = require("./hanzi2num"); |
| 2 | + var { |
| 3 | + hanzi2num, |
| 4 | + hanzi2numstr, |
| 5 | + num2hanzi, |
| 6 | + bool2hanzi |
| 7 | + } = require("./hanzi2num"); |
3 | 8 | var hanzi2pinyin = require("./hanzi2pinyin");
|
4 | 9 | var STDLIB = require("./stdlib");
|
5 | 10 | var { NUMBER_KEYWORDS, KEYWORDS } = require("./keywords");
|
@@ -753,8 +758,69 @@ function compile(
|
753 | 758 | return targ;
|
754 | 759 | }
|
755 | 760 |
|
| 761 | +function isLangSupportedForEval(lang) { |
| 762 | + if (lang !== "js") |
| 763 | + throw new Error( |
| 764 | + `Executing for target language "${lang}" is not supported in current environment` |
| 765 | + ); |
| 766 | + return true; |
| 767 | +} |
| 768 | + |
| 769 | +function hanzinize(value) { |
| 770 | + if (typeof value == "number") { |
| 771 | + return num2hanzi(value); |
| 772 | + } else if (typeof value == "boolean") { |
| 773 | + return bool2hanzi(value); |
| 774 | + } else if (Array.isArray(value)) { |
| 775 | + return value.map(i => hanzinize(i)); |
| 776 | + } else { |
| 777 | + return value; |
| 778 | + } |
| 779 | +} |
| 780 | + |
| 781 | +function outputHanziWrapper(log) { |
| 782 | + return function output(...args) { |
| 783 | + log(...args.map(i => hanzinize(i))); |
| 784 | + }; |
| 785 | +} |
| 786 | + |
| 787 | +function evalCompiled(compiledCode, options = {}) { |
| 788 | + const { outputHanzi = true, scoped = false, lang = "js" } = options; |
| 789 | + |
| 790 | + isLangSupportedForEval(lang); |
| 791 | + |
| 792 | + let code = compiledCode; |
| 793 | + |
| 794 | + (() => { |
| 795 | + const _console_log = console.log; |
| 796 | + if (outputHanzi) { |
| 797 | + console.log = outputHanziWrapper(_console_log); |
| 798 | + } |
| 799 | + try { |
| 800 | + if (!scoped && "window" in this) { |
| 801 | + window.eval(code); |
| 802 | + } else { |
| 803 | + eval(code); |
| 804 | + } |
| 805 | + } catch (e) { |
| 806 | + throw e; |
| 807 | + } finally { |
| 808 | + if (outputHanzi) console.log = _console_log; |
| 809 | + } |
| 810 | + })(); |
| 811 | +} |
| 812 | + |
| 813 | +function execute(source, options = {}) { |
| 814 | + const { lang = "js" } = options; |
| 815 | + isLangSupportedForEval(lang); |
| 816 | + const compiled = compile(options.lang, source, options); |
| 817 | + evalCompiled(compiled, options); |
| 818 | +} |
| 819 | + |
756 | 820 | var parser = {
|
757 | 821 | compile,
|
| 822 | + evalCompiled, |
| 823 | + execute, |
758 | 824 | version,
|
759 | 825 | wy2tokens,
|
760 | 826 | tokens2asc,
|
|
0 commit comments