├── .gitignore ├── LICENSE ├── README.md ├── docs ├── _config.yml ├── builtin_functions.md ├── doc_en.md ├── doc_jp.md └── index.md ├── editor └── gen.vim ├── examples ├── bubble_sort.gen ├── factorial.gen ├── fibonacci.gen ├── fizzbuzz.gen ├── func.gen ├── import.gen └── map.gen └── pygen ├── Makefile ├── main.py └── src ├── builtin_func.py ├── context.py ├── error.py ├── evaluator.py ├── gen_token.py ├── lexer.py ├── node.py ├── parser.py ├── position.py ├── symbol_table.py ├── utils.py └── value.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | .DS_Store 148 | 149 | 150 | 151 | # ------------ groovy 152 | # Compiled class file 153 | *.class 154 | 155 | # Log file 156 | *.log 157 | 158 | # BlueJ files 159 | *.ctxt 160 | 161 | # Mobile Tools for Java (J2ME) 162 | .mtj.tmp/ 163 | 164 | # Package Files # 165 | *.jar 166 | *.war 167 | *.nar 168 | *.ear 169 | *.zip 170 | *.tar.gz 171 | *.rar 172 | 173 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 174 | hs_err_pid* 175 | replay_pid* 176 | 177 | 178 | # -------- C++ 179 | # Prerequisites 180 | *.d 181 | 182 | # Compiled Object files 183 | *.slo 184 | *.lo 185 | *.o 186 | *.obj 187 | 188 | # Precompiled Headers 189 | *.gch 190 | *.pch 191 | 192 | # Compiled Dynamic libraries 193 | *.so 194 | *.dylib 195 | *.dll 196 | 197 | # Fortran module files 198 | *.mod 199 | *.smod 200 | 201 | # Compiled Static libraries 202 | *.lai 203 | *.la 204 | *.a 205 | *.lib 206 | 207 | # Executables 208 | *.exe 209 | *.out 210 | *.app 211 | 212 | #VSCode 213 | .vscode 214 | main.dSYM 215 | main.exe.dSYM 216 | 217 | 218 | # ----------------- nodejs 219 | # Logs 220 | logs 221 | *.log 222 | npm-debug.log* 223 | yarn-debug.log* 224 | yarn-error.log* 225 | lerna-debug.log* 226 | .pnpm-debug.log* 227 | 228 | # Diagnostic reports (https://nodejs.org/api/report.html) 229 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 230 | 231 | # Runtime data 232 | pids 233 | *.pid 234 | *.seed 235 | *.pid.lock 236 | 237 | # Directory for instrumented libs generated by jscoverage/JSCover 238 | lib-cov 239 | 240 | # Coverage directory used by tools like istanbul 241 | coverage 242 | *.lcov 243 | 244 | # nyc test coverage 245 | .nyc_output 246 | 247 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 248 | .grunt 249 | 250 | # Bower dependency directory (https://bower.io/) 251 | bower_components 252 | 253 | # node-waf configuration 254 | .lock-wscript 255 | 256 | # Compiled binary addons (https://nodejs.org/api/addons.html) 257 | build/Release 258 | 259 | # Dependency directories 260 | node_modules/ 261 | jspm_packages/ 262 | 263 | # Snowpack dependency directory (https://snowpack.dev/) 264 | web_modules/ 265 | 266 | # TypeScript cache 267 | *.tsbuildinfo 268 | 269 | # Optional npm cache directory 270 | .npm 271 | 272 | # Optional eslint cache 273 | .eslintcache 274 | 275 | # Optional stylelint cache 276 | .stylelintcache 277 | 278 | # Microbundle cache 279 | .rpt2_cache/ 280 | .rts2_cache_cjs/ 281 | .rts2_cache_es/ 282 | .rts2_cache_umd/ 283 | 284 | # Optional REPL history 285 | .node_repl_history 286 | 287 | # Output of 'npm pack' 288 | *.tgz 289 | 290 | # Yarn Integrity file 291 | .yarn-integrity 292 | 293 | # dotenv environment variable files 294 | .env 295 | .env.development.local 296 | .env.test.local 297 | .env.production.local 298 | .env.local 299 | 300 | # parcel-bundler cache (https://parceljs.org/) 301 | .cache 302 | .parcel-cache 303 | 304 | # Next.js build output 305 | .next 306 | out 307 | 308 | # Nuxt.js build / generate output 309 | .nuxt 310 | dist 311 | 312 | # Gatsby files 313 | .cache/ 314 | # Comment in the public line in if your project uses Gatsby and not Next.js 315 | # https://nextjs.org/blog/next-9-1#public-directory-support 316 | # public 317 | 318 | # vuepress build output 319 | .vuepress/dist 320 | 321 | # vuepress v2.x temp and cache directory 322 | .temp 323 | .cache 324 | 325 | # Docusaurus cache and generated files 326 | .docusaurus 327 | 328 | # Serverless directories 329 | .serverless/ 330 | 331 | # FuseBox cache 332 | .fusebox/ 333 | 334 | # DynamoDB Local files 335 | .dynamodb/ 336 | 337 | # TernJS port file 338 | .tern-port 339 | 340 | # Stores VSCode versions used for testing VSCode extensions 341 | .vscode-test 342 | 343 | # yarn v2 344 | .yarn/cache 345 | .yarn/unplugged 346 | .yarn/build-state.yml 347 | .yarn/install-state.gz 348 | .pnp.* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Gen Programming Language

4 | | 5 | Doc(English) 6 | | 7 | Doc(日本語) 8 | | 9 |
10 | 11 | **WARNING!! THIS LANGUAGE IS NO LONGER MAINTAINED.** 12 | 13 | Gen is an easy-to-learn, dynamic, interpreted, procedural programming language. Gen's syntax is inspired by Ruby and Python.
14 | Gen also has a simple REPL (but you need to write for loops, if statements, and functions in one line, which is possible but hard to write).
15 | And in Gen, a semicolon is the same as a new line, so you can ultimately write everthing in one line. 16 | 17 | 18 | ### TODO 19 | - [x] Basic Built-in functions 20 | - [ ] File I/O Operation 21 | - [x] Official site 22 | 23 | 24 | ### Installation 25 | > *Note:* Using `git clone` to clone the repository is discouraged. Please download the source code from the releases page 26 | ``` 27 | cd Gen/pygen 28 | make install 29 | ``` 30 | Then you can use gen: 31 | ``` 32 | gen some_file.gen 33 | ``` 34 | 35 | ### Hello World 36 | ``` 37 | println("Hello World") 38 | ``` 39 | 40 | ### Example 41 | For examples, see [examples directory](https://github.com/Gen-lang/Gen/tree/master/examples). 42 | ``` 43 | # Bubble sort 44 | 45 | defunc bubble_sort(arr) 46 | for i=0 through size(arr) then 47 | for j=0 through size(arr)-i-1 then 48 | jpls1 = j + 1 49 | if (arr@j) > (arr@jpls1) then 50 | temp = arr@j 51 | arr@j = arr@jpls1 52 | arr@jpls1 = temp 53 | end 54 | end 55 | end 56 | end 57 | 58 | 59 | array = [3734, 3732, 3810, 1649, 4952, 7993, 1225, 2728, 2849, 2113, 9883, 3839, 2839, 5463, 2741, 5684, 6848, 2834, 1838, 2483, 8384, 7885, 4853, 5848, 3838] 60 | 61 | bubble_sort(array) 62 | 63 | println(array) 64 | 65 | ``` 66 | 67 | ### Contributing 68 | Contributions are welcome! Especially, I need help bug fixing. 69 | 70 | ### Reports 71 | If you found a bug, please open a new issue and paste the error message and your code that caused the bug. 72 | 73 | ### Credits 74 | I learned a lot from this [series](https://ruslanspivak.com/lsbasi-part1/) and [T# programming language](https://github.com/Tsharp-lang/Tsharp). 75 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /docs/builtin_functions.md: -------------------------------------------------------------------------------- 1 | # Gen built-in functions 2 | 3 | I will add more built-in functions, but if you want something that's not listed here, please open an issue or contribute. 4 | 5 | > *Note:* This may be a bit outdated. 6 | 7 | | Name | Description | Example | 8 | |------| ----------- | ------- | 9 | | println | Print out the given value with a new line at the end | `println("Hello World")` 10 | | print | Similar to `println` but without a new line | `print("Hello World")` 11 | | input | Read a line from input, convert it to string, and return it | `name = input("Enter your name: ")` 12 | | import | Import a Gen file | `import("some_file.gen")` 13 | | int_input| Similar to `input` but only accepts integer | `age = int_input("Enter your age: ")` 14 | | absolute_number_of | Return the absolute number of the given integer | `num = absolute_number_of(-8)` 15 | | is_number | Check if the given value is a number | `println(is_number(48))` 16 | | is_string | Check if the given value is a string | `println(is_string("some string"))` 17 | | is_array | Check if the given value is an array | `println(is_array([1, 2, 3]))` 18 | | size | Return the number of elements in an array or a string | `println(size([1, 2, 3, 4, 5]))` 19 | | is_function | Check if the given value is a function | `println(is_function(some_func))` 20 | | typeof | Return the type of the given value | `typeof("something")` 21 | | int | Convert the given value to an integer | `int("48")` 22 | | float | Convert the given value to a float | `float("83")` 23 | | string | Convert the given value to a string | `string(383.2)` 24 | | keys | Return an array of keys of a map | `keys(map)` 25 | | values | Return an array of values of a map | `values(map)` 26 | | chars | Split the given value to characters and store it in an array | `chars("bichanna")` 27 | | exit_program | Exit the program | `exit_program()` 28 | -------------------------------------------------------------------------------- /docs/doc_en.md: -------------------------------------------------------------------------------- 1 | 2 | # Gen Syntax 3 | 4 | 5 | ### Variables 6 | Variable assignment is quite similar to Python. 7 | ``` 8 | a = "some string" 9 | b = 28 + (c = 38) 10 | println(c) 11 | ``` 12 | 13 | ### String 14 | Use " 15 | ``` 16 | str = "Hello World " 17 | println(str * 3) 18 | # output: 19 | # Hello World Hello World Hello World 20 | ``` 21 | 22 | ### Array 23 | Gen array can store any type. 24 | ``` 25 | arr = ["Hello", "World", 123, 3.1415, ["me", "gen"]] 26 | # to add a new value, just use '+' 27 | arr = arr + "bichanna" 28 | 29 | # iteration 30 | for i in arr then 31 | println(i) 32 | end 33 | 34 | a = [1, 2, 3, 4] 35 | # use '@' to retrieve specific value from an array 36 | println(a@0) # the first element 37 | println(a@-1) # the last element 38 | ``` 39 | 40 | ### Map 41 | ``` 42 | map = {"foo": "bee"} 43 | println(map@"foo") 44 | ``` 45 | 46 | ### Logical Operators 47 | Just like any other languages. 48 | ``` 49 | gen>> 1 > 10 50 | 0 51 | gen>> 1 < 10 52 | 1 53 | gen>> 2 <= 3 54 | 1 55 | gen>> 2 >= 3 56 | 0 57 | gen>> 2 == 3 58 | 0 59 | gen>> 2 == 2 60 | 1 61 | gen>> 2 != 4 62 | 1 63 | ``` 64 | 65 | ### If statement 66 | ``` 67 | age = 15 68 | if age > 18 then 69 | println("over 18") 70 | elseif age == 15 then 71 | println("15") 72 | else # notice you don't need 'then' keyword for 'else' 73 | println("??") 74 | end 75 | ``` 76 | 77 | ### For loop 78 | Maybe a bit wordy. 79 | ``` 80 | arr = [] 81 | for i = 1 through 12 step 2 then 82 | arr = arr + 2^i 83 | end 84 | println(arr) 85 | # output 86 | # [2, 8, 32, 128, 512, 2048] 87 | 88 | # iteration 89 | for i in arr then 90 | println(i) 91 | end 92 | ``` 93 | 94 | ### While loop 95 | It's quite similar to Python. 96 | ``` 97 | arr = [] 98 | a = 0 99 | while a <= 10 then 100 | arr = arr + a 101 | a = a + 1 102 | end 103 | println(arr) 104 | ``` 105 | 106 | ### Function 107 | It's a bit unique with the keyword 'defunc' (def + func) 108 | ``` 109 | # one-line function 110 | defunc greet(name) -> println("Hello " + name) 111 | 112 | # multi-line function 113 | defunc greet(name) 114 | println("Hello " + name) 115 | end 116 | 117 | # you can return from some value from function 118 | defunc return_greet(name) 119 | return_value = "Hello " + name 120 | return return_value 121 | end 122 | 123 | greet("bichanna") 124 | 125 | println(return_greet("bichanna")) 126 | ``` 127 | 128 | ### Import 129 | ``` 130 | import("some_file.gen") 131 | 132 | # then you can call functions in some_file.gen 133 | some_func_in_some_file() 134 | ``` 135 | 136 | For built-in functions see [this doc](https://github.com/Gen-lang/Gen/blob/master/doc/builtin_functions.md). 137 | 138 | -------------------------------------------------------------------------------- /docs/doc_jp.md: -------------------------------------------------------------------------------- 1 | # Gen文法 2 | 3 | ### 変数 4 | ``` 5 | a = "some string" 6 | b = 28 + (c = 38) 7 | println(c) 8 | ``` 9 | 10 | ### 文字列 11 | ``` 12 | str = "Hello 世界 " 13 | println(str * 3) 14 | # output: 15 | # Hello 世界 Hello 世界 Hello 世界 16 | ``` 17 | 18 | ### Array 19 | ``` 20 | arr = ["Hello", "World", 123, 3.1415, ["me", "gen"]] 21 | # '+' を使って値を配列に追加することができます。 22 | arr = arr + "bichanna" 23 | 24 | # iteration 25 | for i in arr then 26 | println(i) 27 | end 28 | 29 | a = [1, 2, 3, 4] 30 | # 配列から特定の値を取り出すには、'@' を使用します。 31 | println(a@0) # the first element 32 | println(a@-1) # the last element 33 | ``` 34 | 35 | ### Map 36 | ``` 37 | map = {"foo": "bee"} 38 | println(map@"foo") 39 | ``` 40 | 41 | ### 論理演算子 42 | ``` 43 | gen>> 1 > 10 44 | 0 45 | gen>> 1 < 10 46 | 1 47 | gen>> 2 <= 3 48 | 1 49 | gen>> 2 >= 3 50 | 0 51 | gen>> 2 == 3 52 | 0 53 | gen>> 2 == 2 54 | 1 55 | gen>> 2 != 4 56 | 1 57 | ``` 58 | 59 | ### If文 60 | ``` 61 | age = 15 62 | if age > 18 then 63 | println("over 18") 64 | elseif age == 15 then 65 | println("15") 66 | else # 'else' に 'then' キーワードは必要ないです。 67 | println("??") 68 | end 69 | ``` 70 | 71 | ### Forループ 72 | 文法が少し口説いかもしれないけど。 73 | ``` 74 | arr = [] 75 | for i = 1 through 12 step 2 then 76 | arr = arr + 2^i 77 | end 78 | println(arr) 79 | # output 80 | # [2, 8, 32, 128, 512, 2048] 81 | 82 | # iteration 83 | for i in arr then 84 | println(i) 85 | end 86 | ``` 87 | 88 | ### While文 89 | ``` 90 | arr = [] 91 | a = 0 92 | while a <= 10 then 93 | arr = arr + a 94 | a = a + 1 95 | end 96 | println(arr) 97 | ``` 98 | 99 | ### 関数 100 | ``` 101 | # 一行 102 | defunc greet(name) -> println("Hello " + name) 103 | 104 | # 複数行の関数 105 | defunc greet(name) 106 | println("Hello " + name) 107 | end 108 | 109 | # 'return' で関数から値を返すことができます。 110 | defunc return_greet(name) 111 | return_value = "Hello " + name 112 | return return_value 113 | end 114 | 115 | greet("bichanna") 116 | 117 | println(return_greet("bichanna")) 118 | ``` 119 | 120 | ### Import 121 | ``` 122 | import("some_file.gen") 123 | 124 | # 上のようにインポートすると、some_file.gen にある関数を呼び出すことができます。 125 | some_func_in_some_file() 126 | ``` 127 | 128 | [組み込み関数。](https://github.com/Gen-lang/Gen/blob/master/doc/builtin_functions.md) 129 | 130 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
6 | 7 | > *Note:* **WARNING!! THIS LANGUAGE IS IN DEVELOPMENT. ANYTHING CAN CHANGE AT ANY MOMENT.** 8 | 9 | ## About 10 | Gen is a brand new, easy-to-learn, dynamic, interpreted, procedural, programming language by [bichanna](https://github.com/bichanna) and others.
11 | Gen's syntax is greatly inspired by Ruby and Python. But one unique thing in Gen is the use of `@`. It also has a simple REPL (but you need to write for loops, if statements, and functions in one line, which is possible but hard to write).
12 | The language is created from scratch using Python (working on an implementation in C). 13 | 14 | 15 | ## Hello World 16 | It's just one line without any entry function. 17 | ``` 18 | println("Hello World") 19 | ``` 20 | 21 | ## Example 22 | ``` 23 | # Fizzbuzz 24 | 25 | for fizzbuzz = 0 through 15000 then 26 | if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0 then 27 | println("fizzbuzz") 28 | continue 29 | elseif fizzbuzz % 3 == 0 then 30 | println("fizz") 31 | continue 32 | elseif fizzbuzz % 5 == 0 then 33 | println("buzz") 34 | continue 35 | end 36 | end 37 | ``` 38 | 39 | 40 | ### Current State 41 | Gen has many features you would expect: 42 | - All the operators (`+`, `-`, `^`, `%`, `and`, `<=`, etc.) 43 | - Flow control (`if`, `elseif`, `for`/`while` loop) 44 | - Array 45 | - Map 46 | - Function 47 | - Basic built-in functions 48 | 49 | 50 | ### Contributing 51 | Contributions are always welcome! Especially, I need help bug fixing. 52 | -------------------------------------------------------------------------------- /editor/gen.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " Language: Gen 3 | 4 | " Usage Instructions 5 | " Put this file to ~/.vim/syntax directory: 6 | " (if you are on Mac) cp editor/gen.vim ~/.vim/syntax/ 7 | " And add the following line to your ~/.vimrc: 8 | " autocmd BufRead,BufNewFile *.gen set filetype=gen 9 | 10 | if exists("b:current_syntax") 11 | finish 12 | endif 13 | 14 | " Language keywords 15 | syntax keyword genKeywords or and not if elseif else then for through step while defunc end return continue break in 16 | 17 | " Type keywords 18 | syntax keyword genType int float string null 19 | 20 | " Boolean 21 | syntax keyword genBool true false 22 | 23 | " Numbers 24 | syntax match genNumbers "\d\+" 25 | 26 | " Set highlights 27 | highlight default link genKeywords Repeat 28 | highlight default link genNumbers Number 29 | highlight default link genType Type 30 | highlight default link genBool Boolean 31 | 32 | let b:current_syntax = "gen" -------------------------------------------------------------------------------- /examples/bubble_sort.gen: -------------------------------------------------------------------------------- 1 | # Bubble sort 2 | 3 | defunc bubble_sort(arr) 4 | for i=0 through size(arr) then 5 | for j=0 through size(arr)-i-1 then 6 | jpls1 = j + 1 7 | if (arr@j) > (arr@jpls1) then 8 | temp = arr@j 9 | arr@j = arr@jpls1 10 | arr@jpls1 = temp 11 | end 12 | end 13 | end 14 | return arr 15 | end 16 | 17 | 18 | array = [3734, 3732, 3810, 1649, 4952, 7993, 1225, 2728, 2849, 2113, 9883, 3839, 2839, 5463, 2741, 5684, 6848, 2834, 1838, 2483, 8384, 7885, 4853, 5848, 3838] 19 | 20 | sorted_arr = bubble_sort(array) 21 | 22 | println(sorted_arr) 23 | -------------------------------------------------------------------------------- /examples/factorial.gen: -------------------------------------------------------------------------------- 1 | # Factorial 2 | 3 | number = int_input("Enter an integer: ") 4 | 5 | factorial = 1 6 | 7 | if number < 0 then 8 | println("Please enter a positive interger") 9 | elseif number == 0 then 10 | println(1) 11 | else 12 | for i = 1 through (number + 1) then 13 | factorial = factorial * i 14 | end 15 | println("The factorial of " + number + " is " + factorial) 16 | end -------------------------------------------------------------------------------- /examples/fibonacci.gen: -------------------------------------------------------------------------------- 1 | # the Fibonacci sequence 2 | 3 | n = int_input("How many terms: ") 4 | 5 | n1 = 0; n2 = 1; count = 0 6 | 7 | if n <= 0 then 8 | println("Please enter a positive interger.") 9 | elseif n == 1 then 10 | println(n) 11 | else 12 | while count < n then 13 | println(n1) 14 | nth = n1 + n2 15 | n1 = n2 16 | n2 = nth 17 | count = count + 1 18 | end 19 | end -------------------------------------------------------------------------------- /examples/fizzbuzz.gen: -------------------------------------------------------------------------------- 1 | # Fizzbuzz 2 | 3 | for fizzbuzz = 0 through 15000 then 4 | if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0 then 5 | println("fizzbuzz") 6 | continue 7 | elseif fizzbuzz % 3 == 0 then 8 | println("fizz") 9 | continue 10 | elseif fizzbuzz % 5 == 0 then 11 | println("buzz") 12 | continue 13 | end 14 | end -------------------------------------------------------------------------------- /examples/func.gen: -------------------------------------------------------------------------------- 1 | defunc greet(name) 2 | println("Hello " + name + "!") 3 | end 4 | 5 | some_var = "some string" -------------------------------------------------------------------------------- /examples/import.gen: -------------------------------------------------------------------------------- 1 | import("func.gen") 2 | 3 | greet("bichanna") -------------------------------------------------------------------------------- /examples/map.gen: -------------------------------------------------------------------------------- 1 | foo = [{"a": "B", "c": "D"}, {"e": "F", "g": "H"}] 2 | 3 | foo@0 = "Hello World" 4 | 5 | println(foo) -------------------------------------------------------------------------------- /pygen/Makefile: -------------------------------------------------------------------------------- 1 | # Usage 2 | # Just type 'make' or 'make install' 3 | 4 | install: 5 | ifeq ($(OS),Windows_NT) 6 | @pip install pyinstaller 7 | @pyinstaller .\main.py --onefile 8 | @COPY ".\dist\main.exe" ".\gen.exe" 9 | # Set environment variable here 10 | @echo "PyGen Compilation Succeeded" 11 | @echo "Type 'gen'" 12 | else 13 | @pip install pyinstaller 14 | @pyinstaller ./main.py --onefile 15 | @cp ./dist/main /usr/local/bin/gen 16 | @cp ../editor/gen.vim ~/.vim/syntax 17 | @echo "autocmd BufRead,BufNewFile *.gen set filetype=gen" >> ~/.vimrc 18 | @echo "\033[0;32mPyGen Compilation Succeeded" 19 | @echo "\033[0;32mType 'gen'" 20 | endif 21 | -------------------------------------------------------------------------------- /pygen/main.py: -------------------------------------------------------------------------------- 1 | import readline # this is necessary: DO NOT REMOVE 2 | import sys 3 | import signal 4 | from src.value import Number 5 | from src.builtin_func import BuiltinFunction 6 | from src.lexer import Lexer 7 | from src.parser import Parser 8 | from src.evaluator import Evaluator 9 | from src.context import Context 10 | from src.symbol_table import SymbolTable 11 | 12 | def set_default_symbol_table(symbol_table): 13 | symbol_table.set("null", Number.null) 14 | symbol_table.set("true", Number.true) 15 | symbol_table.set("false", Number.false) 16 | symbol_table.set("Pi", Number.Pi) 17 | # built-in functions 18 | symbol_table.set("println", BuiltinFunction.println) 19 | symbol_table.set("print", BuiltinFunction.print) 20 | symbol_table.set("input", BuiltinFunction.input) 21 | symbol_table.set("int_input", BuiltinFunction.int_input) 22 | symbol_table.set("absolute_number_of", BuiltinFunction.absolute_number_of) 23 | symbol_table.set("is_number", BuiltinFunction.is_number) 24 | symbol_table.set("is_string", BuiltinFunction.is_string) 25 | symbol_table.set("is_array", BuiltinFunction.is_array) 26 | symbol_table.set("is_function", BuiltinFunction.is_function) 27 | symbol_table.set("exit_program", BuiltinFunction.exit_program) 28 | symbol_table.set("size", BuiltinFunction.size) 29 | symbol_table.set("typeof", BuiltinFunction.typeof) 30 | symbol_table.set("int", BuiltinFunction.int) 31 | symbol_table.set("float", BuiltinFunction.float) 32 | symbol_table.set("string", BuiltinFunction.string) 33 | symbol_table.set("chars", BuiltinFunction.chars) 34 | symbol_table.set("split", BuiltinFunction.split) 35 | symbol_table.set("import", BuiltinFunction.import_) 36 | symbol_table.set("clear", BuiltinFunction.clear) 37 | symbol_table.set("keys", BuiltinFunction.keys) 38 | symbol_table.set("values", BuiltinFunction.values) 39 | symbol_table.set("read", BuiltinFunction.read) 40 | return symbol_table 41 | 42 | global_symbol_table = SymbolTable() 43 | global_symbol_table = set_default_symbol_table(global_symbol_table) 44 | 45 | def run(filename, text, show_tokens=False): 46 | # generate tokens 47 | lexer = Lexer(filename, text) 48 | tokens, err = lexer.make_tokens() 49 | if err is not None: return None, err 50 | if show_tokens: print(tokens) 51 | 52 | # generate AST 53 | parser = Parser(tokens) 54 | ast = parser.parse() 55 | if ast.error: return None, ast.error 56 | # print(ast.node.element_nodes) 57 | 58 | # call evaluator 59 | evaluator = Evaluator() 60 | context = Context("") 61 | context.symbol_table = global_symbol_table 62 | result = evaluator.visit(ast.node, context) 63 | if result is None: 64 | exit() 65 | return result.value, result.error 66 | 67 | def shell(): 68 | while True: 69 | try: 70 | t = input(">> ") 71 | except EOFError: 72 | ctrl_c_handler(None) 73 | if t.strip() == "": continue 74 | result, err = run("", t) 75 | if err is not None: 76 | print(err) 77 | elif result: 78 | if len(result.elements) == 1: 79 | print(result.elements[0]) 80 | else: 81 | print(result.__repr__()) 82 | 83 | def file(filename, show_tokens): 84 | try: 85 | with open(filename, "r") as fobj: 86 | code = fobj.read() 87 | except Exception: 88 | print(f"Could not open file '{filename}'.") 89 | sys.exit() 90 | _, error = run(filename, code, show_tokens) 91 | if error is not None: print(error) 92 | 93 | def ctrl_c_handler(*_): 94 | print("\nBye bye!") 95 | sys.exit() 96 | 97 | if __name__ == "__main__": 98 | # for catching Ctrl-C 99 | signal.signal(signal.SIGINT, ctrl_c_handler) 100 | 101 | if len(sys.argv) < 2 or sys.argv[-1].endswith(".py"): 102 | shell() 103 | else: 104 | show_tokens = False 105 | if "--show-tokens" in sys.argv: 106 | show_tokens = True 107 | filename = sys.argv[-1] 108 | if filename.endswith(".gen"): 109 | file(filename, show_tokens) 110 | else: 111 | print("Specify a file with .gen extension.") 112 | -------------------------------------------------------------------------------- /pygen/src/builtin_func.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import platform 4 | from src.lexer import Lexer 5 | from src.parser import Parser 6 | from src.value import * 7 | from src.evaluator import RuntimeResult, RuntimeError 8 | 9 | class BuiltinFunction(BaseFunction): 10 | def __init__(self, name): 11 | super().__init__(name) 12 | 13 | def execute(self, args): 14 | res = RuntimeResult() 15 | context = self.generate_new_context() 16 | method = getattr(self, f"execute_{self.name}", self.no_visit_method) 17 | res.register(self.check_and_fill_args(method.arg_names, args, context)) 18 | if res.error: return res 19 | return_value = res.register(method(context)) 20 | if res.error: return res 21 | return res.success(return_value) 22 | 23 | def no_visit_method(self, node, context): 24 | raise Exception(f"execute_{self.name} is not defined") 25 | 26 | def copy(self): 27 | copy = BuiltinFunction(self.name) 28 | copy.set_context(self.context) 29 | copy.set_position(self.pos_start, self.pos_end) 30 | return copy 31 | 32 | def __repr__(self): 33 | return f"" 34 | 35 | def return_type(self): 36 | return String("built-in function") 37 | 38 | ###################################### 39 | ######### BUILT-IN FUNCTIONS ######### 40 | ###################################### 41 | 42 | def execute_println(self, context): 43 | """ 44 | print the value passed in with a new line at the end 45 | example: println("Hello World") 46 | """ 47 | print(str(context.symbol_table.get("value"))) 48 | return RuntimeResult().success(Number.null) 49 | execute_println.arg_names = ["value"] 50 | 51 | def execute_print(self, context): 52 | """ 53 | print the value passed in without a new line at the end 54 | example: print("Hello World!") 55 | """ 56 | print(str(context.symbol_table.get("value")), end="") 57 | return RuntimeResult().success(Number.null) 58 | execute_print.arg_names = ["value"] 59 | 60 | def execute_input(self, context): 61 | """ 62 | read a line from input, convert it to String, and return it 63 | example: value = input("Enter your name: ") 64 | """ 65 | text = "" 66 | try: 67 | text = str(context.symbol_table.get("text")) 68 | except: 69 | pass 70 | input_value = input(text) 71 | return RuntimeResult().success(String(input_value)) 72 | execute_input.arg_names = ["text"] 73 | 74 | def execute_int_input(self, context): 75 | """ 76 | read a line from input, try to convert it to Number, and return it 77 | example 1: value = int_input("Enter a value: ") 78 | """ 79 | text = str(context.symbol_table.get("text")) 80 | error_text = "Input value must be an integer." 81 | while True: 82 | input_value = input(text) 83 | try: 84 | input_value = int(input_value) 85 | break 86 | except ValueError: 87 | print(error_text) 88 | return RuntimeResult().success(Number(input_value)) 89 | execute_int_input.arg_names = ["text"] 90 | 91 | def execute_absolute_number_of(self, context): 92 | """ 93 | try to return the absolute number of the value passed in 94 | example: abs_num = absolute_number_of(-9) 95 | """ 96 | value = context.symbol_table.get("value") 97 | try: 98 | value = int(context.symbol_table.get("value").value) 99 | except ValueError: 100 | return RuntimeResult().failure(RuntimeError( 101 | self.pos_start, self.pos_end, f"{value} does not have an absolute number", context 102 | )) 103 | return RuntimeResult().success(Number(abs(value))) 104 | execute_absolute_number_of.arg_names = ["value"] 105 | 106 | def execute_is_number(self, context): 107 | """ 108 | check if the value passed in is a number 109 | example: is_number(3) 110 | """ 111 | value = context.symbol_table.get("value") 112 | is_number = isinstance(value, Number) 113 | return RuntimeResult().success(Number.true if is_number is True else Number.false) 114 | execute_is_number.arg_names = ["value"] 115 | 116 | def execute_is_string(self, context): 117 | """ 118 | check if the value passed in is a string 119 | example: is_string("Hello World") 120 | """ 121 | value = context.symbol_table.get("value") 122 | is_string = isinstance(value, String) 123 | return RuntimeResult().success(Number.true if is_string is True else Number.false) 124 | execute_is_string.arg_names = ["value"] 125 | 126 | def execute_is_array(self, context): 127 | """ 128 | check if the value passed in is an array 129 | example: is_array([1, 2, 3]) 130 | """ 131 | value = context.symbol_table.get("value") 132 | is_array = isinstance(value, Array) 133 | return RuntimeResult().success(Number.true if is_array is True else Number.false) 134 | execute_is_array.arg_names = ["value"] 135 | 136 | def execute_is_function(self, context): 137 | """ 138 | check if the value passed in is a function 139 | example: is_function(some_func) 140 | """ 141 | value = context.symbol_table.get("value") 142 | is_function = isinstance(value, BaseFunction) 143 | return RuntimeResult().success(Number.true if is_function is True else Number.false) 144 | execute_is_function.arg_names = ["value"] 145 | 146 | def execute_is_map(self, context): 147 | """ 148 | check if the given value is a map or not 149 | """ 150 | value = context.symbol_table.get("value") 151 | is_map = isinstance(value, Map) 152 | return RuntimeResult().success(Number.true if is_map is True else Number.false) 153 | 154 | def execute_exit_program(self, context): 155 | """ 156 | exit the program 157 | example: exit_program() 158 | """ 159 | sys.exit() 160 | execute_exit_program.arg_names = [] 161 | 162 | def execute_size(self, context): 163 | """ 164 | return the size of the value 165 | example: size([1, 2, 3]) 166 | """ 167 | value = context.symbol_table.get("value") 168 | if isinstance(value, Number) or isinstance(value, Map): 169 | return RuntimeResult().failure(RuntimeError( 170 | self.pos_start, self.pos_end, "The argument should be string or array", context 171 | )) 172 | else: 173 | return RuntimeResult().success(Number(len(value.elements) if isinstance(value, Array) else len(value.value))) 174 | execute_size.arg_names = ["value"] 175 | 176 | def execute_typeof(self, context): 177 | """ 178 | return the type of the given value 179 | example: def return_type("string") 180 | """ 181 | value = context.symbol_table.get("value") 182 | return RuntimeResult().success(value.return_type()) 183 | execute_typeof.arg_names = ["value"] 184 | 185 | def execute_int(self, context): 186 | """ 187 | convert the given value to integer type 188 | example: int("3") 189 | """ 190 | value = context.symbol_table.get("value") 191 | if isinstance(value, Array) or isinstance(value, Map): 192 | return RuntimeResult().failure(RuntimeError( 193 | self.pos_start, self.pos_end, "Argument should not be an array or a map", context 194 | )) 195 | try: 196 | int_value = int(value.value) 197 | except: 198 | return RuntimeResult().failure(RuntimeError( 199 | self.pos_start, self.pos_end, f"{value.value} cannot be converted to integer", context 200 | )) 201 | return RuntimeResult().success(Number(int_value)) 202 | execute_int.arg_names = ["value"] 203 | 204 | def execute_float(self, context): 205 | """ 206 | convert the given value to float 207 | example: float(4) 208 | """ 209 | value = context.symbol_table.get("value") 210 | if isinstance(value, Array) or isinstance(value, Map): 211 | return RuntimeResult().failure(RuntimeError( 212 | self.pos_start, self.pos_end, "Arguement should not be an array or a map", context 213 | )) 214 | try: 215 | float_value = float(value.value) 216 | except: 217 | return RuntimeResult().failure(RuntimeError( 218 | self.pos_start, self.pos_end, f"{value.value} cannot be converted to float", context 219 | )) 220 | return RuntimeResult().success(Number(float_value)) 221 | execute_float.arg_names = ["value"] 222 | 223 | def execute_string(self, context): 224 | """ 225 | convert the given value to string 226 | example: string(344.3) 227 | """ 228 | value = context.symbol_table.get("value") 229 | if isinstance(value, Map) or isinstance(value, Array): 230 | return RuntimeResult().failure(RuntimeError( 231 | self.pos_start, self.pos_end, "Argument should not be an array or a map", context 232 | )) 233 | new_value = str(value.value) 234 | return RuntimeResult().success(String(new_value)) 235 | execute_string.arg_names = ["value"] 236 | 237 | def execute_chars(self, context): 238 | """ 239 | convert the given value to array 240 | example 1: chars("some string") 241 | example 2: chars(123) 242 | """ 243 | value = context.symbol_table.get("value") 244 | if isinstance(value, Array) or isinstance(value, Map): 245 | return RuntimeResult().failure(RuntimeError( 246 | self.pos_start, self.pos_end, "Argument should not be an array or a map", context 247 | )) 248 | lst = [] 249 | for i in str(value.value): 250 | lst.append(String(i)) 251 | return RuntimeResult().success(Array(lst)) 252 | execute_chars.arg_names = ["value"] 253 | 254 | def execute_split(self, context): 255 | """ 256 | split the given string 257 | example: split("Bob,Sue,John", ",") 258 | """ 259 | value = context.symbol_table.get("value") 260 | delimiter = context.symbol_table.get("delimiter") 261 | if isinstance(value, Array) or isinstance(value, Map) or not isinstance(value, String) or isinstance(delimiter, Array) or isinstance(delimiter, Map) or not isinstance(delimiter, String): 262 | return RuntimeResult().failure(RuntimeError( 263 | self.pos_start, self.pos_end, "Both arguments should be the type of string", context 264 | )) 265 | lst = value.value.split(delimiter.value) 266 | return RuntimeResult().success(Array(lst)) 267 | execute_split.arg_names = ["value", "delimiter"] 268 | 269 | def execute_import(self, context): 270 | """ 271 | import the specified file 272 | example: import("some_file.gen") 273 | some_function() 274 | """ 275 | filename = context.symbol_table.get("filename") 276 | if not isinstance(filename, String): 277 | return RuntimeResult().failure(RuntimeError( 278 | self.pos_start, self.pos_end, "Argument should be the type of string", context 279 | )) 280 | filename = filename.value 281 | try: 282 | with open(filename, "r") as fobj: 283 | code = fobj.read() 284 | except Exception: 285 | return RuntimeResult().failure(RuntimeError( 286 | self.pos_start, self.pos_end, f"Could not open file'{filename}'", context 287 | )) 288 | 289 | # generate tokens 290 | lexer = Lexer(filename, code) 291 | tokens, err = lexer.make_tokens() 292 | if err is not None: return None, err 293 | 294 | # generate AST 295 | parser = Parser(tokens) 296 | ast = parser.parse() 297 | if ast.error: return None, ast.error 298 | 299 | evaluator = Evaluator() 300 | new_symbol_table = evaluator.visit(ast.node, context, only_return_symtable=True) 301 | 302 | for k, v in new_symbol_table.symbols.items(): 303 | self.context.symbol_table.set(k, v) 304 | return RuntimeResult().success(Number.null) 305 | 306 | # create keys and values 307 | 308 | # Another way 309 | # new_map = Map(new_symbol_table.symbols) 310 | # return RuntimeResult().success(new_map) 311 | execute_import.arg_names = ["filename"] 312 | 313 | def execute_clear(self, context): 314 | """ 315 | clear the terminal (console) 316 | example: clear() 317 | """ 318 | if platform.system() == "Darwin" or platform.system() == "Linux": 319 | os.system("clear") 320 | elif platform.system() == "Windows": 321 | os.system("cls") 322 | return RuntimeResult().success(Number.null) 323 | execute_clear.arg_names = [] 324 | 325 | def execute_keys(self, context): 326 | """ 327 | return an array of keys in a map 328 | example: arr = keys(map) 329 | """ 330 | map = context.symbol_table.get("map") 331 | if not isinstance(map, Map): 332 | return RuntimeResult().failure(RuntimeError( 333 | self.pos_start, self.pos_end, "Argument should be a map", context 334 | )) 335 | lst = [] 336 | for i in list(map.map.keys()): 337 | if isinstance(i, int) or isinstance(i, float): 338 | lst.append(Number(i)) 339 | else: 340 | lst.append(String(i)) 341 | return RuntimeResult().success(Array(lst)) 342 | execute_keys.arg_names = ["map"] 343 | 344 | def execute_values(self, context): 345 | """ 346 | return an array of values in a map 347 | example: arr = values(map) 348 | """ 349 | map = context.symbol_table.get("map") 350 | if not isinstance(map, Map): 351 | return RuntimeResult().failure(RuntimeError( 352 | self.pos_start, self.pos_end, "Argument should be a map", context 353 | )) 354 | lst = [] 355 | for i in list(map.map.values()): 356 | if isinstance(i, int) or isinstance(i, float): 357 | lst.append(Number(i)) 358 | else: 359 | lst.append(String(i)) 360 | return RuntimeResult().success(Array(lst)) 361 | execute_values.arg_names = ["map"] 362 | 363 | def execute_read(self, context): 364 | """ 365 | return the specified file content in string 366 | example: content = read("file.txt") 367 | """ 368 | filename = context.symbol_table.get("filename") 369 | if not isinstance(filename, String): 370 | return RuntimeResult().failure(RuntimeError( 371 | self.pos_start, self.pos_end, "Argument should be the type of string", context 372 | )) 373 | filename = filename.value 374 | try: 375 | fobj = open(filename, "r+") 376 | text = fobj.read() 377 | fobj.close() 378 | except Exception: 379 | return RuntimeResult().failure(RuntimeError( 380 | self.pos_start, self.pos_end, f"Could not open file'{filename}'", context 381 | )) 382 | return RuntimeResult().success(String(text)) 383 | execute_read.arg_names = ["filename"] 384 | 385 | BuiltinFunction.println = BuiltinFunction("println") 386 | BuiltinFunction.print = BuiltinFunction("print") 387 | BuiltinFunction.input = BuiltinFunction("input") 388 | BuiltinFunction.int_input = BuiltinFunction("int_input") 389 | BuiltinFunction.absolute_number_of = BuiltinFunction("absolute_number_of") 390 | BuiltinFunction.is_number = BuiltinFunction("is_number") 391 | BuiltinFunction.Pi = BuiltinFunction("Pi") 392 | BuiltinFunction.is_string = BuiltinFunction("is_string") 393 | BuiltinFunction.is_array = BuiltinFunction("is_array") 394 | BuiltinFunction.is_function = BuiltinFunction("is_function") 395 | BuiltinFunction.exit_program = BuiltinFunction("exit_program") 396 | BuiltinFunction.size = BuiltinFunction("size") 397 | BuiltinFunction.typeof = BuiltinFunction("typeof") 398 | BuiltinFunction.int = BuiltinFunction("int") 399 | BuiltinFunction.float = BuiltinFunction("float") 400 | BuiltinFunction.string = BuiltinFunction("string") 401 | BuiltinFunction.chars = BuiltinFunction("chars") 402 | BuiltinFunction.split = BuiltinFunction("split") 403 | BuiltinFunction.import_ = BuiltinFunction("import") 404 | BuiltinFunction.clear = BuiltinFunction("clear") 405 | BuiltinFunction.keys = BuiltinFunction("keys") 406 | BuiltinFunction.values = BuiltinFunction("values") 407 | BuiltinFunction.read = BuiltinFunction("read") -------------------------------------------------------------------------------- /pygen/src/context.py: -------------------------------------------------------------------------------- 1 | class Context: 2 | def __init__(self, display_name, parent=None, parent_entry_pos=None): 3 | self.display_name = display_name 4 | self.parent = parent 5 | self.parent_entry_pos = parent_entry_pos 6 | self.symbol_table = None -------------------------------------------------------------------------------- /pygen/src/error.py: -------------------------------------------------------------------------------- 1 | from src.utils import string_with_arrows 2 | 3 | class Error: 4 | def __init__(self, pos_start, pos_end, error_name, details): 5 | self.pos_start = pos_start 6 | self.pos_end = pos_end 7 | self.error_name = error_name 8 | self.details = details 9 | 10 | def __str__(self): 11 | string = f"File {self.pos_start.filename}, line {self.pos_start.lnum+1}\n" 12 | string += f"Gen::{self.error_name}: {self.details}" 13 | string += f"\n\n" + string_with_arrows(self.pos_start.filetext, self.pos_start, self.pos_end) 14 | return string 15 | 16 | 17 | class TypeCharError(Error): 18 | def __init__(self, pos_start, pos_end, details): 19 | super().__init__(pos_start, pos_end, "TypeCharError", details) 20 | 21 | 22 | class InvalidSyntaxError(Error): 23 | def __init__(self, pos_start, pos_end, details=""): 24 | super().__init__(pos_start, pos_end, "InvalidSyntaxError", details) 25 | 26 | 27 | class RuntimeError(Error): 28 | def __init__(self, pos_start, pos_end, details, context): 29 | super().__init__(pos_start, pos_end, "RuntimeError", details) 30 | self.context = context 31 | 32 | def __str__(self): 33 | string = self.generate_traceback() 34 | string += f"Gen::{self.error_name}: {self.details}" 35 | string += f"\n\n" + string_with_arrows(self.pos_start.filetext, self.pos_start, self.pos_end) 36 | return string 37 | 38 | def generate_traceback(self): 39 | result = "" 40 | position = self.pos_start 41 | context = self.context 42 | while context: 43 | result = f" File {position.filename}, line {position.lnum+1}, in {context.display_name}\n" + result 44 | position = context.parent_entry_pos 45 | context = context.parent 46 | 47 | return "Traceback (most recent call last):\n" + result 48 | -------------------------------------------------------------------------------- /pygen/src/evaluator.py: -------------------------------------------------------------------------------- 1 | import src.gen_token as tk 2 | import src.value as value 3 | import src.node as nd 4 | from src.error import RuntimeError 5 | 6 | class RuntimeResult: 7 | def __init__(self): 8 | self.reset() 9 | 10 | def reset(self): 11 | self.value = None 12 | self.error = None 13 | self.func_return_value = None 14 | self.loop_continue = False 15 | self.loop_break = False 16 | 17 | def register(self, result): 18 | self.error = result.error 19 | self.func_return_value = result.func_return_value 20 | self.loop_continue = result.loop_continue 21 | self.loop_break = result.loop_break 22 | return result.value 23 | 24 | def success(self, value): 25 | self.reset() 26 | self.value = value 27 | return self 28 | 29 | def success_return(self, value): 30 | self.reset() 31 | self.func_return_value = value 32 | return self 33 | 34 | def success_continue(self): 35 | self.reset() 36 | self.loop_continue = True 37 | return self 38 | 39 | def success_break(self): 40 | self.reset() 41 | self.loop_break = True 42 | return self 43 | 44 | def should_return(self): 45 | return (self.error or self.func_return_value or self.loop_continue or self.loop_break) 46 | 47 | def failure(self, error): 48 | self.reset() 49 | self.error = error 50 | return self 51 | 52 | 53 | class Evaluator: 54 | def visit(self, node, context, only_return_symtable=False): 55 | if isinstance(node, type(None)) is False: 56 | method_to_be_called = f"visit_{type(node).__name__}" 57 | method = getattr(self, method_to_be_called, self.no_visit_method) 58 | if only_return_symtable is False: return method(node, context) 59 | else: 60 | method(node, context) 61 | return context.symbol_table 62 | return None 63 | 64 | def no_visit_method(self, node, context): 65 | raise Exception(f"No visit_{type(node).__name__} method defined.") 66 | 67 | def visit_VarAccessNode(self, node, context): 68 | res = RuntimeResult() 69 | var_name = node.var_name_token.value 70 | value = context.symbol_table.get(var_name) 71 | if value is None: return res.failure(RuntimeError( 72 | node.pos_start, node.pos_end, f"'{var_name}' is not defined", context 73 | )) 74 | value = value.copy().set_position(node.pos_start, node.pos_end) 75 | return res.success(value) 76 | 77 | def visit_VarAssignNode(self, node, context): 78 | res = RuntimeResult() 79 | var_name = node.var_name_token.value 80 | value = res.register(self.visit(node.value_node, context)) 81 | if res.should_return(): return res 82 | context.symbol_table.set(var_name, value) 83 | return res.success(value) 84 | 85 | def visit_ReassignNode(self, node, context): 86 | res = RuntimeResult() 87 | if isinstance(node.var_name_token, list): 88 | return res.failure(RuntimeError( 89 | node.pos_start, node.pos_end, "Modifying an array directly is not allowed", context 90 | )) 91 | elif isinstance(node.var_name_token, dict): 92 | return res.failure(RuntimeError( 93 | node.pos_start, node.pos_end, "Modifying a map directly is not allowed", context 94 | )) 95 | else: 96 | var_name = node.var_name_token.value 97 | index_or_key = res.register(self.visit(node.index_or_key, context)) 98 | if res.should_return(): return res 99 | new_value = res.register(self.visit(node.value_node, context)) 100 | if res.should_return(): return res 101 | if isinstance(context.symbol_table.symbols[var_name], value.Array): 102 | if len(context.symbol_table.symbols[var_name].elements) > index_or_key.value: 103 | context.symbol_table.set_arr(var_name, index_or_key, new_value) 104 | else: 105 | return res.failure(RuntimeError( 106 | node.pos_start, node.pos_end, f"Element at index {index_or_key.value} does not exist", context 107 | )) 108 | elif isinstance(context.symbol_table.symbols[var_name], value.Map): 109 | context.symbol_table.set_map(var_name, index_or_key, new_value) 110 | else: 111 | return res.failure(RuntimeError( 112 | node.pos_start, node.pos_end, "Hmm, that does not work.", context 113 | )) 114 | return res.success(new_value) 115 | 116 | def visit_IfNode(self, node, context): 117 | res = RuntimeResult() 118 | for condition, expression, should_return_null in node.cases: 119 | condition_value = res.register(self.visit(condition, context)) 120 | if res.should_return(): return res 121 | if condition_value.is_true(): 122 | expr_value = res.register(self.visit(expression, context)) 123 | if res.should_return(): return res 124 | return res.success(value.Number.null if should_return_null else expr_value) 125 | if node.else_case is not None: 126 | expr, should_return_null = node.else_case 127 | else_value = res.register(self.visit(expr, context)) 128 | if res.should_return(): return res 129 | return res.success(value.Number.null if should_return_null else else_value) 130 | return res.success(value.Number.null) 131 | 132 | def visit_NumberNode(self, node, context): 133 | return RuntimeResult().success(value.Number(node.token.value).set_context(context).set_position(node.pos_start, node.pos_end)) 134 | 135 | def visit_BinOpNode(self, node, context): 136 | res = RuntimeResult() 137 | left = res.register(self.visit(node.left_node, context)) 138 | if res.should_return(): return res 139 | right = res.register(self.visit(node.right_node, context)) 140 | if res.should_return(): return res 141 | # check the operator type 142 | if node.op_token.type == tk.TT_PLUS: 143 | result, err = left.added_to(right) 144 | elif node.op_token.type == tk.TT_MINUS: 145 | result, err = left.subtracted_by(right) 146 | elif node.op_token.type == tk.TT_AT: 147 | result, err = left.at(right) 148 | elif node.op_token.type == tk.TT_MULT: 149 | result, err = left.multiplied_by(right) 150 | elif node.op_token.type == tk.TT_DIV: 151 | result, err = left.divided_by(right) 152 | elif node.op_token.type == tk.TT_POWER: 153 | result, err = left.powered_by(right) 154 | elif node.op_token.type == tk.TT_MODULO: 155 | result, err = left.modulo(right) 156 | elif node.op_token.type == tk.TT_DEQUALS: 157 | result, err = left.get_comparison_equal(right) 158 | elif node.op_token.type == tk.TT_NEQUALS: 159 | result, err = left.get_comparison_not_equal(right) 160 | elif node.op_token.type == tk.TT_LTHAN: 161 | result, err = left.get_comparison_less_than(right) 162 | elif node.op_token.type == tk.TT_GTHAN: 163 | result, err = left.get_comparison_greater_than(right) 164 | elif node.op_token.type == tk.TT_LTEQUALS: 165 | result, err = left.get_comparison_lt_equals(right) 166 | elif node.op_token.type == tk.TT_GTEQUALS: 167 | result, err = left.get_comparison_gt_equals(right) 168 | elif node.op_token.matches(tk.TT_KEYWORD, "and"): 169 | result, err = left.and_by(right) 170 | elif node.op_token.matches(tk.TT_KEYWORD, "or"): 171 | result, err = left.or_by(right) 172 | 173 | return res.failure(err) if err is not None else res.success(result.set_position(node.pos_start, node.pos_end)) 174 | 175 | def visit_UnaryOpNode(self, node, context): 176 | res = RuntimeResult() 177 | num = res.register(self.visit(node.node, context)) 178 | if res.should_return(): return res 179 | err = None 180 | if node.op_token.type == tk.TT_MINUS: 181 | num, err = num.multiplied_by(value.Number(-1)) 182 | elif node.op_token.matches(tk.TT_KEYWORD, "not"): 183 | num, err = num.notted() 184 | 185 | return res.failure(err) if err is not None else res.success(num.set_position(node.pos_start, node.pos_end)) 186 | 187 | def visit_ForNode(self, node, context): 188 | res = RuntimeResult() 189 | elements = [] 190 | start_value = res.register(self.visit(node.start_value_node, context)) 191 | if res.should_return(): return res 192 | end_value = res.register(self.visit(node.end_value_node, context)) 193 | if res.should_return(): return res 194 | if node.step_value_node: 195 | step_value = res.register(self.visit(node.step_value_node, context)) 196 | if res.should_return(): return res 197 | else: 198 | step_value = value.Number(1) 199 | sv = start_value.value 200 | if step_value.value >= 0: 201 | condition = lambda: sv < end_value.value 202 | else: 203 | condition = lambda: sv > end_value.value 204 | while condition(): 205 | context.symbol_table.set(node.var_name_token.value, value.Number(sv)) 206 | sv += step_value.value 207 | val = res.register(self.visit(node.body_node, context)) 208 | if res.should_return() and res.loop_continue is False and res.loop_break is False: return res 209 | if res.loop_continue is True: 210 | continue 211 | elif res.loop_break is True: 212 | break 213 | else: 214 | elements.append(val) 215 | return res.success(value.Number.null if node.should_return_null else value.Array(elements).set_context(context).set_position(node.pos_start, node.pos_end)) 216 | 217 | def visit_ForInNode(self, node, context): 218 | res = RuntimeResult() 219 | to_be_iterated = res.register(self.visit(node.array_elements, context)) 220 | if res.should_return(): return res 221 | if isinstance(to_be_iterated, value.Array): 222 | for item in to_be_iterated.elements: 223 | context.symbol_table.set(node.var_name_token.value, item) 224 | val = res.register(self.visit(node.body_node, context)) 225 | if res.should_return() and res.loop_continue is False and res.loop_break is False: return res 226 | if res.loop_continue is True: continue 227 | elif res.loop_break is True: break 228 | elif isinstance(to_be_iterated, value.String): 229 | for item in to_be_iterated.value: 230 | context.symbol_table.set(node.var_name_token.value, value.String(item)) 231 | val = res.register(self.visit(node.body_node, context)) 232 | if res.should_return() and res.loop_continue is False and res.loop_break is False: return res 233 | if res.loop_continue is True: continue 234 | elif res.loop_break is True: break 235 | else: 236 | return res.failure(RuntimeError( 237 | node.pos_start, node.pos_end, f"Cannot iterate type {res}", context 238 | )) 239 | return res.success(value.Number.null) 240 | 241 | def visit_ArrayNode(self, node, context): 242 | res = RuntimeResult() 243 | elements = [] 244 | for element in node.element_nodes: 245 | elements.append(res.register(self.visit(element, context))) 246 | if res.should_return(): return res 247 | return res.success(value.Array(elements).set_context(context).set_position(node.pos_start, node.pos_end)) 248 | 249 | def visit_MapNode(self, node, context): 250 | res = RuntimeResult() 251 | map = {} 252 | for key, v in node.map.items(): 253 | if isinstance(key, nd.ArrayNode) or isinstance(key, nd.MapNode): 254 | return res.failure(RuntimeError( 255 | node.pos_start, node.pos_end, f"Array or map cannot be a key", context 256 | )) 257 | map[key.token.value] = res.register(self.visit(v, context)) 258 | if res.should_return(): return res 259 | return res.success(value.Map(map).set_context(context).set_position(node.pos_start, node.pos_end)) 260 | 261 | def visit_WhileNode(self, node, context): 262 | res = RuntimeResult() 263 | elements = [] 264 | while True: 265 | condition = res.register(self.visit(node.condition_node, context)) 266 | if res.should_return(): return res 267 | if condition.is_true() is False: break 268 | val = res.register(self.visit(node.body_node, context)) 269 | if res.should_return() and res.loop_continue is False and res.loop_break is False: return res 270 | if res.loop_continue is True: 271 | continue 272 | elif res.loop_break is True: 273 | break 274 | else: 275 | elements.append(val) 276 | return res.success(value.Number.null if node.should_return_null else value.Array(elements).set_context(context).set_position(node.pos_start, node.pos_end)) 277 | 278 | def visit_FuncDefNode(self, node, context): 279 | res = RuntimeResult() 280 | func_name = node.var_name_token.value if node.var_name_token is not None else None 281 | body_node = node.body_node 282 | arg_names = [arg.value for arg in node.arg_name_tokens] 283 | func_value = value.Function(func_name, body_node, arg_names, node.should_auto_return).set_context(context).set_position(node.pos_start, node.pos_end) 284 | if node.var_name_token is not None: 285 | context.symbol_table.set(func_name, func_value) 286 | return res.success(func_value) 287 | 288 | def visit_CallNode(self, node, context): 289 | res = RuntimeResult() 290 | args = [] 291 | called_value = res.register(self.visit(node.node_to_call, context)) 292 | if res.should_return(): return res 293 | called_value = called_value.copy().set_position(node.pos_start, node.pos_end).set_context(context) 294 | for argnode in node.arg_nodes: 295 | args.append(res.register(self.visit(argnode, context))) 296 | if res.should_return(): return res 297 | 298 | return_value = res.register(called_value.execute(args)) 299 | if res.should_return(): return res 300 | return_value = return_value.copy().set_position(node.pos_start, node.pos_end).set_context(context) 301 | return res.success(return_value) 302 | 303 | def visit_StringNode(self, node, context): 304 | return RuntimeResult().success(value.String(node.token.value).set_context(context).set_position(node.pos_start, node.pos_end)) 305 | 306 | def visit_ReturnNode(self, node, context): 307 | res = RuntimeResult() 308 | if node.node_to_return: 309 | val = res.register(self.visit(node.node_to_return, context)) 310 | if res.should_return(): return res 311 | else: 312 | val = value.Number.null 313 | return res.success_return(val) 314 | 315 | def visit_ContinueNode(self, node, context): 316 | return RuntimeResult().success_continue() 317 | 318 | def visit_BreakNode(self, node, context): 319 | return RuntimeResult().success_break() -------------------------------------------------------------------------------- /pygen/src/gen_token.py: -------------------------------------------------------------------------------- 1 | 2 | TT_INT = "INT" # int 3 | TT_FLOAT = "FLOAT" # float 4 | TT_STRING = "STRING" # string 5 | TT_L_SQ = "L_SQ" # [ 6 | TT_R_SQ = "R_SQ" # ] 7 | TT_L_BRACE = "L_BRACE" # { 8 | TT_R_BRACE = "R_BRACE" # } 9 | TT_MAP_COLON = "MAP_COLON" # : 10 | TT_PLUS = "PLUS" # plus 11 | TT_MINUS = "MINUS" # minus 12 | TT_MULT = "MULT" # multiplication 13 | TT_DIV = "DIV" # division 14 | TT_POWER = "POWER" # power 15 | TT_MODULO = "MODULO" # modulo % 16 | TT_L_PAREN = "L_PAREN" # left parenthesis 17 | TT_R_PAREN = "R_PAREN" # right parenthesis 18 | TT_IDENTIFIER = "IDENTIFIER" # identifier 19 | TT_KEYWORD = "KEYWORD" # keyword 20 | TT_EQUALS = "EQUALS" # = 21 | TT_DEQUALS = "DOUBLE_EQUALS" # == 22 | TT_NEQUALS = "NOT_EQUALS" # != 23 | TT_LTHAN = "L_THAN" # < 24 | TT_GTHAN = "G_THAN" # > 25 | TT_LTEQUALS = "LT_EQUALS" # <= 26 | TT_GTEQUALS = "GT_EQUALS" # >= 27 | TT_COMMA = "COMMA" # , 28 | TT_ARROW = "ARROW" # -> 29 | TT_AT = "AT" # @ 30 | TT_NL = "NEW_LINE" # \n 31 | TT_EOF = "EOF" # End Of File 32 | 33 | KEYWORDS = [ 34 | "or", 35 | "and", 36 | "not", 37 | "if", 38 | "elseif", 39 | "then", 40 | "else", 41 | "for", 42 | "through", 43 | "step", 44 | "while", 45 | "defunc", 46 | "end", 47 | "return", 48 | "continue", 49 | "break", 50 | "in" 51 | ] 52 | 53 | class Token: 54 | def __init__(self, type, value=None, pos_start=None, pos_end=None): 55 | self.type = type 56 | self.value = value 57 | if pos_start is not None: 58 | self.pos_start = pos_start.copy() 59 | self.pos_end = pos_start.copy() 60 | self.pos_end.advance() 61 | if pos_end: 62 | self.pos_end = pos_end.copy() 63 | 64 | def __repr__(self): 65 | return f"{self.type}:{self.value}" if self.value is not None else f"{self.type}" 66 | 67 | def matches(self, type_, value): 68 | return self.type == type_ and self.value == value -------------------------------------------------------------------------------- /pygen/src/lexer.py: -------------------------------------------------------------------------------- 1 | import src.gen_token as tk 2 | import string 3 | from src.error import InvalidSyntaxError, TypeCharError 4 | from src.position import Position 5 | 6 | # for checking if a character is a digit or not 7 | DIGITS = "0123456789" 8 | LETTERS = string.ascii_letters 9 | LETTERS_AND_DIGITS = DIGITS + LETTERS 10 | 11 | class Lexer: 12 | def __init__(self, filename, text): 13 | self.filename = filename 14 | self.text = text 15 | self.position = Position(-1, 0, -1, self.filename, self.text) 16 | self.current_char = None 17 | self.advance() 18 | 19 | def advance(self): 20 | self.position.advance(self.current_char) 21 | self.current_char = self.text[self.position.index] if self.position.index < len(self.text) else None 22 | 23 | def make_tokens(self): 24 | tokens = [] 25 | 26 | while self.current_char is not None: 27 | if self.current_char in " \t": # ignore tabs and spaces 28 | self.advance() 29 | elif self.current_char in DIGITS: 30 | tokens.append(self.make_number()) 31 | elif self.current_char == "#": # comment 32 | self.skip_comment() 33 | elif self.current_char == "\"": # string 34 | tokens.append(self.make_string()) # check for new line or ; 35 | elif self.current_char in ";\n": 36 | tokens.append(tk.Token(tk.TT_NL, pos_start=self.position)) 37 | self.advance() 38 | elif self.current_char == "+": 39 | tokens.append(tk.Token(tk.TT_PLUS, pos_start=self.position)) 40 | self.advance() 41 | elif self.current_char == "-": 42 | tokens.append(self.make_minus_or_arrow()) 43 | elif self.current_char == "*": 44 | tokens.append(tk.Token(tk.TT_MULT, pos_start=self.position)) 45 | self.advance() 46 | elif self.current_char == "/": 47 | tokens.append(tk.Token(tk.TT_DIV, pos_start=self.position)) 48 | self.advance() 49 | elif self.current_char == "^": 50 | tokens.append(tk.Token(tk.TT_POWER, pos_start=self.position)) 51 | self.advance() 52 | elif self.current_char == "%": 53 | tokens.append(tk.Token(tk.TT_MODULO, pos_start=self.position)) 54 | self.advance() 55 | elif self.current_char == "(": 56 | tokens.append(tk.Token(tk.TT_L_PAREN, pos_start=self.position)) 57 | self.advance() 58 | elif self.current_char == ")": 59 | tokens.append(tk.Token(tk.TT_R_PAREN, pos_start=self.position)) 60 | self.advance() 61 | elif self.current_char == "[": 62 | tokens.append(tk.Token(tk.TT_L_SQ, pos_start=self.position)) 63 | self.advance() 64 | elif self.current_char == "]": 65 | tokens.append(tk.Token(tk.TT_R_SQ, pos_start=self.position)) 66 | self.advance() 67 | elif self.current_char == "{": 68 | tokens.append(tk.Token(tk.TT_L_BRACE, pos_start=self.position)) 69 | self.advance() 70 | elif self.current_char == "}": 71 | tokens.append(tk.Token(tk.TT_R_BRACE, pos_start=self.position)) 72 | self.advance() 73 | elif self.current_char == ":": 74 | tokens.append(tk.Token(tk.TT_MAP_COLON, pos_start=self.position)) 75 | self.advance() 76 | elif self.current_char == ",": 77 | tokens.append(tk.Token(tk.TT_COMMA, pos_start=self.position)) 78 | self.advance() 79 | elif self.current_char == "@": 80 | tokens.append(tk.Token(tk.TT_AT, pos_start=self.position)) 81 | self.advance() 82 | elif self.current_char == "!": 83 | token, error = self.make_not_equals() 84 | if error: return [], error 85 | tokens.append(token) 86 | elif self.current_char == "=": 87 | tokens.append(self.make_equals()) 88 | elif self.current_char == "<": 89 | tokens.append(self.make_less_than()) 90 | elif self.current_char == ">": 91 | tokens.append(self.make_greater_than()) 92 | elif self.current_char in LETTERS: 93 | tokens.append(self.make_identifier()) 94 | else: 95 | # return TypeCharError 96 | pos_start = self.position.copy() 97 | char = self.current_char 98 | self.advance() 99 | return [], TypeCharError(pos_start, self.position, f"'{char}'") 100 | tokens.append(tk.Token(tk.TT_EOF, pos_start=self.position)) 101 | return tokens, None 102 | 103 | def make_number(self): 104 | number_str = "" 105 | dot = False 106 | pos_start = self.position.copy() 107 | while self.current_char is not None and self.current_char in DIGITS + ".": 108 | if self.current_char == ".": 109 | if dot is True: break 110 | dot = True 111 | number_str += self.current_char 112 | else: 113 | number_str += self.current_char 114 | self.advance() 115 | 116 | return tk.Token(tk.TT_INT, int(number_str), pos_start, self.position) if dot is False else tk.Token(tk.TT_FLOAT, float(number_str), pos_start, self.position) 117 | 118 | def make_string(self): 119 | pos_start = self.position.copy() 120 | escape_character = False 121 | string_to_return = "" 122 | self.advance() 123 | while self.current_char != None and (self.current_char != "\"" or escape_character is not False): 124 | if escape_character is True: 125 | if self.current_char == "n": # new line 126 | string_to_return += "\n" 127 | elif self.current_char == "t": # tab 128 | string_to_return += "\t" 129 | else: 130 | string_to_return += self.current_char 131 | if self.current_char == "\\": 132 | escape_character = True 133 | else: 134 | string_to_return += self.current_char 135 | self.advance() 136 | escape_character = False 137 | self.advance() 138 | return tk.Token(tk.TT_STRING, string_to_return, pos_start, self.position) 139 | 140 | def make_identifier(self): 141 | string = "" 142 | pos_start = self.position.copy() 143 | while self.current_char is not None and self.current_char in LETTERS_AND_DIGITS+"_": 144 | string += self.current_char 145 | self.advance() 146 | token_type = tk.TT_KEYWORD if string in tk.KEYWORDS else tk.TT_IDENTIFIER 147 | return tk.Token(token_type, string, pos_start, self.position) 148 | 149 | def make_minus_or_arrow(self): 150 | token_type = tk.TT_MINUS 151 | pos_start = self.position.copy() 152 | self.advance() 153 | if self.current_char == ">": 154 | token_type = tk.TT_ARROW 155 | self.advance() 156 | return tk.Token(token_type, pos_start=pos_start, pos_end=self.position) 157 | 158 | 159 | def make_not_equals(self): 160 | pos_start = self.position.copy() 161 | self.advance() 162 | if self.current_char == "=": 163 | self.advance() 164 | return tk.Token(tk.TT_NEQUALS, pos_start=pos_start, pos_end=self.position), None 165 | else: 166 | self.advance() 167 | return None, InvalidSyntaxError( 168 | pos_start, self.position, "Expected '=' after '!'" 169 | ) 170 | 171 | def make_equals(self): 172 | pos_start = self.position.copy() 173 | token_type = tk.TT_EQUALS 174 | self.advance() 175 | if self.current_char == "=": 176 | self.advance() 177 | token_type = tk.TT_DEQUALS 178 | return tk.Token(token_type, pos_start=pos_start, pos_end=self.position) 179 | 180 | def make_less_than(self): 181 | pos_start = self.position.copy() 182 | token_type = tk.TT_LTHAN 183 | self.advance() 184 | if self.current_char == "=": 185 | self.advance() 186 | token_type = tk.TT_LTEQUALS 187 | return tk.Token(token_type, pos_start=pos_start, pos_end=self.position) 188 | 189 | def make_greater_than(self): 190 | pos_start = self.position.copy() 191 | token_type = tk.TT_GTHAN 192 | self.advance() 193 | if self.current_char == "=": 194 | self.advance() 195 | token_type = tk.TT_GTEQUALS 196 | return tk.Token(token_type, pos_start=pos_start, pos_end=self.position) 197 | 198 | def skip_comment(self): # for commenting 199 | self.advance() 200 | while self.current_char != "\n" and self.current_char is not None: 201 | self.advance() 202 | self.advance() 203 | 204 | 205 | -------------------------------------------------------------------------------- /pygen/src/node.py: -------------------------------------------------------------------------------- 1 | class NumberNode: 2 | def __init__(self, token): 3 | self.token = token 4 | self.pos_start = self.token.pos_start 5 | self.pos_end = self.token.pos_end 6 | 7 | def __repr__(self): 8 | return f"{self.token}" 9 | 10 | 11 | class StringNode: 12 | def __init__(self, token): 13 | self.token = token 14 | self.pos_start = self.token.pos_start 15 | self.pos_end = self.token.pos_end 16 | 17 | def __repr__(self): 18 | return str(self.token) 19 | 20 | 21 | class ArrayNode: 22 | def __init__(self, elements, pos_start, pos_end): 23 | self.element_nodes = elements 24 | self.pos_start = pos_start 25 | self.pos_end = pos_end 26 | 27 | 28 | class MapNode: 29 | def __init__(self, map, pos_start, pos_end): 30 | self.map = map 31 | self.pos_start = pos_start 32 | self.pos_end = pos_end 33 | 34 | 35 | class BinOpNode: 36 | def __init__(self, left_node, op_token, right_node): 37 | self.left_node = left_node 38 | self.op_token = op_token 39 | self.right_node = right_node 40 | 41 | self.pos_start = self.left_node.pos_start 42 | self.pos_end = self.right_node.pos_end 43 | 44 | def __repr__(self): 45 | return f"({self.left_node}, {self.op_token}, {self.right_node})" 46 | 47 | 48 | class UnaryOpNode: 49 | def __init__(self, op_token, node): 50 | self.op_token = op_token 51 | self.node = node 52 | self.pos_start = self.op_token.pos_start 53 | self.pos_end = self.node.pos_end 54 | 55 | def __repr__(self): 56 | return f"({self.op_token}, {self.node})" 57 | 58 | 59 | class VarAccessNode: 60 | def __init__(self, var_name_token): 61 | self.var_name_token = var_name_token 62 | self.pos_start = self.var_name_token.pos_start 63 | self.pos_end = self.var_name_token.pos_end 64 | 65 | 66 | class VarAssignNode: 67 | def __init__(self, var_name_token, value_node): 68 | self.var_name_token = var_name_token 69 | self.value_node = value_node 70 | self.pos_start = self.var_name_token.pos_start 71 | self.pos_end = self.value_node.pos_end 72 | 73 | 74 | class ReassignNode: 75 | def __init__(self, var_name_token, index_or_key, value_node, is_direct): 76 | # var_name_token is either an IDENTIFIER or a Python list 77 | self.var_name_token = var_name_token 78 | self.index_or_key = index_or_key 79 | self.value_node = value_node 80 | self.is_direct = is_direct 81 | from src.gen_token import Token 82 | if isinstance(self.var_name_token, list): 83 | self.pos_start = self.var_name_token[0].pos_start 84 | elif isinstance(self.var_name_token, Token): 85 | self.pos_start = self.var_name_token.pos_start 86 | else: 87 | key = list(self.var_name_token.keys())[0] 88 | self.pos_start = self.var_name_token[key].pos_start 89 | self.pos_end = self.value_node.pos_end 90 | 91 | class IfNode: 92 | def __init__(self, cases, else_case): 93 | self.cases = cases 94 | self.else_case = else_case 95 | self.pos_start = self.cases[0][0].pos_start 96 | self.pos_end = (self.else_case or self.cases[len(self.cases)-1])[0].pos_end 97 | 98 | 99 | class ReturnNode: 100 | def __init__(self, node_to_return, pos_start, pos_end): 101 | self.node_to_return = node_to_return 102 | self.pos_start = pos_start 103 | self.pos_end = pos_end 104 | 105 | 106 | class ContinueNode: 107 | def __init__(self, pos_start, pos_end): 108 | self.pos_start = pos_start 109 | self.pos_end = pos_end 110 | 111 | 112 | class BreakNode: 113 | def __init__(self, pos_start, pos_end): 114 | self.pos_start = pos_start 115 | self.pos_end = pos_end 116 | 117 | 118 | class ForNode: 119 | def __init__(self, var_name_token, start_value_node, end_value_node, step_value_node, body_node, should_return_null): 120 | self.var_name_token = var_name_token 121 | self.start_value_node = start_value_node 122 | self.end_value_node = end_value_node 123 | self.step_value_node = step_value_node 124 | self.body_node = body_node 125 | self.pos_start = self.var_name_token.pos_start 126 | self.pos_end = self.body_node.pos_end 127 | self.should_return_null = should_return_null 128 | 129 | 130 | class ForInNode: 131 | def __init__(self, var_name_token, array_elements, body_node): 132 | self.var_name_token = var_name_token 133 | self.array_elements = array_elements 134 | self.body_node = body_node 135 | self.pos_start = self.var_name_token.pos_start 136 | self.pos_end = self.body_node.pos_end 137 | 138 | def __repr__(self): 139 | return f"{self.var_name_token}\n{self.array_elements}" 140 | 141 | 142 | class WhileNode: 143 | def __init__(self, condition, body_node, should_return_null): 144 | self.condition_node = condition 145 | self.body_node = body_node 146 | self.pos_start = self.condition_node.pos_start 147 | self.pos_end = self.body_node.pos_end 148 | self.should_return_null = should_return_null 149 | 150 | 151 | class FuncDefNode: 152 | def __init__(self, var_name_token, arg_name_tokens, body_node, should_auto_return): 153 | self.var_name_token = var_name_token 154 | self.arg_name_tokens = arg_name_tokens 155 | self.body_node = body_node 156 | self.should_auto_return = should_auto_return 157 | if self.var_name_token: 158 | self.pos_start = self.var_name_token.pos_start 159 | elif len(self.arg_name_tokens) > 0: 160 | self.pos_start = self.arg_name_tokens[0].pos_start 161 | else: 162 | self.pos_start = self.body_node.pos_start 163 | self.pos_end = self.body_node.pos_end 164 | 165 | 166 | class CallNode: 167 | def __init__(self, node_to_call, arg_nodes): 168 | self.node_to_call = node_to_call 169 | self.arg_nodes = arg_nodes 170 | self.pos_start = self.node_to_call.pos_start 171 | if len(self.arg_nodes) > 0: 172 | self.pos_end = self.arg_nodes[len(self.arg_nodes)-1].pos_end 173 | else: 174 | self.pos_end = self.node_to_call.pos_end -------------------------------------------------------------------------------- /pygen/src/parser.py: -------------------------------------------------------------------------------- 1 | import src.gen_token as tk 2 | from src.error import InvalidSyntaxError 3 | from src.node import * 4 | 5 | class Parser: 6 | def __init__(self, tokens): 7 | self.tokens = tokens 8 | self.token_index = -1 9 | self.current_token = None 10 | self.advance() 11 | 12 | def advance(self): 13 | self.token_index += 1 14 | self.update_current_token() 15 | return self.current_token 16 | 17 | def update_current_token(self): 18 | if self.token_index < len(self.tokens) and self.token_index >= 0: 19 | self.current_token = self.tokens[self.token_index] 20 | 21 | def reverse(self, amount=1): 22 | self.token_index -= amount 23 | self.update_current_token() 24 | return self.current_token 25 | 26 | def atom(self): 27 | res = ParseResult() 28 | token = self.current_token 29 | 30 | if token.type in (tk.TT_INT, tk.TT_FLOAT): 31 | res.register_advance() 32 | self.advance() 33 | return res.success(NumberNode(token)) 34 | elif token.type == tk.TT_STRING: 35 | res.register_advance() 36 | self.advance() 37 | return res.success(StringNode(token)) 38 | elif token.type == tk.TT_IDENTIFIER: 39 | res.register_advance() 40 | self.advance() 41 | return res.success(VarAccessNode(token)) 42 | elif token.type == tk.TT_L_PAREN: 43 | res.register_advance() 44 | self.advance() 45 | expr = res.register(self.expr()) 46 | if res.error: return res 47 | if self.current_token.type == tk.TT_R_PAREN: 48 | res.register_advance() 49 | self.advance() 50 | return res.success(expr) 51 | else: 52 | return res.failure(InvalidSyntaxError( 53 | self.current_token.pos_start, self.current_token.pos_end, "Expected ')'" 54 | )) 55 | elif token.type == tk.TT_L_SQ: 56 | array_expression = res.register(self.array_expr()) 57 | if res.error: return res 58 | return res.success(array_expression) 59 | elif token.type == tk.TT_L_BRACE: 60 | map_expression = res.register(self.map_expr()) 61 | if res.error: return res 62 | return res.success(map_expression) 63 | elif token.matches(tk.TT_KEYWORD, "if"): 64 | if_expression = res.register(self.if_expr()) 65 | if res.error: return res 66 | return res.success(if_expression) 67 | elif token.matches(tk.TT_KEYWORD, "for"): 68 | for_expression = res.register(self.for_expr()) 69 | if res.error: return res 70 | return res.success(for_expression) 71 | elif token.matches(tk.TT_KEYWORD, "while"): 72 | while_expression = res.register(self.while_expr()) 73 | if res.error: return res 74 | return res.success(while_expression) 75 | elif token.matches(tk.TT_KEYWORD, "defunc"): 76 | defunc = res.register(self.defunc()) 77 | if res.error: return res 78 | return res.success(defunc) 79 | else: 80 | return res.failure(InvalidSyntaxError( 81 | token.pos_start, token.pos_end, "Expected int, float, identifier, +, -, '(', '[', 'if', 'for', 'while', or 'defunc'" 82 | )) 83 | 84 | def power(self): 85 | return self.bin_op(self.call, (tk.TT_POWER,), self.factor) 86 | 87 | def factor(self): 88 | res = ParseResult() 89 | token = self.current_token 90 | 91 | if token.type in (tk.TT_PLUS, tk.TT_MINUS): 92 | res.register_advance() 93 | self.advance() 94 | factor = res.register(self.factor()) 95 | if res.error: return res 96 | return res.success(UnaryOpNode(token, factor)) 97 | 98 | return self.power() 99 | 100 | def term(self): 101 | return self.bin_op(self.factor, (tk.TT_MULT, tk.TT_DIV, tk.TT_AT, tk.TT_MODULO)) 102 | 103 | def array_expr(self): 104 | res = ParseResult() 105 | elements = [] 106 | pos_start = self.current_token.pos_start.copy() 107 | res.register_advance() 108 | self.advance() 109 | if self.current_token.type == tk.TT_R_SQ: 110 | res.register_advance() 111 | self.advance() 112 | else: 113 | elements.append(res.register(self.expr())) 114 | if res.error: return res.failure(InvalidSyntaxError( 115 | self.current_token.pos_start, self.current_token.pos_end, "Expected ']', '[', 'if', 'for', 'while', 'defunc', int, float, identifier" 116 | )) 117 | while self.current_token.type == tk.TT_COMMA: 118 | res.register_advance() 119 | self.advance() 120 | elements.append(res.register(self.expr())) 121 | if res.error: return res 122 | if self.current_token.type != tk.TT_R_SQ: 123 | return res.failure(InvalidSyntaxError( 124 | self.current_token.pos_start, self.current_token.pos_end, "Expected ',', '}', or ']'" 125 | )) 126 | res.register_advance() 127 | self.advance() 128 | return res.success(ArrayNode(elements, pos_start, self.current_token.pos_end.copy())) 129 | 130 | def map_expr(self): 131 | res = ParseResult() 132 | elements = {} 133 | pos_start = self.current_token.pos_start.copy() 134 | res.register_advance() 135 | self.advance() 136 | if self.current_token.type == tk.TT_R_BRACE: 137 | res.register_advance() 138 | self.advance() 139 | else: 140 | while True: 141 | # key = res.success(StringNode(self.current_token)) 142 | # res.register_advance() 143 | # self.advance() 144 | key = res.register(self.expr()) 145 | if res.error: return res 146 | if self.current_token.type != tk.TT_MAP_COLON: 147 | return res.failure(InvalidSyntaxError( 148 | self.current_token.pos_start, self.current_token.pos_end, "Expected ':'" 149 | )) 150 | res.register_advance() 151 | self.advance() 152 | elements[key] = res.register(self.expr()) 153 | if res.error: return res 154 | if self.current_token.type == tk.TT_R_BRACE: 155 | break 156 | if self.current_token.type != tk.TT_COMMA: 157 | return res.failure(InvalidSyntaxError( 158 | self.current_token.pos_start, self.current_token.pos_end, "Expected ','" 159 | )) 160 | res.register_advance() 161 | self.advance() 162 | res.register_advance() 163 | self.advance() 164 | return res.success(MapNode(elements, pos_start, self.current_token.pos_end.copy())) 165 | 166 | def expr(self): 167 | res = ParseResult() 168 | # checking map or array var reassignment 169 | res.deregister_advance() 170 | self.reverse(1) 171 | has_at = False 172 | if self.current_token.type == tk.TT_AT: 173 | has_at = True 174 | res.register_advance() 175 | self.advance() 176 | # checking variable assignment 177 | if self.current_token.type == tk.TT_IDENTIFIER: 178 | var_name = self.current_token 179 | res.register_advance() 180 | self.advance() 181 | if self.current_token.type == tk.TT_EQUALS: 182 | if has_at: 183 | return res.success(VarAccessNode(var_name)) 184 | res.register_advance() 185 | self.advance() 186 | expression = res.register(self.expr()) 187 | if res.error: return res 188 | return res.success(VarAssignNode(var_name, expression)) 189 | else: 190 | res.deregister_advance() 191 | self.reverse(amount=1) 192 | 193 | node = res.register(self.bin_op(self.comp_expr, ((tk.TT_KEYWORD, "and"), (tk.TT_KEYWORD, "or")))) 194 | if res.error: 195 | return res.failure(InvalidSyntaxError( 196 | self.current_token.pos_start, self.current_token.pos_end, "Expected int, float, identifier, +, -, '(', '[', 'if', 'for', 'while', or 'defunc'" 197 | )) 198 | return res.success(node) 199 | 200 | def if_expr(self): 201 | res = ParseResult() 202 | all_cases = res.register(self.if_expr_cases("if")) 203 | if res.error: return res 204 | cases, else_case = all_cases 205 | return res.success(IfNode(cases, else_case)) 206 | 207 | def if_expr_elseif(self): 208 | return self.if_expr_cases("elseif") 209 | 210 | def if_expr_else(self): 211 | res = ParseResult() 212 | else_case = None 213 | if self.current_token.matches(tk.TT_KEYWORD, "else"): 214 | res.register_advance() 215 | self.advance() 216 | if self.current_token.type == tk.TT_NL: 217 | res.register_advance() 218 | self.advance() 219 | statements = res.register(self.statements()) 220 | if res.error: return res 221 | else_case = (statements, True) 222 | if self.current_token.matches(tk.TT_KEYWORD, "end"): 223 | res.register_advance() 224 | self.advance() 225 | else: 226 | return res.failure(InvalidSyntaxError( 227 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'end'" 228 | )) 229 | else: 230 | expr = res.register(self.statement()) 231 | if res.error: return res 232 | else_case = (expr, False) 233 | return res.success(else_case) 234 | 235 | def if_expr_elseif_or_else(self): 236 | res = ParseResult() 237 | cases = [] 238 | else_case = None 239 | if self.current_token.matches(tk.TT_KEYWORD, "elseif"): 240 | all_cases = res.register(self.if_expr_elseif()) 241 | if res.error: return res 242 | cases, else_case = all_cases 243 | else: 244 | else_case = res.register(self.if_expr_else()) 245 | if res.error: return res 246 | return res.success((cases, else_case)) 247 | 248 | def if_expr_cases(self, keyword): 249 | res = ParseResult() 250 | cases = [] 251 | else_case = None 252 | if self.current_token.matches(tk.TT_KEYWORD, keyword) is False: 253 | return res.failure(InvalidSyntaxError( 254 | self.current_token.pos_start, self.current_token.pos_end, f"Expected '{keyword}'" 255 | )) 256 | res.register_advance() 257 | self.advance() 258 | condition = res.register(self.expr()) 259 | if res.error: return res 260 | if self.current_token.matches(tk.TT_KEYWORD, "then") is False: 261 | return res.failure(InvalidSyntaxError( 262 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'then'" 263 | )) 264 | res.register_advance() 265 | self.advance() 266 | if self.current_token.type == tk.TT_NL: 267 | res.register_advance() 268 | self.advance() 269 | statements = res.register(self.statements()) 270 | if res.error: return res 271 | else: cases.append((condition, statements, True)) 272 | if self.current_token.matches(tk.TT_KEYWORD, "end"): 273 | res.register_advance() 274 | self.advance() 275 | else: 276 | all_cases = res.register(self.if_expr_elseif_or_else()) 277 | if res.error: return res 278 | new_cases, else_case = all_cases 279 | cases.extend(new_cases) 280 | else: 281 | expr = res.register(self.statement()) 282 | if res.error: return res 283 | cases.append((condition, expr, False)) 284 | all_cases = res.register(self.if_expr_elseif_or_else()) 285 | if res.error: return res 286 | new_cases, else_case = all_cases 287 | cases.extend(new_cases) 288 | return res.success((cases, else_case)) 289 | 290 | 291 | def for_expr(self): 292 | res = ParseResult() 293 | if self.current_token.matches(tk.TT_KEYWORD, "for") is False: 294 | return res.failure(InvalidSyntaxError( 295 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'for'" 296 | )) 297 | res.register_advance() 298 | self.advance() 299 | if self.current_token.type != tk.TT_IDENTIFIER: 300 | return res.failure(InvalidSyntaxError( 301 | self.current_token.pos_start, self.current_token.pos_end, "Expected an identifier" 302 | )) 303 | var_name = self.current_token 304 | res.register_advance() 305 | self.advance() 306 | if self.current_token.type == tk.TT_EQUALS: 307 | res.register_advance() 308 | self.advance() 309 | start_value = res.register(self.expr()) 310 | if res.error: return res 311 | if self.current_token.matches(tk.TT_KEYWORD, "through") is False: 312 | return res.failure(InvalidSyntaxError( 313 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'through'" 314 | )) 315 | res.register_advance() 316 | self.advance() 317 | end_value = res.register(self.expr()) 318 | if res.error: return res 319 | if self.current_token.matches(tk.TT_KEYWORD, "step"): 320 | res.register_advance() 321 | self.advance() 322 | step_value = res.register(self.expr()) 323 | if res.error: return res 324 | else: 325 | step_value = None 326 | if self.current_token.matches(tk.TT_KEYWORD, "then") is False: 327 | return res.failure(InvalidSyntaxError( 328 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'then'" 329 | )) 330 | res.register_advance() 331 | self.advance() 332 | if self.current_token.type == tk.TT_NL: 333 | res.register_advance() 334 | self.advance() 335 | body = res.register(self.statements()) 336 | if res.error: return res 337 | if self.current_token.matches(tk.TT_KEYWORD, "end") is False: 338 | return res.failure(InvalidSyntaxError( 339 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'end'" 340 | )) 341 | res.register_advance() 342 | self.advance() 343 | return res.success(ForNode(var_name, start_value, end_value, step_value, body, True)) 344 | body = res.register(self.statement()) 345 | if res.error: return res 346 | return res.success(ForNode(var_name, start_value, end_value, step_value, body, False)) 347 | elif self.current_token.matches(tk.TT_KEYWORD, "in"): 348 | res.register_advance() 349 | self.advance() 350 | to_be_iterated = res.register(self.expr()) 351 | if res.error: return res 352 | if self.current_token.matches(tk.TT_KEYWORD, "then") is False: 353 | return res.failure(InvalidSyntaxError( 354 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'then'" 355 | )) 356 | res.register_advance() 357 | self.advance() 358 | if self.current_token.type != tk.TT_NL: 359 | return res.failure(InvalidSyntaxError( 360 | self.current_token.pos_start, self.current_token.pos_end, "Expected a new line or ';'" 361 | )) 362 | res.register_advance() 363 | self.advance() 364 | body = res.register(self.statements()) 365 | if res.error: return res 366 | if self.current_token.matches(tk.TT_KEYWORD, "end") is False: 367 | return res.failure(InvalidSyntaxError( 368 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'end'" 369 | )) 370 | res.register_advance() 371 | self.advance() 372 | return res.success(ForInNode(var_name, to_be_iterated, body)) 373 | else: 374 | return res.failure(InvalidSyntaxError( 375 | self.current_token.pos_start, self.current_token.pos_end, "Expected '=' or 'in'" 376 | )) 377 | 378 | def while_expr(self): 379 | res = ParseResult() 380 | if self.current_token.matches(tk.TT_KEYWORD, "while") is False: 381 | return res.failure(InvalidSyntaxError( 382 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'while'" 383 | )) 384 | res.register_advance() 385 | self.advance() 386 | condition = res.register(self.expr()) 387 | if res.error: return res 388 | if self.current_token.matches(tk.TT_KEYWORD, "then") is False: 389 | return res.failure(InvalidSyntaxError( 390 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'then'" 391 | )) 392 | res.register_advance() 393 | self.advance() 394 | if self.current_token.type == tk.TT_NL: 395 | res.register_advance() 396 | self.advance() 397 | body = res.register(self.statements()) 398 | if res.error: return res 399 | if self.current_token.matches(tk.TT_KEYWORD, "end") is False: 400 | return res.failure(InvalidSyntaxError( 401 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'end'" 402 | )) 403 | res.register_advance() 404 | self.advance() 405 | return res.success(WhileNode(condition, body, True)) 406 | body = res.register(self.statement()) 407 | if res.error: return res 408 | return res.success(WhileNode(condition, body, False)) 409 | 410 | def bin_op(self, func_a, ops, func_b=None): 411 | if func_b is None: 412 | func_b = func_a 413 | res = ParseResult() 414 | left = res.register(func_a()) 415 | if res.error: return res 416 | is_arr_or_map_assign = False 417 | while self.current_token.type in ops or (self.current_token.type, self.current_token.value) in ops: 418 | if self.current_token.type == tk.TT_AT: 419 | is_arr_or_map_assign = True 420 | op_token = self.current_token 421 | res.register_advance() 422 | self.advance() 423 | right = res.register(func_b()) 424 | if res.error: return res 425 | left = BinOpNode(left, op_token, right) 426 | # check for array or map assignment 427 | if is_arr_or_map_assign: 428 | # go back until self.current_token is TT_AT so that the index can be parsed again 429 | while True: 430 | res.deregister_advance() 431 | self.reverse(amount=1) 432 | if self.current_token.type == tk.TT_AT: 433 | res.register_advance() 434 | self.advance() 435 | break 436 | index_or_key = res.register(self.expr()) 437 | if self.current_token.type != tk.TT_EQUALS: 438 | return res.success(left) 439 | res.register_advance() 440 | self.advance() 441 | new_value = res.register(self.expr()) 442 | if res.error: return res 443 | if isinstance(left.left_node, ArrayNode): 444 | new_left = left.left_node.element_nodes 445 | is_direct = True 446 | else: 447 | if isinstance(left.left_node, MapNode): 448 | return res.failure(InvalidSyntaxError( 449 | self.current_token.pos_start, self.current_token.pos_end, "Map cannot be modified directly" 450 | )) 451 | elif isinstance(left.left_node, BinOpNode): 452 | new_left = res.register(self.expr()) 453 | else: 454 | new_left = left.left_node.var_name_token 455 | is_direct = False 456 | return res.success(ReassignNode(new_left, index_or_key, new_value, is_direct)) 457 | return res.success(left) 458 | 459 | def comp_expr(self): 460 | res = ParseResult() 461 | if self.current_token.matches(tk.TT_KEYWORD, "not"): 462 | op_token = self.current_token 463 | res.register_advance() 464 | self.advance() 465 | node = res.register(self.comp_expr()) 466 | if res.error: return res 467 | return res.success(UnaryOpNode(op_token, node)) 468 | else: 469 | node = res.register(self.bin_op(self.arithmatic_expr, (tk.TT_DEQUALS, tk.TT_NEQUALS, tk.TT_LTHAN, tk.TT_GTHAN, tk.TT_LTEQUALS, tk.TT_GTEQUALS))) 470 | if res.error: return res.failure(InvalidSyntaxError( 471 | self.current_token.pos_start, self.current_token.pos_end, "Expected int, float, not, identifier, +, -, '[', or '('" 472 | )) 473 | return res.success(node) 474 | 475 | def arithmatic_expr(self): 476 | return self.bin_op(self.term, (tk.TT_PLUS, tk.TT_MINUS)) 477 | 478 | def defunc(self): 479 | res = ParseResult() 480 | if self.current_token.matches(tk.TT_KEYWORD, "defunc") is False: 481 | res.failure(InvalidSyntaxError( 482 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'defunc'" 483 | )) 484 | else: 485 | self.advance() 486 | # get function name if possible 487 | if self.current_token.type == tk.TT_IDENTIFIER: 488 | func_var_name_token = self.current_token 489 | self.advance() 490 | # check for left paren 491 | if self.current_token.type != tk.TT_L_PAREN: 492 | return res.failure(InvalidSyntaxError( 493 | self.current_token.pos_start, self.current_token.pos_end, "Expected '('" 494 | )) 495 | else: # annonymous function 496 | func_var_name_token = None 497 | # check for left paren 498 | if self.current_token.type != tk.TT_L_PAREN: 499 | return res.failure(InvalidSyntaxError( 500 | self.current_token.pos_start, self.current_token.pos_end, "Expected '(' or an identifier" 501 | )) 502 | res.register_advance() 503 | self.advance() 504 | # get arguments if any is present 505 | arg_name_tokens = [] 506 | if self.current_token.type == tk.TT_IDENTIFIER: 507 | arg_name_tokens.append(self.current_token) 508 | res.register_advance() 509 | self.advance() 510 | while self.current_token.type == tk.TT_COMMA: 511 | res.register_advance() 512 | self.advance() 513 | if self.current_token.type != tk.TT_IDENTIFIER: 514 | return res.failure(InvalidSyntaxError( 515 | self.current_token.pos_start, self.current_token.pos_end, "Expected an identifier after ','" 516 | )) 517 | else: 518 | arg_name_tokens.append(self.current_token) 519 | res.register_advance() 520 | self.advance() 521 | # check for right paren 522 | if self.current_token.type != tk.TT_R_PAREN: 523 | return res.failure(InvalidSyntaxError( 524 | self.current_token.pos_start, self.current_token.pos_end, "Expected ',' or ')'" 525 | )) 526 | else: 527 | if self.current_token.type != tk.TT_R_PAREN: 528 | return res.failure(InvalidSyntaxError( 529 | self.current_token.pos_start, self.current_token.pos_end, "Expected ')'" 530 | )) 531 | res.register_advance() 532 | self.advance() 533 | if self.current_token.type == tk.TT_ARROW: 534 | res.register_advance() 535 | self.advance() 536 | return_node = res.register(self.expr()) 537 | if res.error: return res 538 | return res.success(FuncDefNode( 539 | func_var_name_token, arg_name_tokens, return_node, True 540 | )) 541 | if self.current_token.type != tk.TT_NL: 542 | return res.failure(InvalidSyntaxError( 543 | self.current_token.pos_start, self.current_token.pos_end, "Expected '->' or a new line" 544 | )) 545 | res.register_advance() 546 | self.advance() 547 | body = res.register(self.statements()) 548 | if res.error: return res 549 | if self.current_token.matches(tk.TT_KEYWORD, "end") is False: 550 | return res.failure(InvalidSyntaxError( 551 | self.current_token.pos_start, self.current_token.pos_end, "Expected 'end'" 552 | )) 553 | res.register_advance() 554 | self.advance() 555 | return res.success(FuncDefNode( 556 | func_var_name_token, arg_name_tokens, body, False 557 | )) 558 | 559 | 560 | def call(self): 561 | res = ParseResult() 562 | atom = res.register(self.atom()) 563 | if res.error: return res 564 | if self.current_token.type == tk.TT_L_PAREN: 565 | res.register_advance() 566 | self.advance() 567 | arg_nodes = [] 568 | if self.current_token.type == tk.TT_R_PAREN: # mearning that no arguments are passed 569 | res.register_advance() 570 | self.advance() 571 | else: 572 | arg_nodes.append(res.register(self.expr())) 573 | if res.error: return res.failure(InvalidSyntaxError( 574 | self.current_token.pos_start, self.current_token.pos_end, "Expected ')', ']', 'if', 'for', 'while', 'defunc', int, float, identifier" 575 | )) 576 | while self.current_token.type == tk.TT_COMMA: 577 | res.register_advance() 578 | self.advance() 579 | arg_nodes.append(res.register(self.expr())) 580 | if res.error: return res 581 | if self.current_token.type != tk.TT_R_PAREN: 582 | return res.failure(InvalidSyntaxError( 583 | self.current_token.pos_start, self.current_token.pos_end, "Expected ',' or ')'" 584 | )) 585 | else: 586 | res.register_advance() 587 | self.advance() 588 | return res.success(CallNode(atom, arg_nodes)) 589 | return res.success(atom) 590 | 591 | def statements(self): 592 | res = ParseResult() 593 | statements = [] 594 | pos_start = self.current_token.pos_start.copy() 595 | while self.current_token.type == tk.TT_NL: 596 | res.register_advance() 597 | self.advance() 598 | statement = res.register(self.statement()) 599 | if res.error: return res 600 | statements.append(statement) 601 | more = True 602 | while True: 603 | new_line_count = 0 604 | while self.current_token.type == tk.TT_NL: 605 | res.register_advance() 606 | self.advance() 607 | new_line_count += 1 608 | if new_line_count == 0: more = False 609 | if more is False: break 610 | statement = res.try_register(self.statement()) 611 | if statement is None: 612 | self.reverse(res.to_reverse_count) 613 | more = False 614 | continue 615 | statements.append(statement) 616 | return res.success(ArrayNode( 617 | statements, pos_start, self.current_token.pos_end.copy() 618 | )) 619 | 620 | def statement(self): 621 | res = ParseResult() 622 | pos_start = self.current_token.pos_start.copy() 623 | if self.current_token.matches(tk.TT_KEYWORD, "return"): 624 | res.register_advance() 625 | self.advance() 626 | expr = res.try_register(self.expr()) 627 | if expr is None: self.reverse(res.to_reverse_count) 628 | return res.success(ReturnNode(expr, pos_start, self.current_token.pos_end)) 629 | elif self.current_token.matches(tk.TT_KEYWORD, "continue"): 630 | res.register_advance() 631 | self.advance() 632 | return res.success(ContinueNode(pos_start, self.current_token.pos_end)) 633 | elif self.current_token.matches(tk.TT_KEYWORD, "break"): 634 | res.register_advance() 635 | self.advance() 636 | return res.success(BreakNode(pos_start, self.current_token.pos_end)) 637 | else: 638 | expr = res.register(self.expr()) 639 | if res.error: return res.failure(InvalidSyntaxError( 640 | self.current_token.pos_start, self.current_token.pos_end, "Expected int, float, identifier, +, -, '(', '[', 'if', 'for', 'return', 'continue', 'break', 'while', or 'defunc'" 641 | )) 642 | return res.success(expr) 643 | 644 | 645 | def parse(self): 646 | # check if there's anything to do at all 647 | not_empty = True 648 | for token in self.tokens: 649 | if token.type != tk.TT_NL and token.type != tk.TT_EOF: 650 | not_empty = False 651 | break 652 | if not_empty is True: 653 | return ParseResult() 654 | result = self.statements() 655 | if result.error and self.current_token.type != tk.TT_EOF: 656 | return result.failure(InvalidSyntaxError( 657 | self.current_token.pos_start, self.current_token.pos_end, "Expected +, -, *, or /" 658 | )) 659 | return result 660 | 661 | 662 | class ParseResult: 663 | def __init__(self): 664 | self.error = None 665 | self.node = None 666 | self.count_advanced = 0 667 | self.to_reverse_count = 0 668 | 669 | def register_advance(self): 670 | self.count_advanced += 1 671 | 672 | def deregister_advance(self): 673 | self.count_advanced -= 1 674 | 675 | def try_register(self, res): 676 | if res.error is not None: 677 | self.to_reverse_count = res.count_advanced 678 | return None 679 | else: 680 | return self.register(res) 681 | 682 | def register(self, result): 683 | self.count_advanced += result.count_advanced 684 | if result.error: self.error = result.error 685 | return result.node 686 | 687 | def success(self, node): 688 | self.node = node 689 | return self 690 | 691 | def failure(self, error): 692 | if self.error is None or self.count_advanced == 0: 693 | self.error = error 694 | return self -------------------------------------------------------------------------------- /pygen/src/position.py: -------------------------------------------------------------------------------- 1 | class Position: 2 | def __init__(self, index, lnum, col, filename, filetext): 3 | self.index = index 4 | self.lnum = lnum 5 | self.col = col 6 | self.filename = filename 7 | self.filetext = filetext 8 | 9 | def advance(self, current_char=None): 10 | self.index += 1 11 | self.col += 1 12 | 13 | if current_char == "\n": 14 | self.lnum += 1 15 | self.col = 0 16 | 17 | def copy(self): 18 | return Position(self.index, self.lnum, self.col, self.filename, self.filetext) -------------------------------------------------------------------------------- /pygen/src/symbol_table.py: -------------------------------------------------------------------------------- 1 | class SymbolTable: 2 | def __init__(self, parent=None): 3 | self.symbols = {} 4 | self.parent = parent 5 | 6 | def get(self, var_name): 7 | value = self.symbols.get(var_name, None) 8 | return self.parent.get(var_name) if value is None and self.parent else value 9 | 10 | def set(self, var_name, value): 11 | self.symbols[var_name] = value 12 | 13 | def set_arr(self, var_name, index, value): 14 | self.symbols[var_name].elements[index.value] = value 15 | 16 | def set_map(self, var_name, key, value): 17 | self.symbols[var_name].map[key.value] = value 18 | 19 | def remove(self, var_name): 20 | del self.symbols[var_name] -------------------------------------------------------------------------------- /pygen/src/utils.py: -------------------------------------------------------------------------------- 1 | def string_with_arrows(text, pos_start, pos_end): 2 | result = "" 3 | 4 | index_start = max(text.rfind("\n", 0, pos_start.index), 0) 5 | index_end = text.find("\n", index_start+1) 6 | if index_end < 0: index_end = len(text) 7 | 8 | line_count = pos_end.lnum - pos_start.lnum + 1 9 | for i in range(line_count): 10 | line = text[index_start:index_end] 11 | column_start = pos_start.col if i == 0 else 0 12 | column_end = pos_end.col if i == line_count - 1 else len(line) - 1 13 | result += line + "\n" 14 | result += " " * column_start + "^" * (column_end - column_start) 15 | 16 | index_start = index_end 17 | index_end = text.find("\n", index_start+1) 18 | if index_end < 0: index_end = len(text) 19 | 20 | return result.replace("\t", "") -------------------------------------------------------------------------------- /pygen/src/value.py: -------------------------------------------------------------------------------- 1 | from src.error import RuntimeError 2 | from src.context import Context 3 | from src.symbol_table import SymbolTable 4 | from src.evaluator import Evaluator, RuntimeResult 5 | 6 | import math 7 | 8 | class Value: 9 | def __init__(self): 10 | self.set_position() 11 | self.set_context() 12 | 13 | def set_context(self, context=None): 14 | self.context = context 15 | return self 16 | 17 | def set_position(self, pos_start=None, pos_end=None): 18 | self.pos_start = pos_start 19 | self.pos_end = pos_end 20 | return self 21 | 22 | def added_to(self, other): 23 | return None, self.invalid_operation(other) 24 | 25 | # make these invalid operations unless overriden by Number class 26 | def subtracted_by(self, other): 27 | return None, self.invalid_operation(other) 28 | 29 | def multiplied_by(self, other): 30 | return None, self.invalid_operation(other) 31 | 32 | def divided_by(self, other): 33 | return None, self.invalid_operation(other) 34 | 35 | def powered_by(self, other): 36 | return None, self.invalid_operation(other) 37 | 38 | def modulo(self, other): 39 | return None, self.invalid_operation(other) 40 | 41 | def get_comparison_equal(self, other): 42 | return None, self.invalid_operation(other) 43 | 44 | def get_comparison_not_equal(self, other): 45 | return None, self.invalid_operation(other) 46 | 47 | def get_comparison_less_than(self, other): 48 | return None, self.invalid_operation(other) 49 | 50 | def get_comparison_greater_than(self, other): 51 | return None, self.invalid_operation(other) 52 | 53 | def get_comparison_lt_equals(self, other): 54 | return None, self.invalid_operation(other) 55 | 56 | def get_comparison_gt_equals(self, other): 57 | return None, self.invalid_operation(other) 58 | 59 | def and_by(self, other): 60 | return None, self.invalid_operation(other) 61 | 62 | def or_by(self, other): 63 | return None, self.invalid_operation(other) 64 | 65 | def at(self, other): 66 | return None, self.invalid_operation(other) 67 | 68 | def notted(self): 69 | return None, self.invalid_operation() 70 | 71 | def is_true(self): 72 | return False 73 | 74 | def invalid_operation(self, other=None): 75 | if other is None: other = self 76 | return RuntimeError( 77 | self.pos_start, other.pos_end, "Invalid operation", self.context 78 | ) 79 | 80 | def copy(self): 81 | pass 82 | 83 | def __repr__(self): 84 | return f"{self.value}" 85 | 86 | def return_type(self): 87 | return String("value") 88 | 89 | 90 | class Number(Value): 91 | def __init__(self, value): 92 | super().__init__() 93 | self.value = value 94 | 95 | def added_to(self, other): 96 | if isinstance(other, Number): 97 | return Number(self.value + other.value).set_context(self.context), None 98 | else: 99 | return None, self.invalid_operation(other) 100 | 101 | # make these invalid operations unless overriden 102 | def subtracted_by(self, other): 103 | if isinstance(other, Number): 104 | return Number(self.value - other.value).set_context(self.context), None 105 | else: 106 | return None, self.invalid_operation(other) 107 | 108 | def multiplied_by(self, other): 109 | if isinstance(other, Number): 110 | return Number(self.value * other.value).set_context(self.context), None 111 | else: 112 | return None, self.invalid_operation(other) 113 | 114 | def divided_by(self, other): 115 | if isinstance(other, Number): 116 | if other.value == 0: return None, RuntimeError( 117 | other.pos_start, other.pos_end, "Division by zero is not allowed", self.context 118 | ) 119 | else: 120 | return Number(self.value / other.value), None 121 | else: 122 | return None, self.invalid_operation(other) 123 | 124 | def powered_by(self, other): 125 | if isinstance(other, Number): 126 | return Number(self.value ** other.value).set_context(self.context), None 127 | else: 128 | return None, self.invalid_operation(other) 129 | 130 | def modulo(self, other): 131 | if isinstance(other, Number): 132 | return Number(self.value % other.value).set_context(self.context), None 133 | else: 134 | return None, self.invalid_operation(other) 135 | 136 | def get_comparison_equal(self, other): 137 | if isinstance(other, Number): 138 | return Number(int(self.value == other.value)).set_context(self.context), None 139 | else: 140 | return None, self.invalid_operation(other) 141 | 142 | def get_comparison_not_equal(self, other): 143 | if isinstance(other, Number): 144 | return Number(int(self.value != other.value)).set_context(self.context), None 145 | else: 146 | return None, self.invalid_operation(other) 147 | 148 | def get_comparison_less_than(self, other): 149 | if isinstance(other, Number): 150 | return Number(int(self.value < other.value)).set_context(self.context), None 151 | else: 152 | return None, self.invalid_operation(other) 153 | 154 | def get_comparison_greater_than(self, other): 155 | if isinstance(other, Number): 156 | return Number(int(self.value > other.value)).set_context(self.context), None 157 | else: 158 | return None, self.invalid_operation(other) 159 | def get_comparison_lt_equals(self, other): 160 | if isinstance(other, Number): 161 | return Number(int(self.value <= other.value)).set_context(self.context), None 162 | else: 163 | return None, self.invalid_operation(other) 164 | 165 | def get_comparison_gt_equals(self, other): 166 | if isinstance(other, Number): 167 | return Number(int(self.value >= other.value)).set_context(self.context), None 168 | else: 169 | return None, self.invalid_operation(other) 170 | 171 | def and_by(self, other): 172 | if isinstance(other, Number): 173 | return Number(int(self.value and other.value)).set_context(self.context), None 174 | else: 175 | return None, self.invalid_operation(other) 176 | 177 | def or_by(self, other): 178 | if isinstance(other, Number): 179 | return Number(int(self.value or other.value)).set_context(self.context), None 180 | else: 181 | return None, self.invalid_operation(other) 182 | 183 | def notted(self): 184 | return Number(1 if self.value == 0 else 0).set_context(self.context), None 185 | 186 | def is_true(self): 187 | return self.value != 0 188 | 189 | def return_type(self): 190 | if isinstance(self.value, int): 191 | return String("integer") 192 | else: 193 | return String("float") 194 | 195 | def copy(self): 196 | copy = Number(self.value) 197 | copy.set_position(self.pos_start, self.pos_end) 198 | copy.set_context(self.context) 199 | return copy 200 | 201 | Number.null = Number(0) 202 | Number.true = Number(1) 203 | Number.false = Number(0) 204 | Number.Pi = Number(math.pi) 205 | 206 | 207 | class String(Value): 208 | def __init__(self, value): 209 | super().__init__() 210 | self.value = value 211 | 212 | def added_to(self, other): 213 | if isinstance(other, String): 214 | return String(self.value + other.value).set_context(self.context), None 215 | elif isinstance(other, Number): 216 | return String(self.value + str(other.value)).set_context(self.context), None 217 | else: 218 | return None, self.invalid_operation(other) 219 | 220 | def multiplied_by(self, other): # allow "a" * 8 221 | if isinstance(other, Number): 222 | return String(self.value * other.value).set_context(self.context), None 223 | else: 224 | return None, self.invalid_operation(other) 225 | 226 | def get_comparison_equal(self, other): 227 | if isinstance(other, String): 228 | return Number(int(self.value == other.value)).set_context(self.context), None 229 | else: 230 | return None, self.invalid_operation(other) 231 | 232 | def get_comparison_not_equal(self, other): 233 | if isinstance(other, String): 234 | return Number(int(self.value != other.value)).set_context(self.context), None 235 | else: 236 | return None, self.invalid_operation(other) 237 | 238 | def and_by(self, other): 239 | if isinstance(other, String): 240 | return Number(int(self.value and other.value)).set_context(self.context), None 241 | else: 242 | return None, self.invalid_operation(other) 243 | 244 | def or_by(self, other): 245 | if isinstance(other, String): 246 | return Number(int(self.value or other.value)).set_context(self.context), None 247 | else: 248 | return None, self.invalid_operation(other) 249 | 250 | def at(self, other): 251 | if isinstance(other, Number): 252 | try: 253 | value = str(self.value[int(other.value)]) 254 | return String(value), None 255 | except: 256 | return None, RuntimeError( 257 | other.pos_start, other.pos_end, f"Element at index {other.value} does not exist", self.context 258 | ) 259 | else: 260 | return Value.invalid_operation(self, other) 261 | 262 | def notted(self): 263 | return Number(1 if self.value == 0 else 0).set_context(self.context), None 264 | 265 | def is_true(self): 266 | return len(self.value) > 0 267 | 268 | def copy(self): 269 | copy = String(self.value) 270 | copy.set_position(self.pos_start, self.pos_end) 271 | copy.set_context(self.context) 272 | return copy 273 | 274 | def __repr__(self): 275 | return f'"{self.value}"' 276 | 277 | def __str__(self): 278 | return str(self.value) 279 | 280 | def return_type(self): 281 | return String("string") 282 | 283 | 284 | class Array(Value): 285 | def __init__(self, elements): 286 | super().__init__() 287 | self.elements = elements 288 | 289 | def added_to(self, other): 290 | new_array = self.copy() 291 | if isinstance(other, Array): 292 | new_array.elements.extend(other.elements) 293 | else: 294 | new_array.elements.append(other) 295 | return new_array, None 296 | 297 | def subtracted_by(self, other): 298 | if isinstance(other, Number): 299 | new_array = self.copy() 300 | try: 301 | new_array.elements.pop(other.value) 302 | return new_array, None 303 | except IndexError: 304 | return None, RuntimeError( 305 | other.pos_start, other.pos_end, f"Element at index {other.value} does not exist", self.context 306 | ) 307 | else: 308 | return Value.invalid_operation(self, other) 309 | 310 | def at(self, other): 311 | if isinstance(other, Number): 312 | try: 313 | return self.elements[other.value], None 314 | except: 315 | return None, RuntimeError( 316 | other.pos_start, other.pos_end, f"Element at index {other.value} does not exist", self.context 317 | ) 318 | else: 319 | return Value.invalid_operation(self, other) 320 | 321 | def copy(self): 322 | copy = Array(self.elements) 323 | copy.set_position(self.pos_start, self.pos_end) 324 | copy.set_context(self.context) 325 | return copy 326 | 327 | def __repr__(self): 328 | string = "[" + ', '.join([str(i) for i in self.elements]) + "]" 329 | return string 330 | 331 | def return_type(self): 332 | return String("array") 333 | 334 | 335 | class Map(Value): 336 | def __init__(self, map): 337 | super().__init__() 338 | self.map = map 339 | 340 | def at(self, other): 341 | if isinstance(other, Number) or isinstance(other, String): 342 | try: 343 | return self.map[other.value], None 344 | except: 345 | return None, RuntimeError( 346 | other.pos_start, other.pos_end, f"Element at key '{other.value}' does not exist", self.context 347 | ) 348 | else: 349 | return Value.invalid_operation(self, other) 350 | 351 | def copy(self): 352 | copy = Map(self.map) 353 | copy.set_position(self.pos_start, self.pos_end) 354 | copy.set_context(self.context) 355 | return copy 356 | 357 | def __repr__(self): 358 | string = "{" 359 | for key, value in self.map.items(): 360 | string += f"{key}: {value}, " 361 | if string[-1] == " " and string[-2] == ",": 362 | string = string[:-2] + "}" 363 | else: 364 | string += "}" 365 | return string 366 | 367 | def return_type(self): 368 | return String("map") 369 | 370 | 371 | class BaseFunction(Value): 372 | def __init__(self, name): 373 | super().__init__() 374 | self.name = name if name is not None else "" 375 | 376 | def generate_new_context(self): 377 | new_context = Context(self.name, self.context, self.pos_start) 378 | new_context.symbol_table = SymbolTable(new_context.parent.symbol_table) 379 | return new_context 380 | 381 | def check_arguments(self, argument_names, arguments): 382 | res = RuntimeResult() 383 | # check the number of args are correct or not 384 | if len(arguments) > len(argument_names): 385 | return res.failure(RuntimeError( 386 | self.pos_start, self.pos_end, f"Too many arguments are passed to {self.name}", self.context 387 | )) 388 | elif len(arguments) < len(argument_names): 389 | return res.failure(RuntimeError( 390 | self.pos_start, self.pos_end, f"Too few arguments are passed to {self.name}", self.context 391 | )) 392 | else: 393 | return res.success(None) 394 | 395 | def fill_args(self, argument_names, arguments, context): 396 | for i in range(len(arguments)): 397 | arg_name = argument_names[i] 398 | arg_value = arguments[i] 399 | arg_value.set_context(context) 400 | context.symbol_table.set(arg_name, arg_value) 401 | 402 | def check_and_fill_args(self, arg_names, args, context): 403 | res = RuntimeResult() 404 | res.register(self.check_arguments(arg_names, args)) 405 | if res.should_return(): return res 406 | self.fill_args(arg_names, args, context) 407 | return res.success(None) 408 | 409 | 410 | class Function(BaseFunction): 411 | def __init__(self, name, body_node, arg_names, should_auto_return): 412 | super().__init__(name) 413 | self.body_node = body_node 414 | self.arg_names = arg_names 415 | self.should_auto_return = should_auto_return 416 | 417 | def execute(self, args): 418 | res = RuntimeResult() 419 | evaluator = Evaluator() 420 | context = self.generate_new_context() 421 | res.register(self.check_and_fill_args(self.arg_names, args, context)) 422 | if res.should_return(): return res 423 | value = res.register(evaluator.visit(self.body_node, context)) 424 | if res.should_return() and res.func_return_value is None: return res 425 | return_value = (value if self.should_auto_return else None) or res.func_return_value or Number.null 426 | return res.success(return_value) 427 | 428 | def copy(self): 429 | copy = Function(self.name, self.body_node, self.arg_names, self.should_auto_return) 430 | copy.set_position(self.pos_start, self.pos_end) 431 | copy.set_context(self.context) 432 | return copy 433 | 434 | def __repr__(self): 435 | return f"" 436 | 437 | def return_type(self): 438 | return String("function") 439 | 440 | --------------------------------------------------------------------------------