├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── dictionary.txt ├── docs ├── arn.js ├── bignumber.js ├── constants.js ├── index.html └── main.js ├── examples ├── abundant_numbers.arn ├── evil_numbers.arn ├── fibonacci.arn ├── fizzbuzz.arn └── hello_world.arn ├── src ├── ast.rs ├── lexer.rs ├── main.rs ├── parser.rs └── utils │ ├── compress.rs │ ├── consts.rs │ ├── dict.rs │ ├── env.rs │ ├── mod.rs │ ├── num.rs │ ├── tokens.rs │ └── types.rs └── tools └── yank_fixes.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Some Rust generated files 2 | /target 3 | Cargo.lock 4 | 5 | # Directories I use 6 | /test 7 | 8 | # Benchmarks 9 | *.svg 10 | perf.* 11 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "arn-language" 3 | version = "1.2.1" 4 | edition = "2018" 5 | include = [ 6 | "src/*.rs", 7 | "src/utils/*.rs", 8 | "Cargo.toml", 9 | "Cargo.lock", 10 | "README.md", 11 | "LICENSE", 12 | "dictionary.txt" 13 | ] 14 | 15 | authors = ["Joshua Barnett "] 16 | description = "Rust parser for the Arn golfing language" 17 | repository = "https://github.com/ZippyMagician/Arn" 18 | readme = "README.md" 19 | license = "Apache-2.0" 20 | 21 | categories = [ "parser", "language", "code-golf", "arn" ] 22 | keywords = [ "ast", "parser", "golfing", "language", "arn" ] 23 | 24 | [[bin]] 25 | name = "arn" 26 | path = "src/main.rs" 27 | 28 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 29 | 30 | [dependencies] 31 | rug = { version = "1.12.0", default-features = false, features = [ "float" ] } 32 | clap = "2.33.3" 33 | lazy_static = "1.4" 34 | rand = "0.8.3" 35 | primal = "0.3" 36 | radix_fmt = "1.0.0" 37 | atty = "0.2.14" 38 | 39 | [profile.release] 40 | lto = true 41 | panic = "abort" 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2021] [Joshua Barnett] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Arn 2 | [![Build Status](https://travis-ci.org/ZippyMagician/Arn.svg?branch=master)](https://travis-ci.org/ZippyMagician/Arn) 3 | 4 | A general-purpose functional golfing language. [Tutorial](https://github.com/ZippyMagician/Arn/wiki/Tutorial) 5 | 6 | ## Installation 7 | ### Post 1.0 8 | First, ensure [Rust](https://rust-lang.org) is installed on your system and that [these requirements](https://docs.rs/gmp-mpfr-sys/1.4.4/gmp_mpfr_sys/index.html#building-on-gnulinux) are fulfilled. 9 | You can either build from source by cloning the repository and then running 10 | ``` 11 | cargo install --path path/to/repository 12 | ``` 13 | for the latest features, or by simply running 14 | ``` 15 | cargo install arn-language 16 | ``` 17 | for the current release edition. You then can run 18 | ``` 19 | arn --help 20 | ``` 21 | to get a list of commands. 22 | ### Prior to 1.0 23 | To install **Arn** you must have [Node.js](https://nodejs.org) installed on your system. Once installed, run 24 | ```sh 25 | npm install -g arn-language 26 | ``` 27 | You can then use 28 | ```sh 29 | arn help 30 | ``` 31 | to get a list of commands 32 | ## About 33 | **Arn** is a golfing language; that is, it is designed to perform tasks in as few bytes as possible. It draws heavy inspiration from **J**/**APL** 34 | 35 | Arn is constructed of variable declarations, functions, and symbols. These symbols come in the forms of prefixes, infixes, and suffixes. A full syntax and description can be found at [this page](https://github.com/ZippyMagician/Arn/wiki). 36 | This format, however, may lead to instances where your program needs to be a few bytes shorter in order to compete. This is where **Carn** (Compressed Arn) comes in. 37 | 38 | ### Compression 39 | **Carn** is the compressed version of **Arn**. The interpeter has the ability to distinguish between these two program formats and interpret each separately, without any input from the user. Carn is encoded using its own Code Page, based on __CP1252__. It can be found below. The Arn interpreter will compress your program by passing in the `-c` flag to the compiler through the command line. 40 | 41 | #### Code Page 42 | | `_` | `_0` | `_1` | `_2` | `_3` | `_4` | `_5` | `_6` | `_7` | `_8` | `_9` | `_A` | `_B` | `_C` | `_D` | `_E` | `_F` | 43 | | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: 44 | | **`0_`** | `!` | `"` | `#` | `$` | `%` | `&` | `'` | `(` | `)` | `*` | `+` | `,` | `-` | `.` | `/` | `0` | 45 | | **`1_`** | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` | `:` | `;` | `<` | `=` | `>` | `?` | `@` | 46 | | **`2_`** | `A` | `B` | `C` | `D` | `E` | `F` | `G` | `H` | `I` | `J` | `K` | `L` | `M` | `N` | `O` | `P` | 47 | | **`3_`** | `Q` | `R` | `S` | `T` | `U` | `V` | `W` | `X` | `Y` | `Z` | `[` | `\` | `]` | `^` | `_` | ``` ` ``` | 48 | | **`4_`** | `a` | `b` | `c` | `d` | `e` | `f` | `g` | `h` | `i` | `j` | `k` | `l` | `m` | `n` | `o` | `p` | 49 | | **`5_`** | `q` | `r` | `s` | `t` | `u` | `v` | `w` | `x` | `y` | `z` | `{` | `\|` | `}` | `~` | `¡` | `¢` | 50 | | **`6_`** | `£` | `¤` | `¥` | `¦` | `§` | `¨` | `©` | `ª` | `«` | `¬` | `®` | `¯` | `°` | `○` | `■` | `↑` | 51 | | **`7_`** | `↓` | `→` | `←` | `║` | `═` | `╔` | `╗` | `╚` | `╝` | `░` | `▒` | `►` | `◄` | `│` | `─` | `┌` | 52 | | **`8_`** | `┐` | `└` | `┘` | `├` | `┤` | `┴` | `┬` | `♦` | `┼` | `█` | `▄` | `▀` | `▬` | `±` | `²` | `³` | 53 | | **`9_`** | `´` | `µ` | `¶` | `·` | `¸` | `¹` | `º` | `»` | `¼` | `½` | `¾` | `¿` | `À` | `Á` | `Â` | `Ã` | 54 | | **`A_`** | `Ä` | `Å` | `Æ` | `Ç` | `È` | `É` | `Ê` | `Ë` | `Ì` | `Í` | `Î` | `Ï` | `Ð` | `Ñ` | `Ò` | `Ó` | 55 | | **`B_`** | `Ô` | `Õ` | `Ö` | `×` | `Ø` | `Ù` | `Ú` | `Û` | `Ü` | `Ý` | `Þ` | `ß` | `à` | `á` | `â` | `ã` | 56 | | **`C_`** | `ä` | `å` | `æ` | `ç` | `è` | `é` | `ê` | `ë` | `ì` | `í` | `î` | `ï` | `ð` | `ñ` | `ò` | `ó` | 57 | | **`D_`** | `ô` | `õ` | `ö` | `÷` | `ø` | `ù` | `ú` | `û` | `ü` | `ý` | `þ` | `ÿ` | `Œ` | `œ` | `Š` | `š` | 58 | | **`E_`** | `Ÿ` | `Ž` | `ž` | `ƒ` | `ƥ` | `ʠ` | `ˆ` | `˜` | `–` | `—` | `‘` | `’` | `‚` | `“` | `”` | `„` | 59 | | **`F_`** | `†` | `‡` | `•` | `…` | `‰` | `‹` | `›` | `€` | `™` | `⁺` | `⁻` | `⁼` | `⇒` | `⇐` | `★` | `Δ` | 60 | 61 | ### Some sample programs 62 | #### Hello, World 63 | ``` 64 | 'yt, bs! 65 | ``` 66 | #### Cat program 67 | ``` 68 | _ 69 | ``` 70 | #### FizzBuzz (1->100) 71 | ``` 72 | ~e2@"Fizz"^!%3|`#&`^!%5|| 73 | ``` 74 | #### Fibonacci Sequence 75 | ``` 76 | [1 1{+ 77 | ``` 78 | #### Prime Check 79 | ``` 80 | #.:}= 81 | ``` 82 | *Uses Wilson's Theorem* 83 | ``` 84 | !(f/+1)% 85 | ``` 86 | ### Future Plans 87 | I plan on working on more practical features in the future, and I'm also going to look into changing the way certain operations work on sequences, among other things. 88 | -------------------------------------------------------------------------------- /docs/bignumber.js: -------------------------------------------------------------------------------- 1 | /* bignumber.js v9.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */!function(e){"use strict";var r,x=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,L=Math.ceil,U=Math.floor,I="[BigNumber Error] ",T=I+"Number primitive has more than 15 significant digits: ",C=1e14,M=14,G=9007199254740991,k=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],F=1e7,q=1e9;function j(e){var r=0|e;return 0o[s]^n?1:-1;return u==l?0:l(t=e.length)){for(i=n,r-=t;--r;i+=n);e+=i}else ry?c.c=c.e=null:e.ey)c.c=c.e=null;else if(oy?e.c=e.e=null:e.c=n=a.length){if(!t)break e;for(;a.length<=l;a.push(0));u=c=0,s=(o%=M)-M+(i=1)}else{for(u=f=a[l],i=1;10<=f;f/=10,i++);c=(s=(o%=M)-M+i)<0?0:u/h[i-s-1]%10|0}if(t=t||r<0||null!=a[l+1]||(s<0?u:u%h[i-s-1]),t=n<4?(c||t)&&(0==n||n==(e.s<0?3:2)):5y?e.c=e.e=null:e.e>>11))?(n=crypto.getRandomValues(new Uint32Array(2)),r[s]=n[0],r[s+1]=n[1]):(f.push(o%1e14),s+=2);s=i/2}else{if(!crypto.randomBytes)throw b=!1,Error(I+"crypto unavailable");for(r=crypto.randomBytes(i*=7);sn-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}return function(e,r,n,t,i){var o,s,f,u,l,c,a,h,g=e.indexOf("."),p=N,w=O;for(0<=g&&(u=E,E=0,e=e.replace(".",""),c=(h=new B(r)).pow(e.length-g),E=u,h.c=m(X($(c.c),c.e,"0"),10,n,d),h.e=h.c.length),f=u=(a=m(e,r,n,i?(o=S,d):(o=d,S))).length;0==a[--u];a.pop());if(!a[0])return o.charAt(0);if(g<0?--f:(c.c=a,c.e=f,c.s=t,a=(c=v(c,h,p,w,n)).c,l=c.r,f=c.e),g=a[s=f+p+1],u=n/2,l=l||s<0||null!=a[s+1],l=w<4?(null!=g||l)&&(0==w||w==(c.s<0?3:2)):un;)a[s]=0,s||(++f,a=[1].concat(a));for(u=a.length;!a[--u];);for(g=0,e="";g<=u;e+=o.charAt(a[g++]));e=X(e,f,o.charAt(0))}return e}}(),v=function(){function S(e,r,n){var t,i,o,s,f=0,u=e.length,l=r%F,c=r/F|0;for(e=e.slice();u--;)f=((i=l*(o=e[u]%F)+(t=c*o+(s=e[u]/F|0)*l)%F*F+f)/n|0)+(t/F|0)+c*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function R(e,r,n,t){var i,o;if(n!=t)o=tr[i]?1:-1;break}return o}function _(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n](E[f]||0)&&s--,b<0)g.push(1),u=!0;else{for(v=E.length,O=A.length,b+=2,1<(l=U(i/(A[f=0]+1)))&&(A=S(A,l,i),E=S(E,l,i),O=A.length,v=E.length),m=O,w=(p=E.slice(0,O)).length;w=i/2&&N++;do{if(l=0,(o=R(A,p,O,w))<0){if(d=p[0],O!=w&&(d=d*i+(p[1]||0)),1<(l=U(d/N)))for(i<=l&&(l=i-1),a=(c=S(A,l,i)).length,w=p.length;1==R(c,p,a,w);)l--,_(c,Oo&&(l.c.length=o):t&&(l=l.mod(r))}if(i){if(0===(i=U(i/2)))break;u=i%2}else if(D(e=e.times(n),e.e+1,1),14o&&(c.c.length=o):t&&(c=c.mod(r))}return t?l:(f&&(l=w.div(l)),r?l.mod(r):o?D(l,E,O,void 0):l)},t.integerValue=function(e){var r=new B(this);return null==e?e=O:H(e,0,8),D(r,r.e+1,e)},t.isEqualTo=t.eq=function(e,r){return 0===z(this,new B(e,r))},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(e,r){return 0this.c.length-2},t.isLessThan=t.lt=function(e,r){return z(this,new B(e,r))<0},t.isLessThanOrEqualTo=t.lte=function(e,r){return-1===(r=z(this,new B(e,r)))||0===r},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return 0t&&(t=this.e+1),t},t.shiftedBy=function(e){return H(e,-G,G),this.times("1e"+e)},t.squareRoot=t.sqrt=function(){var e,r,n,t,i,o=this,s=o.c,f=o.s,u=o.e,l=N+4,c=new B("0.5");if(1!==f||!s||!s[0])return new B(!f||f<0&&(!s||s[0])?NaN:s?o:1/0);if((n=0==(f=Math.sqrt(+P(o)))||f==1/0?(((r=$(s)).length+u)%2==0&&(r+="0"),f=Math.sqrt(+r),u=j((u+1)/2)-(u<0||u%2),new B(r=f==1/0?"1e"+u:(r=f.toExponential()).slice(0,r.indexOf("e")+1)+u)):new B(f+"")).c[0])for((f=(u=n.e)+l)<3&&(f=0);;)if(i=n,n=c.times(i.plus(v(o,i,l,1))),$(i.c).slice(0,f)===(r=$(n.c)).slice(0,f)){if(n.e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°○■↑↓→←║═╔╗╚╝░▒►◄│─┌┐└┘├┤┴┬♦┼█▄▀▬±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿŒœŠšŸŽžƒƥʠˆ˜–—‘’‚“”„†‡•…‰‹›€™⁺⁻⁼`.split(""); -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Arn Interpreter 5 | 6 | 78 | 79 | 80 |

Arn Interpreter

81 | 82 | 83 | 84 | 85 | 94 |

When putting in program input: Use a literal newline to separate cases in input. Use [N] if you need a newline in a specific case. A full description of the language can be found here

95 |

A major update has occured to operator precedence recently. If a program that is said to work does not, please try downloading version 0.3.8 through NPM and run it there.

96 |
97 |
98 | 99 | 100 |
101 | 105 |
Output goes here
106 | 107 | 108 | 109 | 110 | 111 | 192 | 193 | 203 | 204 | -------------------------------------------------------------------------------- /docs/main.js: -------------------------------------------------------------------------------- 1 | // Newlines separate different test suites 2 | function runArn(t, inp, flags = "") { 3 | inp = inp.split("\n").map(r => r.replace(/\[N\]/g, "\n")); 4 | 5 | if (inp.length === 1) { 6 | try { 7 | let opts = { stdin: inp[0].split("\n") || "" }; 8 | for (key of flags.split("")) opts[key] = true; 9 | return sprintf(parse(t, opts)); 10 | } catch (error) { 11 | return error; 12 | } 13 | } else { 14 | let output = ""; 15 | let count = 1; 16 | for (let suite of inp) { 17 | output += `* Case ${count++}:\n`; 18 | try { 19 | let opts = { stdin: suite.split("\n") || "" }; 20 | for (key of flags.split("")) opts[key] = true; 21 | output += sprintf(parse(t, opts)); 22 | } catch (error) { 23 | output += t + "\n" + error; 24 | } 25 | output += "\n"; 26 | } 27 | 28 | return output; 29 | } 30 | } 31 | 32 | // Example control 33 | const examples = { 34 | 'Hello World': [`'yt, bs!`, ``], 35 | 'FizzBuzz': [`{("Fizz"^!%3)|(\`#&\`^!%5)||}\\~`, `100`], 36 | 'Fibonacci': [`[1 1 {+} ->]`, `15`], 37 | 'Evil Numbers': [`\${!(+\\;b)%2}~`, `400`], 38 | 'Abundant Numbers': [`\${(+\\$v{!%v}1->)>}~`, '200'] 39 | } 40 | 41 | for (const exampleName in examples) { 42 | if (examples.hasOwnProperty(exampleName)) { 43 | document.getElementById('demolist').innerHTML += `
  • ${exampleName}
  • ` 44 | } 45 | } 46 | 47 | $(document).on('click', '.dropdown-menu li a', function () { 48 | const val = $(this).html() 49 | $('#selectedbox').val(val) 50 | 51 | document.getElementById('code').value = examples[val][0]; 52 | document.getElementById('ins').value = examples[val][1]; 53 | }); -------------------------------------------------------------------------------- /examples/abundant_numbers.arn: -------------------------------------------------------------------------------- 1 | ${(+\$v{!%v}1->)>}~200 -------------------------------------------------------------------------------- /examples/evil_numbers.arn: -------------------------------------------------------------------------------- 1 | ${!(+\;b)%2}~400 -------------------------------------------------------------------------------- /examples/fibonacci.arn: -------------------------------------------------------------------------------- 1 | [1 1 {+}] -------------------------------------------------------------------------------- /examples/fizzbuzz.arn: -------------------------------------------------------------------------------- 1 | {("Fizz"^!%3)|(`#&`^!%5)||}\1=>e2 -------------------------------------------------------------------------------- /examples/hello_world.arn: -------------------------------------------------------------------------------- 1 | ┬d5…╚╚ -------------------------------------------------------------------------------- /src/ast.rs: -------------------------------------------------------------------------------- 1 | use crate::utils::num::Num; 2 | use crate::utils::tokens::*; 3 | use crate::FLOAT_PRECISION; 4 | 5 | pub fn to_ast(postfix: &[Token]) -> Vec { 6 | let mut output = Vec::with_capacity(postfix.len()); 7 | 8 | for tok in postfix { 9 | match tok { 10 | Token::String(val) => output.push(Node::String(val.clone())), 11 | 12 | Token::CmpString(val, chr) => output.push(Node::CmpString(val.clone(), *chr)), 13 | 14 | Token::Number(num) => output.push(Node::Number(num.clone())), 15 | 16 | Token::Variable(val) => output.push(Node::Variable(val.clone())), 17 | 18 | Token::Block(body, chr, nm) => { 19 | output.push(match *chr { 20 | '{' => Node::Block(to_ast(body), nm.clone()), 21 | '(' => Node::Group(to_ast(body)), 22 | '[' => { 23 | let body = to_ast(body); 24 | match body.last() { 25 | // (Maybe) Sized Sequence 26 | Some(Node::Op(f, block_node, size_node)) if f == "->" => { 27 | if let Some(Node::Block(_, _)) = block_node.get(0) { 28 | let seq_body = &body[0..body.len() - 1]; 29 | Node::Sequence( 30 | seq_body.to_owned(), 31 | Box::new(block_node[0].clone()), 32 | Some(Box::new(size_node[0].clone())), 33 | ) 34 | } else { 35 | Node::Sequence( 36 | body.clone(), 37 | Box::new(Node::Block(vec![], None)), 38 | Some(Box::new(Node::Number(Num::with_val( 39 | *FLOAT_PRECISION, 40 | body.len(), 41 | )))), 42 | ) 43 | } 44 | } 45 | 46 | // Infinite sequence 47 | Some(Node::Block(_, _)) => { 48 | let seq_body = &body[0..body.len() - 1]; 49 | Node::Sequence( 50 | seq_body.to_owned(), 51 | Box::new(body.last().unwrap().clone()), 52 | None, 53 | ) 54 | } 55 | 56 | // Constant sequence 57 | _ => Node::Sequence( 58 | body.clone(), 59 | Box::new(Node::Block(vec![], None)), 60 | Some(Box::new(Node::Number(Num::with_val( 61 | *FLOAT_PRECISION, 62 | body.len(), 63 | )))), 64 | ), 65 | } 66 | } 67 | _ => unimplemented!(), 68 | }); 69 | } 70 | 71 | Token::Operator(ident, rank) => { 72 | let mut left = Vec::new(); 73 | let mut right = Vec::new(); 74 | 75 | for _ in 0..rank.1 { 76 | right.insert( 77 | 0, 78 | output 79 | .pop() 80 | .unwrap_or_else(|| Node::Variable("_".to_string())), 81 | ); 82 | } 83 | 84 | for _ in 0..rank.0 { 85 | left.insert( 86 | 0, 87 | output 88 | .pop() 89 | .unwrap_or_else(|| Node::Variable("_".to_string())), 90 | ); 91 | } 92 | 93 | output.push(Node::Op(ident.clone(), left, right)); 94 | } 95 | 96 | _ => panic!("Error on token {:?}", tok), 97 | } 98 | } 99 | 100 | output 101 | } 102 | -------------------------------------------------------------------------------- /src/lexer.rs: -------------------------------------------------------------------------------- 1 | use crate::utils::consts::OPTIONS; 2 | use crate::utils::num; 3 | use crate::utils::tokens::Token; 4 | 5 | // Takes the inputted program and converts it into a stream of tokens 6 | // Inserts the implied variable `_` wherever it is used 7 | pub fn lex(prg: &str) -> Vec { 8 | let mut construct: Vec = Vec::new(); 9 | let mut buf: String = String::new(); 10 | 11 | let mut in_string = false; 12 | let mut in_group: bool = false; 13 | let mut group_count: usize = 0; 14 | let mut group_char: Option = None; 15 | 16 | // Mark end of program with `→` (as that character is not supported in decompressed code) 17 | let bytes = prg.chars().chain("\u{2192}".chars()); 18 | 19 | for tok in bytes { 20 | if buf == "\"" { 21 | in_string = true; 22 | buf.clear(); 23 | } 24 | 25 | if !in_string 26 | && !in_group 27 | && (buf == "\n" || buf == " " || buf == "\r" || buf == "\u{2192}") 28 | { 29 | // \n is an implicit comma 30 | if buf == "\n" { 31 | construct.push(Token::Comma); 32 | } 33 | buf.clear(); 34 | } 35 | 36 | // Why `as_ref`? I don't know. It doesn't work when it's `&&buf` 37 | if !in_group && ["{", "(", "[", "`", "'"].contains(&buf.as_ref()) { 38 | in_group = true; 39 | group_char = Some(buf.chars().next().unwrap()); 40 | } 41 | 42 | if in_group && group_char.unwrap() == tok { 43 | let last = buf.chars().last().unwrap_or('\u{2192}'); 44 | if group_char.unwrap() != '{' || (last != '.' && last != ':') { 45 | group_count += 1; 46 | } 47 | } 48 | 49 | if in_string { 50 | if tok == '"' && buf.ends_with('\\') { 51 | buf.drain(buf.len() - 1..); 52 | buf.push(tok); 53 | } else if tok == '"' || tok == '→' { 54 | construct.push(Token::String(buf.clone())); 55 | buf.clear(); 56 | in_string = false 57 | } else { 58 | buf.push(tok); 59 | } 60 | } else if in_group { 61 | let last = buf.chars().last().unwrap_or('\u{2192}'); 62 | if (tok == ')' || tok == '→') && Some('(') == group_char { 63 | if group_count > 0 { 64 | group_count -= 1; 65 | buf.push(tok); 66 | } else { 67 | construct.push(Token::Block(lex(&buf[1..]), '(', None)); 68 | buf.clear(); 69 | in_group = false; 70 | } 71 | } else if (tok == '}' || tok == '→') 72 | && Some('{') == group_char 73 | && last != '.' 74 | && last != ':' 75 | { 76 | if group_count > 0 { 77 | group_count -= 1; 78 | buf.push(tok); 79 | } else { 80 | if let Some(Token::Variable(name)) = construct.clone().last() { 81 | construct.pop(); 82 | construct.push(Token::Block(lex(&buf[1..]), '{', Some(name.clone()))); 83 | } else { 84 | construct.push(Token::Block(lex(&buf[1..]), '{', None)); 85 | } 86 | buf.clear(); 87 | in_group = false; 88 | } 89 | } else if (tok == ']' || tok == '→') && Some('[') == group_char { 90 | if group_count > 0 { 91 | group_count -= 1; 92 | buf.push(tok); 93 | } else { 94 | construct.push(Token::Block(lex(&buf[1..]), '[', None)); 95 | buf.clear(); 96 | in_group = false; 97 | } 98 | } else if (tok == '`' || tok == '→') && Some('`') == group_char { 99 | construct.push(Token::CmpString(buf[1..].to_owned(), '`')); 100 | buf.clear(); 101 | in_group = false; 102 | } else if (tok == '\'' || tok == '→') && Some('\'') == group_char { 103 | construct.push(Token::CmpString(buf[1..].to_owned(), '\'')); 104 | buf.clear(); 105 | in_group = false; 106 | } else { 107 | buf.push(tok); 108 | } 109 | } else if buf == "_" || num::is_arn_num(&buf) { 110 | buf.push(tok); 111 | if !num::is_arn_num(&buf) { 112 | buf.pop(); 113 | if buf == "_" { 114 | construct.push(Token::Variable("_".to_string())); 115 | } else { 116 | construct.push(Token::Number( 117 | num::parse_arn_num(&buf) 118 | .unwrap_or_else(|_| panic!("Error parsing number `{}`", buf)), 119 | )); 120 | } 121 | buf.clear(); 122 | buf.push(tok); 123 | } 124 | } else if OPTIONS.operators.iter().any(|i| *i == buf) { 125 | buf.push(tok); 126 | let mut consumed = true; 127 | if !OPTIONS.operators.iter().any(|i| *i == buf) { 128 | buf.pop(); 129 | consumed = false; 130 | } 131 | 132 | // Insert mess of precedence logic here 133 | let rank = OPTIONS.rank.get(&buf).unwrap(); 134 | if rank.0 > 0 { 135 | if construct.is_empty() 136 | || construct.len() < rank.0 as usize 137 | || construct.last() == Some(&Token::Comma) 138 | { 139 | for _ in 0..rank.0 - construct.len() as i32 140 | + if construct.last() == Some(&Token::Comma) { 141 | construct.len() as i32 142 | } else { 143 | 0 144 | } 145 | { 146 | construct.push(Token::Variable('_'.to_string())); 147 | } 148 | } else if let Some(Token::Operator(ident, stack_rank)) = construct 149 | .iter() 150 | .rfind(|m| matches!(m, Token::Operator(_, _))) 151 | { 152 | let pos = construct 153 | .iter() 154 | .rposition(|m| matches!(m, Token::Operator(_, _))) 155 | .unwrap(); 156 | // The previous op has a lower precedence or no right rank, shouldn't have `_` inserted after it yet 157 | let used_rank = if OPTIONS.precedence.get(ident).unwrap() 158 | < OPTIONS.precedence.get(&buf).unwrap() 159 | && stack_rank.1 > 0 160 | { 161 | rank.0 as usize 162 | } else { 163 | stack_rank.1 as usize 164 | }; 165 | if construct.len() - pos <= used_rank { 166 | for _ in 0..used_rank - (construct.len() - pos - 1) { 167 | construct.push(Token::Variable('_'.to_string())); 168 | } 169 | } 170 | } 171 | } 172 | 173 | construct.push(Token::Operator(buf.clone(), *rank)); 174 | 175 | buf.clear(); 176 | if !consumed { 177 | buf.push(tok); 178 | } 179 | } else if buf.chars().all(char::is_alphanumeric) && !buf.is_empty() { 180 | if !tok.is_alphanumeric() { 181 | construct.push(Token::Variable(buf.clone())); 182 | buf.clear(); 183 | } 184 | 185 | buf.push(tok); 186 | } else if buf == "," { 187 | construct.push(Token::Comma); 188 | buf.clear(); 189 | buf.push(tok); 190 | } else { 191 | buf.push(tok); 192 | } 193 | } 194 | 195 | // If last op is missing args, push `_` 196 | let pos = construct 197 | .iter() 198 | .rposition(|n| matches!(n, Token::Operator(_, _))) 199 | .unwrap_or(0); 200 | if let Some(Token::Operator(_, rank)) = construct.get(pos) { 201 | let given: usize = construct.len() - pos - 1; 202 | for _ in 0..rank.1 - given as i32 { 203 | construct.push(Token::Variable('_'.to_string())); 204 | } 205 | } 206 | 207 | construct 208 | } 209 | 210 | pub fn to_postfix(tokens: &[Token]) -> Vec { 211 | let indexes = tokens.split(|t| t.clone() == Token::Comma); 212 | let mut output = Vec::new(); 213 | 214 | for chunk in indexes { 215 | output.push(expr_to_postfix(chunk)); 216 | } 217 | 218 | output.join(&[][..]) 219 | } 220 | 221 | // Instead of parsing directly to an AST, I'll try this, which converts to postfix first. A second pass from another function that converts postfix to an ast is trivial. 222 | // Uses the Shunting Yard Algorithm, parses a single expression 223 | #[inline] 224 | fn expr_to_postfix(tokens: &[Token]) -> Vec { 225 | // This enables the parsing to work properly 226 | let mut operators: Vec = Vec::with_capacity(20); 227 | let mut output = Vec::with_capacity(tokens.len()); 228 | 229 | for tok in tokens { 230 | if let Token::Operator(right, rank) = tok { 231 | while !operators.is_empty() { 232 | let op = operators.pop().unwrap(); 233 | if let Token::Operator(ref left, left_rank) = op { 234 | if OPTIONS.precedence.get(left).is_none() 235 | || OPTIONS.precedence.get(right).is_none() 236 | || (OPTIONS.precedence.get(right).unwrap() 237 | > OPTIONS.precedence.get(left).unwrap() 238 | && left_rank.1 > 0) 239 | || rank.0 == 0 240 | { 241 | operators.push(op); 242 | break; 243 | } 244 | 245 | // If there are missing implied `_` from the program, insert them now. These will always be the last ones (so this won't lead to interpretation issues) 246 | // The above will hold true 247 | let total_rank = 248 | crate::utils::sum_rank(left_rank.0 as i128 + left_rank.1 as i128, &output); 249 | for _ in 0..(total_rank - output.len() as i128) { 250 | output.push(Token::Variable('_'.to_string())); 251 | } 252 | output.push(op) 253 | } 254 | } 255 | 256 | operators.push(tok.clone()); 257 | } else if let Token::Block(body, ch, nm) = tok { 258 | let new = to_postfix(&body); 259 | output.push(Token::Block(new, *ch, nm.clone())); 260 | } else { 261 | output.push(tok.clone()); 262 | } 263 | } 264 | 265 | while !operators.is_empty() { 266 | if let Token::Operator(_, rank) = operators.last().unwrap() { 267 | let total_rank = crate::utils::sum_rank(rank.0 as i128 + rank.1 as i128, &output); 268 | for _ in 0..(total_rank - output.len() as i128) { 269 | output.push(Token::Variable('_'.to_string())); 270 | } 271 | output.push(operators.pop().unwrap()); 272 | } else { 273 | // Discard if invalid 274 | operators.pop(); 275 | } 276 | } 277 | 278 | output 279 | } 280 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![deny(rust_2018_idioms, clippy::all)] 2 | #![deny(mutable_borrow_reservation_conflict, clippy::clone_on_ref_ptr)] 3 | #![warn(clippy::pedantic)] 4 | #![allow( 5 | clippy::module_name_repetitions, 6 | clippy::wildcard_imports, 7 | clippy::too_many_lines, 8 | // I have a lot of TODOs, so this is reduntant 9 | clippy::match_same_arms, 10 | // I don't care about this 11 | clippy::cast_possible_wrap, 12 | clippy::cast_sign_loss, 13 | clippy::cast_possible_truncation, 14 | // It's a ******* Rc 15 | clippy::needless_pass_by_value 16 | )] 17 | 18 | #[macro_use] 19 | extern crate clap; 20 | #[macro_use] 21 | extern crate lazy_static; 22 | 23 | #[macro_use] 24 | mod ast; 25 | mod lexer; 26 | mod parser; 27 | mod utils; 28 | 29 | use std::{fmt::Write as FmtWrite, io::Write as IoWrite}; 30 | use std::{fs, io}; 31 | 32 | use clap::{App, Arg, SubCommand}; 33 | 34 | use crate::utils::compress; 35 | 36 | // This is really cursed, but it works so hey 37 | lazy_static! { 38 | pub static ref MATCHES: clap::ArgMatches<'static> = App::new("Arn") 39 | .version(crate_version!()) 40 | .about("The Rust interpreter for Arn") 41 | .arg( 42 | Arg::with_name("file") 43 | .default_value("") 44 | .help("The input file to be run") 45 | ) 46 | .subcommand( 47 | SubCommand::with_name("cli") 48 | .about("Interactive Arn shell") 49 | .arg( 50 | Arg::with_name("stdin") 51 | .help("STDIN to pass into cli, interpreted as Arn code") 52 | .value_name("STDIN") 53 | .default_value("0") 54 | ) 55 | ) 56 | .arg( 57 | Arg::with_name("gen-answer") 58 | .long("cgans") 59 | .help("Generates a sample answer from the provided program for https://codegolf.stackexchange.com") 60 | ) 61 | .arg( 62 | Arg::with_name("precision") 63 | .short("p") 64 | .long("precision") 65 | .help("Precision of internal floats") 66 | .takes_value(true) 67 | .value_name("INTEGER") 68 | ) 69 | .arg( 70 | Arg::with_name("output-precision") 71 | .short("o") 72 | .long("oprecision") 73 | .help("Precision of outputted numbers") 74 | .takes_value(true) 75 | .value_name("INTEGER") 76 | ) 77 | .arg( 78 | Arg::with_name("input") 79 | .long("user-input") 80 | .short("u") 81 | .takes_value(true) 82 | .value_name("STDIN") 83 | .help("Pass STDIN through this command instead of the true stdin stream if you desire.") 84 | ) 85 | .arg( 86 | Arg::with_name("eval") 87 | .long("eval") 88 | .short("e") 89 | .help("Interprets the input as Arn code") 90 | ) 91 | .arg( 92 | Arg::with_name("stack-size") 93 | .long("stack") 94 | .help("Sets the size of the allocated stack for the program") 95 | .takes_value(true) 96 | .value_name("MEGABYTES") 97 | .default_value("2") 98 | ) 99 | .arg( 100 | Arg::with_name("compress") 101 | .short("c") 102 | .long("compress") 103 | .help("The input will be compressed and printed to STDOUT") 104 | ) 105 | .arg( 106 | Arg::with_name("debug") 107 | .long("debug") 108 | .help("Prints some debug information (to help check if what you found was a bug or not)") 109 | ) 110 | .arg( 111 | Arg::with_name("input-left") 112 | .short("t") 113 | .help("Unpacks STDIN with left precedence; [A, B] ==> _ := A, a := B") 114 | ) 115 | .arg( 116 | Arg::with_name("input-right") 117 | .short("T") 118 | .help("Unpacks STDIN with right precedence; [A, B] ==> a := A, _ := B") 119 | ) 120 | .arg( 121 | Arg::with_name("one-ten") 122 | .short("d") 123 | .help("Sets STDIN to the range [1, 10]") 124 | ) 125 | .arg( 126 | Arg::with_name("one-hundred") 127 | .short("h") 128 | .help("Sets STDIN to the range [1, 100]") 129 | ) 130 | .arg( 131 | Arg::with_name("array") 132 | .short("a") 133 | .help("Wraps program in `[ ... ]`") 134 | ) 135 | .arg( 136 | Arg::with_name("rangeify") 137 | .short("r") 138 | .help("Converts STDIN `r` to the range [1, r]") 139 | ) 140 | .arg( 141 | Arg::with_name("map") 142 | .short("m") 143 | .help("Executes the program like it's mapped over the input") 144 | ) 145 | .arg( 146 | Arg::with_name("first") 147 | .short("f") 148 | .help("Returns first value in return value of program") 149 | ) 150 | .arg( 151 | Arg::with_name("last") 152 | .short("l") 153 | .help("Returns last value in return value of program") 154 | ) 155 | .arg( 156 | Arg::with_name("size") 157 | .short("s") 158 | .help("Returns size of return value of program") 159 | ) 160 | .arg( 161 | Arg::with_name("sum") 162 | .short("x") 163 | .help("Sums the returned value of the program") 164 | ) 165 | .arg( 166 | Arg::with_name("index") 167 | .short("i") 168 | .help("Yields the i'th value in the return value of the program, where i is STDIN") 169 | ) 170 | .arg( 171 | Arg::with_name("find") 172 | .short("I") 173 | .help("Gets the index of the input inside the return value of the program") 174 | ) 175 | .arg( 176 | Arg::with_name("not") 177 | .short("!") 178 | .help("Boolean nots the returned value") 179 | ) 180 | .arg( 181 | Arg::with_name("0-range") 182 | .short("R") 183 | .help("Sets STDIN N to the range [0, N)") 184 | ) 185 | .arg( 186 | Arg::with_name("flat") 187 | .short("F") 188 | .help("Flattens returned value") 189 | ) 190 | .get_matches(); 191 | pub static ref FLOAT_PRECISION: u32 = MATCHES 192 | .value_of("precision") 193 | .unwrap_or("50") 194 | .parse() 195 | .unwrap(); 196 | pub static ref OUTPUT_PRECISION: usize = MATCHES 197 | .value_of("output-precision") 198 | .unwrap_or("4") 199 | .parse() 200 | .unwrap(); 201 | } 202 | 203 | fn main() { 204 | if let Some(cli) = MATCHES.subcommand_matches("cli") { 205 | // Always present 206 | let stdin = cli.value_of("stdin").unwrap(); 207 | let mut program = String::new(); 208 | loop { 209 | print!("> "); 210 | io::stdout().flush().expect("Cannot flush STDOUT"); 211 | io::stdin() 212 | .read_line(&mut program) 213 | .expect("Could not read from STDIN"); 214 | if program == ".exit" { 215 | break; 216 | } 217 | parser::parse(&build_ast(&format!( 218 | "_ := ({}),\n{}", 219 | stdin, 220 | program.trim() 221 | ))); 222 | } 223 | } 224 | 225 | if let Some(path) = MATCHES.value_of("file") { 226 | // Read file, remove CRLF 227 | let mut program = read_file(path).replace("\r\n", "\n").trim().to_owned(); 228 | 229 | if MATCHES.is_present("gen-answer") { 230 | let comp_program = compress::pack(&program); 231 | let mut flags = String::new(); 232 | print!("# [Arn](https://github.com/ZippyMagician/Arn)"); 233 | for arg in std::env::args() 234 | .skip(1) 235 | .filter(|h| !h.starts_with("--") && h.starts_with('-')) 236 | .flat_map(|n| n.trim_matches('-').chars().collect::>()) 237 | { 238 | if arg != 'p' && arg != 'o' && arg != 'e' && arg != 'u' { 239 | write!(flags, "{}", arg).unwrap(); 240 | } 241 | } 242 | 243 | if !flags.is_empty() { 244 | print!(" `-{}`", flags); 245 | } 246 | println!( 247 | ", [{} bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)\n", 248 | comp_program.chars().count() 249 | ); 250 | println!( 251 | "Version: **{}**\n```\n{}\n```\n", 252 | crate_version!(), 253 | comp_program 254 | ); 255 | println!( 256 | "# Explained\nUnpacked: `{}`\n```\nELABORATE HERE\n```", 257 | program 258 | ); 259 | std::process::exit(0); 260 | } 261 | 262 | let size = MATCHES 263 | .value_of("stack-size") 264 | .unwrap() 265 | .parse::() 266 | .unwrap(); 267 | 268 | if MATCHES.is_present("compress") { 269 | println!("{}", compress::pack(&program)); 270 | std::process::exit(0); 271 | } 272 | 273 | if compress::is_packed(&program) { 274 | program = compress::unpack(&program); 275 | } 276 | 277 | // Some ARGV handling 278 | if MATCHES.is_present("array") { 279 | program = format!("[{}]", program); 280 | } 281 | if MATCHES.is_present("map") { 282 | program = format!("{{{}}}\\", program); 283 | } 284 | if MATCHES.is_present("flat") { 285 | program = format!("({}):_", program); 286 | } 287 | if MATCHES.is_present("find") { 288 | program = format!("({}):i", program); 289 | } 290 | 291 | // Create thread to run parser in that features much larger stack 292 | let builder = std::thread::Builder::new() 293 | .name("parser".into()) 294 | .stack_size(size * 1024 * 1024); 295 | 296 | let handler = builder 297 | .spawn(move || { 298 | if MATCHES.is_present("debug") { 299 | println!("lexed: {:?}", lexer::lex(&program)); 300 | println!("ast: {:?}", build_ast(&program)); 301 | } 302 | parser::parse(&build_ast(&program)) 303 | }) 304 | .unwrap(); 305 | handler.join().unwrap(); 306 | } 307 | } 308 | 309 | #[inline] 310 | pub fn build_ast(prg: &str) -> Vec { 311 | ast::to_ast(&lexer::to_postfix(&lexer::lex(prg))) 312 | } 313 | 314 | fn read_file(path: &str) -> String { 315 | fs::read_to_string(path).unwrap_or_else(|_| panic!("\nFile '{}' does not exist.\n", path)) 316 | } 317 | -------------------------------------------------------------------------------- /src/parser.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::io::{self, Read}; 3 | use std::rc::Rc; 4 | 5 | use radix_fmt::radix; 6 | use rand::Rng; 7 | 8 | use crate::utils::num::{to_u32, Num}; 9 | use crate::utils::{self, env::Environment, tokens::Node, types::*}; 10 | use crate::{FLOAT_PRECISION, MATCHES}; 11 | 12 | lazy_static! { 13 | static ref DEFAULT: Node = Node::String(String::new()); 14 | static ref USCORE: String = String::from("_"); 15 | } 16 | 17 | fn grab_block_from_fold(fold: &Node, mut block: Option) -> (Option, Node) { 18 | match fold { 19 | Node::Op(n, l, r) => { 20 | let mut r = r.clone(); 21 | let end = r.len() - 1; 22 | let inter = grab_block_from_fold(&r[end], block); 23 | 24 | block = inter.0; 25 | r[end] = inter.1; 26 | (block, Node::Op(n.clone(), l.clone(), r)) 27 | } 28 | 29 | Node::Block(_, _) => (Some(fold.clone()), Node::Variable("_".to_string())), 30 | 31 | _ => (block, fold.clone()), 32 | } 33 | } 34 | 35 | pub fn parse_op(env: Env, op: &str, left: &[Node], right: &[Node]) -> Dynamic { 36 | match op { 37 | // Assign expression to 38 | ":=" => { 39 | let name = format!("{}", left[0]); 40 | let right = right[0].clone(); 41 | env.borrow_mut().define([name.trim()], move |env, arg| { 42 | let child = Rc::new(env.as_ref().clone()); 43 | child.borrow_mut().define_var("_", arg); 44 | parse_node(Rc::clone(&child), &right) 45 | }); 46 | Dynamic::from(false) 47 | } 48 | 49 | // () 50 | "." => { 51 | let v = format!("{}", right[0]); 52 | let arg = parse_node(Rc::clone(&env), &left[0]); 53 | env.borrow().attempt_call(v.trim(), &env, arg) 54 | } 55 | 56 | // pow 57 | "^" => { 58 | let left = parse_node(Rc::clone(&env), &left[0]); 59 | if left.is_string() { 60 | left.mutate_string(|s| s.repeat(to_u32(&env, &right[0]) as usize)) 61 | } else { 62 | let mut left = left.literal_num(); 63 | let o = left.clone(); 64 | let right = to_u32(&env, &right[0]); 65 | for _ in 1..right { 66 | left *= o.clone(); 67 | } 68 | 69 | Dynamic::from(left) 70 | } 71 | } 72 | 73 | // [, ] 74 | "<>" => { 75 | let left = parse_node(Rc::clone(&env), &left[0]); 76 | let right = parse_node(Rc::clone(&env), &right[0]); 77 | Dynamic::from([left, right]) 78 | } 79 | 80 | // × 81 | "*" => { 82 | let left = parse_node(Rc::clone(&env), &left[0]); 83 | let right = parse_node(Rc::clone(&env), &right[0]).literal_num(); 84 | left.mutate_num(|n| n * right) 85 | } 86 | 87 | // ÷ 88 | "/" => { 89 | let left = parse_node(Rc::clone(&env), &left[0]); 90 | let right = parse_node(Rc::clone(&env), &right[0]).literal_num(); 91 | left.mutate_num(|n| n / right) 92 | } 93 | 94 | // mod 95 | "%" => { 96 | let left = parse_node(Rc::clone(&env), &left[0]); 97 | let right = parse_node(Rc::clone(&env), &right[0]).literal_num(); 98 | left.mutate_num(|n| n % right) 99 | } 100 | 101 | // .join() 102 | ":|" => { 103 | let mut left = parse_node(Rc::clone(&env), &left[0]).literal_array(); 104 | left.set_env(Rc::clone(&env)); 105 | Dynamic::from( 106 | left.map(|dy| format!("{}", dy)) 107 | .collect::>() 108 | .join(&parse_node(Rc::clone(&env), &right[0]).literal_string()), 109 | ) 110 | } 111 | 112 | // .split() 113 | ":!" => { 114 | let left = parse_node(Rc::clone(&env), &left[0]).literal_string(); 115 | let right = parse_node(Rc::clone(&env), &right[0]).literal_string(); 116 | 117 | Dynamic::from( 118 | left.split(&right) 119 | .map(str::to_owned) 120 | .collect::>(), 121 | ) 122 | } 123 | 124 | // + 125 | "+" => { 126 | let left = parse_node(Rc::clone(&env), &left[0]); 127 | let right = parse_node(Rc::clone(&env), &right[0]).literal_num(); 128 | left.mutate_num(|n| n + right) 129 | } 130 | 131 | // - 132 | "-" => { 133 | let left = parse_node(Rc::clone(&env), &left[0]); 134 | let right = parse_node(Rc::clone(&env), &right[0]).literal_num(); 135 | left.mutate_num(|n| n - right) 136 | } 137 | 138 | // ==> [[..], [..]] 139 | ".$" => { 140 | let mut left = parse_node(Rc::clone(&env), &left[0]).literal_array(); 141 | let i = to_u32(&env, &right[0]) as usize; 142 | left.set_env(Rc::clone(&env)); 143 | let seq = left.collect::>(); 144 | 145 | let (l, r) = seq.split_at(i); 146 | Dynamic::from([l, r]) 147 | } 148 | 149 | // Descending range [, 1] 150 | ".~" => { 151 | let end = to_u32(&env, &left[0]) as usize; 152 | 153 | Dynamic::from( 154 | (1..=end) 155 | .rev() 156 | .map(|n| Dynamic::from(Num::with_val(*FLOAT_PRECISION, n))) 157 | .collect::>(), 158 | ) 159 | } 160 | 161 | // [, ] 162 | "=>" => { 163 | let left = to_u32(&env, &left[0]) as usize; 164 | let right = to_u32(&env, &right[0]) as usize; 165 | 166 | Dynamic::new( 167 | Val::Array(Box::new(Sequence::from_iter( 168 | (left..=right).map(|n| Dynamic::from(Num::with_val(*FLOAT_PRECISION, n))), 169 | Node::Block(vec![], None), 170 | Some(right - left + 1), 171 | ))), 172 | 4, 173 | ) 174 | } 175 | 176 | // [, ) 177 | "->" => { 178 | let left = to_u32(&env, &left[0]) as usize; 179 | let right = to_u32(&env, &right[0]) as usize; 180 | 181 | Dynamic::new( 182 | Val::Array(Box::new(Sequence::from_iter( 183 | (left..right).map(|n| Dynamic::from(Num::with_val(*FLOAT_PRECISION, n))), 184 | Node::Block(vec![], None), 185 | Some(right - left), 186 | ))), 187 | 4, 188 | ) 189 | } 190 | 191 | // [1, ] 192 | "~" => { 193 | let right = to_u32(&env, &right[0]) as usize; 194 | 195 | Dynamic::new( 196 | Val::Array(Box::new(Sequence::from_iter( 197 | (1..=right).map(|n| Dynamic::from(Num::with_val(*FLOAT_PRECISION, n))), 198 | Node::Block(vec![], None), 199 | Some(right), 200 | ))), 201 | 4, 202 | ) 203 | } 204 | 205 | // .length 206 | "#" => Dynamic::from(Num::with_val( 207 | *FLOAT_PRECISION, 208 | parse_node(Rc::clone(&env), &left[0]) 209 | .literal_array() 210 | .len() 211 | .expect("Cannot take length of infinite sequence"), 212 | )), 213 | 214 | // Base conversion of based on 215 | ";" => { 216 | let ops = if env.borrow().vals.get(&right[0].to_string()).is_none() { 217 | right[0].to_string() 218 | } else { 219 | parse_node(Rc::clone(&env), &right[0]).to_string() 220 | }; 221 | let chars = ops.trim().trim_matches('"').chars(); 222 | let mut cur = parse_node(Rc::clone(&env), &left[0]); 223 | cur = if cur.clone().to_string().matches('\n').count() > 0 { 224 | let temp = cur 225 | .to_string() 226 | .trim() 227 | .split('\n') 228 | .map(str::to_owned) 229 | .collect::>(); 230 | if chars 231 | .clone() 232 | .next() 233 | .map_or(true, |c| c != 'H' && c != 'O' && c != 'B') 234 | { 235 | Dynamic::from(temp) 236 | } else { 237 | Dynamic::from(temp.join("")) 238 | } 239 | } else { 240 | cur.into_string() 241 | }; 242 | let mut num = String::new(); 243 | 244 | for char in chars.chain("\u{2192}".chars()) { 245 | if !num.is_empty() && !char.is_numeric() { 246 | cur = Dynamic::from(utils::nbase_padded(cur, |cur| { 247 | radix( 248 | cur.parse::().expect("Invalid base10 number"), 249 | num.parse().unwrap(), 250 | ) 251 | .to_string() 252 | })); 253 | num.clear(); 254 | } 255 | 256 | cur = match char { 257 | 'b' => Dynamic::from(utils::nbase_padded(cur, |cur| { 258 | radix(cur.parse::().expect("Invalid base10 number"), 2).to_string() 259 | })), 260 | 'o' => Dynamic::from(utils::nbase_padded(cur, |cur| { 261 | radix(cur.parse::().expect("Invalid base10 number"), 8).to_string() 262 | })), 263 | 'h' => Dynamic::from(utils::nbase_padded(cur, |cur| { 264 | radix(cur.parse::().expect("Invalid base10 number"), 16).to_string() 265 | })), 266 | 'B' => Dynamic::from( 267 | i128::from_str_radix(&cur.literal_string(), 2) 268 | .expect("Invalid base2 number") 269 | .to_string(), 270 | ), 271 | 'O' => Dynamic::from( 272 | i128::from_str_radix(&cur.literal_string(), 8) 273 | .expect("Invalid base8 number") 274 | .to_string(), 275 | ), 276 | 'H' => Dynamic::from( 277 | i128::from_str_radix(&cur.literal_string(), 16) 278 | .expect("Invalid base16 number") 279 | .to_string(), 280 | ), 281 | '0'..='9' => { 282 | num.push(char); 283 | cur 284 | } 285 | '\u{2192}' => cur, 286 | _ => panic!("Unrecognized base conversion char {}", char), 287 | } 288 | } 289 | 290 | Dynamic::from(cur) 291 | } 292 | 293 | // Flatten 294 | ":_" => { 295 | let orig = parse_node(Rc::clone(&env), &left[0]).literal_array(); 296 | if !orig.is_finite() { 297 | panic!("Cannot flatten infinite sequence"); 298 | } 299 | 300 | // Get a ballpark for allocation size 301 | let mut new = Vec::with_capacity( 302 | orig.len().unwrap() 303 | * orig 304 | .clone() 305 | .next() 306 | .unwrap() 307 | .literal_array() 308 | .len() 309 | .expect("Cannot flatten sequence of inifnite sequences"), 310 | ); 311 | for dy in orig { 312 | if dy.is_array() { 313 | for n in parse_node(Rc::clone(&env), &dy.into_node()).literal_array() { 314 | new.push(n); 315 | } 316 | } else { 317 | new.push(dy.clone()); 318 | } 319 | } 320 | 321 | Dynamic::from(new) 322 | } 323 | 324 | // Transpose 325 | ":%" => { 326 | let mut parent = parse_node(Rc::clone(&env), &left[0]).literal_array(); 327 | parent.set_env(Rc::clone(&env)); 328 | 329 | let mut pre = Vec::new(); 330 | for item in parent { 331 | pre.push(item.literal_array()); 332 | } 333 | 334 | Dynamic::from( 335 | vec![ 336 | 0; 337 | pre.iter() 338 | .cloned() 339 | .max_by(|l, r| l.clone().count().cmp(&r.clone().count())) 340 | .unwrap_or_else(|| Sequence::from_vec_dyn( 341 | &[], 342 | Node::String(String::new()), 343 | Some(0) 344 | )) 345 | .count() 346 | ] 347 | .iter() 348 | .enumerate() 349 | .map(|(i, _)| { 350 | pre.iter() 351 | .filter_map(|array| array.clone().nth(i)) 352 | .collect() 353 | }) 354 | .collect::>>(), 355 | ) 356 | } 357 | 358 | // || 359 | ".|" => { 360 | let left = parse_node(Rc::clone(&env), &left[0]); 361 | left.mutate_num(Num::abs) 362 | } 363 | 364 | // Reverse 365 | ".<" => Dynamic::from( 366 | parse_node(Rc::clone(&env), &left[0]) 367 | .literal_array() 368 | .rev() 369 | .collect::>(), 370 | ), 371 | 372 | // Rangify , exclusive or inclusive 373 | ".." | ".=" => { 374 | let mut left = parse_node(Rc::clone(&env), &left[0]).literal_array(); 375 | left.set_env(Rc::clone(&env)); 376 | let left: Vec = left 377 | .map(|n| { 378 | n.literal_num() 379 | .to_u32_saturating_round(rug::float::Round::Down) 380 | .unwrap() 381 | }) 382 | .collect(); 383 | 384 | #[allow(clippy::range_plus_one)] 385 | let range = if op == ".." { 386 | left[0]..left[1] 387 | } else { 388 | left[0]..left[1] + 1 389 | }; 390 | 391 | Dynamic::new( 392 | Val::Array(Box::new(Sequence::from_iter( 393 | range 394 | .clone() 395 | .map(|n| Dynamic::from(Num::with_val(*FLOAT_PRECISION, n))), 396 | Node::Block(vec![], None), 397 | Some(range.count()), 398 | ))), 399 | 4, 400 | ) 401 | } 402 | 403 | // Split on newlines 404 | ":n" => Dynamic::from( 405 | parse_node(Rc::clone(&env), &left[0]) 406 | .literal_string() 407 | .split('\n') 408 | .map(str::to_owned) 409 | .collect::>(), 410 | ), 411 | 412 | // Split on spaces 413 | ":s" => Dynamic::from( 414 | parse_node(Rc::clone(&env), &left[0]) 415 | .literal_string() 416 | .split(' ') 417 | .map(str::to_owned) 418 | .collect::>(), 419 | ), 420 | 421 | // Tail of 422 | ":}" => { 423 | let mut seq = parse_node(Rc::clone(&env), &left[0]).literal_array(); 424 | seq.set_env(Rc::clone(&env)); 425 | 426 | seq.last() 427 | .expect("Cannot take last element of infinite sequence") 428 | } 429 | 430 | // Head of 431 | ":{" => { 432 | let mut seq = parse_node(Rc::clone(&env), &left[0]).literal_array(); 433 | seq.set_env(Rc::clone(&env)); 434 | 435 | seq.next().unwrap() 436 | } 437 | 438 | // Behead 439 | ".{" => { 440 | let mut seq = parse_node(Rc::clone(&env), &left[0]).literal_array(); 441 | seq.set_env(Rc::clone(&env)); 442 | 443 | Dynamic::from(seq.collect::>()[1..].to_owned()) 444 | } 445 | 446 | // Drop 447 | ".}" => { 448 | let mut seq = parse_node(Rc::clone(&env), &left[0]).literal_array(); 449 | seq.set_env(Rc::clone(&env)); 450 | 451 | Dynamic::from(seq.clone().collect::>()[..seq.count() - 1].to_owned()) 452 | } 453 | 454 | // Group entries in based on frequencies 455 | ":@" => { 456 | let mut arr = parse_node(Rc::clone(&env), &left[0]).literal_array(); 457 | arr.set_env(Rc::clone(&env)); 458 | let arr = arr.collect::>(); 459 | 460 | Dynamic::from(arr.iter().fold(Vec::new(), |mut acc, val| { 461 | if acc.is_empty() { 462 | vec![vec![val.clone()]] 463 | } else { 464 | let filter = acc.iter().filter(|e| e[0].clone() == val.clone()); 465 | if filter.clone().count() > 0 { 466 | let filter = filter.cloned().collect::>(); 467 | let pos = acc.iter().cloned().position(|e| e == filter[0]).unwrap(); 468 | acc[pos].push(val.clone()); 469 | acc 470 | } else { 471 | acc.push(vec![val.clone()]); 472 | acc 473 | } 474 | } 475 | })) 476 | } 477 | 478 | // is perfect square? 479 | "^*" => { 480 | let left = parse_node(Rc::clone(&env), &left[0]).literal_num(); 481 | Dynamic::from(left.sqrt().is_integer()) 482 | } 483 | 484 | // Repeat times with initial value 485 | "&." => { 486 | let mut loop_arg = parse_node(Rc::clone(&env), &right[1]); 487 | let count = parse_node(Rc::clone(&env), &right[2]) 488 | .literal_num() 489 | .to_u32_saturating_round(rug::float::Round::Down) 490 | .unwrap(); 491 | let child_env = Rc::new(env.as_ref().clone()); 492 | 493 | for _ in 0..count { 494 | if let Node::Block(_, name) = &right[0] { 495 | child_env 496 | .borrow_mut() 497 | .define_var(name.as_ref().unwrap_or(&USCORE), loop_arg) 498 | } else { 499 | child_env.borrow_mut().define_var("_", loop_arg); 500 | } 501 | loop_arg = parse_node_uniq(Rc::clone(&child_env), &right[0]); 502 | } 503 | 504 | loop_arg 505 | } 506 | 507 | // Index of in 508 | ":i" => { 509 | let mut seq = parse_node(Rc::clone(&env), &left[0]).literal_array(); 510 | let val = parse_node(Rc::clone(&env), &right[0]); 511 | seq.set_env(Rc::clone(&env)); 512 | 513 | Dynamic::from(Num::with_val( 514 | *FLOAT_PRECISION, 515 | seq.position(|e| e == val).map_or(-1, |v| v as i128), 516 | )) 517 | } 518 | 519 | // not 520 | "!" => Dynamic::from(!parse_node(Rc::clone(&env), &right[0]).literal_bool()), 521 | 522 | // Filter with condition , .any() 523 | "$" | "$:" => { 524 | let mut seq = parse_node(Rc::clone(&env), &right[1]).literal_array(); 525 | seq.set_env(Rc::clone(&env)); 526 | let child_env = Rc::new(env.as_ref().clone()); 527 | let filter = seq 528 | .filter(|v| { 529 | if let Node::Block(_, name) = &right[0] { 530 | child_env 531 | .borrow_mut() 532 | .define_var(name.as_ref().unwrap_or(&USCORE), v.clone()) 533 | } else { 534 | child_env.borrow_mut().define_var("_", v.clone()); 535 | } 536 | 537 | parse_node_uniq(Rc::clone(&child_env), &right[0]).literal_bool() 538 | }) 539 | .collect::>(); 540 | 541 | if op == "$" { 542 | Dynamic::from(filter) 543 | } else { 544 | Dynamic::from(!filter.is_empty()) 545 | } 546 | } 547 | 548 | // Fold + map op, Cumulative fold + map op 549 | "\\" | ":\\" => { 550 | let seq = Box::new( 551 | parse_node(Rc::clone(&env), &right[0]) 552 | .literal_array() 553 | .set_env_self(Rc::clone(&env)), 554 | ); 555 | 556 | let (block, rest) = grab_block_from_fold(&left[0], None); 557 | 558 | let res = Box::new(if let Some(Node::Block(_, name)) = block.clone() { 559 | let child_env = Rc::new(env.as_ref().clone()); 560 | let block = block.unwrap(); 561 | 562 | seq.map(|val| { 563 | child_env 564 | .borrow_mut() 565 | .define_var(name.as_ref().unwrap_or(&USCORE), val); 566 | parse_node_uniq(Rc::clone(&child_env), &block) 567 | }) 568 | .collect::>() 569 | } else { 570 | seq.collect::>() 571 | }); 572 | 573 | if rest == Node::Variable("_".to_string()) { 574 | Dynamic::from(res.as_ref().clone()) 575 | } else if op == "\\" { 576 | let constructed = format!("{}", rest); 577 | let seperator = constructed.trim().trim_matches('_'); 578 | let program = res 579 | .iter() 580 | .cloned() 581 | .map(|n| format!("{}", n.into_node())) 582 | .collect::>() 583 | .join(seperator); 584 | 585 | // This looks like a Vec, but in reality it is a single Node (only one value) 586 | let val = crate::build_ast(&program); 587 | parse_node(Rc::clone(&env), &val[0]) 588 | } else { 589 | let constructed = format!("{}", rest); 590 | let seperator = constructed.trim().trim_matches('_'); 591 | let mut v = res.as_ref().clone(); 592 | for i in 1..v.len() { 593 | v[i] = parse_node( 594 | Rc::clone(&env), 595 | &crate::build_ast(&format!( 596 | "{} {} {}", 597 | v[i - 1].clone().into_node(), 598 | seperator, 599 | v[i].clone().into_node() 600 | ))[0], 601 | ) 602 | } 603 | 604 | Dynamic::from(v) 605 | } 606 | } 607 | 608 | // Floor 609 | ":v" => { 610 | let right = parse_node(Rc::clone(&env), &right[0]); 611 | if right.is_string() { 612 | right.mutate_string(|s| s.to_ascii_lowercase()) 613 | } else { 614 | right.mutate_num(Num::floor) 615 | } 616 | } 617 | 618 | // Ceil 619 | ":^" => { 620 | let right = parse_node(Rc::clone(&env), &right[0]); 621 | if right.is_string() { 622 | right.mutate_string(|s| s.to_ascii_uppercase()) 623 | } else { 624 | right.mutate_num(Num::ceil) 625 | } 626 | } 627 | 628 | // Inc 629 | "++" => { 630 | if let Node::Variable(name) = &right[0] { 631 | let mut val = env.borrow().get_var(name); 632 | val = val.mutate_num(|n| n + 1); 633 | env.borrow_mut().define_var(name, val.clone()); 634 | val 635 | } else { 636 | let right = parse_node(Rc::clone(&env), &right[0]); 637 | right.mutate_num(|n| n + 1) 638 | } 639 | } 640 | 641 | // Dec 642 | "--" => { 643 | if let Node::Variable(name) = &right[0] { 644 | let mut val = env.borrow().get_var(name); 645 | val = val.mutate_num(|n| n - 1); 646 | env.borrow_mut().define_var(name, val.clone()); 647 | val 648 | } else { 649 | let right = parse_node(Rc::clone(&env), &right[0]); 650 | right.mutate_num(|n| n - 1) 651 | } 652 | } 653 | 654 | // ^ 2 655 | ":*" => parse_node(Rc::clone(&env), &right[0]).mutate_num(Num::square), 656 | 657 | // √ 658 | ":/" => parse_node(Rc::clone(&env), &right[0]).mutate_num(Num::sqrt), 659 | 660 | // 2 661 | ":+" => parse_node(Rc::clone(&env), &right[0]).mutate_num(|n| n * 2), 662 | 663 | // ½ 664 | ":-" => parse_node(Rc::clone(&env), &right[0]).mutate_num(|n| n / 2), 665 | 666 | // Sort in descending order 667 | ":>" => { 668 | let mut seq = parse_node(Rc::clone(&env), &right[0]).literal_array(); 669 | seq.set_env(Rc::clone(&env)); 670 | let mut seq = seq.collect::>(); 671 | seq.sort_by(|a, b| b.partial_cmp(a).unwrap()); 672 | Dynamic::from(seq) 673 | } 674 | 675 | // Sort in ascending order 676 | ":<" => { 677 | let mut seq = parse_node(Rc::clone(&env), &right[0]).literal_array(); 678 | seq.set_env(Rc::clone(&env)); 679 | let mut seq = seq.collect::>(); 680 | seq.sort_by(|a, b| a.partial_cmp(b).unwrap()); 681 | Dynamic::from(seq) 682 | } 683 | 684 | // Bifurcate 685 | "|:" => { 686 | let string = parse_node(Rc::clone(&env), &right[0]).literal_string(); 687 | let mid = string.len() / 2; 688 | Dynamic::from([ 689 | string[..mid].to_owned(), 690 | string[mid..].to_owned().chars().rev().collect(), 691 | ]) 692 | } 693 | 694 | // Get random item within 695 | "?." => { 696 | let mut seq = parse_node(Rc::clone(&env), &right[0]).literal_array(); 697 | seq.set_env(Rc::clone(&env)); 698 | let seq = seq.collect::>(); 699 | 700 | let mut rng = rand::thread_rng(); 701 | 702 | seq[(rng.gen::() * seq.len() as f64).floor() as usize].clone() 703 | } 704 | 705 | // All primes up to 706 | "#." => { 707 | let num = to_u32(&env, &right[0]) as usize; 708 | let sieve = primal::Primes::all() 709 | .take_while(|n| *n <= num) 710 | .map(|n| Num::with_val(*FLOAT_PRECISION, n)) 711 | .collect::>(); 712 | Dynamic::new( 713 | Val::Array(Box::new(Sequence::from_vec( 714 | &sieve, 715 | Node::Block(vec![], None), 716 | Some(sieve.len()), 717 | ))), 718 | 4, 719 | ) 720 | } 721 | 722 | // All factors of 723 | "*." => { 724 | let num = to_u32(&env, &right[0]) as usize; 725 | let mut fac = Vec::new(); 726 | let mut i = 1; 727 | let mut ind = 0; 728 | 729 | while i <= (num as f64).sqrt().floor() as usize { 730 | if num % i == 0 { 731 | fac.insert(ind, Num::with_val(*FLOAT_PRECISION, i)); 732 | if i != num / i { 733 | fac.insert(fac.len() - ind, Num::with_val(*FLOAT_PRECISION, num / i)); 734 | } 735 | ind += 1; 736 | } 737 | 738 | i += 1; 739 | } 740 | 741 | let len = fac.len(); 742 | let temp = fac[len - 1].clone(); 743 | fac[len - 1] = fac[0].clone(); 744 | fac[0] = temp; 745 | 746 | Dynamic::from(fac) 747 | } 748 | 749 | // Split array at mid 750 | "$." => { 751 | let mut seq = parse_node(Rc::clone(&env), &right[0]).literal_array(); 752 | seq.set_env(Rc::clone(&env)); 753 | let seq = seq.collect::>(); 754 | 755 | Dynamic::from([ 756 | seq[..seq.len() / 2].to_owned(), 757 | seq[seq.len() / 2..].to_owned(), 758 | ]) 759 | } 760 | 761 | // Evaluate as arn code 762 | "!." => { 763 | let program = parse_node(Rc::clone(&env), &right[0]).literal_string(); 764 | parse_node(Rc::clone(&env), &crate::build_ast(&program)[0]) 765 | } 766 | 767 | // Zip and 768 | "z" => { 769 | let left = parse_node(Rc::clone(&env), &left[0]) 770 | .literal_array() 771 | .set_env_self(Rc::clone(&env)) 772 | .collect::>(); 773 | let right = parse_node(Rc::clone(&env), &right[0]) 774 | .literal_array() 775 | .set_env_self(Rc::clone(&env)) 776 | .collect::>(); 777 | let mut output = Vec::with_capacity(left.len()); 778 | 779 | for i in 0..left.len() { 780 | output.push([left[i].clone(), right[i].clone()]); 781 | } 782 | 783 | Dynamic::from(output) 784 | } 785 | 786 | // Dedup 787 | "#>" => { 788 | let mut hash = std::collections::HashSet::new(); 789 | let mut result = Vec::new(); 790 | let array = parse_node(Rc::clone(&env), &right[0]) 791 | .literal_array() 792 | .set_env_self(Rc::clone(&env)); 793 | for item in array { 794 | if hash.get(&item).is_none() { 795 | hash.insert(item.clone()); 796 | result.push(item); 797 | } 798 | } 799 | 800 | Dynamic::from(result) 801 | } 802 | 803 | // Dedup sieve 804 | "#:" => { 805 | let mut hash = std::collections::HashSet::new(); 806 | let mut result = Vec::new(); 807 | let array = parse_node(Rc::clone(&env), &right[0]) 808 | .literal_array() 809 | .set_env_self(Rc::clone(&env)); 810 | for item in array { 811 | if hash.get(&item).is_none() { 812 | result.push(Num::with_val(*FLOAT_PRECISION, 1)); 813 | hash.insert(item); 814 | } else { 815 | result.push(Num::new(*FLOAT_PRECISION)); 816 | } 817 | } 818 | 819 | Dynamic::from(result) 820 | } 821 | 822 | // .nth() 823 | "?" => { 824 | let mut left = parse_node(Rc::clone(&env), &left[0]) 825 | .literal_array() 826 | .set_env_self(Rc::clone(&env)); 827 | let index = to_u32(&env, &right[0]) as usize; 828 | left.nth(index).unwrap() 829 | } 830 | 831 | // Concat and , special case for arrays 832 | "|" => { 833 | let left = parse_node(Rc::clone(&env), &left[0]); 834 | let right = parse_node(Rc::clone(&env), &right[0]); 835 | if left.is_array() { 836 | let mut left = left 837 | .literal_array() 838 | .set_env_self(Rc::clone(&env)) 839 | .collect::>(); 840 | if right.is_array() { 841 | Dynamic::from( 842 | [ 843 | left, 844 | right 845 | .literal_array() 846 | .set_env_self(Rc::clone(&env)) 847 | .collect::>(), 848 | ] 849 | .concat(), 850 | ) 851 | } else { 852 | left.push(right); 853 | Dynamic::from(left) 854 | } 855 | } else if right.is_array() { 856 | let mut right = right 857 | .literal_array() 858 | .set_env_self(Rc::clone(&env)) 859 | .collect::>(); 860 | right.insert(0, left); 861 | Dynamic::from(right) 862 | } else { 863 | let mut left = left.literal_string(); 864 | left.push_str(&right.literal_string()); 865 | Dynamic::from(left) 866 | } 867 | } 868 | 869 | // Very weakly typed, see `src/utils/types.rs`, PartialEq for Dynamic 870 | // == 871 | "=" => Dynamic::from( 872 | parse_node(Rc::clone(&env), &left[0]) == parse_node(Rc::clone(&env), &right[0]), 873 | ), 874 | 875 | // != 876 | "!=" => Dynamic::from( 877 | parse_node(Rc::clone(&env), &left[0]) != parse_node(Rc::clone(&env), &right[0]), 878 | ), 879 | 880 | // < 881 | "<" => Dynamic::from( 882 | parse_node(Rc::clone(&env), &left[0]).literal_num() 883 | < parse_node(Rc::clone(&env), &right[0]).literal_num(), 884 | ), 885 | 886 | // <= 887 | "<=" => Dynamic::from( 888 | parse_node(Rc::clone(&env), &left[0]).literal_num() 889 | <= parse_node(Rc::clone(&env), &right[0]).literal_num(), 890 | ), 891 | 892 | // > 893 | ">" => Dynamic::from( 894 | parse_node(Rc::clone(&env), &left[0]).literal_num() 895 | > parse_node(Rc::clone(&env), &right[0]).literal_num(), 896 | ), 897 | 898 | // >= 899 | ">=" => Dynamic::from( 900 | parse_node(Rc::clone(&env), &left[0]).literal_num() 901 | >= parse_node(Rc::clone(&env), &right[0]).literal_num(), 902 | ), 903 | 904 | // && yields if both truthy 905 | "&&" => { 906 | let left = parse_node(Rc::clone(&env), &left[0]); 907 | let right = parse_node(Rc::clone(&env), &right[0]); 908 | 909 | if left.is_bool() { 910 | if right.is_bool() { 911 | Dynamic::from(left.literal_bool() && right.literal_bool()) 912 | } else if left.clone().literal_bool() && right.clone().literal_bool() { 913 | right 914 | } else { 915 | left 916 | } 917 | } else if right.is_bool() { 918 | Dynamic::from(left.literal_bool() && right.literal_bool()) 919 | } else if left.clone().literal_bool() && right.clone().literal_bool() { 920 | right 921 | } else { 922 | left 923 | } 924 | } 925 | 926 | // || Yields if truthy and otherwise 927 | "||" => { 928 | let left = parse_node(Rc::clone(&env), &left[0]); 929 | let right = parse_node(Rc::clone(&env), &right[0]); 930 | 931 | if left.clone().literal_bool() { 932 | left 933 | } else { 934 | right 935 | } 936 | } 937 | 938 | // Do while (left & right take previous left value as arg), yields final mutated value 939 | ":" => { 940 | let child_env = Rc::new(env.as_ref().clone()); 941 | if let Node::Block(_, name) = &left[0] { 942 | let val = child_env.borrow().get_var("_"); 943 | child_env 944 | .borrow_mut() 945 | .define_var(name.as_ref().unwrap_or(&USCORE), val) 946 | } 947 | let mut block = parse_node_uniq(Rc::clone(&child_env), &left[0]); 948 | 949 | while { 950 | let child_env = Rc::new(env.as_ref().clone()); 951 | if let Node::Block(_, name) = &right[0] { 952 | child_env 953 | .borrow_mut() 954 | .define_var(name.as_ref().unwrap_or(&USCORE), block.clone()) 955 | } else { 956 | child_env.borrow_mut().define_var("_", block.clone()); 957 | } 958 | 959 | parse_node_uniq(Rc::clone(&child_env), &right[0]).literal_bool() 960 | } { 961 | if let Node::Block(_, name) = &left[0] { 962 | child_env 963 | .borrow_mut() 964 | .define_var(name.as_ref().unwrap_or(&USCORE), block.clone()) 965 | } else { 966 | child_env.borrow_mut().define_var("_", block.clone()); 967 | } 968 | 969 | block = parse_node_uniq(Rc::clone(&child_env), &left[0]); 970 | } 971 | 972 | block 973 | } 974 | 975 | // Compare adjacent values in array and, if evaluates to true, groups them 976 | "::" => { 977 | let mut groups = Vec::new(); 978 | let orig = parse_node(Rc::clone(&env), &left[0]) 979 | .literal_array() 980 | .set_env_self(Rc::clone(&env)); 981 | 982 | for node in orig { 983 | if groups.last().is_none() { 984 | groups.push(vec![node]); 985 | } else { 986 | let mut vals = vec![ 987 | groups.last().unwrap().last().unwrap().clone().into_node(), 988 | node.clone().into_node(), 989 | ]; 990 | let block = utils::traverse_replace(&mut vals, right[0].clone()); 991 | if parse_node(Rc::clone(&env), &block).literal_bool() { 992 | groups.last_mut().unwrap().push(node); 993 | } else { 994 | groups.push(vec![node]); 995 | } 996 | } 997 | } 998 | 999 | Dynamic::from(groups) 1000 | } 1001 | 1002 | // If then bind to , else yield 1003 | "??" => { 1004 | let val = parse_node(Rc::clone(&env), &left[0]); 1005 | let condition = parse_node(Rc::clone(&env), &right[0]).literal_bool(); 1006 | let child_env = Rc::new(env.as_ref().clone()); 1007 | 1008 | if condition { 1009 | if let Node::Block(_, name) = &right[1] { 1010 | child_env 1011 | .borrow_mut() 1012 | .define_var(name.as_ref().unwrap_or(&USCORE), val.clone()) 1013 | } else { 1014 | child_env.borrow_mut().define_var("_", val.clone()); 1015 | } 1016 | 1017 | parse_node(Rc::clone(&child_env), &right[1]) 1018 | } else { 1019 | val 1020 | } 1021 | } 1022 | 1023 | // Bind to each value in 1024 | "@" => { 1025 | let seq = parse_node(Rc::clone(&env), &left[0]) 1026 | .literal_array() 1027 | .set_env_self(Rc::clone(&env)); 1028 | let child_env = Rc::new(env.as_ref().clone()); 1029 | 1030 | Dynamic::from( 1031 | seq.map(|val| { 1032 | if let Node::Block(_, name) = &right[0] { 1033 | child_env 1034 | .borrow_mut() 1035 | .define_var(name.as_ref().unwrap_or(&USCORE), val) 1036 | } else { 1037 | child_env.borrow_mut().define_var("_", val); 1038 | } 1039 | 1040 | parse_node_uniq(Rc::clone(&child_env), &right[0]) 1041 | }) 1042 | .collect::>(), 1043 | ) 1044 | } 1045 | 1046 | // Bind to 1047 | "&" => { 1048 | let left = parse_node(Rc::clone(&env), &left[0]); 1049 | let child_env = Rc::new(env.as_ref().clone()); 1050 | 1051 | if let Node::Block(_, name) = &right[0] { 1052 | child_env 1053 | .borrow_mut() 1054 | .define_var(name.as_ref().unwrap_or(&USCORE), left) 1055 | } else { 1056 | child_env.borrow_mut().define_var("_", left); 1057 | } 1058 | 1059 | parse_node_uniq(Rc::clone(&child_env), &right[0]) 1060 | } 1061 | 1062 | // Count of entries in that, when bound by , yield a truthy value 1063 | "/:" => { 1064 | let array = parse_node(Rc::clone(&env), &right[1]) 1065 | .literal_array() 1066 | .set_env_self(Rc::clone(&env)); 1067 | let child_env = Rc::new(env.as_ref().clone()); 1068 | 1069 | Dynamic::from(Num::with_val( 1070 | *FLOAT_PRECISION, 1071 | array 1072 | .filter(|val| { 1073 | if let Node::Block(_, name) = &right[0] { 1074 | child_env 1075 | .borrow_mut() 1076 | .define_var(name.as_ref().unwrap_or(&USCORE), val.clone()) 1077 | } else { 1078 | child_env.borrow_mut().define_var("_", val.clone()); 1079 | } 1080 | 1081 | parse_node_uniq(Rc::clone(&child_env), &right[0]).literal_bool() 1082 | }) 1083 | .count(), 1084 | )) 1085 | } 1086 | 1087 | _ => unimplemented!(), 1088 | } 1089 | } 1090 | 1091 | // Parses Node::Block, assuming it's key has already been initialized 1092 | // Call if the key is checked before 1093 | fn parse_node_uniq(env: Env, block: &Node) -> Dynamic { 1094 | match block { 1095 | Node::Block(block, _) => { 1096 | for node in &block[..block.len() - 1] { 1097 | parse_node(Rc::clone(&env), node); 1098 | } 1099 | 1100 | parse_node(Rc::clone(&env), block.last().unwrap_or(&DEFAULT)) 1101 | } 1102 | 1103 | _ => parse_node(env, block), 1104 | } 1105 | } 1106 | 1107 | pub fn parse_node(env: Env, node: &Node) -> Dynamic { 1108 | match node { 1109 | Node::Op(op, left, right) => parse_op(env, op, left, right), 1110 | 1111 | Node::String(v) => Dynamic::from(v.clone()), 1112 | 1113 | Node::CmpString(v, chr) => Dynamic::from(utils::dict::decompress(v, *chr == '\'')), 1114 | 1115 | Node::Number(v) => Dynamic::from(v.clone()), 1116 | 1117 | Node::Variable(v) => env 1118 | .borrow() 1119 | .attempt_call(v, &env, env.borrow().get_var("_")), 1120 | 1121 | Node::Group(body) => { 1122 | for node in &body[..body.len() - 1] { 1123 | parse_node(Rc::clone(&env), node); 1124 | } 1125 | 1126 | parse_node(Rc::clone(&env), body.last().unwrap_or(&DEFAULT)) 1127 | } 1128 | 1129 | Node::Block(body, name) => { 1130 | let child_env = Rc::new(env.as_ref().clone()); 1131 | let val = child_env.borrow().get_var("_"); 1132 | child_env 1133 | .borrow_mut() 1134 | .define_var(name.as_ref().unwrap_or(&USCORE), val); 1135 | for node in &body[..body.len() - 1] { 1136 | parse_node(Rc::clone(&child_env), node); 1137 | } 1138 | 1139 | parse_node(Rc::clone(&child_env), body.last().unwrap_or(&DEFAULT)) 1140 | } 1141 | 1142 | // This will maybe be parsed differently in the future? 1143 | Node::Sequence(arr, block, len) => { 1144 | let mut seq = Sequence::from_vec_dyn( 1145 | &arr.iter() 1146 | .map(|n| parse_node(Rc::clone(&env), n)) 1147 | .collect::>(), 1148 | block.as_ref().clone(), 1149 | len.as_ref().map(|n| to_u32(&env, n.as_ref()) as usize), 1150 | ); 1151 | 1152 | seq.set_env(Rc::clone(&env)); 1153 | Dynamic::new(Val::Array(Box::new(seq)), 4) 1154 | } 1155 | } 1156 | } 1157 | 1158 | macro_rules! def_builtins { 1159 | ($env:ident; $($($name:literal),*: $value:literal);*) => { 1160 | $( 1161 | $env.define([$($name),*], |e, val| { 1162 | let child = Rc::new(e.as_ref().clone()); 1163 | child.borrow_mut().define_var("_", val); 1164 | parse_node(Rc::clone(&child), &crate::build_ast($value)[0]) 1165 | }); 1166 | )* 1167 | } 1168 | } 1169 | 1170 | pub fn parse(ast: &[Node]) { 1171 | let mut env = Environment::init(); 1172 | 1173 | let mut stdin = if let Some(val) = MATCHES.value_of("input") { 1174 | val.to_owned() 1175 | } else if atty::is(atty::Stream::Stdin) { 1176 | String::from("") 1177 | } else { 1178 | let mut buffer = String::new(); 1179 | io::stdin() 1180 | .read_to_string(&mut buffer) 1181 | .expect("Could not read from stdin"); 1182 | buffer.trim_end_matches('\n').to_owned() 1183 | }; 1184 | 1185 | if MATCHES.is_present("one-ten") { 1186 | stdin = utils::create_str_range(1, 10); 1187 | } 1188 | if MATCHES.is_present("one-hundred") { 1189 | stdin = utils::create_str_range(1, 100); 1190 | } 1191 | if MATCHES.is_present("rangeify") { 1192 | stdin = utils::create_str_range( 1193 | 1, 1194 | stdin 1195 | .parse::() 1196 | .expect("Input was not a valid integer"), 1197 | ); 1198 | } 1199 | if MATCHES.is_present("0-range") { 1200 | stdin = utils::create_str_range( 1201 | 0, 1202 | stdin 1203 | .parse::() 1204 | .expect("Input was not a valid integer") 1205 | - 1, 1206 | ); 1207 | } 1208 | 1209 | // Defined variables 1210 | env.define_var( 1211 | "_", 1212 | // Eval code as input if `-e` present 1213 | if MATCHES.is_present("eval") { 1214 | parse_node( 1215 | Rc::new(RefCell::new(env.clone())), 1216 | &crate::build_ast(&stdin)[0], 1217 | ) 1218 | } else { 1219 | Dynamic::from(stdin.clone()) 1220 | }, 1221 | ); 1222 | env.define_var( 1223 | "E", 1224 | Num::with_val( 1225 | *FLOAT_PRECISION, 1226 | Num::parse("2.7182818284590452353602874713527").unwrap(), 1227 | ), 1228 | ); 1229 | env.define_var( 1230 | "pi", 1231 | Num::with_val(*FLOAT_PRECISION, rug::float::Constant::Pi), 1232 | ); 1233 | env.define_var( 1234 | "phi", 1235 | Num::with_val( 1236 | *FLOAT_PRECISION, 1237 | Num::parse("1.61803398874989484820458683436563811").unwrap(), 1238 | ), 1239 | ); 1240 | env.define_var("a", Vec::::new()); 1241 | env.define_var("c", String::new()); 1242 | env.define_var("Fi", "Fizz".to_string()); 1243 | env.define_var("Bu", "Buzz".to_string()); 1244 | let dummy_env = Rc::new(RefCell::new(Environment::init())); 1245 | env.define_var( 1246 | "sH", 1247 | Sequence::from_vec( 1248 | &crate::build_ast("1/2"), 1249 | crate::build_ast("/2")[0].clone(), 1250 | None, 1251 | ) 1252 | .set_env_self(Rc::clone(&dummy_env)), 1253 | ); 1254 | env.define_var( 1255 | "sA", 1256 | Sequence::from_vec( 1257 | &crate::build_ast("1"), 1258 | crate::build_ast("!")[0].clone(), 1259 | None, 1260 | ) 1261 | .set_env_self(Rc::clone(&dummy_env)), 1262 | ); 1263 | env.define_var( 1264 | "sE", 1265 | Sequence::from_vec( 1266 | &crate::build_ast("2"), 1267 | crate::build_ast("+2")[0].clone(), 1268 | None, 1269 | ) 1270 | .set_env_self(Rc::clone(&dummy_env)), 1271 | ); 1272 | env.define_var( 1273 | "sO", 1274 | Sequence::from_vec( 1275 | &crate::build_ast("1"), 1276 | crate::build_ast("+2")[0].clone(), 1277 | None, 1278 | ) 1279 | .set_env_self(Rc::clone(&dummy_env)), 1280 | ); 1281 | env.define_var( 1282 | "sF", 1283 | Sequence::from_vec( 1284 | &crate::build_ast("1 1"), 1285 | crate::build_ast("+")[0].clone(), 1286 | None, 1287 | ) 1288 | .set_env_self(Rc::clone(&dummy_env)), 1289 | ); 1290 | // I don't care what people say, I am never adding a constant for "Hello, World!" 1291 | 1292 | if MATCHES.is_present("input-left") { 1293 | let orig = env.get_var("_"); 1294 | let as_vec = orig.literal_array().collect::>(); 1295 | env.define_var("_", as_vec[0].clone()); 1296 | env.define_var("a", as_vec[1..].iter().cloned().collect::>()); 1297 | } else if MATCHES.is_present("input-right") { 1298 | let orig = env.get_var("_"); 1299 | let as_vec = orig.literal_array().collect::>(); 1300 | env.define_var("_", as_vec[1..].iter().cloned().collect::>()); 1301 | env.define_var("a", as_vec[0].clone()); 1302 | } 1303 | 1304 | // Defined functions 1305 | env.define(["ol", "outl"], |_, d| { 1306 | println!("{}", d); 1307 | d 1308 | }); 1309 | env.define(["o", "out"], |_, d| { 1310 | print!("{}", d); 1311 | d 1312 | }); 1313 | def_builtins! {env; 1314 | "f", "fact": r#"~||[1]&*\"#; 1315 | "me", "mean": r#"(+\)/(#"#; 1316 | "ma", "max": r#":>&:{"#; 1317 | "mo", "mode": r#":@&ma:{"#; 1318 | "mi", "min": r#":<&:{"#; 1319 | "med", "median": r#"(:-#&%2=0)&&:-(((:<)?(--:-#))+((:<)?:-#))||(:<)?:v:-#"#; 1320 | "sdev": r#":/((@v{:*(v-me)).me"#; 1321 | "crt", "cartesian": r#":{@a{:}@a<>}&:_"#; 1322 | "eq", "equal": r#":@#=1"#; 1323 | "pst", "powerset": r#":<(0->2^(#);2@a{|{+0&&[:}]||[}\a.>() 1339 | .first() 1340 | .unwrap() 1341 | .clone(); 1342 | } 1343 | if MATCHES.is_present("last") { 1344 | result = result 1345 | .literal_array() 1346 | .set_env_self(Rc::clone(&env)) 1347 | .collect::>() 1348 | .last() 1349 | .unwrap() 1350 | .clone(); 1351 | } 1352 | if MATCHES.is_present("index") { 1353 | result = result 1354 | .literal_array() 1355 | .set_env_self(Rc::clone(&env)) 1356 | .nth(stdin.parse::().unwrap()) 1357 | .unwrap(); 1358 | } 1359 | if MATCHES.is_present("sum") { 1360 | result = Dynamic::from( 1361 | result 1362 | .literal_array() 1363 | .set_env_self(Rc::clone(&env)) 1364 | .map(|n| n.literal_num()) 1365 | .fold(Num::new(*FLOAT_PRECISION), |acc, val| acc + val), 1366 | ); 1367 | } 1368 | if MATCHES.is_present("size") { 1369 | result = Dynamic::from(Num::with_val( 1370 | *FLOAT_PRECISION, 1371 | result.literal_array().set_env_self(Rc::clone(&env)).count(), 1372 | )); 1373 | } 1374 | if MATCHES.is_present("not") { 1375 | result = Dynamic::from(!result.literal_bool()) 1376 | } 1377 | 1378 | println!("{}", result); 1379 | } 1380 | -------------------------------------------------------------------------------- /src/utils/compress.rs: -------------------------------------------------------------------------------- 1 | use super::{consts::CODEPAGE, num::Num}; 2 | 3 | pub fn pack(code: &str) -> String { 4 | let code = code.replace('\n', "\\n").chars().collect::>(); 5 | let bytes = code.iter().map(|r| (*r as u8 as i32 - 32) as u8); 6 | 7 | let bytes = pack_bytes(bytes); 8 | return bytes 9 | .iter() 10 | .map(|r| CODEPAGE[*r as usize].to_string()) 11 | .collect::>() 12 | .join(""); 13 | } 14 | 15 | #[inline] 16 | fn pack_bytes(bytes: T) -> Vec 17 | where 18 | T: Iterator + DoubleEndedIterator, 19 | { 20 | let mut result = Vec::new(); 21 | let mut big = Num::new(1000); 22 | 23 | for byte in bytes.rev() { 24 | big = big * 95 + byte; 25 | } 26 | 27 | while !big.is_zero() { 28 | result.push((big.clone() % 256_u16).floor().to_u32_saturating().unwrap() as u8); 29 | big = (big / 256_u16).floor(); 30 | } 31 | 32 | result 33 | } 34 | 35 | pub fn unpack(packed: &str) -> String { 36 | let code = packed.chars().collect::>(); 37 | let bytes = code 38 | .iter() 39 | .map(|r| CODEPAGE.iter().position(|n| *n == *r).unwrap_or(0) as u8); 40 | 41 | let bytes = unpack_bytes(bytes); 42 | bytes 43 | .iter() 44 | .map(|r| String::from_utf8(vec![*r + 32]).unwrap()) 45 | .collect::>() 46 | .join("") 47 | .replace("\\n", "\n") 48 | } 49 | 50 | #[inline] 51 | fn unpack_bytes(bytes: T) -> Vec 52 | where 53 | T: Iterator + DoubleEndedIterator, 54 | { 55 | let mut result = Vec::new(); 56 | let mut big = Num::new(1000); 57 | 58 | for byte in bytes.rev() { 59 | big = big * 256 + byte; 60 | } 61 | 62 | while !big.is_zero() { 63 | result.push((big.clone() % 95_u8).floor().to_u32_saturating().unwrap() as u8); 64 | big = (big / 95_u8).floor(); 65 | } 66 | 67 | result 68 | } 69 | 70 | #[inline] 71 | pub fn is_packed(code: &str) -> bool { 72 | unpack(&pack(code)) != code 73 | } 74 | -------------------------------------------------------------------------------- /src/utils/consts.rs: -------------------------------------------------------------------------------- 1 | // An easier way to create the precedence and operator global constants 2 | macro_rules! operators { 3 | ($($chr:literal : $prec:literal; $left_rank:literal - $right_rank:literal),*) => { 4 | #[derive(Clone)] 5 | pub struct Operators { 6 | pub precedence: std::collections::HashMap, 7 | pub operators: [String; len!($($chr),*)], 8 | pub rank: std::collections::HashMap, 9 | } 10 | 11 | impl Operators { 12 | pub fn new() -> Self { 13 | Self { 14 | precedence: hashmap![i32, 15 | $( 16 | $chr => $prec 17 | ),* 18 | ], 19 | operators: [ 20 | $( 21 | $chr.to_string() 22 | ),* 23 | ], 24 | rank: hashmap![(i32, i32), 25 | $( 26 | $chr => ($left_rank, $right_rank) 27 | ),* 28 | ] 29 | } 30 | } 31 | } 32 | }; 33 | } 34 | 35 | // Get length based on number of items inputted 36 | macro_rules! len { 37 | () => { 0 }; 38 | ($item:literal) => { 1 }; 39 | ($item:literal, $($extras:literal),*) => { 1 + len!($($extras),*) } 40 | } 41 | 42 | macro_rules! hashmap { 43 | ($type:ty, $($key:literal => $val:literal),*) => {{ 44 | use std::collections::HashMap; 45 | let mut hash: HashMap = HashMap::new(); 46 | 47 | $( 48 | hash.insert($key.to_string(), $val); 49 | )* 50 | 51 | hash 52 | }}; 53 | 54 | ($type:ty, $($key:literal => $val:expr),*) => {{ 55 | use std::collections::HashMap; 56 | let mut hash: HashMap = HashMap::new(); 57 | 58 | $( 59 | hash.insert($key.to_string(), $val); 60 | )* 61 | 62 | hash 63 | }}; 64 | } 65 | 66 | // REWORKS/PATCHES NEEDED: `;`, `\`, `@` 67 | // REMOVED: `n_` 68 | // UNUSED: `!!` 69 | // NEEDS CHANGING: numbers 70 | 71 | // Little macro I created to make the global Operators class much nicer. 72 | // First number is precedence, second is left # of args, third is right # of args 73 | operators! { 74 | '.': 11; 1-1, 75 | '^': 10; 1-1, "<>": 10; 1-1, 76 | '*': 9; 1-1, '/': 9; 1-1, 77 | '%': 8; 1-1, 78 | ":|": 7; 1-1, ":!": 7; 1-1, 79 | '+': 6; 1-1, '-': 6; 1-1, ".$": 6; 1-1, 80 | ".~": 5; 1-0, "=>": 5; 1-1, "->": 5; 1-1, '~': 5; 0-1, '#': 5; 1-0, ';': 5; 1-1, ":_": 5; 1-0, ":%": 5; 1-0, ".|": 5; 1-0, ".<": 5; 1-0, "..": 5; 1-0, ".=": 5; 1-0, 81 | ":n": 4; 1-0, ":s": 4; 1-0, ":}": 4; 1-0, ":{": 4; 1-0, ".}": 4; 1-0, ".{": 4; 1-0, ":@": 4; 1-0, "^*": 4; 1-0, "&.": 4; 0-3, ":i": 4; 1-1, 82 | '!': 4; 0-1, ":v": 4; 0-1, ":^": 4; 0-1, "++": 4; 0-1, "--": 4; 0-1, ":*": 4; 0-1, ":/": 4; 0-1, 83 | ":+": 4; 0-1, ":-": 4; 0-1, ":>": 4; 0-1, ":<": 4; 0-1, "|:": 4; 0-1, "?.": 4; 0-1, "#.": 4; 0-1, "*.": 4; 0-1, 84 | "$.": 4; 0-1, 'z': 4; 1-1, "#>": 4; 0-1, "#:": 4; 0-1, '?': 4; 1-1, "!.": 4; 0-1, 85 | '|': 3; 1-1, 86 | '=': 2; 1-1, "!=": 2; 1-1, '<': 2; 1-1, "<=": 2; 1-1, '>': 2; 1-1, ">=": 2; 1-1, 87 | "&&": 1; 1-1, "||": 1; 1-1, 88 | ':': 0; 1-1, "::": 0; 1-1, "??": 0; 1-2, '@': 0; 1-1, '&': 0; 1-1, '$': 0; 0-2, "$:": 0; 0-2, "/:": 0; 0-2, "\\": 0; 1-1, ":\\": 0; 1-1, 89 | ":=": -1; 1-1 90 | } 91 | 92 | lazy_static! { 93 | pub static ref OPTIONS: Operators = Operators::new(); 94 | pub static ref CODEPAGE: Vec = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°○■↑↓→←║═╔╗╚╝░▒►◄│─┌┐└┘├┤┴┬♦┼█▄▀▬±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿŒœŠšŸŽžƒƥʠˆ˜–—‘’‚“”„†‡•…‰‹›€™⁺⁻⁼⇒⇐★Δ".chars().collect(); 95 | pub static ref COMPRESSED_CHARS: Vec = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`1234567890-=[]\\;'/~@#$%^&*()_+{}|\"<>".chars().collect(); 96 | } 97 | -------------------------------------------------------------------------------- /src/utils/dict.rs: -------------------------------------------------------------------------------- 1 | // This file was ported directly from js, so excuse the mess 2 | 3 | use super::consts::COMPRESSED_CHARS; 4 | 5 | fn capitalize(word: &str, existing: bool) -> String { 6 | if existing { 7 | word.to_owned() 8 | } else { 9 | word.chars().next().unwrap().to_uppercase().to_string() + &word[1..] 10 | } 11 | } 12 | 13 | pub fn decompress(chars: &str, all_cap: bool) -> String { 14 | let dictionary = include_str!("../../dictionary.txt") 15 | .split("\n") 16 | .filter(|n| !n.is_empty()) 17 | .collect::>(); 18 | let s = chars.trim().chars().collect::>(); 19 | 20 | let mut decomp = String::new(); 21 | let mut chr = 0; 22 | 23 | while chr < s.len() { 24 | let first = s[chr]; 25 | let second = *s.get(chr + 1).unwrap_or(&'\u{0000}'); // lol 26 | if COMPRESSED_CHARS.contains(&first) { 27 | if COMPRESSED_CHARS.contains(&second) { 28 | decomp.push_str(&capitalize( 29 | dictionary[COMPRESSED_CHARS.iter().position(|c| *c == first).unwrap() * 100 30 | + COMPRESSED_CHARS.iter().position(|c| *c == second).unwrap()] 31 | .trim(), 32 | !all_cap && !decomp.is_empty(), 33 | )); 34 | } else { 35 | decomp.push_str(&format!( 36 | "{}{}", 37 | capitalize( 38 | dictionary 39 | [COMPRESSED_CHARS.iter().position(|c| *c == first).unwrap() * 100] 40 | .trim(), 41 | !all_cap && !decomp.is_empty() 42 | ), 43 | second 44 | )); 45 | } 46 | chr += 2; 47 | } else { 48 | chr += 1; 49 | decomp.push_str(&first.to_string()); 50 | } 51 | } 52 | 53 | decomp 54 | } 55 | -------------------------------------------------------------------------------- /src/utils/env.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::rc::Rc; 3 | use std::{cell::RefCell, collections::HashMap}; 4 | 5 | use super::types::{Dynamic, Env}; 6 | 7 | #[derive(Clone)] 8 | pub struct Environment { 9 | pub vals: HashMap Dynamic>>, 10 | } 11 | 12 | impl Environment { 13 | pub fn init() -> Self { 14 | Self { 15 | vals: HashMap::new(), 16 | } 17 | } 18 | 19 | pub fn define(&mut self, names: [&str; SIZE], f: T) 20 | where 21 | T: Fn(Env, Dynamic) -> Dynamic, 22 | { 23 | let ptr: Rc Dynamic> = Rc::new(f); 24 | for name in std::array::IntoIter::new(names) { 25 | self.vals.insert(name.trim().to_owned(), Rc::clone(&ptr)); 26 | } 27 | } 28 | 29 | pub fn define_var(&mut self, name: &str, val: T) 30 | where 31 | Dynamic: From, 32 | { 33 | self.vals.insert( 34 | name.trim().to_owned(), 35 | Rc::new(move |_, _| Dynamic::from(val.clone())), 36 | ); 37 | } 38 | 39 | #[inline] 40 | pub fn get_var(&self, name: &str) -> Dynamic { 41 | // Dummy call, assumes it is a constant value 42 | self.attempt_call( 43 | name, 44 | &Rc::new(RefCell::new(Environment::init())), 45 | Dynamic::from(false), 46 | ) 47 | } 48 | 49 | pub fn attempt_call(&self, name: &str, env: &Env, arg: Dynamic) -> Dynamic { 50 | let f = self 51 | .vals 52 | .get(name) 53 | .unwrap_or_else(|| panic!("Unrecognized value {}", name)); 54 | f(Rc::clone(env), arg) 55 | } 56 | } 57 | 58 | impl fmt::Debug for Environment { 59 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 60 | f.debug_struct("Environment").finish() 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | use self::tokens::*; 2 | 3 | pub mod compress; 4 | pub mod consts; 5 | pub mod dict; 6 | pub mod env; 7 | pub mod num; 8 | pub mod tokens; 9 | pub mod types; 10 | 11 | // Creates a space-separated range [s, n] 12 | pub fn create_str_range(s: usize, n: usize) -> String { 13 | (s..=n).map(|v| v.to_string()).collect::>().join(" ") 14 | } 15 | 16 | // Sums the rank from the start and slice of Tokens 17 | pub fn sum_rank(start: i128, rest: &[Token]) -> i128 { 18 | start 19 | + rest.iter().cloned().fold(0_i128, |acc, op| { 20 | if let Token::Operator(_, rank) = op { 21 | acc + rank.0 as i128 + rank.1 as i128 22 | } else { 23 | acc 24 | } 25 | }) 26 | } 27 | 28 | // Systematically replace `_` with values from entries 29 | pub fn traverse_replace(entries: &mut Vec, tree: Node) -> Node { 30 | match &tree { 31 | Node::Block(body, nm) => { 32 | // Blocks that use a key of `_` should not be messed with 33 | let new_body = if nm.is_none() || nm.as_ref().unwrap() == "_" { 34 | body.clone() 35 | } else { 36 | body.iter() 37 | .map(|n| traverse_replace(entries, n.clone())) 38 | .collect() 39 | }; 40 | Node::Block(new_body, nm.clone()) 41 | } 42 | 43 | Node::String(_) => tree, 44 | 45 | Node::Number(_) => tree, 46 | 47 | Node::Variable(v) => { 48 | if v == "_" { 49 | entries 50 | .pop() 51 | .expect("Too many `_` found in block by utils::traverse_replace") 52 | .clone() 53 | } else { 54 | tree 55 | } 56 | } 57 | 58 | Node::Group(body) => { 59 | let new_body = body 60 | .iter() 61 | .map(|n| traverse_replace(entries, n.clone())) 62 | .collect(); 63 | Node::Group(new_body) 64 | } 65 | 66 | Node::Op(n, largs, rargs) => { 67 | // Fold shouldn't have the left args replaced 68 | let nl = if n == "\\" || n == ":\\" { 69 | largs.clone() 70 | } else { 71 | largs 72 | .iter() 73 | .map(|n| traverse_replace(entries, n.clone())) 74 | .collect() 75 | }; 76 | let nr = rargs 77 | .iter() 78 | .map(|n| traverse_replace(entries, n.clone())) 79 | .collect(); 80 | Node::Op(n.clone(), nl, nr) 81 | } 82 | 83 | Node::Sequence(body, block, len) => { 84 | let new_body = body 85 | .iter() 86 | .map(|n| traverse_replace(entries, n.clone())) 87 | .collect(); 88 | let new_len = len 89 | .as_ref() 90 | .map(|n| Box::new(traverse_replace(entries, n.as_ref().clone()))); 91 | Node::Sequence(new_body, block.clone(), new_len) 92 | } 93 | 94 | _ => unimplemented!(), 95 | } 96 | } 97 | 98 | // Create non-base10 matrix 99 | pub fn nbase_padded String>( 100 | mut orig: self::types::Dynamic, 101 | mut f: T, 102 | ) -> Vec { 103 | if !orig.is_array() { 104 | orig = self::types::Dynamic::from([orig]); 105 | } 106 | // This should be inferred, but isn't 107 | let mut v: Vec = orig 108 | .literal_array() 109 | .map(|d| f(d.literal_string())) 110 | .collect(); 111 | let max = v.iter().map(|n| n.len()).max().unwrap(); 112 | v = v 113 | .iter() 114 | .map(|n| format!("{:0>size$}", n, size = max)) 115 | .collect(); 116 | v 117 | } 118 | -------------------------------------------------------------------------------- /src/utils/num.rs: -------------------------------------------------------------------------------- 1 | use rug::Float; 2 | 3 | use crate::FLOAT_PRECISION; 4 | 5 | // Alias 6 | pub type Num = Float; 7 | 8 | pub fn is_arn_num(string: &str) -> bool { 9 | let count_ = string.matches('_').count(); 10 | if string.is_empty() || count_ > 2 { 11 | return false; 12 | } 13 | 14 | let mut expos = None; 15 | 16 | for (i, chr) in string.char_indices() { 17 | match chr { 18 | '_' => { 19 | if i > 0 && Some(i - 1) != expos { 20 | return false; 21 | } 22 | } 23 | 24 | 'e' => { 25 | if expos.is_some() { 26 | return false; 27 | } 28 | 29 | expos = Some(i); 30 | } 31 | 32 | '0'..='9' => {} 33 | 34 | _ => return false, 35 | } 36 | } 37 | 38 | if expos.is_some() { 39 | true 40 | } else { 41 | count_ <= 1 42 | } 43 | } 44 | 45 | pub fn parse_arn_num(string: &str) -> Result> { 46 | let mut num = String::with_capacity(string.len() + 1); 47 | if string.starts_with('e') { 48 | num.push('1'); 49 | num.push_str(string); 50 | } else if string.starts_with("_e") { 51 | num.push_str("-1"); 52 | num.push_str(&string[1..]); 53 | } else { 54 | num.push_str(string); 55 | } 56 | num = num.replace('_', "-"); 57 | 58 | Ok({ 59 | let num = Num::parse(&num)?; 60 | Num::with_val(*FLOAT_PRECISION, num) 61 | }) 62 | } 63 | 64 | #[inline] 65 | pub fn to_u32(env: &super::types::Env, n: &super::tokens::Node) -> u32 { 66 | crate::parser::parse_node(std::rc::Rc::clone(env), n) 67 | .literal_num() 68 | .floor() 69 | .to_u32_saturating_round(rug::float::Round::Down) 70 | .unwrap() 71 | } 72 | -------------------------------------------------------------------------------- /src/utils/tokens.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Display, Formatter}; 2 | 3 | use super::num::Num; 4 | 5 | #[derive(Debug, Clone, PartialEq)] 6 | pub enum Token { 7 | /// String Node 8 | String(String), 9 | 10 | /// Compressed String Node 11 | CmpString(String, char), 12 | 13 | /// Numeric Node 14 | Number(Num), 15 | 16 | /// Variable Node 17 | Variable(String), 18 | 19 | /// A block that contains some code 20 | Block(Vec, char, Option), 21 | 22 | /// Operator 23 | Operator(String, (i32, i32)), 24 | 25 | /// Comma 26 | Comma, 27 | } 28 | 29 | // Will be used by ast once implemented 30 | #[derive(Debug, Clone, PartialEq)] 31 | pub enum Node { 32 | /// A fix is any operation (usually denoted by punctuation) 33 | /// that takes in arguments on the left and/or right. 34 | Op(String, Vec, Vec), 35 | 36 | /// String Node 37 | String(String), 38 | 39 | /// Compressed String Node 40 | CmpString(String, char), 41 | 42 | /// Numeric Node 43 | Number(Num), 44 | 45 | /// Variable Node 46 | Variable(String), 47 | 48 | /// A Group `( ... )` 49 | Group(Vec), 50 | 51 | /// A Block `{ ... }` 52 | Block(Vec, Option), 53 | 54 | /// A Sequence `[ ... ]` 55 | /// Body, block, size 56 | Sequence(Vec, Box, Option>), 57 | } 58 | 59 | // Hacky but it'll do 60 | impl Display for Node { 61 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 62 | match &self { 63 | Self::Op(val, l, r) => { 64 | for item in l { 65 | write!(f, "{}", item)?; 66 | } 67 | write!(f, "{} ", val)?; 68 | for item in r { 69 | write!(f, "{}", item)?; 70 | } 71 | 72 | Ok(()) 73 | } 74 | 75 | Self::String(st) => write!(f, "\"{}\" ", st), 76 | 77 | Self::CmpString(cst, chr) => { 78 | write!(f, "\"{}\"", super::dict::decompress(cst, *chr == '\'')) 79 | } 80 | 81 | Self::Number(num) => write!(f, "{} ", super::types::Dynamic::from(num.clone())), 82 | 83 | Self::Variable(st) => write!(f, "{} ", st), 84 | 85 | Self::Group(nodes) => { 86 | write!(f, "(")?; 87 | for node in nodes { 88 | write!(f, "{}", node)?; 89 | } 90 | write!(f, ")") 91 | } 92 | 93 | Self::Block(nodes, name) => { 94 | if let Some(name) = name { 95 | write!(f, "{}", name)?; 96 | } 97 | write!(f, "{{")?; 98 | for node in nodes { 99 | write!(f, "{}", node)?; 100 | } 101 | write!(f, "}} ") 102 | } 103 | 104 | Self::Sequence(entries, block, len) => { 105 | write!(f, "[")?; 106 | for entry in entries { 107 | write!(f, "{}, ", entry)?; 108 | } 109 | write!(f, "{}", block.as_ref())?; 110 | 111 | if let Some(len) = len { 112 | write!(f, "-> {}", len.as_ref())?; 113 | } 114 | 115 | write!(f, "]") 116 | } 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/utils/types.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | 3 | use std::fmt::{self, Display, Formatter}; 4 | use std::hash::{Hash, Hasher}; 5 | use std::{cell::RefCell, cmp::Ordering, rc::Rc}; 6 | 7 | use super::env::Environment; 8 | use super::num::{to_u32, Num}; 9 | use super::tokens::Node; 10 | use crate::{FLOAT_PRECISION, OUTPUT_PRECISION}; 11 | 12 | // Shorthand for this monstrosity 13 | pub type Env = Rc>; 14 | 15 | // Inner value enum for dynamic type 16 | #[derive(Clone, Debug)] 17 | pub enum Val { 18 | String(String), 19 | 20 | Number(Num), 21 | 22 | Boolean(bool), 23 | 24 | Array(Box), 25 | 26 | Empty, 27 | } 28 | 29 | impl Hash for Val { 30 | fn hash(&self, state: &mut H) { 31 | match self { 32 | Val::String(s) => s.hash(state), 33 | Val::Number(n) => n.clone().floor().to_u32_saturating().unwrap().hash(state), 34 | Val::Boolean(b) => b.hash(state), 35 | Val::Array(s) => s.as_ref().clone().collect::>().hash(state), 36 | Val::Empty => "".hash(state), 37 | } 38 | } 39 | } 40 | 41 | // Struct that represents types in Arn 42 | #[derive(Clone, Debug, Hash)] 43 | pub struct Dynamic { 44 | val: Val, 45 | cur: u8, 46 | } 47 | 48 | #[allow(clippy::clippy::wrong_self_convention)] 49 | impl Dynamic { 50 | pub fn empty() -> Self { 51 | Self { 52 | val: Val::Empty, 53 | cur: 0, 54 | } 55 | } 56 | 57 | pub fn new(val: Val, cur: u8) -> Self { 58 | Self { val, cur } 59 | } 60 | 61 | #[inline] 62 | pub fn as_string(&mut self) { 63 | *self = self.into_string(); 64 | } 65 | 66 | #[inline] 67 | pub fn as_num(&mut self) { 68 | *self = self.into_num(); 69 | } 70 | 71 | #[inline] 72 | pub fn as_bool(&mut self) { 73 | *self = self.into_bool(); 74 | } 75 | 76 | // Cast inner value to a `Val::String` 77 | pub fn into_string(&self) -> Self { 78 | match &self.val { 79 | Val::String(_) => self.clone(), 80 | 81 | Val::Number(_) => Self { 82 | val: Val::String(format!("{}", self)), 83 | cur: 1, 84 | }, 85 | 86 | Val::Boolean(b) => Self { 87 | val: Val::String(b.to_string()), 88 | cur: 1, 89 | }, 90 | 91 | Val::Array(n) => Self { 92 | val: Val::String( 93 | n.clone() 94 | .next() 95 | .unwrap_or_else(|| Dynamic::from("")) 96 | .literal_string(), 97 | ), 98 | cur: 1, 99 | }, 100 | 101 | Val::Empty => Self { 102 | val: Val::String(String::new()), 103 | cur: 1, 104 | }, 105 | } 106 | } 107 | 108 | // Cast to `Val::Number` 109 | pub fn into_num(&self) -> Self { 110 | match &self.val { 111 | Val::String(s) => Self { 112 | val: Val::Number(Num::with_val( 113 | *FLOAT_PRECISION, 114 | Num::parse(s).unwrap_or_else(|_| Num::parse("0").unwrap()), 115 | )), 116 | cur: 2, 117 | }, 118 | 119 | Val::Number(_) => self.clone(), 120 | 121 | Val::Boolean(b) => Self { 122 | val: Val::Number(Num::with_val(*FLOAT_PRECISION, if *b { 1 } else { 0 })), 123 | cur: 2, 124 | }, 125 | 126 | Val::Array(n) => Self { 127 | val: Val::Number(Num::with_val( 128 | *FLOAT_PRECISION, 129 | Num::parse( 130 | n.clone() 131 | .next() 132 | .unwrap_or_else(|| Dynamic::from("")) 133 | .literal_string(), 134 | ) 135 | .unwrap_or_else(|_| Num::parse("0").unwrap()), 136 | )), 137 | cur: 2, 138 | }, 139 | 140 | Val::Empty => Self { 141 | val: Val::Number(Num::with_val(*FLOAT_PRECISION, 0)), 142 | cur: 2, 143 | }, 144 | } 145 | } 146 | 147 | // Cast to `Val::Boolean` 148 | pub fn into_bool(&self) -> Self { 149 | match &self.val { 150 | Val::String(s) => Self { 151 | val: Val::Boolean(!s.is_empty()), 152 | cur: 3, 153 | }, 154 | 155 | Val::Number(n) => Self { 156 | val: Val::Boolean(*n != 0), 157 | cur: 3, 158 | }, 159 | 160 | Val::Boolean(_) => self.clone(), 161 | 162 | Val::Array(n) => Self { 163 | val: Val::Boolean( 164 | n.clone() 165 | .next() 166 | .unwrap_or_else(|| Dynamic::from(false)) 167 | .literal_bool(), 168 | ), 169 | cur: 3, 170 | }, 171 | 172 | Val::Empty => Self { 173 | val: Val::Boolean(false), 174 | cur: 3, 175 | }, 176 | } 177 | } 178 | 179 | pub fn into_array(&self) -> Self { 180 | match &self.val { 181 | Val::String(s) => { 182 | if s.contains(' ') { 183 | let iter = s.split(' ').map(Dynamic::from); 184 | Self { 185 | val: Val::Array(Box::new(Sequence::from_iter( 186 | iter.clone(), 187 | Node::String(String::new()), 188 | Some(iter.count()), 189 | ))), 190 | cur: 4, 191 | } 192 | } else { 193 | let iter = s.chars().map(|n| Dynamic::from(n.to_string())); 194 | Self { 195 | val: Val::Array(Box::new(Sequence::from_iter( 196 | iter.clone(), 197 | Node::String(String::new()), 198 | Some(iter.count()), 199 | ))), 200 | cur: 4, 201 | } 202 | } 203 | } 204 | 205 | Val::Number(_) => Dynamic::from(format!("{}", self)).into_array(), 206 | 207 | Val::Boolean(_) => Dynamic::from(format!("{}", self)).into_array(), 208 | 209 | Val::Array(_) => self.clone(), 210 | 211 | Val::Empty => Self { 212 | val: Val::Array(Box::new(Sequence::from_vec::( 213 | &[], 214 | Node::String(String::new()), 215 | Some(0), 216 | ))), 217 | cur: 4, 218 | }, 219 | } 220 | } 221 | 222 | #[inline] 223 | pub fn literal_num(self) -> Num { 224 | match self.val { 225 | Val::Number(n) => n, 226 | _ => self.into_num().literal_num(), 227 | } 228 | } 229 | 230 | #[inline] 231 | pub fn literal_string(self) -> String { 232 | match self.val { 233 | Val::String(s) => s, 234 | _ => self.into_string().literal_string(), 235 | } 236 | } 237 | 238 | #[inline] 239 | pub fn literal_bool(self) -> bool { 240 | match self.val { 241 | Val::Boolean(b) => b, 242 | _ => self.into_bool().literal_bool(), 243 | } 244 | } 245 | 246 | #[inline] 247 | pub fn literal_array(self) -> Sequence { 248 | match &self.val { 249 | Val::Array(seq) => seq.as_ref().clone(), 250 | _ => self.into_array().literal_array(), 251 | } 252 | } 253 | 254 | #[inline] 255 | pub fn is_string(&self) -> bool { 256 | self.cur == 1 257 | } 258 | 259 | #[inline] 260 | pub fn is_num(&self) -> bool { 261 | self.cur == 2 262 | } 263 | 264 | #[inline] 265 | pub fn is_bool(&self) -> bool { 266 | self.cur == 3 267 | } 268 | 269 | #[inline] 270 | pub fn is_array(&self) -> bool { 271 | self.cur == 4 272 | } 273 | 274 | // Mutate inner `Val::String` 275 | pub fn mutate_string String>(&self, f: T) -> Self { 276 | match &self.val { 277 | Val::String(s) => Self::from(f(s.clone())), 278 | 279 | _ => self.into_string().mutate_string(f), 280 | } 281 | } 282 | 283 | // Mutate inner `Val::Number` 284 | pub fn mutate_num Num>(&self, f: T) -> Self { 285 | match &self.val { 286 | Val::Number(n) => Self::from(f(n.clone())), 287 | 288 | _ => self.into_num().mutate_num(f), 289 | } 290 | } 291 | 292 | // Mutate inner `Val::Boolean` 293 | pub fn mutate_bool bool>(&self, f: T) -> Self { 294 | match &self.val { 295 | Val::Boolean(b) => Self::from(f(*b)), 296 | 297 | _ => self.into_bool().mutate_bool(f), 298 | } 299 | } 300 | 301 | // Mutate inner `Val::Array` 302 | pub fn mutate_array &mut Sequence>(&mut self, f: T) -> Self { 303 | match &mut self.val { 304 | Val::Array(seq) => Self { 305 | val: Val::Array(Box::new(f(seq.as_mut()).clone())), 306 | cur: 4, 307 | }, 308 | 309 | _ => self.into_array().mutate_array(f), 310 | } 311 | } 312 | 313 | // Convert to Node 314 | pub fn into_node(self) -> Node { 315 | match self.val { 316 | Val::String(s) => Node::String(s), 317 | Val::Number(n) => Node::Number(n), 318 | Val::Boolean(b) => Node::Number(Num::with_val(*FLOAT_PRECISION, if b { 1 } else { 0 })), 319 | Val::Array(s) => { 320 | if !s.is_finite() { 321 | panic!("Cannot convert infinite sequence into Node"); 322 | } 323 | 324 | let s = s.as_ref().clone(); 325 | Node::Sequence( 326 | s.cstr.iter().cloned().map(Dynamic::into_node).collect(), 327 | Box::new(s.block), 328 | s.length 329 | .map(|n| Box::new(Node::Number(Num::with_val(*FLOAT_PRECISION, n)))), 330 | ) 331 | } 332 | Val::Empty => unreachable!(), 333 | } 334 | } 335 | } 336 | 337 | // Equivalent to sprintf function in the js version 338 | impl Display for Dynamic { 339 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 340 | match &self.val { 341 | Val::String(s) => write!(f, "{}", s), 342 | 343 | Val::Number(n) => { 344 | let s = n.to_string_radix_round( 345 | 10, 346 | Some(*OUTPUT_PRECISION), 347 | rug::float::Round::Nearest, 348 | ); 349 | 350 | write!( 351 | f, 352 | "{}", 353 | if s.contains('.') && !s.contains('e') { 354 | // First remove trailing zeros, then the dot if that was everything 355 | s.trim_end_matches('0') 356 | .trim_end_matches('.') 357 | .replace('-', "_") 358 | } else { 359 | s.replace('-', "_") 360 | } 361 | ) 362 | } 363 | 364 | Val::Boolean(b) => write!(f, "{}", if *b { 1 } else { 0 }), 365 | 366 | Val::Array(seq) => { 367 | let seq = seq.as_ref().clone(); 368 | let is_infinite = !seq.is_finite(); 369 | 370 | for entry in seq { 371 | let mut as_string = format!("{}", entry); 372 | 373 | if entry.is_array() { 374 | as_string = as_string.replace('\n', " "); 375 | } 376 | 377 | if is_infinite { 378 | println!("{}", as_string); 379 | } else { 380 | writeln!(f, "{}", as_string)?; 381 | } 382 | } 383 | 384 | Ok(()) 385 | } 386 | 387 | Val::Empty => write!(f, ""), 388 | } 389 | } 390 | } 391 | 392 | impl PartialEq for Dynamic { 393 | #[inline] 394 | fn eq(&self, other: &Self) -> bool { 395 | match &self.val { 396 | Val::String(s) => match &other.val { 397 | Val::String(o) => s == o, 398 | Val::Number(n) => match Num::parse(s) { 399 | Ok(s) => Num::with_val(*FLOAT_PRECISION, s) == n.clone(), 400 | Err(_) => false, 401 | }, 402 | Val::Boolean(b) => { 403 | if *b { 404 | s == "1" 405 | } else { 406 | s == "0" 407 | } 408 | } 409 | _ => false, 410 | }, 411 | 412 | Val::Number(n) => match &other.val { 413 | Val::String(s) => match Num::parse(s) { 414 | Ok(s) => Num::with_val(*FLOAT_PRECISION, s) == n.clone(), 415 | Err(_) => false, 416 | }, 417 | Val::Number(o) => n == o, 418 | Val::Boolean(b) => { 419 | if *b { 420 | n.clone() == 1 421 | } else { 422 | n.is_zero() 423 | } 424 | } 425 | _ => false, 426 | }, 427 | 428 | Val::Boolean(b) => match &other.val { 429 | Val::Number(n) => { 430 | if *b { 431 | n.clone() == 1 432 | } else { 433 | n.is_zero() 434 | } 435 | } 436 | Val::Boolean(n) => b == n, 437 | _ => false, 438 | }, 439 | 440 | Val::Array(_) => todo!(), 441 | 442 | Val::Empty => matches!(other.val, Val::Empty), 443 | } 444 | } 445 | } 446 | 447 | // Technically this isn't true 448 | impl Eq for Dynamic {} 449 | 450 | impl PartialOrd for Dynamic { 451 | #[inline] 452 | fn partial_cmp(&self, other: &Dynamic) -> Option { 453 | match &self.val { 454 | Val::String(s) => match &other.val { 455 | Val::String(o) => s.partial_cmp(o), 456 | Val::Number(n) => match Num::parse(s) { 457 | Ok(s) => Num::with_val(*FLOAT_PRECISION, s).partial_cmp(n), 458 | Err(_) => None, 459 | }, 460 | Val::Boolean(b) => { 461 | if *b { 462 | s.partial_cmp(&"1".to_string()) 463 | } else { 464 | s.partial_cmp(&"0".to_string()) 465 | } 466 | } 467 | _ => s.partial_cmp(&other.clone().literal_string()), 468 | }, 469 | 470 | Val::Number(n) => match &other.val { 471 | Val::String(s) => match Num::parse(s) { 472 | Ok(s) => n.partial_cmp(&Num::with_val(*FLOAT_PRECISION, s)), 473 | Err(_) => None, 474 | }, 475 | Val::Number(o) => n.partial_cmp(o), 476 | Val::Boolean(b) => { 477 | if *b { 478 | n.partial_cmp(&1) 479 | } else { 480 | n.cmp0() 481 | } 482 | } 483 | _ => n.partial_cmp(&other.clone().literal_num()), 484 | }, 485 | 486 | Val::Boolean(b) => match &other.val { 487 | Val::Number(n) => { 488 | if *b { 489 | Num::with_val(*FLOAT_PRECISION, 1).partial_cmp(&1) 490 | } else { 491 | Num::new(*FLOAT_PRECISION).partial_cmp(n) 492 | } 493 | } 494 | Val::Boolean(n) => b.partial_cmp(n), 495 | _ => b.partial_cmp(&other.clone().literal_bool()), 496 | }, 497 | 498 | Val::Array(s) => match &other.val { 499 | Val::Array(o) => { 500 | let s = s.as_ref().clone().count(); 501 | let o = o.as_ref().clone().count(); 502 | 503 | s.partial_cmp(&o) 504 | } 505 | 506 | _ => s 507 | .as_ref() 508 | .clone() 509 | .collect::>() 510 | .partial_cmp(&other.clone().literal_array().collect::>()), 511 | }, 512 | 513 | Val::Empty => None, 514 | } 515 | } 516 | } 517 | 518 | impl<'a> From<&'a str> for Dynamic { 519 | fn from(v: &'a str) -> Self { 520 | Self { 521 | val: Val::String(v.to_owned()), 522 | cur: 1, 523 | } 524 | } 525 | } 526 | 527 | impl From for Dynamic { 528 | fn from(v: String) -> Self { 529 | Self { 530 | val: Val::String(v), 531 | cur: 1, 532 | } 533 | } 534 | } 535 | 536 | impl From for Dynamic { 537 | fn from(v: Num) -> Self { 538 | Self { 539 | val: Val::Number(v), 540 | cur: 2, 541 | } 542 | } 543 | } 544 | 545 | impl From for Dynamic { 546 | fn from(v: bool) -> Self { 547 | Self { 548 | val: Val::Boolean(v), 549 | cur: 3, 550 | } 551 | } 552 | } 553 | 554 | impl<'a, T> From<&'a [T]> for Dynamic 555 | where 556 | Dynamic: From, 557 | T: Clone, 558 | { 559 | fn from(v: &'a [T]) -> Self { 560 | Self { 561 | val: Val::Array(Box::new(Sequence::from_vec( 562 | v, 563 | Node::Block(vec![], None), 564 | Some(v.len()), 565 | ))), 566 | cur: 4, 567 | } 568 | } 569 | } 570 | 571 | impl From> for Dynamic 572 | where 573 | Dynamic: From, 574 | T: Clone, 575 | { 576 | fn from(v: Vec) -> Self { 577 | Self { 578 | val: Val::Array(Box::new(Sequence::from_vec( 579 | &v, 580 | Node::Block(vec![], None), 581 | Some(v.len()), 582 | ))), 583 | cur: 4, 584 | } 585 | } 586 | } 587 | 588 | impl From<[T; N]> for Dynamic 589 | where 590 | Dynamic: From, 591 | T: Clone, 592 | { 593 | fn from(v: [T; N]) -> Self { 594 | Self { 595 | val: Val::Array(Box::new(Sequence::from_vec( 596 | &v, 597 | Node::Block(vec![], None), 598 | Some(N), 599 | ))), 600 | cur: 4, 601 | } 602 | } 603 | } 604 | 605 | impl From for Dynamic { 606 | fn from(v: Sequence) -> Self { 607 | Self { 608 | val: Val::Array(Box::new(v)), 609 | cur: 4, 610 | } 611 | } 612 | } 613 | 614 | impl From for Dynamic { 615 | fn from(v: Node) -> Self { 616 | crate::parser::parse_node(Rc::new(RefCell::new(Environment::init())), &v) 617 | } 618 | } 619 | 620 | #[allow(clippy::from_over_into)] 621 | impl Into for Dynamic { 622 | fn into(self) -> Node { 623 | match self.val { 624 | Val::String(st) => Node::String(st), 625 | Val::Number(nm) => Node::Number(nm), 626 | Val::Boolean(bl) => { 627 | Node::Number(Num::with_val(*FLOAT_PRECISION, if bl { 1 } else { 0 })) 628 | } 629 | _ => panic!("Cannot convert emtpy value into Node"), 630 | } 631 | } 632 | } 633 | 634 | #[derive(Clone, Debug)] 635 | pub struct Sequence { 636 | pub cstr: Vec, 637 | pub length: Option, 638 | pub block: Node, 639 | unparsed_length: Option, 640 | t_i: Option, 641 | env: Option, 642 | index: usize, 643 | } 644 | 645 | impl Sequence { 646 | pub fn from_iter(iter: T, block: Node, length: Option) -> Self 647 | where 648 | T: Iterator, 649 | Dynamic: From, 650 | { 651 | let v = iter.map(Dynamic::from).collect(); 652 | Self { 653 | cstr: v, 654 | unparsed_length: None, 655 | length, 656 | block, 657 | t_i: None, 658 | env: None, 659 | index: 0, 660 | } 661 | } 662 | 663 | pub fn from_vec(v: &[T], block: Node, length: Option) -> Self 664 | where 665 | Dynamic: From, 666 | T: Clone, 667 | { 668 | let v = v.iter().map(|n| Dynamic::from(n.clone())).collect(); 669 | Self { 670 | cstr: v, 671 | unparsed_length: None, 672 | length, 673 | block, 674 | t_i: None, 675 | env: None, 676 | index: 0, 677 | } 678 | } 679 | 680 | pub fn from_vec_dyn(v: &[Dynamic], block: Node, length: Option) -> Self { 681 | Self { 682 | cstr: v.to_owned(), 683 | unparsed_length: None, 684 | length, 685 | block, 686 | t_i: None, 687 | env: None, 688 | index: 0, 689 | } 690 | } 691 | 692 | #[inline] 693 | pub fn is_finite(&self) -> bool { 694 | self.length.is_some() || self.unparsed_length.is_some() 695 | } 696 | 697 | #[inline] 698 | pub fn len(&self) -> Option { 699 | self.length 700 | } 701 | 702 | #[inline] 703 | pub fn set_env(&mut self, env: Env) { 704 | self.env = Some(Rc::new(env.as_ref().clone())); 705 | } 706 | 707 | #[inline] 708 | pub fn set_env_self(self, env: Env) -> Self { 709 | Self { 710 | cstr: self.cstr, 711 | unparsed_length: self.unparsed_length, 712 | length: self.length, 713 | block: self.block, 714 | t_i: self.t_i, 715 | env: Some(env), 716 | index: self.index, 717 | } 718 | } 719 | 720 | fn traverse_replace(&mut self, n: Node) -> Node { 721 | let mut vals = self.cstr.iter().cloned().map(|n| n.into_node()).collect(); 722 | if let Node::Block(mut body, n) = n { 723 | for i in 0..body.len() { 724 | body[i] = super::traverse_replace(&mut vals, body[i].clone()); 725 | } 726 | Node::Block(body, n) 727 | } else { 728 | unreachable!() 729 | } 730 | } 731 | 732 | #[allow(clippy::unnecessary_wraps)] 733 | #[inline] 734 | fn _next(&mut self) -> Option { 735 | if self.index < self.cstr.len() { 736 | self.index += 1; 737 | Some(self.cstr[self.index - 1].clone()) 738 | } else { 739 | self.index += 1; 740 | let block = self.traverse_replace(self.block.clone()); 741 | self.env 742 | .as_ref() 743 | .unwrap() 744 | .borrow_mut() 745 | .define_var("p", Dynamic::from(self.cstr.as_slice())); 746 | let res = crate::parser::parse_node(Rc::clone(self.env.as_ref().unwrap()), &block); 747 | self.cstr.push(res.clone()); 748 | 749 | Some(res) 750 | } 751 | } 752 | } 753 | 754 | impl Iterator for Sequence { 755 | type Item = Dynamic; 756 | 757 | #[inline] 758 | fn next(&mut self) -> Option { 759 | if self.length.is_none() && self.unparsed_length.is_some() { 760 | self.length = Some(to_u32( 761 | self.env.as_ref().unwrap(), 762 | self.unparsed_length.as_ref().unwrap(), 763 | ) as usize); 764 | } 765 | 766 | if self.length.is_none() { 767 | self._next() 768 | } else if self.index == self.length.unwrap() { 769 | None 770 | } else { 771 | self._next() 772 | } 773 | } 774 | } 775 | 776 | impl DoubleEndedIterator for Sequence { 777 | fn next_back(&mut self) -> Option { 778 | if self.len().is_none() { 779 | panic!("Can only implement DoubleEndedIterator for a finite Sequence"); 780 | } 781 | 782 | while let Some(_) = self.next() { 783 | // Build the values, the starting index is initialized 784 | self.t_i = Some(self.index as isize - 1); 785 | } 786 | 787 | if self.t_i.unwrap() < 0 { 788 | None 789 | } else { 790 | self.t_i = Some(self.t_i.unwrap() - 1); 791 | Some(self.cstr[(self.t_i.unwrap() + 1) as usize].clone()) 792 | } 793 | } 794 | } 795 | -------------------------------------------------------------------------------- /tools/yank_fixes.js: -------------------------------------------------------------------------------- 1 | // Pulls out all fixes, their rank, and definitions from the rust program and formats them for the wiki. 2 | const fs = require('fs'); 3 | 4 | async function yank() { 5 | let consts = fs.readFileSync(__dirname + "/../src/utils/consts.rs").toString(); 6 | let help = fs.readFileSync(__dirname + "/../src/parser.rs").toString(); 7 | let defs = {}; 8 | 9 | consts.replace(/['"](.{1,3})['"]: (.{1,2}); (.-.)/g, (_, name, prec, ranks) => defs[name.replace("\\\\", "\\")] = [prec, ranks.split("-")]); 10 | help.replace(/\/\/\s*(.+)\n\s*\"(.{1,3})\" =>/g, (_, help, name) => defs[name.replace("\\\\", "\\")].push(help)); 11 | help.replace(/\/\/\s*(.+)\n\s*\"(.{1,3})\" \| \"(.{1,3})\" =>/g, (_, helps, n1, n2) => { 12 | helps = helps.split(",").map(n => n.trim()); 13 | n1 = n1.replace("\\\\", "\\"); 14 | n2 = n2.replace("\\\\", "\\"); 15 | defs[n1].push(helps[0]); 16 | defs[n2].push(helps[1]); 17 | }); 18 | 19 | let base = "|"; 20 | let titles = ["Symbol", "Prec", "Rank", "About"]; 21 | for (let i of titles) base += ` \`${i}\` |`; 22 | base += '\n' 23 | for (let _ in titles) base += '| :---: '; 24 | base += '|\n'; 25 | 26 | for (n in defs) { 27 | base += `| \`${n.replace(/([\|])/g, "\\$1")}\` | \`${defs[n][0]}\` | \`${defs[n][1].map(c => " _ ".repeat(c)).join(n.replace(/([\|])/g, "\\$1")).trim()}\` | **${defs[n][2].replace(/([\<\>\|])/g, "\\$1")}** |\n`; 28 | } 29 | 30 | console.log(base); 31 | } 32 | 33 | yank(); --------------------------------------------------------------------------------