Compare commits

...
544 Commits
Author SHA1 Message Date
selimaj-dev 352d0594b2 Merge pull request #120 from mist-go/patches
Patches
2026-07-14 09:20:05 +02:00
selimaj-dev 48ca58725a RA passthrough 2026-07-14 09:13:22 +02:00
selimaj-dev 708b956750 fix Analyzer file path #118 2026-07-14 08:46:33 +02:00
selimaj-dev df9e31e26d fix Analyzer file path #118 2026-07-14 07:59:36 +02:00
selimaj-dev c716b6352c Fix mapping for analyzer 2026-07-14 07:47:25 +02:00
selimaj-dev 6f675b4253 Fix mapping for compiler 2026-07-14 07:37:16 +02:00
selimaj-dev 5079b10819 Added other struct types #117 2026-07-14 07:32:42 +02:00
selimaj-dev d834ff595d Added more struct rules #117 2026-07-14 07:19:43 +02:00
selimaj-dev 70ec348f4d Fix mutability #119 2026-07-14 07:15:17 +02:00
selimaj-dev 93ba0e97da Bump to full release 2026-07-12 06:44:13 -04:00
selimaj-dev 9c0aa3d182 Merge pull request #116 from mist-go/patches
Patches
2026-07-12 12:02:00 +02:00
selimaj-dev e1b851911d Fix completion polution 2026-07-12 06:00:16 -04:00
selimaj-dev 72f7b8430d Fix publish command 2026-07-12 05:43:50 -04:00
selimaj-dev 0100abfa53 Fix analyzer bugs 2026-07-12 05:36:57 -04:00
selimaj-dev 01b7e816ee Fix include manifest path #106 2026-07-12 05:26:33 -04:00
selimaj-dev ac94882e5a Fix mapping system #115 2026-07-12 05:15:00 -04:00
selimaj-dev 9220ee3b29 Merge pull request #114 from mist-go/type-patches
Type patches
2026-07-09 12:12:54 +02:00
selimaj-dev b15f13880a Fix generics and fn types 2026-07-09 12:07:37 +02:00
selimaj-dev d538168692 Removed unnecessary type (lifetime) 2026-07-09 12:00:11 +02:00
selimaj-dev b68e4245d4 Using core for classes 2026-07-09 10:53:07 +02:00
selimaj-dev c5354ff424 Using core for c_void 2026-07-09 10:51:44 +02:00
selimaj-dev be68f93038 Updated bootstrap 2026-07-09 10:26:06 +02:00
selimaj-dev e3c9657b07 Bump version to 0.4.0-alpha.0 2026-07-09 07:39:46 +02:00
selimaj-dev 2aab50d36d Merge pull request #112 from mist-go/virtual-methods
Virtual methods
2026-07-09 07:38:25 +02:00
selimaj-dev e75b707981 Virtual and overrides in analyzer 2026-07-09 07:34:08 +02:00
selimaj-dev 18a13dd170 Override and virtual semantic checking 2026-07-09 06:59:25 +02:00
selimaj-dev aacc08b983 Updated class tests 2026-07-09 06:51:36 +02:00
selimaj-dev df8e67fd4f Implicit virtual on override 2026-07-09 06:37:37 +02:00
selimaj-dev 08771fe5be Virtual functions 2026-07-09 06:30:11 +02:00
selimaj-dev 0d2199ee3a virtual keyword parsing and ast 2026-07-09 06:23:04 +02:00
selimaj-dev 442d1e66a8 Merge pull request #111 from mist-go/include
Include
2026-07-08 11:26:29 +02:00
selimaj-dev 8198b8d5cb Local include 2026-07-08 11:23:36 +02:00
selimaj-dev 44ac3c365d Inline doc gen 2026-07-08 10:52:11 +02:00
selimaj-dev c564fc3e90 Added use include 2026-07-08 10:44:09 +02:00
selimaj-dev bb006c1ba2 Added global include 2026-07-08 10:11:26 +02:00
selimaj-dev 4b69bbaed0 Merge pull request #110 from mist-go/array-type
Array type
2026-07-05 02:47:19 +02:00
selimaj-dev f574d6e8af Fix parenthesis 2026-07-05 02:45:38 +02:00
selimaj-dev 13664413c5 Array types 2026-07-05 02:37:48 +02:00
selimaj-dev b6256283a6 Merge pull request #109 from mist-go/more-tests
Add comprehensive test coverage for grammar rules
2026-07-04 21:59:58 +02:00
selimaj-dev f30613f094 Added more tests 2026-07-04 21:55:29 +02:00
selimaj-dev a1fd169568 Added more links 2026-07-04 21:39:30 +02:00
selimaj-dev 3c5f13f3f6 Merge pull request #108 from mist-go/struct-field-style
Allman struct/enum field style, tuple var decls, cleanup
2026-07-04 19:34:57 +02:00
selimaj-dev f4f92c57ee Fix as type 2026-07-04 19:26:25 +02:00
selimaj-dev df34c72c97 Add tuple type variable decleration 2026-07-04 19:23:10 +02:00
selimaj-dev 517a2e5a2b Var decl with repeat 2026-07-04 09:55:23 +02:00
selimaj-dev eeac773c06 Removed duped module declerations 2026-07-04 09:40:04 +02:00
selimaj-dev 4f3966d8d8 Allman struct and enum field style 2026-07-04 09:38:13 +02:00
selimaj-dev 409301b3d6 Allman struct and enum field style 2026-07-04 09:16:13 +02:00
selimaj-dev 223bafaad7 Merge pull request #107 from mist-go/fix-class-initializers
Fix default initializers in classes
2026-07-04 09:05:27 +02:00
selimaj-dev 603ce1eb1e Fix default initializers in classes 2026-07-04 09:03:52 +02:00
selimaj-dev b02439edfc Bump version 2026-07-02 22:06:33 +02:00
selimaj-dev 0449789159 Merge pull request #105 from mist-go/cli-improvements
CLI improvements, module system fixes, project scaffolding, and bug fixes
2026-07-02 21:56:39 +02:00
selimaj-dev 2738f57bd9 Updated usage command 2026-07-02 21:49:33 +02:00
selimaj-dev f3046e3442 Fixed module system 2026-07-02 21:24:13 +02:00
selimaj-dev 28e9fb664c Fixed mapping 2026-07-02 21:07:57 +02:00
selimaj-dev 3a8537682e Added more cli commands #100 2026-07-02 20:57:02 +02:00
selimaj-dev eb23ff1e5a Gitignore, and mist new 2026-07-02 20:51:02 +02:00
selimaj-dev b8394bba52 Fix init 2026-07-02 20:45:00 +02:00
selimaj-dev ff861095e3 Using toml for init 2026-07-02 20:38:01 +02:00
selimaj-dev 744adeb068 Add mist toml on init 2026-07-02 20:28:25 +02:00
selimaj-dev 113ae54e6e Improved cli command options #100 2026-07-02 18:46:45 +02:00
selimaj-dev c7bf4f7131 Merge pull request #104 from mist-go/syntax-improvements
Syntax improvements
2026-07-02 07:25:26 +02:00
selimaj-dev 579d229cad Type aliases 2026-07-02 07:05:19 +02:00
selimaj-dev d62d884add Removed fmt (will add when i have close to 1:1 syntax support) 2026-07-02 06:53:47 +02:00
selimaj-dev 5346cd05be constants and static #102 2026-07-02 06:51:04 +02:00
selimaj-dev 493c668495 Working top level statement #103 2026-07-02 06:40:20 +02:00
selimaj-dev 4579c656b9 Possibly removed the need for ensure_semicolon 2026-07-02 06:33:17 +02:00
selimaj-dev 68cf239f92 Top level as statement #103 2026-07-02 06:25:44 +02:00
selimaj-dev 9021da224e Merge pull request #101 from mist-go/bug-patches
Bug patches
2026-06-30 21:04:56 +02:00
selimaj-dev d0a72b49f0 Fix module system in analyzer 2026-06-30 21:04:12 +02:00
selimaj-dev a5dad690bf Fix bug 2026-06-30 20:51:57 +02:00
selimaj-dev e9b7312362 Added include to Mist.toml 2026-06-30 19:58:47 +02:00
selimaj-dev 6e67fd852b bump to alpha 1 2026-06-30 19:48:33 +02:00
selimaj-dev 67acef8270 Merge pull request #99 from mist-go/subcrates-and-diagnostics
Subcrates and diagnostics
2026-06-30 19:46:58 +02:00
selimaj-dev a3da192b9a Analyzer Sub crate support 2026-06-30 19:41:34 +02:00
selimaj-dev 310ff6b53c Fix include non mist crates #86 2026-06-30 19:28:27 +02:00
selimaj-dev 4e1bcf36fc Include sub crates #86 2026-06-30 19:14:12 +02:00
selimaj-dev c1d7152992 Deduped config 2026-06-30 18:30:19 +02:00
selimaj-dev bd938ec3e7 Updated transpiler config 2026-06-30 18:23:15 +02:00
selimaj-dev bfaa9eeea5 Fix Diagnostics #93 2026-06-30 07:08:39 +02:00
selimaj-dev 3ff4c2ab08 Using FS for saving files #93 2026-06-30 06:24:55 +02:00
selimaj-dev 3d30e0a092 Fix fmt expr path generics 2026-06-28 17:39:35 +02:00
selimaj-dev 502bde1536 Updated boostrap 2026-06-28 17:38:16 +02:00
selimaj-dev d8fd8cf999 Bump version 2026-06-28 16:01:01 +02:00
selimaj-dev 3ce8fe5278 Merge pull request #98 from mist-go/mist-fmt-style
Mist fmt style
2026-06-28 15:59:22 +02:00
selimaj-dev 2426e585d6 Fix constructor and non allman 2026-06-28 15:57:00 +02:00
selimaj-dev 2174b99a3f Fmt config 2026-06-28 15:52:02 +02:00
selimaj-dev 31eebb4baa Modularized bracket style 2026-06-28 15:16:33 +02:00
selimaj-dev 41f8b94c82 Merge pull request #97 from mist-go/tidy-grammar
VC: Tidy up the grammar/parser #94
2026-06-28 07:31:26 +02:00
selimaj-dev 64081bc494 Tidy up the grammar #94 2026-06-28 07:30:49 +02:00
selimaj-dev 3c6ebb66c6 Merge pull request #96 from mist-go/function-types
Function types
2026-06-28 06:06:50 +02:00
selimaj-dev a867dbc797 Fixed codegen for function type 2026-06-28 06:04:39 +02:00
selimaj-dev a2fc8a4922 AST gen for function type 2026-06-28 06:00:11 +02:00
selimaj-dev dbfcaa9b0d Void type 2026-06-28 05:49:35 +02:00
selimaj-dev 76541040c9 Function types 2026-06-28 05:45:13 +02:00
selimaj-dev 3ddb1bc601 Unsafe pointer 2026-06-28 05:24:30 +02:00
selimaj-dev bf5d243036 Merge pull request #92 from mist-go/small-analyzer-patches
Small analyzer patches
2026-06-27 04:31:02 +02:00
selimaj-dev b6b5214684 Fixed proc macro server error 2026-06-26 17:06:53 +02:00
selimaj-dev a37dffb94b On creation 2026-06-26 05:01:15 +02:00
selimaj-dev 84c75c290f Merge pull request #91 from mist-go/mist-fmt
Mist fmt
2026-06-26 02:36:03 +02:00
selimaj-dev 46e9783257 Fixed bugs 2026-06-26 02:04:33 +02:00
selimaj-dev 9b7de09b0a Fmt Allman style 2026-06-26 01:49:00 +02:00
selimaj-dev 6c9c0e03d2 Fix formatter bugs 2026-06-26 01:29:51 +02:00
selimaj-dev e5509e89a4 Working formatter #90 2026-06-26 01:02:01 +02:00
selimaj-dev fda193b8ff Mist fmt 2026-06-26 00:37:41 +02:00
selimaj-dev c78c9985f4 Mist fmt 2026-06-26 00:37:33 +02:00
selimaj-dev d0341deef9 Merge pull request #89 from mist-go/analyzer-patches
Analyzer(LSP) patches: Major Dev Exp improvements
2026-06-26 00:09:44 +02:00
selimaj-dev 26c0fb34e0 Improved keywords 2026-06-26 00:07:09 +02:00
selimaj-dev 75dd2e4af2 Fix a few snippets 2026-06-26 00:05:25 +02:00
selimaj-dev c47beae67d Contextual snippets (massive DX improvement) 2026-06-25 23:49:05 +02:00
selimaj-dev c6c33bf83b Improved completions 2026-06-25 23:28:11 +02:00
selimaj-dev 065dc575a5 Improved scope checking 2026-06-25 23:00:13 +02:00
selimaj-dev a1a3ce1a29 Removed analyzer debug file 2026-06-25 22:44:00 +02:00
selimaj-dev a63199a41d Removed fn from keywords 2026-06-25 22:24:25 +02:00
selimaj-dev 33430f9541 Merge pull request #88 from mist-go/separate-self-param
Separate self param
2026-06-25 20:08:38 +02:00
selimaj-dev 2549535e4b Updated codegen for class decl 2026-06-25 19:47:07 +02:00
selimaj-dev 243b4ba5d0 Updated codegen 2026-06-25 19:16:07 +02:00
selimaj-dev 4ab7827955 Added separate self param 2026-06-25 19:08:52 +02:00
selimaj-dev 2c11131e1a Merge pull request #87 from mist-go/rm-err-recovery
Remove: Error recovery
2026-06-25 04:21:24 +02:00
selimaj-dev 93e7a0fdef Updated api and analyzer with error recovery 2026-06-25 04:15:47 +02:00
selimaj-dev 0dd9e2fb37 Removed error recovery from items 2026-06-25 04:13:57 +02:00
selimaj-dev ae60aee85c Removed error recovery from common 2026-06-25 04:08:31 +02:00
selimaj-dev 6cc46751f9 Removed error recovery 2026-06-24 23:38:05 +02:00
selimaj-dev 2ef2232b84 Bump version 2026-06-24 14:40:39 +02:00
selimaj-dev 0cbfa10281 Merge pull request #85 from mist-go/improved-analyzer
Improved analyzer
2026-06-24 14:34:00 +02:00
selimaj-dev 9ce6d44eb4 Improved errors 2026-06-24 14:33:11 +02:00
selimaj-dev 1f2e989522 Fixed bugs #83 2026-06-24 14:11:57 +02:00
selimaj-dev ca11866328 Improved LSP completion ordering 2026-06-24 03:44:32 +02:00
selimaj-dev 055d50edd5 Bump version 2026-06-24 02:47:49 +02:00
selimaj-dev c8d7f05e67 Merge pull request #84 from mist-go/syntax-philosphy-update
Syntax philosphy update
2026-06-23 19:23:11 +02:00
selimaj-dev 9b1519b068 Updated code and readme 2026-06-23 19:19:22 +02:00
selimaj-dev dc8acdc2bd Improved match statements 2026-06-23 19:03:47 +02:00
selimaj-dev 97de75252d Updated api bootstrap 2026-06-23 18:33:05 +02:00
selimaj-dev 2f12f5ac53 Updated closure syntax 2026-06-23 17:41:49 +02:00
selimaj-dev e4b7b4abf9 Updated api bootstrap 2026-06-23 17:25:26 +02:00
selimaj-dev 208e4dac6b Updated main bootstrap 2026-06-23 16:41:56 +02:00
selimaj-dev b73396afb7 Fixed mod attribute generation 2026-06-23 13:24:46 +02:00
selimaj-dev 7f7c1e2000 Fixed mod attributes 2026-06-23 12:47:38 +02:00
selimaj-dev 2f6303ba30 Updated tests and fixed grammar 2026-06-23 03:44:54 +02:00
selimaj-dev 2ae4ca510d Using & for refrences, and switched to type name 2026-06-23 03:26:30 +02:00
selimaj-dev b6ed825bf6 Fixed transpiler errors 2026-06-22 03:17:13 +02:00
selimaj-dev 77e7430776 Update api bootstrap 2026-06-22 02:30:18 +02:00
selimaj-dev d58d4c74cd Update bootstrap 2026-06-22 02:22:57 +02:00
selimaj-dev 00ab0b84ce Bump version 2026-06-22 02:17:06 +02:00
selimaj-dev 320758fd81 Fixed codegen 2026-06-22 02:13:52 +02:00
selimaj-dev 008b37b0de Merge pull request #82 from mist-go/working-analyzer
Working analyzer
2026-06-22 02:08:45 +02:00
selimaj-dev b257ff5c1a Fixed syntax errors 2026-06-22 01:49:02 +02:00
selimaj-dev e58a4a8524 Added void 2026-06-22 01:29:11 +02:00
selimaj-dev 08e2eff4ab Keyword injection 2026-06-22 01:28:04 +02:00
selimaj-dev cb626757ba completion syntax exceptions 2026-06-22 00:59:30 +02:00
selimaj-dev 2718a5028a Fixed module system 2026-06-22 00:48:13 +02:00
selimaj-dev b69168f135 Fixed native rust goto 2026-06-22 00:23:50 +02:00
selimaj-dev 48c24235b1 Goto works (kind of) 2026-06-22 00:19:42 +02:00
selimaj-dev 5c6b3bbca1 Fixed punctuation 2026-06-22 00:09:27 +02:00
selimaj-dev c3f56dd3e9 Fixed punctuation error 2026-06-22 00:01:24 +02:00
selimaj-dev 173c983c6f Working markers 2026-06-21 23:37:50 +02:00
selimaj-dev 5054185e0d Fixed bugs 2026-06-21 23:14:07 +02:00
selimaj-dev 6a7c45ffbe Debugging 2026-06-21 23:08:53 +02:00
selimaj-dev 1546660435 Fixed initialization error 2026-06-21 22:52:49 +02:00
selimaj-dev ee95fc60fc VC: hopfully fixed 2026-06-21 22:06:19 +02:00
selimaj-dev c735441f37 VC: Tmp fix 2026-06-21 19:48:49 +02:00
selimaj-dev cd7a62dc34 VC: Tmp fix 2026-06-21 19:45:06 +02:00
selimaj-dev fae231d481 VC: Fix initialization error 2026-06-21 19:43:05 +02:00
selimaj-dev 8f57517a9f VC: Marker based positions 2026-06-21 19:30:00 +02:00
selimaj-dev 16803aa0f6 Merge pull request #81 from mist-go/analyzer-patch
VC: LSP Analyzer patch
2026-06-21 17:10:48 +02:00
selimaj-dev d1335bb613 (VC): LSP 2026-06-21 15:45:01 +02:00
selimaj-dev 4b733f6b9c Cleaned up lsp 2026-06-21 15:05:58 +02:00
selimaj-dev 8f115353bb Removed comment mapping completely 2026-06-20 19:21:10 +02:00
selimaj-dev 0dd1016980 Merge pull request #80 from mist-go/class-semantics
Class semantics
2026-06-16 16:27:44 +02:00
selimaj-dev 4def6db820 Moved ovveride to after params 2026-06-16 16:19:28 +02:00
selimaj-dev 8b95497725 Super semantics 2026-06-16 16:14:02 +02:00
selimaj-dev e369c94d21 Method calls 2026-06-16 16:00:52 +02:00
selimaj-dev d434ec78e7 More advanced class semantics 2026-06-16 15:54:21 +02:00
selimaj-dev ecfff0ac0d Improved semantic errors 2026-06-16 15:37:34 +02:00
selimaj-dev bbb94a4f97 Semantic error handling and slight error improvements 2026-06-16 15:19:58 +02:00
selimaj-dev 2bb29991da Class semantics 2026-06-16 14:59:34 +02:00
selimaj-dev 175e7fa858 Merge pull request #79 from mist-go/syntax-patches
Syntax patches
2026-06-16 13:55:48 +02:00
selimaj-dev 2122698000 Better class test 2026-06-16 13:49:38 +02:00
selimaj-dev 001165ee58 Fixed lifetime on ref 2026-06-16 13:17:06 +02:00
selimaj-dev e4fbab190c Added items 2026-06-16 13:15:01 +02:00
selimaj-dev fa6765cdd9 Updated common tests 2026-06-16 12:46:07 +02:00
selimaj-dev f07bde8d3f Unsafe lifetime 2026-06-16 03:59:28 +02:00
selimaj-dev d7e5e72bbb Syntax: Tuples as () 2026-06-16 03:32:45 +02:00
selimaj-dev aadccb7f38 Syntax: fn type name 2026-06-16 03:29:01 +02:00
selimaj-dev eea72f5bb3 Modularized the transpiler 2026-06-15 17:10:15 +02:00
selimaj-dev 3b6fc03546 Fixed analyzer output 2026-06-15 16:38:51 +02:00
selimaj-dev 48e3522543 Fix: postfix expr on statement bodies 2026-06-15 16:32:52 +02:00
selimaj-dev f45d83d261 Bump to 0.3.4-alpha.0 2026-06-15 16:23:12 +02:00
selimaj-dev 0e3e0bdb56 removed bloat from mapping 2026-06-15 15:38:56 +02:00
selimaj-dev b6eb46d985 Merge pull request #78 from mist-go/rewrite-map-system
Rewrite map system
2026-06-15 15:34:59 +02:00
selimaj-dev 6b618f3eb3 Removed warnings from api 2026-06-15 15:21:49 +02:00
selimaj-dev 1163849039 Fixed class method indentation 2026-06-15 15:08:48 +02:00
selimaj-dev 12cf4e94d8 Implemented updated mapping data structure 2026-06-15 15:04:10 +02:00
selimaj-dev 663dab52ec Updated mapping data structure 2026-06-15 14:49:44 +02:00
selimaj-dev 44f10d3fb7 Updated builder with new mapping 2026-06-15 14:32:51 +02:00
selimaj-dev bed7b17134 Made add in codegen faster 2026-06-15 14:21:53 +02:00
selimaj-dev 5f0b1fa67a Working mapgen and fixed indentation 2026-06-15 14:12:33 +02:00
selimaj-dev 37e0a574d5 Working map shift gen 2026-06-14 04:18:57 +02:00
selimaj-dev 33d6c931f5 Working map gen 2026-06-14 04:06:39 +02:00
selimaj-dev db3ae3f37e Temp disable old err mapping 2026-06-14 03:57:48 +02:00
selimaj-dev 4d50c8c1be Map generation is separated 2026-06-14 03:22:41 +02:00
selimaj-dev 70924e13c8 Bump to 0.3.3-alpha.0 2026-06-13 20:14:18 +02:00
selimaj-dev b6f755cef6 Merge pull request #77 from mist-go/module-system-caching
Module system caching
2026-06-13 20:11:50 +02:00
selimaj-dev 01e3c30e2b child condition for packages 2026-06-13 20:04:16 +02:00
selimaj-dev b2ff76d691 Working module cache 2026-06-13 19:54:05 +02:00
selimaj-dev c8187379a5 Working pre-processing module name 2026-06-13 19:06:34 +02:00
selimaj-dev 5d3e393d5a Parse module function 2026-06-13 18:43:42 +02:00
selimaj-dev 3196b2b652 Patched if statements acting like structs 2026-06-13 03:23:13 +02:00
selimaj-dev 919447875a Update api bootstrap 2026-06-12 19:17:34 +02:00
selimaj-dev a31f6633fe Update main bootstrap 2026-06-12 19:02:32 +02:00
selimaj-dev 1a7e6c5f37 Bump to 0.3.2-alpha.0 2026-06-12 18:49:34 +02:00
selimaj-dev 52b472ed94 Removed zeroed warning on tests 2026-06-12 18:38:03 +02:00
selimaj-dev 9785d0a430 removed warning from mist api 2026-06-12 18:29:59 +02:00
selimaj-dev ddcffaea92 Optional constructor 2026-06-12 18:25:26 +02:00
selimaj-dev d4992e76fc Merge pull request #76 from mist-go/class-optimizations
Massive Class optimizations
2026-06-12 17:34:30 +02:00
selimaj-dev d0716fb735 Override target testing 2026-06-12 17:19:53 +02:00
selimaj-dev fab7326357 Optimized v table and vptr 2026-06-12 17:04:24 +02:00
selimaj-dev d3ff834111 Put super as the first field, and removed _pin 2026-06-12 16:25:16 +02:00
selimaj-dev b19b1bb41d Fixed vptr condition on static methods 2026-06-12 16:21:46 +02:00
selimaj-dev 526b479ea4 Added method vptr condition 2026-06-12 16:14:32 +02:00
selimaj-dev 37e3da5d67 Simplified vptr 2026-06-12 16:04:33 +02:00
selimaj-dev 5a1285a2a8 Removed allocation in favor of stack 2026-06-12 15:53:51 +02:00
selimaj-dev 076f1f6d33 Merge pull request #75 from mist-go/module-system
Module system
2026-06-12 15:02:56 +02:00
selimaj-dev 05fc8fa7f3 Fixed package gen 2026-06-11 21:13:59 +02:00
selimaj-dev c06eebe50b Mist package test 2026-06-11 20:22:23 +02:00
selimaj-dev da3923830d added analyzer 2026-06-11 20:19:16 +02:00
selimaj-dev b547c7d934 removed yo 2026-06-11 20:18:49 +02:00
selimaj-dev 9ad253e916 Fixing 2026-06-11 20:17:29 +02:00
selimaj-dev a5a3d6566b Working package ignore 2026-06-11 19:34:37 +02:00
selimaj-dev 74d53fff97 Mist.toml support 2026-06-11 19:06:07 +02:00
selimaj-dev c37392046a Working explicit module system 2026-06-11 16:05:45 +02:00
selimaj-dev 2256ef2a9f Parser 2026-06-11 10:21:04 +02:00
selimaj-dev cb3f1bcde1 Fixed where module needs to be placed 2026-06-10 05:54:19 +02:00
selimaj-dev e7f1072050 Implemented tests 2026-06-10 05:48:51 +02:00
selimaj-dev 14e88e2e4d Fixed API 2026-06-10 05:44:58 +02:00
selimaj-dev 1619250ba5 Updated parser 2026-06-10 05:37:08 +02:00
selimaj-dev 562bcd7f1e Merge pull request #74 from mist-go/removed-c-flow
Removed c control flow
2026-06-10 05:20:32 +02:00
selimaj-dev 15a0f9e491 Fixed gen 2026-06-10 04:48:49 +02:00
selimaj-dev e3ef968033 Fixed unsafe 2026-06-10 04:43:36 +02:00
selimaj-dev afd3d05e2f Removed C style flow control 2026-06-10 04:35:11 +02:00
selimaj-dev 286894c5db Bump version to 0.0.3-alpha.0 2026-06-09 21:43:51 +02:00
selimaj-dev 947e5f931e Improved OOP errors 2026-06-09 20:44:47 +02:00
selimaj-dev 1b6340e7a6 ptr write assignments 2026-06-09 20:24:57 +02:00
selimaj-dev 7a613e93e8 Updated image 2026-06-09 20:08:38 +02:00
selimaj-dev 4780f5ce68 Updated image 2026-06-09 20:08:09 +02:00
selimaj-dev be0550b57a Updated readme 2026-06-09 20:03:57 +02:00
selimaj-dev 1e58de02be Merge pull request #70 from mist-go/fully-working-inheritance
Fully working inheritance & OOP
2026-06-09 19:44:41 +02:00
selimaj-dev 41fd60dd12 Optimized vt tests 2026-06-09 19:03:25 +02:00
selimaj-dev 9949027bc9 Fixed returning 2026-06-09 18:05:47 +02:00
selimaj-dev ba5145d9ad Fixed args 2026-06-09 18:01:08 +02:00
selimaj-dev b20337b385 Fixed deref with generics 2026-06-09 17:50:40 +02:00
selimaj-dev abda2c4c41 Working override target 2026-06-09 17:25:27 +02:00
selimaj-dev 72fa94bdc6 Updated VTABLE and constructor 2026-06-09 17:18:05 +02:00
selimaj-dev e3e6caf4e6 Refactored class decl generator 2026-06-09 16:43:52 +02:00
selimaj-dev f37a1019ae Working improved inheritance generics 2026-06-09 14:56:55 +02:00
selimaj-dev 0215e295b5 Working with generics 2026-06-09 14:47:41 +02:00
selimaj-dev 9206ca440e Improved override 2026-06-09 14:27:27 +02:00
selimaj-dev a9f6cce1b3 Improved override 2026-06-09 13:51:32 +02:00
selimaj-dev 0347892056 Override(path) syntax 2026-06-09 12:30:22 +02:00
selimaj-dev 20762a01bd Merge pull request #69 from mist-go/oop-inheritance
OOP & inheritance
2026-06-07 23:48:53 +02:00
selimaj-dev 3e7863afed V table type checking 2026-06-07 10:24:13 +02:00
selimaj-dev 27e78dc377 Improved safety 2026-06-07 09:49:30 +02:00
selimaj-dev 9001c1c3e2 Removed void 2026-06-07 03:40:23 +02:00
selimaj-dev 206b2fa414 super edge case 2026-06-07 03:38:10 +02:00
selimaj-dev fa4a7ee4c7 Super and super 2026-06-07 03:36:02 +02:00
selimaj-dev e70e813497 Working inheritance #68 2026-06-07 01:57:09 +02:00
selimaj-dev 1977bd59be VTable update 2026-06-07 01:32:00 +02:00
selimaj-dev 58e1f9ddd2 Super VTable generation 2026-06-07 01:18:14 +02:00
selimaj-dev fafc03d5d8 Heap super 2026-06-07 00:40:22 +02:00
selimaj-dev 982b0bf4a5 Improved constructor 2026-06-07 00:38:14 +02:00
selimaj-dev d0796aa5df Working param and return type fn type 2026-06-07 00:30:27 +02:00
selimaj-dev e7b4e65b71 Working method point 2026-06-07 00:17:28 +02:00
selimaj-dev 7acef24e09 Plan for redo 2026-06-07 00:02:06 +02:00
selimaj-dev 5e5d22f3c5 Added static fn type 2026-06-06 23:52:53 +02:00
selimaj-dev 330beaea75 Generating body 2026-06-06 23:50:40 +02:00
selimaj-dev 7229cfd9f5 VTABLE OOP 2026-06-06 23:16:27 +02:00
selimaj-dev eb2552b19a Separated class decl 2026-06-06 22:20:32 +02:00
selimaj-dev 6e26b283fa Updated api bootstrap 2026-06-05 23:11:48 +02:00
selimaj-dev 1a281cd344 Updated main bootstrap 2026-06-05 22:57:48 +02:00
selimaj-dev c8b43a3e90 Bump version to 0.3.0-alpha.0 2026-06-05 20:35:40 +02:00
selimaj-dev 721700ea03 Merge pull request #67 from mist-go/syntax-philosphy-rewrite
Syntax philosphy rewrite
2026-06-05 20:25:37 +02:00
selimaj-dev 8c28e61e42 Updated test #64 2026-06-05 20:06:38 +02:00
selimaj-dev a9eb77f158 Update: Closures #64 2026-06-05 18:51:55 +02:00
selimaj-dev 765e2ded93 Update: Self param #64 2026-06-05 18:16:37 +02:00
selimaj-dev d364c41c26 Update: Function #65 2026-06-05 18:07:47 +02:00
selimaj-dev ac9ee5a4b6 Update: Decleration Helpers, parser #65 2026-06-05 17:52:04 +02:00
selimaj-dev 56c22eb1ed Update: Decleration Helpers, grammar #65 2026-06-05 17:43:59 +02:00
selimaj-dev cac497a560 Fixed type bugs #65 2026-06-05 17:39:41 +02:00
selimaj-dev b559215212 Updated type codegen #65 2026-06-05 17:34:06 +02:00
selimaj-dev 143d496ee8 Updated type parser #65 2026-06-05 17:25:39 +02:00
selimaj-dev a589d7173d Updated type ast #65 2026-06-05 17:11:46 +02:00
selimaj-dev 40b2981252 Updated type grammar #65 2026-06-05 17:06:06 +02:00
selimaj-dev 94320bafa6 Merge pull request #66 from mist-go/closures-and-tests
Closures and tests
2026-06-05 13:31:18 +02:00
selimaj-dev 970441b905 Removed debug in struct_pattern 2026-06-05 13:02:39 +02:00
selimaj-dev 2e09ee85d4 Fixed class test 2026-06-05 12:59:59 +02:00
selimaj-dev 3fed475c1c Fixed array 2026-06-05 12:58:13 +02:00
selimaj-dev 1e09b7043a Test cargo lock 2026-06-05 12:56:48 +02:00
selimaj-dev b311dbd16c Fixed test 2026-06-05 12:56:14 +02:00
selimaj-dev 595ddc789d Fixed array expr 2026-06-05 12:38:25 +02:00
selimaj-dev d5501ef25e Tests 2026-06-05 12:32:12 +02:00
selimaj-dev 0955bca5bc Updated closures 2026-06-05 12:14:19 +02:00
selimaj-dev 8df4351563 Updated api bootstrap 2026-06-04 19:56:17 +02:00
selimaj-dev 2384c4438b Updated main bootstrap 2026-06-04 19:53:16 +02:00
selimaj-dev 14ae964be4 Updated version 2026-06-04 19:49:22 +02:00
selimaj-dev f128bb0008 Fixed trailing 2026-06-04 19:34:49 +02:00
selimaj-dev 1810520d2c Merge pull request #64 from mist-go/syntax-patches
Syntax patches
2026-06-04 19:24:40 +02:00
selimaj-dev 202f41c0e6 Fixed type/generics parsing 2026-06-04 18:50:33 +02:00
selimaj-dev 6cacfd7135 Identifier setting via struct #59 2026-06-04 18:20:54 +02:00
selimaj-dev d4dc1571b2 Tuple field access #59 2026-06-04 18:14:52 +02:00
selimaj-dev d3b54b4114 Fix else if statements #49 2026-06-04 17:57:27 +02:00
selimaj-dev e571d98cd0 Fix undeclared lifetime and simplifed grammar #50 2026-06-04 17:44:41 +02:00
selimaj-dev a8717aa5c4 Fix methods #58 and #55 2026-06-04 17:38:49 +02:00
selimaj-dev 20d9641dda Merge pull request #63 from mist-go/syntax-patches
Syntax patches & bootstrapping
2026-06-04 17:18:26 +02:00
selimaj-dev fc4dd0aa3c Etc pattern 2026-06-04 11:01:28 +02:00
selimaj-dev 7a5e03afd6 Fixed constructor args 2026-06-04 10:39:41 +02:00
selimaj-dev a4df59927e Removed <> from use 2026-06-04 10:01:26 +02:00
selimaj-dev a568d465af Updated api bootstrap 2026-06-04 09:51:27 +02:00
selimaj-dev 0677d15405 Updated main bootstrap 2026-06-04 09:47:41 +02:00
selimaj-dev 5771d15d74 Bump version to 0.2.0-alpha.0 2026-06-03 20:18:57 +02:00
selimaj-dev 5dda3dd32e Merge pull request #62 from mist-go/syntax-changes
Syntax changes
2026-06-03 20:01:16 +02:00
selimaj-dev c07e0bcb3e Fixed constructor args #60 2026-06-03 19:51:27 +02:00
selimaj-dev 269e43930f Macro delimiter 2026-06-03 18:12:30 +02:00
selimaj-dev 4683a3039e fixed var to let 2026-06-03 17:36:44 +02:00
selimaj-dev f4072b08a3 Removed new keyword 2026-06-03 17:29:39 +02:00
selimaj-dev 9a500c4bcf Replaced var with let 2026-06-03 17:27:38 +02:00
selimaj-dev 1608b10af8 Merge pull request #61 from mist-go/refactor-module-system
Refactor module system
2026-06-03 16:49:13 +02:00
selimaj-dev a3455e1b68 Removed should_skip 2026-06-03 16:19:32 +02:00
selimaj-dev 248462e467 Sidefiles and empty dir ignore 2026-06-03 16:17:21 +02:00
selimaj-dev 71e4f74c24 Fixed module system 2026-06-03 16:00:23 +02:00
selimaj-dev e0b52a0216 Fixed sidefiles in module system 2026-06-03 15:44:41 +02:00
selimaj-dev 8a0eee547d Removed warnings from transpiler 2026-06-02 23:28:59 +02:00
selimaj-dev 280e11a95e Bootstrapped builder 2026-06-02 23:24:11 +02:00
selimaj-dev cdcc69f975 Bootstrapped builder 2026-06-02 23:24:05 +02:00
selimaj-dev ece3d2fbf6 Fixed versions 2026-06-02 13:58:02 +02:00
selimaj-dev 7641d866b8 Fixed versions 2026-06-02 13:55:30 +02:00
selimaj-dev fe96e3aec6 Release 0.1.7-alpha.2
[email protected]
[email protected]

Generated by cargo-workspaces
2026-06-02 13:41:28 +02:00
selimaj-dev 72010faf03 Fixed tuple pattern 2026-06-02 12:37:15 +02:00
selimaj-dev e5df8df9b0 Release 0.1.7-alpha.1
[email protected]
[email protected]
[email protected]

Generated by cargo-workspaces
2026-06-01 13:50:49 +02:00
selimaj-dev ee40450f3a Merge pull request #57 from mist-go/module-system
Module system
2026-06-01 13:49:21 +02:00
selimaj-dev be6d2de39c improved code quality 2026-06-01 13:10:46 +02:00
selimaj-dev aff15f67c7 Working module system 2026-06-01 12:26:20 +02:00
selimaj-dev cfd1910f39 Working transpiler 2026-06-01 12:10:33 +02:00
selimaj-dev 082981f0bd Working module reading 2026-06-01 11:40:01 +02:00
selimaj-dev b384f55c77 Updated analyzer to remove the need for .mist/lib 2026-05-31 12:56:54 +02:00
selimaj-dev c4756262e1 ts sucks 2026-05-31 12:47:24 +02:00
selimaj-dev 74f10cc74b Removed lsp dev 2026-05-31 12:45:53 +02:00
selimaj-dev acef0888a3 Thinking of better ways to make analyzer work 2026-05-31 12:42:55 +02:00
selimaj-dev 18ab88af64 Thinking of better ways to make analyzer work 2026-05-31 12:41:48 +02:00
selimaj-dev 5e6cdc84b9 Updated cargo version 2026-05-31 12:39:10 +02:00
selimaj-dev 2dc5cdc9d9 Release 0.1.7-alpha.0
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Generated by cargo-workspaces
2026-05-31 12:36:23 +02:00
selimaj-dev 893c981a41 Merge pull request #56 from mist-go/future-proofed-modules
Future proofed module stucture
2026-05-29 20:35:12 +02:00
selimaj-dev 0b3c4b8143 Module structure 2026-05-29 20:33:30 +02:00
selimaj-dev 86a1df7ad5 Mist Module system basic structure 2026-05-29 16:13:52 +02:00
selimaj-dev 3fa04cddd0 mist api lsp 2026-05-29 09:17:51 +02:00
selimaj-dev 371365b8cf Separated mist api 2026-05-29 09:04:58 +02:00
selimaj-dev b74da3255a Init mist-api 2026-05-29 08:58:42 +02:00
selimaj-dev 83e5e98641 Added mist.toml 2026-05-29 08:52:30 +02:00
selimaj-dev c774737074 Merge pull request #53 from mist-go/inheritance
Inheritance
2026-05-28 17:43:56 +02:00
selimaj-dev 9e1b9ad564 Fixed attributes 2026-05-28 16:28:20 +02:00
selimaj-dev 97b2cc4413 Working inheritance 2026-05-28 16:21:36 +02:00
selimaj-dev 99ff0ead2d Inheritance gen 2026-05-28 16:08:31 +02:00
selimaj-dev b0f3dccc87 Inheritance parsing 2026-05-28 15:55:00 +02:00
selimaj-dev 86a781c3f2 Merge pull request #52 from mist-go/parser-patches
Parser patches
2026-05-28 15:47:44 +02:00
selimaj-dev 583d51141f Fixed empty items 2026-05-28 15:44:52 +02:00
selimaj-dev ad11a3bd6a Improved match item span 2026-05-28 12:16:28 +02:00
selimaj-dev 7a2ba74d9c Working mut pattern 2026-05-28 11:52:40 +02:00
selimaj-dev 7007aa32f1 Refactored mutability 2026-05-28 11:45:26 +02:00
selimaj-dev 3444f93546 Updated codegen 2026-05-28 11:36:28 +02:00
selimaj-dev e09c7926e5 Updated pattern ast 2026-05-28 11:34:14 +02:00
selimaj-dev 83e98573aa Updated pattern grammar 2026-05-28 11:30:47 +02:00
selimaj-dev 3368696523 Merge pull request #51 from mist-go/bootstrapped-transpiler
Bootstrapped transpiler in mist
2026-05-25 19:45:57 +02:00
selimaj-dev ec1864334c Bootstrapped transpiler in mist 2026-05-25 16:06:04 +02:00
selimaj-dev 7c4595aeb9 Updated cargo.toml for lsp 2026-05-24 18:36:13 +02:00
selimaj-dev 8202cd6773 Merge pull request #48 from mist-go/lsp-patches-and-completions
Lsp patches and completions
2026-05-24 17:44:37 +02:00
selimaj-dev ecdbc9416a Build all on initialize 2026-05-24 17:38:35 +02:00
selimaj-dev 24134ec925 Production safe analyzer 2026-05-24 17:24:37 +02:00
selimaj-dev dbf3a80387 Working completions 2026-05-24 17:04:08 +02:00
selimaj-dev cdffc87161 Using ropey 2026-05-24 16:49:53 +02:00
selimaj-dev fbf60944a8 using ropey 2026-05-24 16:24:22 +02:00
selimaj-dev 5a6adbc5e4 updated capabilities 2026-05-24 16:19:51 +02:00
selimaj-dev 354965b425 Completion 2026-05-24 15:45:01 +02:00
selimaj-dev f5fcbbacb6 did change and close 2026-05-24 15:11:24 +02:00
selimaj-dev e358636e41 Updated version 2026-05-24 14:51:01 +02:00
selimaj-dev 2c5a845c57 Merge pull request #47 from mist-go/closures-and-bodies
Closures and fix statement bodies
2026-05-24 14:47:32 +02:00
selimaj-dev f21cd5a927 Fixed statement bodies 2026-05-24 14:43:09 +02:00
selimaj-dev 63cc20107c Soft returning refactor 2026-05-24 13:20:08 +02:00
selimaj-dev f4fe38140a statement body parsing 2026-05-24 12:55:33 +02:00
selimaj-dev 6551aee03b Fixed block propaganda 2026-05-24 12:43:35 +02:00
selimaj-dev 1c2cc94cb9 Closures 2026-05-24 12:29:42 +02:00
selimaj-dev fde41b9a22 Merge pull request #46 from mist-go/working-lsp
Working lsp
2026-05-24 12:00:29 +02:00
selimaj-dev 9eec07ca2e Improved compiler error message 2026-05-24 11:57:17 +02:00
selimaj-dev 5bfccb0fc4 Improved error handling 2026-05-24 10:41:28 +02:00
selimaj-dev bad6034ba5 Working goto with mist 2026-05-24 10:11:06 +02:00
selimaj-dev f05849ee45 Working did open and goto 2026-05-24 09:34:02 +02:00
selimaj-dev c36d07f0dd Working goto request 2026-05-24 07:56:31 +02:00
selimaj-dev f181806f65 Working request 2026-05-24 07:34:04 +02:00
selimaj-dev 8b0f2ac1b9 Working req res 2026-05-24 07:08:23 +02:00
selimaj-dev 64c612fe3c Removed unnecessary package 2026-05-24 07:03:46 +02:00
selimaj-dev 831fa544fc Pending 2026-05-24 07:01:53 +02:00
selimaj-dev 9b1acb8cc3 Working req res 2026-05-24 06:29:58 +02:00
selimaj-dev b2f5f2fdc8 Sending goto to rust 2026-05-23 15:40:47 +02:00
selimaj-dev c405a2059e Improved rust analyzer client 2026-05-23 15:26:15 +02:00
selimaj-dev ff58a92b3f Rust analyzer init 2026-05-23 14:55:44 +02:00
selimaj-dev 763473ef57 Merge pull request #45 from mist-go/working-lsp-diagnostics
Working lsp diagnostics
2026-05-23 11:27:45 +02:00
selimaj-dev eb24767617 idk 2026-05-23 11:27:05 +02:00
selimaj-dev fa00b3a199 Position injection 2026-05-23 10:14:23 +02:00
selimaj-dev b149bcde4a Refactored transpiler LSP 2026-05-23 09:50:04 +02:00
selimaj-dev 77b6991226 Improved error system LSp 2026-05-23 08:52:45 +02:00
selimaj-dev b96a6f154d errors 2026-05-23 04:36:56 +02:00
selimaj-dev 9f6ec4a20d Working LSP error checking 2026-05-22 15:53:25 +02:00
selimaj-dev 52efdda744 On save 2026-05-22 09:59:13 +02:00
selimaj-dev 97e8f32473 Working lsp build 2026-05-22 09:29:35 +02:00
selimaj-dev 21019cd54f Inject cargo error fix 2026-05-22 04:39:37 +02:00
selimaj-dev bb7e78d042 Fixed error line 2026-05-22 04:35:53 +02:00
selimaj-dev a8ec265c1c Refactored cargo structure 2026-05-22 04:25:33 +02:00
selimaj-dev b7c68da6de Updated tags 2026-05-22 04:15:18 +02:00
selimaj-dev 8d0adb3bb9 Include mist build 2026-05-22 04:04:43 +02:00
selimaj-dev 76f5eccddf Improved cargo structure 2026-05-22 04:01:16 +02:00
selimaj-dev 5539ebde61 Updated versions 2026-05-22 03:49:54 +02:00
selimaj-dev ae25b0044b Merge pull request #44 from mist-go/statement-patches-and-errors
Statement patches and errors
2026-05-22 03:48:17 +02:00
selimaj-dev 1a026f69cb Fixed errors 2026-05-22 03:44:44 +02:00
selimaj-dev c5c5e885bf Improved loop bodies 2026-05-22 03:25:05 +02:00
selimaj-dev a26c1c31fb Added forever loop 2026-05-22 03:05:08 +02:00
selimaj-dev d33763be2e Fixed block statements 2026-05-22 03:00:43 +02:00
selimaj-dev b7cfa9fbe6 Improved for loops 2026-05-22 02:52:22 +02:00
selimaj-dev 960cc40886 Improved codegen 2026-05-22 02:34:01 +02:00
selimaj-dev c9a3c4693c Optimised main.mist 2026-05-21 15:21:04 +02:00
selimaj-dev 76b267a886 Merge pull request #43 from mist-go/rewritten-codegen
Rewritten codegen
2026-05-21 15:16:38 +02:00
selimaj-dev 119f93cf79 Prettier codegen output 2026-05-21 15:14:51 +02:00
selimaj-dev 4112dcac3b Improved match statements 2026-05-21 14:38:37 +02:00
selimaj-dev 80ff10503a Working constructor and statements 2026-05-21 14:19:32 +02:00
selimaj-dev f2257a4e81 Fixed some bugs 2026-05-21 14:04:12 +02:00
selimaj-dev 8703ac4254 Finished expr, and removed old codegen 2026-05-21 13:48:09 +02:00
selimaj-dev 70a1fa332b Top level 2026-05-21 13:43:42 +02:00
selimaj-dev 7b94969379 Top level 2026-05-21 13:36:38 +02:00
selimaj-dev 357a25a859 base top level 2026-05-21 13:14:48 +02:00
selimaj-dev 7af6416921 Statements 2026-05-21 13:03:46 +02:00
selimaj-dev 827b674be2 Expression 2026-05-21 12:25:06 +02:00
selimaj-dev 87bc8a0d69 Rewriting codegen' 2026-05-21 11:29:01 +02:00
selimaj-dev aba8badd90 Merge pull request #42 from mist-go/init-and-expr-statements
Init and expression statements
2026-05-21 11:16:48 +02:00
selimaj-dev 224b367ff1 Removed trailing semicolons 2026-05-21 11:10:44 +02:00
selimaj-dev 9da4a50ef5 Removed invalid statement 2026-05-21 11:07:49 +02:00
selimaj-dev 2fcb8c3831 Fixed naming error 2026-05-21 11:05:00 +02:00
selimaj-dev 702af9da3b Fixed self and added tests back 2026-05-21 08:09:26 +02:00
selimaj-dev 7688599504 Working soft return 2026-05-21 07:59:00 +02:00
selimaj-dev 70e6eb6276 Control flow 2026-05-21 07:28:19 +02:00
selimaj-dev 197afbfb35 bin op stuff 2026-05-21 07:23:11 +02:00
selimaj-dev 0878b9f0b9 Improving operators and suffix 2026-05-21 07:05:58 +02:00
selimaj-dev b28591f9e6 Working expr statements 2026-05-21 06:51:34 +02:00
selimaj-dev 0c8dc53617 Rewriting statement system for expr statements 2026-05-21 06:34:27 +02:00
selimaj-dev cc7bc49efe Added init to list 2026-05-21 06:16:51 +02:00
selimaj-dev 959f786dc8 Working init 2026-05-21 06:14:50 +02:00
selimaj-dev da819c22f6 Init project 2026-05-21 05:43:10 +02:00
selimaj-dev d408d01002 Using .mist/src 2026-05-21 05:33:23 +02:00
selimaj-dev 856c9dfdfa Rewriting mist project structure 2026-05-21 05:26:52 +02:00
selimaj-dev 812fa5d540 Merge pull request #39 from mist-go/lsp-base
Lsp base
2026-05-20 13:34:21 +02:00
selimaj-dev b55b35623b Preparing for mapping 2026-05-20 13:14:48 +02:00
selimaj-dev ff38c809e7 Simple completion example 2026-05-20 10:17:14 +02:00
selimaj-dev 64418cb52d cargo lock 2026-05-20 09:31:58 +02:00
selimaj-dev 674b809586 cargo lock 2026-05-20 09:31:50 +02:00
selimaj-dev 6b14ab0308 Working hello world lsp 2026-05-20 09:03:00 +02:00
selimaj-dev b86b4831ce Added analyzer 2026-05-20 08:54:56 +02:00
selimaj-dev 949135bd3b Include 2026-05-19 12:37:49 +02:00
selimaj-dev c30d686eb5 Merge pull request #38 from mist-go/snake
A snake is eating itself
2026-05-19 12:31:25 +02:00
selimaj-dev 47e62f96d9 Updated version 2026-05-19 12:30:29 +02:00
selimaj-dev b856450cc1 Header for rust IDE support 2026-05-19 12:27:32 +02:00
selimaj-dev 3ed17e007f Multiple commands bootstrapped 2026-05-19 12:23:57 +02:00
selimaj-dev bffc9f073b Match multiple patterns 2026-05-19 12:21:20 +02:00
selimaj-dev 318480f0b5 Fixed string and macro, and main 2026-05-19 12:14:25 +02:00
selimaj-dev 1a469689a7 Fixed amgibuitiy 2026-05-19 11:25:14 +02:00
selimaj-dev 6d7beb20ca Bootstrapped main 2026-05-19 11:19:49 +02:00
selimaj-dev 5f7dcc859c Preparing for bootstrapping 2026-05-19 11:06:26 +02:00
selimaj-dev 7febf84cd8 Updated version (again) 2026-05-19 11:02:06 +02:00
selimaj-dev 93eb467814 Updated quick patch version 2026-05-19 10:47:54 +02:00
selimaj-dev 0e27344012 Merge pull request #37 from mist-go/quick-patches
Quick patches
2026-05-19 10:45:50 +02:00
selimaj-dev 8f820bfb50 Fix: future ambiguities via !keyword 2026-05-19 10:44:51 +02:00
selimaj-dev 0031fb7152 Fix: statement 2026-05-19 10:39:35 +02:00
selimaj-dev 28a7658ce7 Updated version 2026-05-19 10:18:26 +02:00
selimaj-dev 67b60a9e4f Fix: statement order 2026-05-19 10:14:24 +02:00
selimaj-dev 16bca21981 Merge pull request #36 from mist-go/refactors-and-patches
Refactors and patches
2026-05-19 10:02:25 +02:00
selimaj-dev 349f9ba59e Refactor: Error handling in builder 2026-05-19 10:01:29 +02:00
selimaj-dev 3620f0432a Fix: mappings 2026-05-19 09:46:24 +02:00
selimaj-dev 69e5ab2a5e Dyn type 2026-05-19 06:55:58 +02:00
selimaj-dev bcefabe2d2 Fixed expression statement bug 2026-05-19 06:39:38 +02:00
selimaj-dev 551f14f81e Merge pull request #35 from mist-go/errors-and-caching
Errors and caching
2026-05-19 06:36:42 +02:00
selimaj-dev a5ccd9651a Added check command and updated help 2026-05-19 06:24:35 +02:00
selimaj-dev 9d051c68e9 Impl spanned functions 2026-05-19 06:11:52 +02:00
selimaj-dev fd7455c71e Fixed traits 2026-05-19 06:06:04 +02:00
selimaj-dev 1e191cf3c8 Class items, struct items, enum items, mapping 2026-05-19 06:00:35 +02:00
selimaj-dev 6412daa514 Dramatically improved transpile times by caching 2026-05-19 05:28:14 +02:00
selimaj-dev 1b4c925f9f Improved transpiler output 2026-05-19 05:24:59 +02:00
selimaj-dev bfd768a162 Working app stdout 2026-05-19 05:20:16 +02:00
selimaj-dev ffe868e0cd Fixed build stdout 2026-05-19 05:08:27 +02:00
selimaj-dev 8343740b11 Fixed build error on inner dir 2026-05-19 04:40:33 +02:00
selimaj-dev 4e98257438 Improved paths 2026-05-19 04:36:35 +02:00
selimaj-dev 95ae7b8d52 Improved paths, and added rust specific errors 2026-05-19 04:35:12 +02:00
selimaj-dev e30722dde3 Warning 2026-05-19 03:32:17 +02:00
selimaj-dev eb84103ed6 Improved diagnostic conversion 2026-05-19 03:24:12 +02:00
selimaj-dev 49a3186d26 Diagnostic conversion 2026-05-19 02:58:57 +02:00
selimaj-dev 670835a5e7 Added cargo_metadata and renamed compiler module 2026-05-19 02:04:37 +02:00
selimaj-dev 2b43e0c004 Working mapping 2026-05-19 01:47:02 +02:00
selimaj-dev 11e408cc17 find mapping 2026-05-19 00:46:07 +02:00
selimaj-dev 5e8946a126 Mapping 2026-05-19 00:40:28 +02:00
selimaj-dev 6b314dabf4 Spanned statements 2026-05-18 21:56:07 +02:00
selimaj-dev c5d8c12c14 Fix: visibility spacing 2026-05-18 21:42:22 +02:00
selimaj-dev d1330500b2 Spanned 2026-05-18 21:40:01 +02:00
selimaj-dev a88ff4c8dd Spanned impl 2026-05-18 14:42:41 +02:00
selimaj-dev 5648c1da61 Spanned 2026-05-18 13:58:59 +02:00
selimaj-dev de1784f914 Merge pull request #32 from mist-go/refactor-generics
Refactor generics & Sidefiles
2026-05-17 20:10:36 +02:00
selimaj-dev aa948a50cb Moving instead of borrowing in codegen 2026-05-17 20:02:07 +02:00
selimaj-dev f9f86fcc67 Implementation: sidefiles 2026-05-17 19:39:21 +02:00
selimaj-dev 907d9d7f9d Fix: Generics decl constraints 2026-05-17 19:30:20 +02:00
selimaj-dev 1d4473906f Fix: Generics decl not working 2026-05-17 19:21:10 +02:00
selimaj-dev 7fe91b8e36 Fix: Generics 2026-05-17 11:39:18 +02:00
selimaj-dev 94e113d227 Fix: Generics decl 2026-05-17 11:26:04 +02:00
selimaj-dev c566ac9a54 Fix: reveresed type postfix 2026-05-17 11:13:29 +02:00
selimaj-dev 5fa3e77b8f Added expr? syntax 2026-05-17 06:08:53 +02:00
selimaj-dev e270ec727e Merge pull request #31 from mist-go/assignments-expressions
Improved Assignments & expressions
2026-05-17 06:03:11 +02:00
selimaj-dev e89f5e805c Cleaned up AST 2026-05-17 06:00:26 +02:00
selimaj-dev dd647afd59 Indentation increment 2026-05-17 05:55:43 +02:00
selimaj-dev 46c6f5ffdd Fixed range 2026-05-17 05:52:23 +02:00
selimaj-dev 212d5d69b5 Fixed as 2026-05-17 05:49:37 +02:00
selimaj-dev a893f9a12d Increment and decrement via ++ or -- 2026-05-17 05:43:16 +02:00
selimaj-dev 77f35e0517 Removed incrementing tmp 2026-05-17 05:32:46 +02:00
selimaj-dev 1bcbca00b8 Fixed loose error 2026-05-17 05:13:28 +02:00
selimaj-dev c7529412f4 Adding increment 2026-05-17 04:44:38 +02:00
selimaj-dev 9b632fcc0e New generics 2026-05-17 04:35:00 +02:00
selimaj-dev 4742fbebf7 Codegen generics 2026-05-17 04:30:00 +02:00
selimaj-dev 82d748224f Fixed expression 2026-05-17 04:13:27 +02:00
selimaj-dev 16f169cdb0 Codegen 2026-05-17 04:00:15 +02:00
selimaj-dev 2a95ad4eb0 extended expression 2026-05-17 03:49:34 +02:00
selimaj-dev 33fae13c8a Updated AST for extensive expressions 2026-05-17 03:28:22 +02:00
selimaj-dev 23cf00975d Updated grammar for more extensive expressions 2026-05-17 03:25:02 +02:00
selimaj-dev 2c67d4e316 Tuple fix 2026-05-17 02:37:18 +02:00
selimaj-dev bfaaa4006b Codegen 2026-05-17 02:32:41 +02:00
selimaj-dev 50c98cf5f7 Adapted parser and ast with grammar 2026-05-17 02:30:03 +02:00
selimaj-dev 020eebdaba Updated expr ast 2026-05-17 02:21:12 +02:00
selimaj-dev 675e357297 Using term based expressions: grammar 2026-05-17 02:18:09 +02:00
selimaj-dev 6a0011c009 Restored grammar for now 2026-05-16 23:40:45 +02:00
selimaj-dev 95f253c0ce Refactored ast structure 2026-05-16 23:04:05 +02:00
selimaj-dev b802c51369 updated expr grammar 2026-05-16 22:53:08 +02:00
selimaj-dev 0bd8bc2f03 track caller on bug_unimplemented 2026-05-16 22:43:44 +02:00
selimaj-dev 13480b2c54 removed var assign statement struct 2026-05-16 22:40:39 +02:00
selimaj-dev c9030809fd Compound assign statement 2026-05-16 22:40:01 +02:00
82 changed files with 11711 additions and 3131 deletions
+6 -2
View File
@@ -26,5 +26,9 @@ target
/target
/mist-test/build
/mist-test/output.json
**/build
.mist/
analyzer.bat
analyzer.sh
Generated
+952 -3
View File
File diff suppressed because it is too large Load Diff
+35 -7
View File
@@ -1,19 +1,47 @@
[package]
name = "mist-lang"
version = "0.0.2-alpha0"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language compiler"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
readme = "README.md"
keywords = ["compiler", "language", "mist"]
categories = ["compilers"]
keywords = ["compiler", "language", "mist", "lang"]
categories = ["compilers", "command-line-interface", "development-tools", "development-tools::build-utils"]
default-run = "mist"
include = [
".mist/src/**",
"Cargo.toml",
"README.md",
]
[dependencies]
serde = { version = "1.0.228", features = ["serde_derive"] }
serde_json = "1.0.149"
mist-parser = { path = "./parser", version = "0.1.1"}
mist-analyzer = { workspace = true }
mist-api = { workspace = true }
toml = "1.1.2"
[workspace]
members = [
"crates/parser",
"crates/analyzer",
"crates/codegen",
"crates/mist-api",
]
exclude = [
"mist-test",
]
[workspace.dependencies]
mist-parser = { path = "crates/parser", version = "0.4.0" }
mist-analyzer = { path = "crates/analyzer", version = "0.4.0" }
mist-codegen = { path = "crates/codegen", version = "0.4.0" }
mist-api = { path = "crates/mist-api", version = "0.4.0" }
[[bin]]
name = "mist"
path = "src/main.rs"
path = ".mist/src/main.rs"
[[bin]]
name = "mist-analyzer"
path = ".mist/src/analyzer.rs"
+3
View File
@@ -0,0 +1,3 @@
package = "main.mist"
packages = []
include = ["crates/*"]
+6 -6
View File
@@ -1,15 +1,15 @@
# Mist Language: <br/> A C++ inspired langauge in the Rust ecosystem
# Mist - A Pragmatic Systems Language built on Rust
<!--
Originally this readme was part of the Carbon Language project, licensed with Apache-2.0
-->
<p align="center">
<a href="https://mist.selimaj.dev">Documentation</a>
<a href="https://mist.selimaj.dev/docs">Documentation</a> ∙ <a href="https://mist.selimaj.dev/blog">Blog</a> ∙ <a href="https://mist.selimaj.dev/faq">FAQ</a>
</p>
<img src="code.png" align="right" width="575" alt="">
<img src="code.png" align="right" width="450" alt="">
<!--
Don't let the text wrap too narrowly to the left of the above image.
@@ -19,7 +19,7 @@ The `div` reduces the vertical height. The `picture` prevents autolinking.
**Fast and works with Rust**
- All of your favourite Rust libraries work with Mist
- All of your favorite Rust libraries work with Mist
- Compiles directly into efficient Rust code
- Zero-cost abstractions, no runtime overhead
@@ -29,6 +29,6 @@ The `div` reduces the vertical height. The `picture` prevents autolinking.
- Designed for fast, readable systems code
**Class and type system**
- class is syntactic sugar for a Rust struct
- `struct B extends A` provides inheritance-style syntax over struct composition
- class is syntactic sugar for a Rust struct with V Tables
- `class B : A` provides inheritance-style syntax over struct composition
- Classes and structs compile into the same underlying Rust type system model
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 55 KiB

+863
View File
@@ -0,0 +1,863 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "async-trait"
version = "0.1.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "auto_impl"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdcb70bdbc4d478427380519163274ac86e52916e10f0a8889adf0f96d3fee7"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "dashmap"
version = "5.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856"
dependencies = [
"cfg-if",
"hashbrown",
"lock_api",
"once_cell",
"parking_lot_core",
]
[[package]]
name = "dashmap"
version = "6.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"
dependencies = [
"cfg-if",
"crossbeam-utils",
"hashbrown",
"lock_api",
"once_cell",
"parking_lot_core",
]
[[package]]
name = "displaydoc"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-io"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
[[package]]
name = "futures-macro"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"slab",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "icu_collections"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
[[package]]
name = "icu_properties"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
dependencies = [
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
[[package]]
name = "icu_provider"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "litemap"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "lsp-types"
version = "0.94.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c66bfd44a06ae10647fe3f8214762e9369fd4248df1350924b4ef9e770a85ea1"
dependencies = [
"bitflags 1.3.2",
"serde",
"serde_json",
"serde_repr",
"url",
]
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "mist-analyzer"
version = "0.0.1"
dependencies = [
"dashmap 6.2.1",
"tokio",
"tower-lsp",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "potential_utf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
dependencies = [
"zerovec",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.11.1",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_repr"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "socket2"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tinystr"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tokio"
version = "1.52.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tower"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
dependencies = [
"futures-core",
"futures-util",
"pin-project",
"pin-project-lite",
"tower-layer",
"tower-service",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-lsp"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4ba052b54a6627628d9b3c34c176e7eda8359b7da9acd497b9f20998d118508"
dependencies = [
"async-trait",
"auto_impl",
"bytes",
"dashmap 5.5.3",
"futures",
"httparse",
"lsp-types",
"memchr",
"serde",
"serde_json",
"tokio",
"tokio-util",
"tower",
"tower-lsp-macros",
"tracing",
]
[[package]]
name = "tower-lsp-macros"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84fd902d4e0b9a4b27f2f440108dc034e1758628a9b702f8ec61ad66355422fa"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
"serde_derive",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "writeable"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
[[package]]
name = "yoke"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"synstructure",
]
[[package]]
name = "zerotrie"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "mist-analyzer"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language Analyzer LSP"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
keywords = ["language-server", "language", "mist"]
categories = ["compilers"]
[dependencies]
mist-api = { workspace = true }
mist-parser = { workspace = true }
mist-codegen = { workspace = true }
pest = "2.8.6"
dashmap = "6.1.0"
tokio = { version = "1.52.3", features = ["full", "macros", "rt", "rt-multi-thread"] }
tower-lsp = "0.20.0"
cargo_metadata = "0.23.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
ropey = "1"
heck = "0.5.0"
toml = "1.1.2"
File diff suppressed because it is too large Load Diff
+408
View File
@@ -0,0 +1,408 @@
use std::{collections::HashMap, path::PathBuf, process::Stdio, sync::Arc, time::Duration};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Value, json};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
sync::{Mutex, oneshot},
time::timeout,
};
use tower_lsp::lsp_types::{
self, ClientCapabilities, InitializeParams, InitializedParams, Url, WorkspaceFolder,
notification::{Initialized, Notification},
request::{self, Request},
};
const MAX_CONTENT_LENGTH: usize = 50 * 1024 * 1024;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Deserialize)]
pub struct JsonRpcResponse<T> {
pub jsonrpc: String,
pub id: Option<serde_json::Value>,
pub result: Option<T>,
pub error: Option<JsonRpcError>,
}
#[derive(Debug, Deserialize)]
pub struct JsonRpcError {
pub code: i64,
pub message: String,
pub data: Option<serde_json::Value>,
}
type PendingMap = Arc<Mutex<HashMap<usize, oneshot::Sender<Result<Value, String>>>>>;
#[derive(Debug)]
pub struct RustAnalyzer {
stdin: Arc<Mutex<tokio::process::ChildStdin>>,
pending: PendingMap,
id: usize,
_child: tokio::process::Child,
}
async fn send_lsp_message<W: AsyncWriteExt + Unpin>(
writer: &mut W,
value: &serde_json::Value,
) -> std::io::Result<()> {
let payload = serde_json::to_string(value)?;
let frame = format!("Content-Length: {}\r\n\r\n{}", payload.len(), payload);
writer.write_all(frame.as_bytes()).await?;
writer.flush().await?;
Ok(())
}
async fn read_lsp_message<R: AsyncBufReadExt + Unpin>(
reader: &mut R,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
let mut line = String::new();
let mut content_length = 0;
let mut eof = false;
for _ in 0..100 {
line.clear();
let bytes_read = reader.read_line(&mut line).await?;
if bytes_read == 0 {
eof = true;
break;
}
if line.trim().is_empty() {
break;
}
if line.to_ascii_lowercase().starts_with("content-length:") {
if let Some(val_str) = line.split(':').nth(1) {
let trimmed = val_str.trim();
if !trimmed.is_empty() {
content_length = trimmed.parse::<usize>()?;
}
}
}
}
if content_length == 0 {
if eof {
return Err("LSP stream closed (EOF)".into());
}
return Err("Missing, invalid, or zero Content-Length header".into());
}
if content_length > MAX_CONTENT_LENGTH {
return Err(format!(
"Content-Length {} exceeds maximum threshold",
content_length
)
.into());
}
let mut buffer = vec![0u8; content_length];
reader.read_exact(&mut buffer).await?;
Ok(String::from_utf8(buffer)?)
}
impl RustAnalyzer {
pub fn new(
notification_tx: tokio::sync::mpsc::UnboundedSender<Value>,
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
let mut child = tokio::process::Command::new("rustup")
.args(["run", "stable", "rust-analyzer"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdin = child
.stdin
.take()
.ok_or("Failed to open child stdin pipe")?;
let stdout = child
.stdout
.take()
.ok_or("Failed to open child stdout pipe")?;
let stderr = child
.stderr
.take()
.ok_or("Failed to open child stderr pipe")?;
tokio::spawn(async move {
let mut stderr = stderr;
let mut buf = vec![0u8; 4096];
loop {
match stderr.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
eprintln!(
"[ra-stderr] {}",
String::from_utf8_lossy(&buf[..n]).trim_end()
);
}
Err(e) => {
eprintln!("[ra-stderr] read error: {e}");
break;
}
}
}
eprintln!("[ra-stderr] stream closed");
});
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
let pending_clone = pending.clone();
tokio::spawn(async move {
let mut stdout = BufReader::new(stdout);
eprintln!("[ra-reader] started");
loop {
let raw = match read_lsp_message(&mut stdout).await {
Ok(v) => v,
Err(err) => {
eprintln!("LSP stream error: {err}");
// Drain pending requests so they don't hang forever.
let mut lock = pending_clone.lock().await;
for (_, tx) in lock.drain() {
let _ = tx.send(Err(format!("LSP reader error: {}", err)));
}
// EOF means the child process exited — stop the reader.
// Other errors (malformed frames) get a brief backoff then retry.
if err.to_string().contains("LSP stream closed (EOF)") {
eprintln!("LSP reader task: EOF detected, stopping reader");
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
continue;
}
};
let value: Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(err) => {
eprintln!("Corrupted JSON received: {err}");
continue;
}
};
let is_notification = value.get("method").is_some() && value.get("id").is_none();
if is_notification {
let _ = notification_tx.send(value);
continue;
}
let id = value.get("id").and_then(|v| v.as_u64()).map(|v| v as usize);
if let Some(id) = id {
let tx = pending_clone.lock().await.remove(&id);
if let Some(tx) = tx {
let _ = tx.send(Ok(value));
} else {
eprintln!("Received orphaned or delayed frame for ID: {id}");
}
} else {
eprintln!("Received unhandled protocol notification framework: {raw}");
}
}
});
Ok(Self {
stdin: Arc::new(Mutex::new(stdin)),
pending,
id: 0,
_child: child,
})
}
pub async fn request<R: Request>(
&mut self,
params: R::Params,
) -> Result<R::Result, Box<dyn std::error::Error + Send + Sync>>
where
R::Result: DeserializeOwned,
{
let id = {
self.id += 1;
self.id
};
let (tx, rx) = oneshot::channel();
{
self.pending.lock().await.insert(id, tx);
}
let payload = json!({
"jsonrpc": "2.0",
"id": id,
"method": R::METHOD,
"params": params,
});
let mut stdin_lock = self.stdin.lock().await;
if let Err(err) = send_lsp_message(&mut *stdin_lock, &payload).await {
self.pending.lock().await.remove(&id);
return Err(Box::new(err));
}
drop(stdin_lock);
let response_payload = match timeout(REQUEST_TIMEOUT, rx).await {
Ok(Ok(Ok(value))) => value,
Ok(Ok(Err(task_err))) => return Err(task_err.into()),
Ok(Err(_oneshot_canceled)) => {
return Err(
"Bridge connection closed down; reader channel dropped unexpectedly".into(),
);
}
Err(_timeout_elapsed) => {
self.pending.lock().await.remove(&id);
return Err(
format!("Request ID {} timed out after {:?}", id, REQUEST_TIMEOUT).into(),
);
}
};
let envelope: JsonRpcResponse<R::Result> =
serde_json::from_value(response_payload.clone())?;
if let Some(err) = envelope.error {
return Err(format!("LSP Engine Error ({}): {}", err.code, err.message).into());
}
envelope.result.ok_or_else(|| {
format!(
"Missing inner structural payload result: {:?}",
response_payload
)
.into()
})
}
pub async fn notify<T: Serialize>(
&mut self,
method: &str,
req: T,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let payload = json!({
"jsonrpc": "2.0",
"method": method,
"params": req,
});
let mut stdin_lock = self.stdin.lock().await;
send_lsp_message(&mut *stdin_lock, &payload).await?;
Ok(())
}
}
impl RustAnalyzer {
pub async fn initialize(
&mut self,
root: &PathBuf,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let project_uri = Url::from_directory_path(root)
.map_err(|_| "Failed to convert path to valid file:// URL")?;
#[allow(deprecated)]
let init_params = InitializeParams {
process_id: Some(std::process::id()),
root_uri: Some(project_uri.clone()),
workspace_folders: Some(vec![WorkspaceFolder {
uri: project_uri,
name: "workspace".to_string(),
}]),
capabilities: ClientCapabilities {
workspace: Some(lsp_types::WorkspaceClientCapabilities {
workspace_folders: Some(true),
..Default::default()
}),
text_document: Some(lsp_types::TextDocumentClientCapabilities {
..Default::default()
}),
..Default::default()
},
..Default::default()
};
self.request::<request::Initialize>(init_params).await?;
Ok(())
}
pub async fn initialized(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(<Initialized as Notification>::METHOD, InitializedParams {})
.await?;
Ok(())
}
}
impl RustAnalyzer {
pub async fn did_open(
&mut self,
uri: Url,
text: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(
"textDocument/didOpen",
json!({
"textDocument": {
"uri": uri,
"languageId": "rust",
"version": 1,
"text": text,
}
}),
)
.await
}
pub async fn did_change(
&mut self,
uri: Url,
text: &str,
version: i32,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(
"textDocument/didChange",
json!({
"textDocument": {
"uri": uri,
"version": version,
},
"contentChanges": [{
"text": text,
}],
}),
)
.await
}
pub async fn did_save(
&mut self,
uri: Url,
text: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(
"textDocument/didSave",
json!({
"textDocument": {
"uri": uri,
},
"text": text,
}),
)
.await
}
pub async fn did_close(
&mut self,
uri: Url,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.notify(
"textDocument/didClose",
json!({
"textDocument": {
"uri": uri,
}
}),
)
.await
}
}
+115
View File
@@ -0,0 +1,115 @@
use std::path::{Path, PathBuf};
use mist_codegen::RustCodegen;
use mist_parser::rev_mapper::Mapping;
use mist_parser::{MistFmtConfig, parse, parse_module};
pub struct TranspiledFile {
pub mist_path: PathBuf,
pub rust_path: PathBuf,
pub rust_content: String,
pub mapping: Mapping,
}
#[derive(Debug)]
pub enum TranspileError<'a> {
Parse(mist_parser::error::ParseError<'a>),
Semantic(Vec<mist_parser::semantics::SemanticError>),
}
/// Resolve the output `.rs` path for a `.mist` source file.
///
/// Always checks for a `pub module x;` declaration via `parse_module` and
/// uses the declared module name as the filename when present. Falls back
/// to the literal file stem when parsing fails or the file has no module
/// declaration.
pub fn resolve_rust_path(mist_path: &Path, source: Option<&str>) -> PathBuf {
let mut rust_path = crate::from_mist_to_rust(mist_path.to_path_buf());
// Package files (package.mist) must output as <dir>/mod.rs so the Rust
// module hierarchy resolves correctly.
if mist_path.file_name().and_then(|n| n.to_str()) == Some("package.mist") {
rust_path.set_file_name("mod.rs");
} else if let Some(src) = source {
// Prioritize the module declaration from the source over the file stem.
// Every caller re-parses so we always pick up the current declaration.
if let Ok(Some((_, ref name))) = parse_module(src) {
if rust_path.file_name().map(|v| v.to_str()).unwrap_or_default() != Some("mod.rs") {
if let Some(ext) = rust_path.extension().map(|e| e.to_owned()) {
let mut new_name = std::ffi::OsString::from(&name.0);
new_name.push(".");
new_name.push(ext);
rust_path.set_file_name(new_name);
} else {
rust_path.set_file_name(&name.0);
}
}
}
}
rust_path
}
pub fn transpile_mist<'a>(
mist_path: &Path,
source: &'a str,
extra_mod_decl: &str,
) -> Result<TranspiledFile, TranspileError<'a>> {
let rust_path = resolve_rust_path(mist_path, Some(source));
let parsed = parse(source).map_err(TranspileError::Parse)?;
for item in &parsed.items {
mist_parser::semantics::check_class_semantics(item).map_err(TranspileError::Semantic)?;
}
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
codegen.generate(parsed.mod_attributes);
codegen.add(extra_mod_decl);
let output = codegen.generate(parsed.items);
Ok(TranspiledFile {
mist_path: mist_path.to_path_buf(),
rust_path,
rust_content: output,
mapping: codegen.mapping,
})
}
/// No Semantics
pub fn transpile_mist_no_sem(
mist_path: &Path,
source: &str,
extra_mod_decl: &str,
) -> Result<TranspiledFile, String> {
let rust_path = resolve_rust_path(mist_path, Some(source));
let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
let mut codegen = RustCodegen::new(mist_path.to_path_buf());
codegen.generate(parsed.mod_attributes);
codegen.add(extra_mod_decl);
let output = codegen.generate(parsed.items);
Ok(TranspiledFile {
mist_path: mist_path.to_path_buf(),
rust_path,
rust_content: output,
mapping: codegen.mapping,
})
}
pub fn format_mist(source: &str, _config: MistFmtConfig) -> Result<String, String> {
// let parsed = parse(source).map_err(|e| format!("parse error: {e:?}"))?;
// let mut codegen = MistCodegen::new(config);
// codegen.generate(parsed.mod_attributes);
// let output = codegen.generate(parsed.items);
// Ok(output)
Ok(source.to_string())
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "mist-codegen"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language Rust code generator"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
keywords = ["compiler", "language", "mist"]
categories = ["compilers"]
[dependencies]
bytecount = "0.6.9"
mist-parser = { workspace = true }
+628
View File
@@ -0,0 +1,628 @@
use std::collections::HashMap;
use mist_parser::ast::*;
use crate::{Context, GenRust, GenSpanTranslation, GetRust, RustCodegen};
pub struct ClassProcessedData {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
inherits: Option<ExprPath>,
self_path: ExprPath,
self_ty: TypeExpr,
fields: Vec<Spanned<FieldDeclStmt>>,
constructor: Option<Spanned<ClassConstructor>>,
items: Vec<ClassItem>,
methods: Vec<Spanned<FunctionDecl>>,
v_table: Vec<Identifier>,
override_v_table: HashMap<Override, Spanned<Vec<(Identifier, bool)>>>,
}
impl ClassProcessedData {
pub fn analyze(
visibility: &Visibility,
name: &Identifier,
generics: &GenericsDecl,
inherits: &Option<ExprPath>,
fields: &Vec<Spanned<FieldDeclStmt>>,
constructor: &Option<Spanned<ClassConstructor>>,
items: &Vec<ClassItem>,
) -> Self {
let self_path = ExprPath(vec![ExprPathSegment {
ident: name.clone(),
generics: generics.clone().into(),
}]);
let self_ty = get_type_from_path(&self_path);
let methods = items
.iter()
.filter_map(|item| match item {
ClassItem::ImplDecl(_) => None,
ClassItem::Method(method) => Some(method.clone()),
})
.collect::<Vec<Spanned<FunctionDecl>>>();
let mut v_table = Vec::new();
let mut override_v_table = HashMap::new();
for method in &methods {
if matches!(method.item.visibility, Visibility::Public) {
match &method.item.is_override {
None => {
if method.item.is_virtual && method.item.self_param.is_some() {
v_table.push(method.item.name.clone());
}
}
Some(override_spec) => {
override_v_table
.entry(override_spec.clone())
.or_insert_with(|| Spanned {
line: method.line,
column: method.column,
item: Vec::new(),
})
.item
.push((method.item.name.clone(), method.item.is_virtual));
}
}
}
}
ClassProcessedData {
visibility: visibility.clone(),
name: name.clone(),
generics: generics.clone(),
inherits: inherits.clone(),
self_path,
self_ty,
fields: fields.clone(),
constructor: constructor.clone(),
items: items.clone(),
methods,
v_table,
override_v_table,
}
}
// ── Stage 2: Code Emission ───────────────────────────────────────
pub fn emit(&self, ctx: &mut Context, cg: &mut RustCodegen) {
ctx.expr_super = self.inherits.clone();
self.emit_struct_decl(cg);
self.emit_impl_block(ctx, cg);
self.emit_impl_decls(ctx, cg);
self.emit_deref_impls(cg);
ctx.expr_super = None;
}
fn emit_struct_decl(&self, cg: &mut RustCodegen) {
cg.addln(&format!(
"{}struct {}{} {{",
self.visibility.get_rust(),
self.name.get_rust(),
self.generics.get_rust()
));
cg.indent += 1;
if let Some(ref inherits) = self.inherits {
cg.add_indented("pub _super: ");
cg.add(&get_type_from_path(inherits).get_rust());
cg.addln(",");
} else {
cg.add_indentedln("pub _vptr: &'static [*const core::ffi::c_void],");
}
for field in &self.fields {
field.gen_span(cg);
cg.add_indentedln(&field.item.decl.get_rust());
}
cg.indent -= 1;
cg.addln("}\n");
}
fn emit_impl_block(&self, ctx: &mut Context, cg: &mut RustCodegen) {
cg.addln(&format!(
"impl{} {} {{",
self.generics.get_rust(),
self.self_ty.get_rust()
));
cg.indent += 1;
self.emit_unified_vtable(cg);
self.emit_super_v_tests(cg);
if let Some(constructor) = &self.constructor {
self.emit_constructor(constructor, ctx, cg);
}
self.emit_methods(ctx, cg);
cg.indent -= 1;
cg.addln("}\n");
}
fn emit_unified_vtable(&self, cg: &mut RustCodegen) {
let has_parent = self.inherits.is_some();
let parent_path = self
.inherits
.as_ref()
.map(|p| p.get_rust())
.unwrap_or_default();
if has_parent {
cg.add_indentedln(&format!(
"pub const __PARENT_V_COUNT: usize = {}::__V_COUNT;",
parent_path
));
} else {
cg.add_indentedln("pub const __PARENT_V_COUNT: usize = 0;");
}
for (i, method_name) in self.v_table.iter().enumerate() {
cg.add_indentedln(&format!(
"pub const __FN_{}: usize = Self::__PARENT_V_COUNT + {i};",
method_name.0.to_uppercase()
));
}
cg.add_indentedln(&format!(
"pub const __V_COUNT: usize = Self::__PARENT_V_COUNT + {};",
self.v_table.len()
));
cg.add_indentedln("pub const __V_TABLE: &'static [*const core::ffi::c_void] = &{");
cg.indent += 1;
if has_parent {
cg.add_indentedln("let mut table = [core::ptr::null(); Self::__V_COUNT];");
cg.add_indentedln(&format!("let parent_table = {}::__V_TABLE;", parent_path));
cg.add_indentedln(
"let mut i = 0; while i < Self::__PARENT_V_COUNT {{ table[i] = parent_table[i]; i += 1; }}",
);
for (override_tier, overriden_method_idents) in &self.override_v_table {
let base_class_path = override_tier
.0
.as_ref()
.unwrap_or(self.inherits.as_ref().unwrap())
.get_rust();
for (method_ident, is_virtual) in &overriden_method_idents.item {
cg.add_indentedln(&format!(
"table[{}::__FN_{}] = {}::{} as *const core::ffi::c_void;",
base_class_path,
method_ident.0.to_uppercase(),
self.self_path.get_rust(),
get_virtual_name(method_ident, *is_virtual)
));
}
}
for method_name in &self.v_table {
cg.add_indentedln(&format!(
"table[Self::__FN_{}] = Self::__m_{} as *const core::ffi::c_void;",
method_name.0.to_uppercase(),
method_name.get_rust()
));
}
cg.add_indentedln("table");
} else {
cg.add_indentedln("[");
cg.indent += 1;
for method_name in &self.v_table {
cg.add_indentedln(&format!(
"Self::__m_{} as *const core::ffi::c_void,",
method_name.get_rust()
));
}
cg.indent -= 1;
cg.add_indentedln("]");
}
cg.indent -= 1;
cg.add_indentedln("};");
}
fn emit_super_v_tests(&self, cg: &mut RustCodegen) {
cg.add_indentedln("#[allow(invalid_value)]");
cg.add_indentedln(&format!("fn __test_vt() {{"));
cg.indent += 1;
for (override_tier, _) in self.override_v_table.iter() {
let target_path = match &override_tier.0 {
Some(path) => path.clone(),
None => {
if let Some(parent_path) = &self.inherits {
parent_path.clone()
} else {
continue;
}
}
};
let target_rust_path = target_path.get_rust();
for method in &self.methods {
if method.item.is_override.as_ref() == Some(override_tier) {
let mut params = method
.item
.params
.0
.clone()
.into_iter()
.filter_map(|v| v.type_)
.collect::<Vec<_>>();
if params.is_empty() {
continue;
}
if let Some((_, _, mutable)) = &method.item.self_param {
method.gen_span(cg);
cg.add_indented(&format!("{}::__m_", target_rust_path));
cg.add(&method.item.name.get_rust());
cg.add(" as ");
params.insert(
0,
TypeExpr::Ref {
lifetime: None,
mutable: *mutable,
ty: Box::new(get_type_from_path(&target_path)),
},
);
cg.add(
&TypeExpr::StaticFn(
params,
method.item.return_type.clone().map(Box::new),
)
.get_rust(),
);
cg.addln(";");
}
}
}
}
// Deref tests for override targets
if self.inherits.is_some() && !self.override_v_table.is_empty() {
cg.add_indentedln("let this: &Self = &unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
for (override_tier, v) in &self.override_v_table {
if let Some(path) = &override_tier.0 {
v.gen_span(cg);
// This forces the compiler to statically verify that &Self can Deref into &Target
cg.add_indentedln(&format!("let _: &{} = this;", path.get_rust()));
}
}
}
cg.indent -= 1;
cg.add_indentedln("}");
}
fn emit_constructor(
&self,
constructor: &Spanned<ClassConstructor>,
ctx: &mut Context,
cg: &mut RustCodegen,
) {
cg.add_indentedln("#[allow(invalid_value)]");
constructor.gen_span(cg);
cg.add_indented(&format!(
"{}fn new{}(",
constructor.item.visibility.get_rust(),
constructor.item.generics.get_rust()
));
let params = constructor
.item
.params
.0
.clone()
.into_iter()
.enumerate()
.map(|(idx, mut v)| {
v.name = construct_pattern(&v.name, idx);
(idx, v)
})
.collect::<Vec<_>>();
for (i, param) in &params {
if *i > 0 {
cg.add(", ");
}
param.gen_rust(ctx, cg);
}
cg.addln(") -> Self {");
cg.indent += 1;
cg.add_indentedln("let mut this: Self = unsafe { core::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
for field in &self.fields {
if let Some(init) = &field.item.init {
field.gen_span(cg);
cg.add_indented(&format!("this.{} = ", field.item.decl.name.get_rust()));
init.gen_rust(ctx, cg);
cg.addln(";");
}
}
cg.add_indented("this.constructor(");
for (i, param) in &params {
if *i > 0 {
cg.add(", ");
}
param.name.gen_rust(ctx, cg);
}
cg.addln(");");
cg.add_indentedln("this._vptr = &Self::__V_TABLE;");
constructor.gen_span(cg);
cg.add_indentedln("this");
cg.indent -= 1;
cg.add_indentedln("}\n");
Spanned {
line: constructor.line,
column: constructor.column,
item: FunctionDecl {
visibility: constructor.item.visibility.clone(),
is_virtual: false,
is_override: None,
name: Identifier(String::from("constructor")),
generics: constructor.item.generics.clone(),
params: constructor.item.params.clone(),
self_param: Some((true, None, true)),
return_type: Some(TypeExpr::Tuple(Vec::new())),
body: Some(constructor.item.body.clone()),
},
}
.gen_rust(ctx, cg);
}
fn emit_methods(&self, ctx: &mut Context, cg: &mut RustCodegen) {
for method in &self.methods {
match method.item.visibility {
Visibility::Public => {
if method.item.is_virtual && method.item.self_param.is_some() {
if method.item.is_override.is_none() {
gen_method_point(&method.item, ctx, cg);
}
let mut prefixed = method.clone();
prefixed.item.name.0.insert_str(0, "__m_");
prefixed.gen_rust(ctx, cg);
} else {
method.gen_rust(ctx, cg);
}
}
_ => {
method.gen_rust(ctx, cg);
}
}
}
}
fn emit_impl_decls(&self, ctx: &mut Context, cg: &mut RustCodegen) {
for item in &self.items {
if let ClassItem::ImplDecl(impl_) = item {
let mut impl_ = impl_.clone();
impl_.item.trait_ = Some(impl_.item.target);
impl_.item.target = TypeExpr::Path(Path(vec![self.name.clone()]), None);
impl_.gen_rust(ctx, cg);
}
}
}
fn emit_deref_impls(&self, cg: &mut RustCodegen) {
if let Some(ref inherits) = self.inherits {
let generics_str = self.generics.get_rust();
let generics_expr_str = Generics::from(self.generics.clone()).get_rust();
cg.add(&format!(
"impl{} core::ops::Deref for {}{}",
generics_str,
self.name.get_rust(),
generics_expr_str
));
cg.addln(" {");
cg.indent += 1;
cg.add_indented("type Target = ");
cg.add(&inherits.get_rust());
cg.addln(";");
cg.add_indentedln("fn deref(&self) -> &Self::Target { &self._super }");
cg.indent -= 1;
cg.addln("}");
cg.add(&format!(
"impl{} core::ops::DerefMut for {}{}",
generics_str,
self.name.get_rust(),
generics_expr_str
));
cg.addln(" {");
cg.indent += 1;
cg.add_indentedln("fn deref_mut(&mut self) -> &mut Self::Target { &mut self._super }");
cg.indent -= 1;
cg.addln("}");
}
}
}
pub fn class_decl(
ctx: &mut Context,
cg: &mut RustCodegen,
visibility: &Visibility,
name: &Identifier,
generics: &GenericsDecl,
inherits: &Option<ExprPath>,
fields: &Vec<Spanned<FieldDeclStmt>>,
constructor: &Option<Spanned<ClassConstructor>>,
items: &Vec<ClassItem>,
) {
let data = ClassProcessedData::analyze(
visibility,
name,
generics,
inherits,
fields,
constructor,
items,
);
data.emit(ctx, cg);
}
fn construct_pattern(pat: &Pattern, idx: usize) -> Pattern {
match pat {
Pattern::Literal(v) => Pattern::Literal(v.clone()),
Pattern::Path(is_mut, v) => Pattern::Path(*is_mut, v.clone().into()),
_ => Pattern::Path(false, Path(vec![Identifier(format!("_{idx}"))])),
}
}
pub fn gen_method_point(method: &FunctionDecl, ctx: &mut Context, cg: &mut RustCodegen) {
let mutable_self = if let Some((is_ref, lifetime, is_mut)) = &method.self_param {
cg.add_indented(&format!(
"{}fn {}{}(",
method.visibility.get_rust(),
method.name.get_rust(),
method.generics.get_rust(),
));
if *is_ref {
cg.add("&");
}
if let Some(lifetime) = lifetime {
cg.add(&format!("'{} ", lifetime.0));
}
if *is_mut {
cg.add("mut ");
}
cg.add("self,");
*is_mut
} else {
panic!();
};
let params = method
.params
.0
.clone()
.into_iter()
.enumerate()
.map(|(idx, mut v)| {
v.name = construct_pattern(&v.name, idx);
(idx, v)
})
.collect::<Vec<_>>();
for (i, param) in &params {
if *i > 0 {
cg.add(", ");
}
param.gen_rust(ctx, cg);
}
cg.add(") ");
if let Some(return_type) = &method.return_type {
cg.add("-> ");
cg.add(&return_type.get_rust());
}
cg.addln("{");
cg.indent += 1;
cg.add_indentedln("unsafe {");
cg.indent += 1;
cg.add_indentedln(&format!(
"let func_ptr = self._vptr[Self::__FN_{}];",
method.name.0.to_uppercase()
));
cg.add_indented("let func: ");
let mut param_types: Vec<TypeExpr> = method
.params
.clone()
.0
.into_iter()
.filter_map(|v| v.type_)
.collect();
param_types.insert(
0,
TypeExpr::UnsafePtr {
mutable: mutable_self,
ty: Box::new(TypeExpr::Path(
Path(vec![
Identifier(String::from("core")),
Identifier(String::from("ffi")),
Identifier(String::from("c_void")),
]),
None,
)),
},
);
cg.add(&TypeExpr::StaticFn(param_types, method.return_type.clone().map(Box::new)).get_rust());
cg.addln(" = core::mem::transmute(func_ptr);");
if mutable_self {
cg.add_indented("func(self as *mut Self as *mut core::ffi::c_void");
} else {
cg.add_indented("func(self as *const Self as *const core::ffi::c_void");
}
for (_, param) in &params {
cg.add(", ");
param.name.gen_rust(ctx, cg);
}
cg.addln(")");
cg.indent -= 1;
cg.add_indentedln("}");
cg.indent -= 1;
cg.add_indentedln("}");
}
pub fn get_type_from_path(path: &ExprPath) -> TypeExpr {
TypeExpr::Path(
Path(path.0.iter().map(|v| v.ident.clone()).collect::<Vec<_>>()),
path.0.last().unwrap().generics.clone(),
)
}
pub fn get_virtual_name(name: &Identifier, is_virtual: bool) -> String {
if is_virtual {
format!("__m_{}", name.get_rust())
} else {
name.get_rust()
}
}
+273
View File
@@ -0,0 +1,273 @@
use mist_parser::ast::*;
use crate::Context;
use crate::{GenRust, GetRust, RustCodegen};
impl GetRust for ExprPath {
fn get_rust(&self) -> String {
self.0
.iter()
.map(ExprPathSegment::get_rust)
.collect::<Vec<_>>()
.join("::")
}
fn get_rust_ctx(&self, cx: &mut Context) -> String {
let mut a = self.clone();
if let Some(path) = &cx.expr_super {
if self.0[0].ident.0 == "super" && self.0.len() == 1 {
a.0[0].ident.0 = String::from("self._super");
} else if self.0[0].ident.0 == "Super" {
a.0[0] = path.0[0].clone();
}
}
a.get_rust()
}
}
impl GetRust for ExprPathSegment {
fn get_rust(&self) -> String {
format!(
"{}{}",
self.ident.get_rust(),
self.generics
.as_ref()
.map(|v| format!("::{}", v.get_rust()))
.unwrap_or_default()
)
}
}
impl GenRust for Literal {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Self::Int(n) => cg.add(&n.to_string()),
Self::Float(n) => cg.add(&format!("{n:?}")),
Self::Bool(b) => cg.add(&b.to_string()),
Self::String(s) => cg.add(&format!("\"{s}\"")),
Self::Tuple(values) => {
cg.add("(");
for (i, val) in values.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
val.gen_rust(ctx, cg);
}
cg.add(")");
}
}
}
}
impl GenRust for Expression {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Expression::Path(path) => cg.add(&path.get_rust_ctx(ctx)),
Expression::Literal(literal) => literal.gen_rust(ctx, cg),
Expression::Statement(stmt) => stmt.gen_rust(ctx, cg),
Expression::Array(values) => {
cg.add("[");
for (i, val) in values.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
val.gen_rust(ctx, cg);
}
cg.add("]");
}
Expression::ArrayRepeat(value, repeat) => {
cg.add("[");
value.gen_rust(ctx, cg);
cg.add("; ");
repeat.gen_rust(ctx, cg);
cg.add("]");
}
Expression::Fix {
initial,
prefixes,
postfixes,
} => {
prefixes.gen_rust(ctx, cg);
initial.gen_rust(ctx, cg);
for postfix in postfixes {
postfix.gen_rust(ctx, cg);
}
}
Expression::Binary { lhs, op, rhs } => {
if op == "->" {
cg.add("unsafe { std::ptr::write(&mut ");
lhs.gen_rust(ctx, cg);
cg.add(", ");
rhs.gen_rust(ctx, cg);
cg.add(") }");
} else {
lhs.gen_rust(ctx, cg);
cg.add(op);
rhs.gen_rust(ctx, cg);
}
}
Expression::Closure {
return_type,
params,
body,
} => {
cg.add("|");
for (i, arg) in params.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
arg.gen_rust(ctx, cg);
}
cg.add("| ");
if let Some(ty) = return_type {
cg.add("-> ");
cg.add(&ty.get_rust());
cg.add(" ");
cg.ensure_brackets_expr(ctx, body);
} else {
body.gen_rust(ctx, cg);
}
}
}
}
}
impl GenRust for Prefix {
fn gen_rust(&self, _ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Self::Deref => cg.add("*"),
Self::Ref => cg.add("&"),
Self::RefMut => cg.add("&mut "),
Self::Not => cg.add("!"),
Self::Neg => cg.add("-"),
}
}
}
impl GenRust for Vec<Prefix> {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
for prefix in self {
prefix.gen_rust(ctx, cg);
}
}
}
impl GenRust for Postfix {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Postfix::TupleFieldAccess(field, generics) => cg.add(&format!(
".{}{}",
field,
generics
.iter()
.map(|v| format!("::{}", v.get_rust()))
.collect::<String>()
)),
Postfix::FieldAccess(field, generics) => cg.add(&format!(
".{}{}",
field.get_rust(),
generics
.iter()
.map(|v| format!("::{}", v.get_rust()))
.collect::<String>()
)),
Postfix::Call(args) => {
cg.add("(");
for (i, arg) in args.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
arg.gen_rust(ctx, cg);
}
cg.add(")");
}
Postfix::MacroCall { inner, delimiter } => {
let (open, close) = match delimiter {
MacroDelimiter::Paren => ("!(", ")"),
MacroDelimiter::Bracket => ("![", "]"),
MacroDelimiter::Brace => ("!{", "}"),
};
cg.add(open);
cg.add(inner);
cg.add(close);
}
Postfix::StructCall(fields) => {
cg.add("{");
for (name, expr) in fields {
cg.add(&name.get_rust());
if let Some(expr) = expr {
cg.add(": ");
expr.gen_rust(ctx, cg);
}
cg.add(",");
}
cg.add("}");
}
Postfix::Index(idx) => {
cg.add("[");
idx.gen_rust(ctx, cg);
cg.add("]");
}
Postfix::As(ty) => {
cg.add(" as ");
cg.add(&ty.get_rust());
}
Postfix::Try => cg.add("?"),
Postfix::Increment => cg.add("+=1"),
Postfix::Decrement => cg.add("-=1"),
}
}
}
impl GetRust for Generics {
fn get_rust(&self) -> String {
if self.0.len() == 0 {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(Generic::get_rust)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetRust for Generic {
fn get_rust(&self) -> String {
match self {
Self::Lifetime(name) => format!("'{}", name.get_rust()),
Self::Type(ty) => ty.get_rust(),
}
}
}
+394
View File
@@ -0,0 +1,394 @@
pub mod class_decl;
pub mod expr;
pub mod statement;
pub mod top_level;
use std::{collections::HashMap, path::PathBuf};
use mist_parser::{
ast::*,
rev_mapper::{Mapping, MistMap, RustMap},
};
pub struct Context {
pub expr_super: Option<ExprPath>,
}
pub trait GenRust {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen);
}
pub trait GetRust {
fn get_rust(&self) -> String;
fn get_rust_ctx(&self, cx: &mut Context) -> String {
let _ = cx;
self.get_rust()
}
}
pub enum Include {
Glob(Path),
Use(Visibility, Path),
}
pub struct RustCodegen {
output: String,
indent: usize,
pub crates: HashMap<Identifier, Vec<Include>>,
pub mapping: Mapping,
position: RustMap,
}
impl RustCodegen {
pub fn new(mist_path: PathBuf) -> Self {
Self {
output: String::new(),
indent: 0,
crates: HashMap::new(),
mapping: Mapping::new(mist_path),
position: RustMap(0, 0),
}
}
fn indent_str(&self) -> String {
" ".repeat(self.indent)
}
pub fn add(&mut self, s: &str) {
let newline_count = bytecount::count(s.as_bytes(), b'\n');
if newline_count == 0 {
self.position.1 += s.len();
} else {
self.position.0 += newline_count;
let last_newline = s.rfind('\n').unwrap();
self.position.1 = s.len() - last_newline - 1;
}
self.output.push_str(s);
}
pub fn addln(&mut self, s: &str) {
self.add(s);
self.add("\n");
}
pub fn add_indented(&mut self, s: &str) {
let line = format!("{}{}", self.indent_str(), s);
self.add(&line);
}
pub fn add_indentedln(&mut self, s: &str) {
let line = format!("{}{}\n", self.indent_str(), s);
self.add(&line);
}
pub fn generate(&mut self, toplevels: Vec<TopLevel>) -> String {
let mut ctx = Context { expr_super: None };
for tl in toplevels {
tl.gen_rust(&mut ctx, self);
}
let mut crates = HashMap::new();
std::mem::swap(&mut self.crates, &mut crates);
for (c, items) in crates {
self.add("mod ");
c.gen_rust(&mut ctx, self);
self.addln(" {");
self.indent += 1;
self.add_indented("extern crate ");
c.gen_rust(&mut ctx, self);
self.addln(";");
for item in items {
self.add_indentedln("#[doc(inline)]");
self.add_indented("pub use ");
match item {
Include::Glob(item) => {
item.gen_rust(&mut ctx, self);
self.add("::*");
}
Include::Use(vis, item) => {
vis.gen_rust(&mut ctx, self);
item.gen_rust(&mut ctx, self);
}
}
self.addln(";");
}
self.indent -= 1;
self.addln("}");
}
self.output.clone()
}
pub fn ensure_brackets(&mut self, ctx: &mut Context, stmt: &Box<Statement>) {
match &**stmt {
Statement::Block(_) => stmt.gen_rust(ctx, self),
_ => {
self.add("{");
self.indent += 1;
stmt.gen_rust(ctx, self);
self.indent -= 1;
self.add("}");
}
}
}
pub fn ensure_brackets_expr(&mut self, ctx: &mut Context, expr: &Expression) {
match expr {
Expression::Statement(stmt) => self.ensure_brackets(ctx, stmt),
_ => {
self.add("{");
self.indent += 1;
expr.gen_rust(ctx, self);
self.indent -= 1;
self.add("}");
}
}
}
}
impl GenRust for Attribute {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Self::Path(path) => cg.add(&path.get_rust()),
Self::NameValue { path, value } => {
cg.add(&format!("{} = ", path.get_rust()));
value.gen_rust(ctx, cg);
}
Self::List { path, items } => {
cg.add(&path.get_rust());
cg.add("(");
for (i, item) in items.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
item.gen_rust(ctx, cg);
}
cg.add(")");
}
}
}
}
pub trait GenSpanTranslation {
fn gen_span(&self, _cg: &mut RustCodegen);
}
impl<T> GenSpanTranslation for Spanned<T> {
fn gen_span(&self, cg: &mut RustCodegen) {
cg.mapping
.map
.insert((cg.position, MistMap(self.line, self.column - 1)));
}
}
impl<T: GetRust> GenRust for T {
fn gen_rust(&self, _: &mut Context, cg: &mut RustCodegen) {
cg.add(&self.get_rust());
}
}
impl<T: GenRust> GenRust for Spanned<T> {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
self.gen_span(cg);
self.item.gen_rust(ctx, cg);
}
}
impl GetRust for Path {
fn get_rust(&self) -> String {
self.0
.iter()
.map(Identifier::get_rust)
.collect::<Vec<String>>()
.join("::")
}
}
impl GetRust for Visibility {
fn get_rust(&self) -> String {
match self {
Visibility::Public => "pub ".to_string(),
Visibility::PublicTarget(path) => format!("pub({}) ", path.get_rust()),
Visibility::Private => "".to_string(),
}
}
}
impl GetRust for Identifier {
fn get_rust(&self) -> String {
self.0.clone()
}
}
impl GetRust for TypeExpr {
fn get_rust(&self) -> String {
match self {
Self::Path(path, generics) => {
if let Some(generics) = generics {
format!("{}{}", path.get_rust(), generics.get_rust())
} else {
path.get_rust()
}
}
Self::Tuple(types) => format!(
"({})",
types
.into_iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", ")
),
Self::StaticFn(types, return_type) => {
if let Some(return_type) = return_type {
format!(
"fn({}) -> {}",
types
.into_iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", "),
return_type.get_rust()
)
} else {
format!(
"fn({})",
types
.into_iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", "),
)
}
}
Self::UnsafePtr { mutable, ty } => {
let mutable = if *mutable { "mut " } else { "const " };
format!("*{mutable}{}", ty.get_rust())
}
Self::Ref {
lifetime,
mutable,
ty,
} => {
if let Some(lifetime) = lifetime {
format!(
"&'{} {}{}",
lifetime.get_rust(),
if *mutable { "mut " } else { "" },
ty.get_rust()
)
} else {
format!("&{}{}", if *mutable { "mut " } else { "" }, ty.get_rust())
}
}
Self::Dyn(ty) => {
format!("dyn {}", ty.get_rust())
}
Self::Void => "()".to_string(),
Self::Fn {
kind,
return_type,
params,
} => {
format!(
"{}({}) -> {}",
kind.get_rust(),
params
.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join(", "),
return_type.get_rust(),
)
}
Self::Array(ty, count) => {
if let Some(count) = count {
format!("[{}; {count}]", ty.get_rust())
} else {
format!("[{}]", ty.get_rust())
}
}
}
}
}
impl GetRust for FnKind {
fn get_rust(&self) -> String {
match self {
Self::Fn => "fn",
Self::UnsafeFn => "unsafe fn",
Self::FnClosure => "Fn",
Self::FnMut => "FnMut",
Self::FnOnce => "FnOnce",
}
.to_string()
}
}
impl GenRust for Pattern {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Self::Etc => cg.add(".."),
Self::Literal(lit) => lit.gen_rust(ctx, cg),
Self::Path(mutable, path) => {
if *mutable {
cg.add("mut ");
};
cg.add(&path.get_rust())
}
Self::Struct(path, inner) => {
cg.add(&path.get_rust());
cg.add(" {");
for (idx, i) in inner.iter().enumerate() {
if idx > 0 {
cg.add(", ");
}
if let Some((name, pat)) = i {
cg.add(&name.get_rust());
if let Some(pat) = pat {
cg.add(": ");
pat.gen_rust(ctx, cg);
}
} else {
cg.add("..");
}
}
cg.add("}");
}
Self::NamedTuple(path, inner) => {
cg.add(&path.get_rust());
cg.add(" (");
for pat in inner {
pat.gen_rust(ctx, cg);
cg.add(",");
}
cg.add(")");
}
Self::Tuple(inner) => {
cg.add("(");
for pat in inner {
pat.gen_rust(ctx, cg);
cg.add(",");
}
cg.add(")");
}
}
}
}
+228
View File
@@ -0,0 +1,228 @@
use mist_parser::ast::*;
use crate::{Context, GenSpanTranslation};
use crate::{GenRust, GetRust, RustCodegen};
impl GenRust for Block {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
cg.addln("{");
cg.indent += 1;
for stmt in &self.statements {
cg.add_indented("");
stmt.gen_rust(ctx, cg);
if stmt.item.is_semicolon_required() {
cg.add(";");
}
cg.addln("");
}
if let Some(soft_return) = &self.soft_return {
cg.add_indented("");
soft_return.gen_rust(ctx, cg);
cg.addln("");
}
cg.indent -= 1;
cg.add_indented("}");
}
}
impl GenRust for Statement {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Statement::TopLevel(tl) => tl.gen_rust(ctx, cg),
Statement::Block(block) => block.gen_rust(ctx, cg),
Statement::UnsafeBlock(block) => {
cg.add("unsafe ");
block.gen_rust(ctx, cg);
}
Statement::VarDecl(VarDeclStmt { decl, init }) => {
cg.add("let ");
decl.gen_rust(ctx, cg);
if let Some(init) = init {
cg.add(" = ");
init.gen_rust(ctx, cg);
}
}
Statement::Match(expr, match_items) => {
cg.add("match ");
expr.gen_rust(ctx, cg);
cg.add(" {");
cg.indent += 1;
for match_item in match_items {
match_item.gen_span(cg);
let MatchItem(pat, body) = &match_item.item;
for (i, p) in pat.iter().enumerate() {
cg.addln("");
cg.add_indented("");
if i > 0 {
cg.add(" | ");
}
p.gen_rust(ctx, cg);
}
cg.add(" => ");
cg.ensure_brackets_expr(ctx, body);
}
cg.indent -= 1;
cg.addln("");
cg.add_indented("}");
}
Statement::If {
initial,
else_if,
else_branch,
} => {
cg.add("if ");
initial.condition.gen_rust(ctx, cg);
cg.add(" ");
initial.body.gen_rust(ctx, cg);
for else_if_branch in else_if {
cg.add(" else if ");
else_if_branch.condition.gen_rust(ctx, cg);
cg.add(" ");
else_if_branch.body.gen_rust(ctx, cg);
}
if let Some(else_br) = else_branch {
cg.add(" else ");
else_br.gen_rust(ctx, cg);
}
}
Statement::While(StatementBranch { condition, body }) => {
cg.add("while ");
condition.gen_rust(ctx, cg);
cg.add(" ");
body.gen_rust(ctx, cg);
}
Statement::Loop(body) => {
cg.add("loop ");
body.gen_rust(ctx, cg);
}
Statement::CStyleFor {
init,
condition,
update,
body,
} => {
cg.addln("{");
cg.indent += 1;
cg.add_indented("");
init.gen_rust(ctx, cg);
if init.is_semicolon_required() {
cg.add(";");
}
cg.addln("");
cg.add_indented("while ");
condition.gen_rust(ctx, cg);
cg.add(" ");
cg.add("{");
cg.indent += 1;
body.gen_rust(ctx, cg);
update.gen_rust(ctx, cg);
if update.is_semicolon_required() {
cg.add(";");
}
cg.addln("");
cg.indent -= 1;
cg.add_indentedln("}");
cg.indent -= 1;
cg.add_indented("}");
}
Statement::For {
pattern,
iterator,
body,
} => {
cg.add("for ");
pattern.gen_rust(ctx, cg);
cg.add(" in ");
iterator.gen_rust(ctx, cg);
body.gen_rust(ctx, cg);
}
Statement::Return(expr) => {
cg.add("return ");
if let Some(expr) = expr {
expr.gen_rust(ctx, cg);
}
}
Statement::Break => cg.add_indentedln("break"),
Statement::Continue => cg.add_indentedln("continue"),
}
}
}
impl GenRust for VarDecl {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
if self.tuple_names.is_empty() {
self.name.gen_rust(ctx, cg);
} else {
cg.add("(");
self.name.gen_rust(ctx, cg);
for name in &self.tuple_names {
cg.add(", ");
name.gen_rust(ctx, cg);
}
cg.add(")");
}
if self.true_type {
cg.add(
&self
.type_
.as_ref()
.map(|t| format!(": {}", t.get_rust()))
.unwrap_or_default(),
);
} else {
cg.add(
&self
.type_
.as_ref()
.map(|t| {
let t = vec![t.get_rust(); self.tuple_names.len() + 1];
if self.tuple_names.is_empty() {
format!(": {}", t.join(", "))
} else {
format!(": ({})", t.join(", "))
}
})
.unwrap_or_default(),
);
}
}
}
+389
View File
@@ -0,0 +1,389 @@
use mist_parser::ast::*;
use crate::{Context, class_decl};
use crate::{GenRust, GetRust, RustCodegen};
impl GetRust for GenericsDecl {
fn get_rust(&self) -> String {
if self.0.len() == 0 {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(|v| v.get_rust())
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetRust for GenericDecl {
fn get_rust(&self) -> String {
match self {
GenericDecl::Lifetime(name, requirements) => {
format!("'{}", name.get_rust())
+ &(if requirements.len() != 0 {
format!(
": {}",
requirements
.into_iter()
.map(GetRust::get_rust)
.collect::<Vec<_>>()
.join("+")
)
} else {
String::new()
})
}
GenericDecl::Type(name, requirements) => {
name.get_rust()
+ &(if requirements.len() != 0 {
format!(
": {}",
requirements
.into_iter()
.map(GetRust::get_rust)
.collect::<Vec<_>>()
.join("+")
)
} else {
String::new()
})
}
}
}
}
impl GenRust for ImplDecl {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
if let Some(trait_) = &self.trait_ {
cg.add_indentedln(&format!(
"impl{} {} for {} {{",
self.generics.get_rust(),
trait_.get_rust(),
self.target.get_rust()
));
} else {
cg.add_indentedln(&format!(
"impl{} {} {{",
self.generics.get_rust(),
self.target.get_rust()
));
}
cg.indent += 1;
for method in &self.methods {
method.gen_rust(ctx, cg);
}
cg.indent -= 1;
cg.add_indentedln("}");
}
}
impl GenRust for FunctionDecl {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
cg.add_indented(&format!(
"{}fn {}{}(",
self.visibility.get_rust(),
self.name.get_rust(),
self.generics.get_rust(),
));
if let Some((is_ref, lifetime, is_mut)) = &self.self_param {
if *is_ref {
cg.add("&");
}
if let Some(lifetime) = lifetime {
cg.add(&format!("'{} ", lifetime.0));
}
if *is_mut {
cg.add("mut ");
}
cg.add("self,");
}
for (i, param) in self.params.0.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
param.gen_rust(ctx, cg);
}
cg.add(") ");
if let Some(return_type) = &self.return_type {
cg.add("-> ");
cg.add(&return_type.get_rust());
}
if let Some(body) = &self.body {
cg.add(" ");
body.gen_rust(ctx, cg);
cg.addln("");
} else {
cg.addln(";");
}
}
}
impl GetRust for FieldDecl {
fn get_rust(&self) -> String {
format!(
"{}{}: {},",
self.visibility.get_rust(),
self.name.get_rust(),
self.type_.get_rust()
)
}
}
impl GetRust for EnumItem {
fn get_rust(&self) -> String {
match self {
Self::Named(id) => id.get_rust(),
Self::Struct(id, s) => format!(
"{} {{{}}}",
id.get_rust(),
s.into_iter()
.map(|field| format!("{}: {}", field.name.get_rust(), field.type_.get_rust()))
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(id, t) => format!(
"{} ({})",
id.get_rust(),
t.into_iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GenRust for ParamList {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
for (i, param) in self.0.iter().enumerate() {
if i > 0 {
cg.add(", ");
}
param.gen_rust(ctx, cg);
}
}
}
impl GenRust for TopLevel {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
if let TopLevelKind::ModAttribute = self.0.item {
for attr in &self.1 {
cg.add("#![");
attr.gen_rust(ctx, cg);
cg.addln("]");
}
} else {
for attr in &self.1 {
cg.add("#[");
attr.gen_rust(ctx, cg);
cg.addln("]");
}
}
self.0.gen_rust(ctx, cg);
}
}
impl GenRust for TopLevelKind {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen) {
match self {
Self::ModAttribute => {}
Self::TypeAlias { name, generics, ty } => {
cg.add("type ");
name.gen_rust(ctx, cg);
if let Some(g) = generics {
g.gen_rust(ctx, cg);
}
cg.add(" = ");
ty.gen_rust(ctx, cg);
cg.addln(";");
}
Self::ConstDecl(decl) => {
cg.add("const ");
decl.decl.gen_rust(ctx, cg);
if let Some(init) = &decl.init {
cg.add(" = ");
init.gen_rust(ctx, cg);
}
cg.addln(";");
}
Self::StaticDecl(decl) => {
cg.add("static ");
decl.decl.gen_rust(ctx, cg);
if let Some(init) = &decl.init {
cg.add(" = ");
init.gen_rust(ctx, cg);
}
cg.addln(";");
}
Self::Import(vis, path) => {
cg.addln(&format!("{}use {};", vis.get_rust(), path.get_rust()))
}
Self::DeclareModule(_, _) => {}
Self::FunctionDecl(decl) => decl.gen_rust(ctx, cg),
Self::ImplDecl(impl_) => impl_.gen_rust(ctx, cg),
Self::StructDecl {
visibility,
name,
generics,
fields,
} => {
cg.addln(&format!(
"{}struct {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indented("");
field.gen_rust(ctx, cg);
cg.addln("");
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::StructDeclTupleUnit {
visibility,
name,
generics,
unit,
} => {
cg.addln(&format!(
"{}struct {}{}",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
if let Some(unit) = unit {
cg.add(" (");
for unit in unit {
cg.add_indented("");
unit.gen_rust(ctx, cg);
cg.add(", ");
}
cg.add(")");
}
cg.indent -= 1;
cg.addln(";\n");
}
Self::EnumDecl {
visibility,
name,
generics,
fields,
} => {
cg.addln(&format!(
"{}enum {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indented("");
field.gen_rust(ctx, cg);
cg.addln(",");
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::TraitDecl {
visibility,
name,
generics,
requirements,
items,
} => {
cg.addln(&format!(
"{}trait {}{}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust(),
if requirements.len() != 0 {
String::from(": ")
+ &requirements
.into_iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join("+")
} else {
String::new()
},
));
cg.indent += 1;
for item in items {
item.gen_rust(ctx, cg);
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::ClassDecl {
visibility,
name,
generics,
inherits,
fields,
constructor,
items,
} => class_decl::class_decl(
ctx,
cg,
visibility,
name,
generics,
inherits,
fields,
constructor,
items,
),
Self::IncludeGlobal(incl) => {
cg.crates
.entry(incl.0[0].clone())
.or_insert(Vec::new())
.push(crate::Include::Glob(incl.clone()));
}
Self::IncludeUse(vis, incl) => {
cg.crates
.entry(incl.0[0].clone())
.or_insert(Vec::new())
.push(crate::Include::Use(vis.clone(), incl.clone()));
}
Self::IncludeLocal(path) => {
cg.add("include!(\"");
cg.add(&path.replace(".mist", ".rs"));
cg.add("\");");
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "mist-api"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language module system"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
keywords = ["compiler", "language", "mist", "module-system"]
categories = ["compilers"]
include = [
".mist/src/**",
"Cargo.toml",
"README.md",
]
[dependencies]
serde = { version = "1.0.228", features = ["serde_derive"] }
serde_json = "1.0.149"
cargo_metadata = "0.23.1"
mist-parser = { workspace = true }
mist-codegen = { workspace = true }
toml = "1.1.2"
[lib]
name = "mist_api"
path = ".mist/src/lib.rs"
+2
View File
@@ -0,0 +1,2 @@
package = "lib.mist"
packages = []
+147
View File
@@ -0,0 +1,147 @@
pub module builder;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use cargo_metadata::CompilerMessage;
use cargo_metadata::Message;
use mist_parser::rev_mapper;
#[derive(Debug, Clone)]
pub struct MistDiagnosticMessage
{
pub String message;
pub PathBuf file_path;
pub String file_name;
pub usize line;
pub usize column;
}
#[derive(Debug, Clone)]
pub enum MistDiagnostic
{
Error(MistDiagnosticMessage);
Warning(MistDiagnosticMessage);
Rust(CompilerMessage);
}
pub bool build(Vec<String> mut args, PathBuf root)
{
args.remove(0);
args.insert(1, "--message-format=json".to_string());
let mut command = Command::new("cargo").args(args).stdout(Stdio::piped()).stderr(Stdio::inherit()).stdin(Stdio::inherit()).spawn().expect("Failed to run cargo");
let mut reader = std::io::BufReader::new(command.stdout.take().expect("Failed to get reader"));
let mut diagnostics = Vec::new();
let mut mapping = HashMap::new();
for message in cargo_metadata::Message::parse_stream(&mut reader) {
match message {
Ok(Message::CompilerMessage(msg)) => {
for span in &msg.message.spans {
if span.is_primary {
let rust_path = root.join(&span.file_name);
let mapping_path = rust_path.with_extension("map.json");
if !fs::exists(&mapping_path).expect("Unable to check if map file exists") {
diagnostics.push(MistDiagnostic::Rust(msg));
break;
}
let map = mapping.entry(mapping_path.clone()).or_insert_with(() => {
let map_str = fs::read_to_string(mapping_path).expect("Failed to read map file");
serde_json::from_str<rev_mapper::Mapping>(&map_str).expect("Failed to parse map file")
});
let mist_file = map.mist_path.strip_prefix(&root);
let rust_lookup = rev_mapper::RustMap(span.line_end - 1, span.column_start - 1);
match map.find(&rust_lookup) {
Some((_, rev_mapper::MistMap(line, column))) => {
let mist_msg = MistDiagnosticMessage {
message: format!("{}: {}",
msg.message.message,
span.label.clone().unwrap_or_default()),
file_name: if let Ok(mist_file) = mist_file {
mist_file.to_string_lossy().to_string()
} else {
map.mist_path.to_string_lossy().to_string()
},
file_path: map.mist_path.clone(),
line: line,
column: column,
};
match msg.message.level {
cargo_metadata::diagnostic::DiagnosticLevel::Error => {
diagnostics.push(MistDiagnostic::Error(mist_msg))
}
cargo_metadata::diagnostic::DiagnosticLevel::Warning => {
diagnostics.push(MistDiagnostic::Warning(mist_msg))
}
_ => {
}
}
}
None => {
diagnostics.push(MistDiagnostic::Rust(msg));
break;
}
}
}
}
}
Ok(Message::BuildFinished(finish)) => {
print_diagnostics(&diagnostics);
let mut raw_reader = reader.into_inner();
let mut stdout = std::io::stdout();
std::io::copy(&mut raw_reader, &mut stdout).map_err((v) => v.to_string()).expect("(Mist) Failed to copy IO");
command.wait().unwrap();
return finish.success;
}
Ok(Message::TextLine(text)) => println!("{text}"),
_ => {
}
}
}
false
}
pub void print_diagnostics(Vec<MistDiagnostic>& diagnostics)
{
let mut files = HashMap::new();
for diag in diagnostics {
match diag {
MistDiagnostic::Error(msg) => {
let line = get_line(&mut files, &msg);
println!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}",
msg.file_name,
msg.line,
msg.column,
msg.message,
line.unwrap_or_default(),)
}
MistDiagnostic::Warning(msg) => {
let line = get_line(&mut files, &msg);
println!("\n{}:{}:{}\n \x1b[33mWarning\x1b[0m: {}\n\t{}",
msg.file_name,
msg.line,
msg.column,
msg.message,
line.unwrap_or_default(),)
}
MistDiagnostic::Rust(rs) => println!("{rs}"),
}
}
}
pub Option<String> get_line(HashMap<PathBuf, Vec<String>> mut& files, MistDiagnosticMessage& msg)
{
let src_path = msg.file_path.clone();
let lines = files.entry(src_path.clone()).or_insert_with(() => {
fs::read_to_string(src_path).expect("Unable to read mist file").lines().into_iter().map(String::from).collect()
});
lines.get(msg.line.saturating_sub(1)).map((v) => v.trim().to_string())
}
View File
+92
View File
@@ -0,0 +1,92 @@
pub module modules;
use std::path::Path;
use std::path::PathBuf;
use std::fs;
use std::process;
use crate::transpiler::MistConfig;
#[derive(Debug)]
pub class Module
{
pub String name;
pub PathBuf path;
pub Vec<Module> children;
pub constructor(PathBuf mist_path, MistConfig& config)
{
self.children = Vec::new();
self.name = mist_path.file_stem().and_then((s) => s.to_str()).expect("Failed to get module name").to_string();
self.path = mist_path;
if self.path.is_dir() {
let dir = self.path.clone();
let pkg_gate = self.path.join("package.mist");
if pkg_gate.exists() {
self.path = pkg_gate;
}
self.scan_directory(&dir, config);
} else if config.should_ignore(&self.path) {
let dir = self.path.parent().expect("Failed to get parent directory to scan").to_path_buf();
self.scan_directory(&dir, config);
}
}
void scan_directory(&mut self, Path& search_dir, MistConfig& config)
{
let entries = match fs::read_dir(search_dir) {
Ok(entries) => entries,
Err(e) => {
eprintln!("error: failed to read directory {}\n {}", search_dir.display(), e);
process::exit(1);
}
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
eprintln!("error: failed to read directory entry\n {}", e);
process::exit(1);
}
};
let child_path = entry.path();
if child_path == self.path || child_path == config.package {
continue;
}
self.children.push(Module::new(child_path, config));
}
}
pub bool is_package(&self)
{
self.path.file_name().map((v) => v.to_str()).unwrap_or_default() == Some("package.mist")
}
pub PathBuf output_dir(&self, PathBuf& parent_dir)
{
if self.path.is_dir() || self.is_package() {
parent_dir.join(&self.name)
} else {
parent_dir.clone()
}
}
pub PathBuf output_path(&self, PathBuf& parent_dir, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
{
let name = if self.path.is_dir() || self.is_package() {
&self.name
} else if let Some((_, name)) = curr_mod_decl {
&name.0
} else {
&self.name
};
if self.path.is_dir() || self.is_package() {
parent_dir.join(name).join("mod.rs")
} else {
parent_dir.join(name).with_extension("rs")
}
}
}
+305
View File
@@ -0,0 +1,305 @@
pub module transpiler;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process;
use std::time;
use mist_parser::error;
use crate::modules;
use mist_codegen::GetRust;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(default)]
pub struct MistConfig
{
pub PathBuf package;
pub Vec<PathBuf> packages;
pub Vec<PathBuf> include;
pub mist_parser::MistFmtConfig fmt;
}
impl MistConfig
{
pub bool should_ignore(&self, Path& path)
{
if path == self.package {
return true;
}
for pkg in &self.packages {
if path.ends_with(pkg) {
return true;
}
}
false
}
}
impl Default for MistConfig
{
Self default()
{
Self {
package: PathBuf::from("main.mist"),
packages: Vec::new(),
include: Vec::new(),
fmt: mist_parser::MistFmtConfig {
allman_bracket_style: true,
},
}
}
}
pub void transpile(Path& root)
{
println!("\x1b[32m\nTranspiling\x1b[0m \x1b[94m{:?}\x1b[0m", root.file_name().unwrap_or_default());
let start = time::Instant::now();
let toml_path = root.join("Mist.toml");
let src = root.join("src");
let out = root.join(".mist/src");
let toml_content = fs::read_to_string(&toml_path).unwrap_or_else((_) => panic!("Could not read file at {:?}", toml_path));
MistConfig mut config = toml::from_str(&toml_content).unwrap_or_else((_) => panic!("Failed to parse Mist.toml from {:?}", toml_path));
for pkg in &mut config.packages {
*pkg = src.join(&*pkg);
}
config.package = src.join(&*config.package);
let master = modules::Module::new(config.package.clone(), &config);
master.transpile(&out, &mut config, &mut String::new());
let elapsed = start.elapsed();
println!("\x1b[32m\nTranspile successful\x1b[0m in \x1b[34m{:.2?}\x1b[0m", elapsed);
for incl in &config.include {
let incl = if incl.is_relative() { root.join(incl) } else { incl.clone() };
if ends_with_star(&incl) {
let sub_crates = incl.parent().expect("Failed to get parent");
let entries = match fs::read_dir(sub_crates) {
Ok(entries) => entries,
Err(e) => {
eprintln!("error: failed to read directory {}\n {}", sub_crates.display(), e);
process::exit(1);
}
};
for sub_crate in entries {
if let Ok(sub_crate) = sub_crate {
let sub_crate = sub_crate.path();
if fs::exists(sub_crate.join("Mist.toml")).unwrap_or_default() {
transpile(&sub_crate);
}
}
}
} else {
transpile(&incl);
}
}
}
bool ends_with_star(Path& path)
{
path.file_name().and_then((name) => name.to_str()).is_some_and((name) => name.ends_with("*"))
}
impl modules::Module
{
(bool, String) transpile(&self, PathBuf& parent_dir, MistConfig mut& config, String mut& main_mods)
{
if !self.path.is_dir() && self.path.extension().and_then((v) => v.to_str()) != Some("mist") {
let file_name = self.path.file_name().and_then((s) => s.to_str()).expect("Failed to get file name");
fs::copy(&self.path, parent_dir.join(&file_name)).expect("Failed to copy SideFile");
return (true, String::new());
}
let dir = self.output_dir(parent_dir);
let _ = fs::create_dir_all(&dir);
let mut output = String::new();
let mut child_changed = false;
for child in &self.children {
if !config.should_ignore(&child.path) {
let out = child.transpile(&dir, config, main_mods);
if out.0 {
child_changed = true;
}
output.push_str(&out.1);
}
}
if self.path == config.package {
*main_mods = output.clone();
} else if config.should_ignore(&self.path) {
output.push_str(main_mods)
}
self.write_transpile(output, parent_dir, child_changed)
}
(bool, String) write_transpile(&self, String output, PathBuf& parent_dir, bool child_changed)
{
if self.path.is_dir() || self.is_package() {
let output_file = self.output_path(parent_dir, &None);
let final_output = if self.is_package() {
let source = match fs::read_to_string(&self.path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
process::exit(1);
}
};
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
let (result_path, gc, rust_code) = match transpile_code(&self.path, &source, output_file.clone(), &output, &curr_mod_decl) {
Ok(v) => v,
Err(e) => {
decode_err(&e, &self.path);
process::exit(1);
}
};
let map_path = result_path.with_extension("map.json");
if let Some(parent) = map_path.parent() {
let _ = fs::create_dir_all(parent);
}
fs::write(&map_path, serde_json::to_string(&gc.mapping).unwrap()).expect("Failed to write map file");
rust_code
} else {
if output.len() == 0 {
return (true, String::new());
}
output
};
let res = fs::write(&output_file, final_output);
if res.is_err() {
eprintln!("error: failed to write output {}\n {}",
output_file.display(),
res.unwrap_err(),);
process::exit(1);
}
(false, format!("pub mod {};\n", self.name))
} else {
let source = match fs::read_to_string(&self.path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read file {}\n {}", self.path.display(), e);
process::exit(1);
}
};
let curr_mod_decl = mist_parser::parse_module(&source).expect("Failed parsing module");
let output_file = self.output_path(parent_dir, &curr_mod_decl);
let should_change = is_source_newer(&self.path, &output_file).expect("Failed to cache");
if should_change || child_changed {
transpile_file(&self.path, &source, output_file, &output, &curr_mod_decl);
}
(should_change, if let Some((vis, name)) = &curr_mod_decl {
format!("{}mod {};\n", vis.get_rust(), name.get_rust())
} else {
String::new()
})
}
}
}
std::io::Result<bool> is_source_newer(Path& source, Path& output)
{
if !output.exists() {
return Ok(true);
}
let source_time = fs::metadata(source)?.modified()?;
let output_time = fs::metadata(output)?.modified()?;
Ok(source_time > output_time)
}
pub enum TranspileError<'a>
{
Parse(error::ParseError<'a>);
Semantic(Vec<mist_parser::semantics::SemanticError>);
}
pub Result<(PathBuf, mist_codegen::RustCodegen, String), TranspileError<'a>> transpile_code<'a>(PathBuf& path, str 'a& source, PathBuf mut output_file, str& mod_decl, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
{
if let Some((_, name)) = &curr_mod_decl {
if output_file.file_name().map((v) => v.to_str()).unwrap_or_default() != Some("mod.rs") {
if let Some(ext) = output_file.extension().map((e) => e.to_owned()) {
let mut new_name = std::ffi::OsString::from(&name.0);
new_name.push(".");
new_name.push(ext);
output_file.set_file_name(new_name);
} else {
output_file.set_file_name(&name.0);
}
}
}
let mut gc = mist_codegen::RustCodegen::new(path.clone());
let parsed = mist_parser::parse(source).map_err(TranspileError::Parse)?;
for i in &parsed.items {
let _ = mist_parser::semantics::check_class_semantics(i).map_err(TranspileError::Semantic)?;
}
gc.generate(parsed.mod_attributes);
gc.add(mod_decl);
let output = gc.generate(parsed.items);
Ok((output_file, gc, output))
}
pub void transpile_file(PathBuf& path, str& source, PathBuf output_file, str& mod_decl, Option<(mist_parser::ast::Visibility, mist_parser::ast::Identifier)>& curr_mod_decl)
{
let (output_file, gc, output) = match transpile_code(path, source, output_file, mod_decl, curr_mod_decl) {
Ok(output) => output,
Err(e) => {
decode_err(&e, path);
process::exit(1);
}
};
if let Some(parent) = output_file.parent() {
let _ = fs::create_dir_all(parent);
}
let res = fs::write(&output_file, output);
let output_file_map = output_file.with_extension("map.json");
let res_map = fs::write(&output_file_map, serde_json::to_string(&gc.mapping).unwrap());
if res_map.is_err() {
eprintln!("error: failed to write mapping output {}\n {}",
output_file_map.display(),
res_map.as_ref().unwrap_err(),);
}
if res.is_err() {
eprintln!("error: failed to write output {}\n {}",
output_file.display(),
res.as_ref().unwrap_err(),);
}
if res_map.is_err() || res.is_err() {
process::exit(1);
}
}
pub void decode_err<'a>(TranspileError<'a>& err, PathBuf& path)
{
let curr_dir = std::env::current_dir().unwrap();
match err {
TranspileError::Semantic(e_list) => {
for e in e_list {
eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}",
path.strip_prefix(&curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
e.line,
e.column,
e.error_message,);
}
}
TranspileError::Parse(e) => {
match e {
error::ParseError::Ast(e) => {
let start_pos = e.span.start_pos().line_col();
let span = e.span.as_str();
eprintln!("\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
path.strip_prefix(curr_dir).unwrap_or_else(|_| path).as_os_str().display(),
start_pos.0,
start_pos.1,
e.error_message,
span,
if span.ends_with("\n") { "" } else { "\n" },
"^".repeat(span.trim().len()),);
}
error::ParseError::PreAst(e) => {
eprintln!("error: parse failed in {}\n{}", path.strip_prefix(curr_dir).unwrap_or_else(|_| path).display(), e);
}
}
}
}
}
@@ -1,12 +1,12 @@
[package]
name = "mist-parser"
version = "0.1.1"
version = "0.4.0"
edition = "2024"
description = "The Mist programming language parser"
license = "Apache-2.0"
repository = "https://github.com/mist-go/mist"
keywords = ["compiler", "language", "mist"]
categories = ["compilers"]
categories = ["compilers", "parser-implementations", "parsing"]
[dependencies]
pest = "2.8.6"
+131
View File
@@ -0,0 +1,131 @@
use serde::Serialize;
use super::*;
#[derive(Debug, Clone, Serialize)]
pub enum Expression {
Literal(Literal),
Path(ExprPath),
Statement(Box<Statement>),
Array(Vec<Expression>),
ArrayRepeat(Box<Expression>, Box<Expression>),
Closure {
return_type: Option<TypeExpr>,
params: Vec<VarDecl>,
body: Box<Expression>,
},
Fix {
initial: Box<Expression>,
prefixes: Vec<Prefix>,
postfixes: Vec<Postfix>,
},
Binary {
lhs: Box<Expression>,
op: String,
rhs: Box<Expression>,
},
}
#[derive(Debug, Clone, Serialize)]
pub enum Literal {
String(String),
Int(i64),
Float(f64),
Bool(bool),
Tuple(Vec<Expression>),
}
#[derive(Debug, Clone, Serialize)]
pub enum Pattern {
NamedTuple(Path, Vec<Box<Pattern>>),
Struct(Path, Vec<Option<(Identifier, Option<Box<Pattern>>)>>),
Tuple(Vec<Box<Pattern>>),
Literal(Literal),
Path(bool, Path),
Etc,
}
#[derive(Debug, Clone, Serialize)]
pub enum MacroDelimiter {
Paren,
Bracket,
Brace,
}
#[derive(Debug, Clone, Serialize)]
pub enum Postfix {
FieldAccess(Identifier, Option<Generics>),
TupleFieldAccess(u8, Option<Generics>),
Call(Vec<Expression>),
MacroCall {
inner: String,
delimiter: MacroDelimiter,
},
StructCall(Vec<(Identifier, Option<Expression>)>),
Index(Expression),
As(TypeExpr),
Increment,
Decrement,
Try,
}
#[derive(Debug, Clone, Serialize)]
pub enum Prefix {
Ref,
RefMut,
Deref,
Not,
Neg,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct ExprPathSegment {
pub ident: Identifier,
pub generics: Option<Generics>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct ExprPath(pub Vec<ExprPathSegment>);
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct Generics(pub Vec<Generic>);
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub enum Generic {
Lifetime(Identifier),
Type(TypeExpr),
}
impl From<Path> for ExprPath {
fn from(path: Path) -> Self {
Self(
path.0
.into_iter()
.map(|v| ExprPathSegment {
ident: v,
generics: None,
})
.collect(),
)
}
}
impl Expression {
pub fn is_semicolon_required(&self) -> bool {
match self {
Self::Statement(v) => match &**v {
Statement::TopLevel(_) => false,
stmt => !stmt.is_block(),
},
_ => true,
}
}
pub fn is_block(&self) -> bool {
if let Expression::Statement(stmt) = self {
stmt.is_block()
} else {
false
}
}
}
+83
View File
@@ -0,0 +1,83 @@
use serde::Serialize;
pub mod expr;
pub mod statement;
pub mod top_level;
pub use expr::*;
pub use statement::*;
pub use top_level::*;
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct Path(pub Vec<Identifier>);
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct Identifier(pub String);
#[derive(Debug, Clone, Serialize, Default)]
pub struct ParamList(pub Vec<VarDecl>);
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub enum FnKind {
Fn,
UnsafeFn,
FnClosure,
FnOnce,
FnMut,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub enum TypeExpr {
Ref {
lifetime: Option<Identifier>,
mutable: bool,
ty: Box<TypeExpr>,
},
UnsafePtr {
mutable: bool,
ty: Box<TypeExpr>,
},
Dyn(Box<TypeExpr>),
Path(Path, Option<Generics>),
StaticFn(Vec<TypeExpr>, Option<Box<TypeExpr>>),
Tuple(Vec<TypeExpr>),
Void,
Fn {
kind: FnKind,
return_type: Box<TypeExpr>,
params: Vec<TypeExpr>,
},
Array(Box<TypeExpr>, Option<isize>)
}
#[derive(Debug, Clone, Serialize)]
pub struct Spanned<T> {
pub line: usize,
pub column: usize,
pub item: T,
}
impl From<GenericDecl> for Generic {
fn from(value: GenericDecl) -> Self {
match value {
GenericDecl::Lifetime(life, _) => Generic::Lifetime(life),
GenericDecl::Type(ty, _) => Generic::Type(TypeExpr::Path(Path(vec![ty]), None)),
}
}
}
impl Into<Option<Generics>> for GenericsDecl {
fn into(self) -> Option<Generics> {
if self.0.len() == 0 {
None
} else {
Some(self.into())
}
}
}
impl From<GenericsDecl> for Generics {
fn from(value: GenericsDecl) -> Self {
Self(value.0.into_iter().map(Generic::from).collect())
}
}
+72
View File
@@ -0,0 +1,72 @@
use serde::Serialize;
use super::*;
#[derive(Debug, Clone, Serialize, Default)]
pub struct Block {
pub statements: Vec<Spanned<Expression>>,
pub soft_return: Option<Spanned<Expression>>,
}
#[derive(Debug, Clone, Serialize)]
pub enum Statement {
UnsafeBlock(Block),
Block(Block),
TopLevel(Box<TopLevel>),
If {
initial: StatementBranch,
else_if: Vec<StatementBranch>,
else_branch: Option<Block>,
},
Loop(Block),
While(StatementBranch),
CStyleFor {
init: Expression,
condition: Expression,
update: Expression,
body: Block,
},
For {
pattern: Pattern,
iterator: Expression,
body: Block,
},
Match(Expression, Vec<Spanned<MatchItem>>),
VarDecl(VarDeclStmt),
Return(Option<Expression>),
Break,
Continue,
}
#[derive(Debug, Clone, Serialize)]
pub struct MatchItem(pub Vec<Pattern>, pub Expression);
#[derive(Debug, Clone, Serialize)]
pub struct VarDecl {
pub type_: Option<TypeExpr>,
pub name: Pattern,
pub true_type: bool,
pub tuple_names: Vec<Pattern>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt {
pub decl: VarDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)]
pub struct StatementBranch {
pub condition: Expression,
pub body: Box<Block>,
}
impl Statement {
pub fn is_block(&self) -> bool {
match self {
Self::VarDecl(_) | Self::Return(_) | Self::Break | Self::Continue => false,
_ => true,
}
}
}
+145
View File
@@ -0,0 +1,145 @@
use serde::Serialize;
use super::*;
#[derive(Debug, Clone, Serialize)]
pub enum Visibility {
Public,
PublicTarget(Path),
Private,
}
#[derive(Debug, Clone, Serialize)]
pub enum Attribute {
/// #[test]
Path(Path),
/// #[name = "value"]
NameValue { path: Path, value: Literal },
/// #[derive(Clone, Copy)]
List { path: Path, items: Vec<Attribute> },
}
#[derive(Debug, Clone, Serialize)]
pub struct TopLevel(pub Spanned<TopLevelKind>, pub Vec<Attribute>);
#[derive(Debug, Clone, Serialize)]
pub enum TopLevelKind {
ModAttribute,
Import(Visibility, Path),
IncludeGlobal(Path),
IncludeUse(Visibility, Path),
IncludeLocal(String),
DeclareModule(Visibility, Identifier),
ImplDecl(ImplDecl),
StaticDecl(VarDeclStmt),
ConstDecl(VarDeclStmt),
TypeAlias {
name: Identifier,
generics: Option<GenericsDecl>,
ty: TypeExpr,
},
TraitDecl {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
requirements: Vec<TypeExpr>,
items: Vec<Spanned<FunctionDecl>>,
},
EnumDecl {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
fields: Vec<Spanned<EnumItem>>,
},
StructDecl {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
fields: Vec<Spanned<FieldDecl>>,
},
StructDeclTupleUnit {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
unit: Option<Vec<Spanned<TypeExpr>>>,
},
FunctionDecl(FunctionDecl),
ClassDecl {
visibility: Visibility,
name: Identifier,
generics: GenericsDecl,
inherits: Option<ExprPath>,
fields: Vec<Spanned<FieldDeclStmt>>,
constructor: Option<Spanned<ClassConstructor>>,
items: Vec<ClassItem>,
},
}
#[derive(Debug, Clone, Serialize)]
pub enum ClassItem {
Method(Spanned<FunctionDecl>),
ImplDecl(Spanned<ImplDecl>),
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct GenericsDecl(pub Vec<GenericDecl>);
#[derive(Debug, Clone, Serialize)]
pub enum GenericDecl {
Lifetime(Identifier, Vec<Generic>),
Type(Identifier, Vec<Generic>),
}
#[derive(Debug, Clone, Serialize)]
pub enum EnumItem {
Named(Identifier),
Tuple(Identifier, Vec<TypeExpr>),
Struct(Identifier, Vec<FieldDecl>),
}
#[derive(Debug, Clone, Serialize)]
pub struct ClassConstructor {
pub visibility: Visibility,
pub generics: GenericsDecl,
pub params: ParamList,
pub body: Block,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
pub struct Override(pub Option<ExprPath>);
#[derive(Debug, Clone, Serialize)]
pub struct FunctionDecl {
pub visibility: Visibility,
pub is_virtual: bool,
pub return_type: Option<TypeExpr>,
pub name: Identifier,
pub generics: GenericsDecl,
pub self_param: Option<(bool, Option<Identifier>, bool)>,
pub params: ParamList,
pub is_override: Option<Override>,
pub body: Option<Block>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ImplDecl {
pub generics: GenericsDecl,
pub target: TypeExpr,
pub trait_: Option<TypeExpr>,
pub methods: Vec<Spanned<FunctionDecl>>,
}
#[derive(Debug, Clone, Serialize)]
pub struct FieldDecl {
pub visibility: Visibility,
pub type_: TypeExpr,
pub name: Identifier,
}
#[derive(Debug, Clone, Serialize)]
pub struct FieldDeclStmt {
pub decl: FieldDecl,
pub init: Option<Expression>,
}
+111
View File
@@ -0,0 +1,111 @@
use std::fmt::Debug;
use pest::iterators::Pair;
use crate::Rule;
pub type AstResult<'a, T> = Result<T, AstError<'a>>;
#[derive(Debug, Clone)]
pub enum ParseError<'a> {
PreAst(pest::error::Error<Rule>),
Ast(AstError<'a>),
}
#[derive(Debug, Clone)]
pub struct AstError<'a> {
pub span: pest::Span<'a>,
pub error_code: ErrorCode,
pub error_message: String,
}
#[derive(Debug, Clone)]
pub enum ErrorCode {
InvalidStatement,
AstGenBug,
Module,
NumberParse,
}
impl From<pest::error::Error<Rule>> for ParseError<'_> {
fn from(value: pest::error::Error<Rule>) -> Self {
Self::PreAst(value)
}
}
impl<'a> From<AstError<'a>> for ParseError<'a> {
fn from(value: AstError<'a>) -> Self {
Self::Ast(value)
}
}
impl<'a> AstError<'a> {
#[track_caller]
pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T> {
let loc = std::panic::Location::caller();
Err(Self {
span: pair.as_span(),
error_code: ErrorCode::AstGenBug,
error_message: format!(
"Possible bug, unimplemented: {:#?}, at {}:{}",
pair.as_rule(),
loc.file(),
loc.line(),
),
})
}
}
pub trait IntoErr<T, FA, FR> {
fn get(self) -> T;
fn get_map(self, m: impl Fn(FA) -> FR) -> T;
}
pub trait GetLength {
fn len(&self) -> usize;
}
impl<T, E> GetLength for Result<Vec<T>, E> {
fn len(&self) -> usize {
if let Ok(v) = self { v.len() } else { 0 }
}
}
pub fn collect_recovered<'a, T: Debug>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
) -> AstResult<'a, Vec<T>>
where
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a>>,
{
collect_recovered_map(pairs, T::try_from)
}
pub fn collect_recovered_map<'a, T: Debug, F>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
f: F,
) -> AstResult<'a, Vec<T>>
where
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T>,
{
let mut items = Vec::new();
let mut last_error: Option<AstError<'a>> = None;
for pair in pairs {
match f(pair) {
Ok(item) => items.push(item),
Err(e) => {
last_error = Some(e);
}
}
}
match last_error {
Some(ast_err) => Err(AstError {
span: ast_err.span,
error_code: ast_err.error_code,
error_message: ast_err.error_message,
}),
None => Ok(items),
}
}
+715
View File
@@ -0,0 +1,715 @@
// ======================================================
// LEXICAL
// ======================================================
WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
// ------------------------------------------------------
// PRIMITIVES
// ------------------------------------------------------
keyword = {
"if"
| "else"
| "fn"
| "for"
| "while"
| "match"
| "return"
| "break"
| "continue"
| "struct"
| "enum"
| "class"
| "trait"
| "impl"
| "use"
| "pub"
| "mut"
| "let"
| "true"
| "false"
| "dyn"
| "loop"
| "unsafe"
| "override"
| "const"
| "type"
| "virtual"
}
identifier = @{
!(keyword ~ !(ASCII_ALPHANUMERIC | "_")) ~ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")*
}
integer = @{ ASCII_DIGIT+ }
float = @{
ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+
}
boolean = {
"true"
| "false"
}
string_lit = {
"\"" ~ inner_str ~ "\""
}
inner_str = @{
(!"\"" ~ ("\\\"" | ANY))*
}
semicolon = _{ ";" }
static_path = {
identifier ~ ("::" ~ identifier)*
}
// ======================================================
// PROGRAM
// ======================================================
program = {
SOI ~ top_level* ~ EOI
}
module_program = {
SOI ~ top_level?
}
// ======================================================
// MODIFIERS
// ======================================================
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
mutable = { "mut" }
// ======================================================
// GENERICS
// ======================================================
generic_decl = { (lifetime | identifier) ~ (":" ~ generic ~ ("+" ~ generic)*)? }
generics_decl = { "<" ~ (generic_decl ~ ("," ~ generic_decl)*)? ~ ">" }
generic = { lifetime | type_expr }
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
// ======================================================
// TYPES
// ======================================================
tuple_type = {
"(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ","? ~ ")"
}
path_type = {
static_path ~ generics?
}
unsafe_ref_type = {
mutable? ~ "unsafe" ~ "*"
}
ref_type = {
mutable? ~ lifetime? ~ "&"
}
fn_kind_fn = { "fn" }
fn_kind_unsafe = { "unsafe" ~ "fn" }
fn_kind_closure = { "Fn" }
fn_kind_once = { "FnOnce" }
fn_kind_mut = { "FnMut" }
fn_kind = _{
fn_kind_fn
| fn_kind_unsafe
| fn_kind_once
| fn_kind_mut
| fn_kind_closure
}
fn_type = {
fn_kind ~ "(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
}
dyn_type = {
"dyn" ~ type_expr
}
void_type = {
"void"
}
array_type = {
"[" ~ integer? ~ "]"
}
type_expr = {
(void_type | path_type | tuple_type | dyn_type) ~ (unsafe_ref_type | ref_type | fn_type | array_type)*
}
lifetime = {
"'" ~ identifier
}
// ======================================================
// LITERALS
// ======================================================
literal = {
float
| integer
| boolean
| string_lit
}
// ======================================================
// PATTERNS
// ======================================================
etc_pattern = { ".." }
multi_pat_template = _{
((pattern | etc_pattern) ~ ("," ~ (pattern | etc_pattern))* ~ ","?)?
}
tuple_pattern = {
"(" ~ (pattern | etc_pattern) ~ "," ~ multi_pat_template ~ ")"
}
named_tuple_pattern = {
static_path ~ "(" ~ multi_pat_template ~ ")"
}
struct_destruct = {
identifier ~ (":" ~ pattern)?
}
struct_pattern = {
static_path ~ "{" ~ ((struct_destruct | etc_pattern) ~ ("," ~ (struct_destruct | etc_pattern))*)? ~ "}"
}
path_pattern = {
mutable? ~ static_path
}
pattern = _{
named_tuple_pattern
| tuple_pattern
| struct_pattern
| literal
| path_pattern
}
// ======================================================
// ATTRIBUTES / META
// ======================================================
attribute = {
"#" ~ "[" ~ meta ~ "]"
}
mod_attribute = {
"#" ~ "!" ~ "[" ~ meta ~ "]"
}
meta = {
static_path ~ ("=" ~ literal | "(" ~ meta_list? ~ ")")?
}
meta_list = {
(meta ~ ("," ~ meta)* ~ ","?)?
}
attributes = {
attribute*
}
// ======================================================
// DECLARATION HELPERS
// ======================================================
as_kw = { "as" }
var_decl = {
("let" ~ pattern ~ ("," ~ pattern)*)
| (type_expr ~ as_kw ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)+))
| (type_expr ~ (!tuple_pattern ~ pattern ~ ("," ~ pattern)*))
}
field = {
visibility? ~ type_expr ~ identifier
}
param = {
(type_expr ~ pattern)
| pattern
}
field_list = {
(field ~ ";")*
}
param_list = {
(param ~ ("," ~ param)* ~ ","?)?
}
// ======================================================
// IMPORTS / MODULES
// ======================================================
include_global = {
"#" ~ "include" ~ "<" ~ identifier ~ ("/" ~ identifier)* ~ ">"
}
include_use_global = {
visibility? ~ "#" ~ "use" ~ static_path ~ semicolon
}
include_local = {
"#" ~ "include" ~ string_lit
}
import = {
visibility? ~ "use" ~ static_path ~ semicolon
}
declare_module = {
visibility? ~ "module" ~ identifier ~ semicolon
}
// ======================================================
// STRUCTS
// ======================================================
struct_decl = {
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ "{" ~ field_list ~ "}"
}
tuple_struct_decl = {
visibility? ~ "struct" ~ identifier ~ generics_decl? ~ tuple_type? ~ ";"
}
// ======================================================
// ENUMS
// ======================================================
enum_named = {
identifier
}
enum_tuple = {
identifier ~ tuple_type
}
enum_struct = {
identifier ~ "{" ~ field_list ~ "}"
}
enum_field = _{
enum_tuple
| enum_struct
| enum_named
}
enum_decl = {
visibility? ~ "enum" ~ identifier ~ generics_decl? ~ "{" ~ (enum_field ~ ";")* ~ "}"
}
// ======================================================
// CLASSES
// ======================================================
class_constructor = {
visibility? ~ "constructor" ~ generics_decl? ~ "(" ~ param_list ~ ")" ~ block
}
class_fields = {
class_field*
}
class_field = {
field ~ ("=" ~ expr)? ~ semicolon
}
self_param = {
(ref_px ~ lifetime?)? ~ mutable? ~ "self"
}
method_args = _{
((self_param ~ ("," ~ param_list)?) | param_list) ~ ","?
}
class_item = _{
impl_decl
| function_decl
}
class_decl = {
visibility? ~ "class" ~ identifier ~ generics_decl? ~ (":" ~ expr_path)? ~ "{" ~ class_fields ~ class_constructor? ~ class_item* ~ "}"
}
// ======================================================
// IMPL
// ======================================================
impl_for_decl = {
"impl" ~ generics_decl? ~ type_expr ~ "for" ~ type_expr ~ "{" ~ function_decl* ~ "}"
}
impl_decl = {
"impl" ~ generics_decl? ~ type_expr ~ "{" ~ function_decl* ~ "}"
}
// ======================================================
// Traits
// ======================================================
trait_requirements = { ":" ~ generic ~ ("+" ~ generic)* }
trait_item = _{
function_decl
}
trait_decl = {
visibility? ~ "trait" ~ identifier ~ generics_decl? ~ trait_requirements? ~ "{" ~ trait_item* ~ "}"
}
// ======================================================
// FUNCTIONS
// ======================================================
virtual_kw = { "virtual" }
override_kw = { "override" ~ ("(" ~ expr_path ~ ")")? }
function_decl = {
visibility? ~ virtual_kw? ~ ("void" | type_expr) ~ identifier ~ generics_decl? ~ "(" ~ method_args ~ ")" ~ override_kw? ~ (block | semicolon)
}
// ======================================================
// CONSTANTS / STATIC
// ======================================================
const_decl = { "const" ~ var_decl_statement ~ ";" }
static_decl = { "static" ~ var_decl_statement ~ ";" }
// ======================================================
// Type aliases
// ======================================================
type_alias = { "type" ~ identifier ~ generics_decl? ~ "=" ~ type_expr ~ ";" }
// ======================================================
// TOP LEVEL
// ======================================================
top_level = {
mod_attribute
| (attributes ~ (include_global | include_local | include_use_global | import | impl_for_decl | impl_decl | trait_decl | struct_decl | tuple_struct_decl | enum_decl | class_decl | declare_module | function_decl | const_decl | static_decl | type_alias))
}
// ======================================================
// STATEMENTS
// ======================================================
block = {
"{" ~ statement_list ~ expr? ~ "}"
}
unsafe_block = {
"unsafe" ~ block
}
statement_list = {
statement*
}
statement = _{
control_flow
| top_level
| (expr ~ semicolon)
}
// ------------------------------------------------------
// BASIC STATEMENTS
// ------------------------------------------------------
basic_stmt = {
return_stmt
| break_stmt
| continue_stmt
| var_decl_statement
}
return_stmt = {
"return" ~ expr?
}
break_stmt = {
"break"
}
continue_stmt = {
"continue"
}
var_decl_statement = {
var_decl ~ ("=" ~ expr)?
}
// ------------------------------------------------------
// CONDITIONALS
// ------------------------------------------------------
control_flow = {
if_stmt
| while_stmt
| c_for_stmt
| for_stmt
| match_stmt
| loop_stmt
| block
| unsafe_block
}
statement_branch = { (expr_no_struct | ("(" ~ expr ~ ")")) ~ block }
else_if = _{
"else" ~ "if" ~ statement_branch
}
else_if_list = {
else_if*
}
if_stmt = {
"if" ~ statement_branch ~ else_if_list ~ ("else" ~ block)?
}
// ------------------------------------------------------
// LOOPS
// ------------------------------------------------------
while_stmt = {
"while" ~ statement_branch
}
c_for_stmt = {
"for" ~ "(" ~ statement ~ statement ~ expr ~ ")" ~ block
}
for_stmt = {
"for" ~ pattern ~ "in" ~ expr ~ block
}
loop_stmt = {
"loop" ~ block
}
// ------------------------------------------------------
// MATCH
// ------------------------------------------------------
pattern_list = { pattern ~ ("|" ~ pattern)* }
match_item = {
pattern_list ~ "=>" ~ (block | (expr ~ ","))
}
match_stmt = {
"match" ~ (expr_no_struct | "(" ~ expr ~ ")") ~ "{" ~ match_item* ~ "}"
}
// ======================================================
// EXPRESSIONS
// ======================================================
// ------------------------------------------------------
// CLOSURES
// ------------------------------------------------------
closure = {
("(" ~ param_list ~ ")" ~ "=>" ~ expr)
| (type_expr ~ "(" ~ param_list ~ ")" ~ "=>" ~ expr)
}
// ------------------------------------------------------
// TUPLES & ARRAYS
// ------------------------------------------------------
tuple = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ","? ~ ")"
}
array_repeat = {
"[" ~ expr ~ ";" ~ expr ~ "]"
}
array = {
"[" ~ (expr ~ ("," ~ expr)* ~ ","?)? ~ "]"
}
// ------------------------------------------------------
// MACROS
// ------------------------------------------------------
macro_inner_v = @{
string_lit
| ("(" ~ macro_inner_v* ~ ")")
| ("[" ~ macro_inner_v* ~ "]")
| ("{" ~ macro_inner_v* ~ "}")
| (!("(" | ")" | "[" | "]" | "{" | "}") ~ ANY)
}
// ------------------------------------------------------
// PRIMARY EXPRESSIONS
// ------------------------------------------------------
expr_path_segment = {
identifier ~ generics?
}
expr_path = {
expr_path_segment ~ ("::" ~ expr_path_segment)*
}
primary = {
control_flow
| closure
| basic_stmt
| literal
| expr_path
| tuple
| array_repeat
| array
}
// ------------------------------------------------------
// POSTFIX EXPRESSIONS
// ------------------------------------------------------
field_px = {
"." ~ identifier ~ generics?
}
tuple_field_px = {
"." ~ integer ~ generics?
}
call_px = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
}
macro_call_paren = { "!" ~ "(" ~ macro_inner_v* ~ ")" }
macro_call_bracket = { "!" ~ "[" ~ macro_inner_v* ~ "]" }
macro_call_brace = { "!" ~ "{" ~ macro_inner_v* ~ "}" }
struct_field_decl = {
identifier ~ (":" ~ expr)?
}
struct_px = {
"{" ~ (struct_field_decl ~ ("," ~ struct_field_decl)*)? ~ ","? ~ "}"
}
index_px = {
"[" ~ expr ~ "]"
}
as_px = {
"as" ~ type_expr
}
try_px = {
"?"
}
increment = {
"++"
}
decrement = {
"--"
}
postfix = {
field_px
| tuple_field_px
| call_px
| macro_call_paren
| macro_call_bracket
| macro_call_brace
| struct_px
| index_px
| as_px
| try_px
| increment
| decrement
}
// ------------------------------------------------------
// PREFIX EXPRESSIONS
// ------------------------------------------------------
deref_px = { "*" }
mut_ref_px = { "&" ~ mutable }
ref_px = { "&" }
not_px = { "!" }
neg_px = { "-" }
prefix = {
deref_px
| mut_ref_px
| ref_px
| not_px
| neg_px
}
// ------------------------------------------------------
// OPERATORS
// ------------------------------------------------------
bin_op = {
"+="
| "-="
| "*="
| "/="
| "%="
| "&="
| "|="
| "^="
| "<<="
| ">>="
| "<<"
| ">>"
| "..="
| ".."
| "<="
| ">="
| "=="
| "!="
| "&&"
| "||"
| "->"
| "+"
| "-"
| "*"
| "/"
| "%"
| "<"
| ">"
| "&"
| "|"
| "^"
| "="
}
// ------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------
expr = { term ~ (bin_op ~ term)* }
term = { prefix* ~ primary ~ postfix* }
expr_no_struct = { term_no_struct ~ (bin_op ~ term_no_struct)* }
term_no_struct = { prefix* ~ primary ~ (!struct_px ~ postfix)* }
+85
View File
@@ -0,0 +1,85 @@
use pest::Parser;
use pest_derive::Parser;
pub mod ast;
pub mod error;
pub mod parser;
pub mod rev_mapper;
pub mod semantics;
use ast::*;
use crate::error::ParseError;
#[derive(Parser)]
#[grammar = "./src/grammar.pest"]
pub struct MistParser;
pub struct Program {
pub mod_attributes: Vec<TopLevel>,
pub items: Vec<TopLevel>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MistFmtConfig {
pub allman_bracket_style: bool,
}
pub fn parse<'a>(source: &'a str) -> Result<Program, ParseError<'a>> {
let mut pairs = MistParser::parse(Rule::program, source)?;
let mut statements = vec![];
for pair in pairs.next().unwrap().into_inner() {
if pair.as_rule() != Rule::EOI {
statements.push(TopLevel::try_from(pair)?);
}
}
let (mod_attributes, items): (Vec<_>, Vec<_>) = statements
.into_iter()
.partition(|item| matches!(item.0.item, TopLevelKind::ModAttribute));
Ok(Program {
items,
mod_attributes,
})
}
pub fn parse_module<'a>(
source: &'a str,
) -> Result<Option<(Visibility, Identifier)>, ParseError<'a>> {
let mut pairs = MistParser::parse(Rule::module_program, source)?;
if let Some(v) = pairs
.next()
.unwrap()
.into_inner()
.next()
.map(TopLevel::try_from)
.transpose()?
{
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
Ok(Some((vis.clone(), name.clone())))
} else {
Ok(None)
}
} else {
Ok(None)
}
}
#[macro_export]
macro_rules! ast_ensure {
($pair:expr, $rule:expr $(, $rules:expr)* => $body:block) => {
if $pair.as_rule() == $rule $(|| $pair.as_rule() == $rules)*
$body
else {
Err(AstError {
span: $pair.as_span(),
error_code: crate::error::ErrorCode::AstGenBug,
error_message: format!("Possible bug: expected {:?}, got {:?}", $rule, $pair.as_rule()),
})
}
};
}
@@ -1,22 +1,21 @@
use crate::{
Rule,
ast::*,
ast_expr,
error::{AstError, AstResult, IntoErr},
parser::listen_rule,
error::{AstError, collect_recovered},
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::var_decl_statement => {
let mut inner = pair.into_inner();
ast_expr!(VarDeclStmt {
decl: inner.next().unwrap().try_into(),
init: inner.next().map(Expression::try_from).transpose()
Ok(VarDeclStmt {
decl: inner.next().unwrap().try_into()?,
init: inner.next().map(Expression::try_from).transpose()?,
})
}
@@ -26,16 +25,16 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::class_field => {
let mut inner = pair.into_inner();
ast_expr!(FieldDeclStmt {
decl: inner.next().unwrap().try_into(),
init: inner.next().map(Expression::try_from).transpose(),
Ok(FieldDeclStmt {
decl: inner.next().unwrap().try_into()?,
init: inner.next().map(Expression::try_from).transpose()?,
})
}
@@ -45,32 +44,20 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::var_decl => {
Rule::var_decl | Rule::param => {
let mut inner = pair.into_inner();
let type_ = inner
.next()
.and_then(|pair| {
if pair.as_str().trim() == "var" {
None
} else {
Some(TypeExpr::try_from(pair))
}
})
.transpose();
let mutable: AstResult<'_, bool> = Ok(listen_rule(&mut inner, Rule::mutable));
let name = Pattern::try_from(inner.next().unwrap());
ast_expr!(VarDecl {
type_: type_,
mutable: mutable,
name: name,
Ok(VarDecl {
type_: consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose()?,
true_type: listen_rule(&mut inner, Rule::as_kw),
name: Pattern::try_from(inner.next().unwrap())?,
tuple_names: collect_recovered(inner)?,
})
}
@@ -80,17 +67,17 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::field => {
let mut inner = pair.into_inner();
ast_expr!(FieldDecl {
visibility: Visibility::try_from(&mut inner),
type_: TypeExpr::try_from(inner.next().unwrap()),
name: Identifier::try_from(inner.next().unwrap()),
Ok(FieldDecl {
visibility: Visibility::try_from(&mut inner)?,
type_: TypeExpr::try_from(inner.next().unwrap())?,
name: Identifier::try_from(inner.next().unwrap())?,
})
}
@@ -98,3 +85,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(ParamList(collect_recovered(pair.into_inner())?))
}
}
+202
View File
@@ -0,0 +1,202 @@
use crate::{
Rule,
ast::*,
ast_ensure,
error::{AstError, collect_recovered, collect_recovered_map},
parser::consume_rule,
};
use pest::pratt_parser::PrattParser;
use std::sync::OnceLock;
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::expr | Rule::expr_no_struct => {
static PRATT_PARSER: OnceLock<PrattParser<Rule>> = OnceLock::new();
let pratt = PRATT_PARSER.get_or_init(|| {
use pest::pratt_parser::{Assoc::*, Op};
PrattParser::new().op(Op::infix(Rule::bin_op, Left))
});
pratt
.map_primary(|primary_pair| Expression::try_from(primary_pair))
.map_infix(|expr, op, rhs| {
Ok(Expression::Binary {
lhs: expr.map(Box::new)?,
op: op.as_str().to_string(),
rhs: rhs.map(Box::new)?,
})
})
.parse(inner)
}
Rule::term | Rule::term_no_struct => {
let mut prefix_pairs = Vec::new();
let mut primary_pair = None;
let mut postfix_pairs = Vec::new();
for p in inner {
match p.as_rule() {
Rule::prefix => prefix_pairs.push(p),
Rule::primary => primary_pair = Some(p),
Rule::postfix => postfix_pairs.push(p),
_ => {}
}
}
let prefixes = collect_recovered::<Prefix>(prefix_pairs.into_iter())?;
let exp = Expression::try_from(
primary_pair.expect("Term must contain a primary expression"),
)?;
let postfixes = collect_recovered::<Postfix>(postfix_pairs.into_iter())?;
if postfixes.len() > 0 || prefixes.len() > 0 {
Ok(Expression::Fix {
initial: Box::new(exp),
prefixes: prefixes,
postfixes: postfixes,
})
} else {
Ok(exp)
}
}
Rule::tuple => Ok(Expression::Literal(Literal::Tuple(collect_recovered(
pair.into_inner(),
)?))),
Rule::closure => Ok(Expression::Closure {
return_type: consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose()?,
params: collect_recovered(inner.next().unwrap().into_inner())?,
body: Box::new(Expression::try_from(inner.next().unwrap())?),
}),
Rule::array => Ok(Expression::Array(collect_recovered(inner)?)),
Rule::array_repeat => Ok(Expression::ArrayRepeat(
Box::new(Expression::try_from(inner.next().unwrap())?),
Box::new(Expression::try_from(inner.next().unwrap())?),
)),
Rule::primary => pair.into_inner().next().unwrap().try_into(),
Rule::static_path => Ok(Expression::Path(pair.try_into()?)),
Rule::literal => Ok(Expression::Literal(pair.try_into()?)),
Rule::expr_path => Ok(Expression::Path(pair.try_into()?)),
Rule::statement
| Rule::basic_stmt
| Rule::control_flow
| Rule::block
| Rule::unsafe_block
| Rule::top_level => Ok(Expression::Statement(Box::new(pair.try_into()?))),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(match pair.as_rule() {
Rule::prefix => Self::try_from(pair.into_inner().next().unwrap())?,
Rule::deref_px => Self::Deref,
Rule::mut_ref_px => Self::RefMut,
Rule::ref_px => Self::Ref,
Rule::not_px => Self::Not,
Rule::neg_px => Self::Neg,
_ => return AstError::bug_unimplemented(pair),
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
Rule::field_px => Ok(Postfix::FieldAccess(
inner.next().unwrap().try_into()?,
inner.next().map(Generics::try_from).transpose()?,
)),
Rule::tuple_field_px => Ok(Postfix::TupleFieldAccess(
inner.next().unwrap().as_str().parse().unwrap_or(255_u8),
inner.next().map(Generics::try_from).transpose()?,
)),
Rule::call_px => Ok(Postfix::Call(collect_recovered(inner)?)),
Rule::struct_px => Ok(Postfix::StructCall(collect_recovered_map(inner, |p| {
let mut pi = p.into_inner();
Ok((
Identifier::try_from(pi.next().unwrap())?,
pi.next().map(Expression::try_from).transpose()?,
))
})?)),
Rule::index_px => Ok(Postfix::Index(Expression::try_from(inner.next().unwrap())?)),
Rule::macro_call_paren => Ok(Postfix::MacroCall {
inner: inner.as_str().to_string(),
delimiter: MacroDelimiter::Paren,
}),
Rule::macro_call_bracket => Ok(Postfix::MacroCall {
inner: inner.as_str().to_string(),
delimiter: MacroDelimiter::Bracket,
}),
Rule::macro_call_brace => Ok(Postfix::MacroCall {
inner: inner.as_str().to_string(),
delimiter: MacroDelimiter::Brace,
}),
Rule::as_px => Ok(Postfix::As(inner.next().unwrap().try_into()?)),
Rule::try_px => Ok(Postfix::Try),
Rule::increment => Ok(Postfix::Increment),
Rule::decrement => Ok(Postfix::Decrement),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPath {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
ast_ensure!(pair, Rule::expr_path => {
Ok(ExprPath(collect_recovered(pair.into_inner())?))
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ExprPathSegment {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::expr_path_segment => {
Ok(ExprPathSegment {
ident: Identifier::try_from(inner.next().unwrap())?,
generics: inner.next().map(Generics::try_from).transpose()?,
})
})
}
}
@@ -6,13 +6,13 @@ pub mod types;
use crate::{
Rule,
ast::*,
ast_ensure, ast_expr,
error::{AstError, IntoErr, collect_recovered},
parser::consume_rule,
ast_ensure,
error::{AstError, collect_recovered, collect_recovered_map},
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
ast_ensure!(pair, Rule::identifier => {
@@ -22,18 +22,18 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Path {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner())?)),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
@@ -46,37 +46,55 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
Rule::string_lit => Literal::String(inner.as_str().to_string()),
Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
Rule::tuple => Literal::Tuple(collect_recovered(inner)?),
_ => return AstError::bug_unimplemented(pair),
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered(pair.into_inner()))),
Rule::tuple_pattern => Ok(Pattern::Tuple(collect_recovered_map(inner, |v| {
Self::try_from(v).map(Box::new)
})?)),
Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
Path::try_from(inner.next().unwrap()),
collect_recovered(inner),
Rule::named_tuple_pattern => Ok(Pattern::NamedTuple(
Path::try_from(inner.next().unwrap())?,
collect_recovered_map(inner, |v| Self::try_from(v).map(Box::new))?,
)),
Rule::struct_pattern => ast_expr!(Pattern::Struct(
Path::try_from(inner.next().unwrap()),
collect_recovered(inner),
Rule::struct_pattern => Ok(Pattern::Struct(
Path::try_from(inner.next().unwrap())?,
collect_recovered_map(inner, |v| {
if v.as_rule() == Rule::etc_pattern {
return Ok(None);
}
let mut inner = v.into_inner();
Ok(Some((
Identifier::try_from(inner.next().unwrap())?,
inner
.next()
.map(|v| Self::try_from(v).map(Box::new))
.transpose()?,
)))
})?,
)),
Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
Rule::literal => Ok(Pattern::Literal(pair.try_into()?)),
Rule::identifier => ast_expr!(Pattern::Id(pair.try_into())),
Rule::path_pattern => Ok(Pattern::Path(
listen_rule(&mut inner, Rule::mutable),
inner.next().unwrap().try_into()?,
)),
Rule::static_path => ast_expr!(Pattern::Path(pair.try_into())),
Rule::etc_pattern => Ok(Pattern::Etc),
_ => AstError::bug_unimplemented(pair),
}
@@ -84,13 +102,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
}
impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pairs: &mut pest::iterators::Pairs<'a, Rule>) -> Result<Self, Self::Error> {
Ok(consume_rule(pairs, Rule::visibility)
.map(|pair| -> Result<Visibility, AstError<'a, Self>> {
.map(|pair| -> Result<Visibility, AstError<'a>> {
if let Some(path) = pair.into_inner().next() {
ast_expr!(Visibility::PublicTarget(Path::try_from(path)))
Ok(Visibility::PublicTarget(Path::try_from(path)?))
} else {
Ok(Visibility::Public)
}
@@ -0,0 +1,110 @@
use crate::{
Rule,
ast::*,
ast_ensure,
error::{AstError, collect_recovered},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::block => {
Ok(Block {
statements: collect_recovered(inner.next().unwrap().into_inner())?,
soft_return: inner.next().map(Spanned::try_from).transpose()?,
})
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::statement_branch => {
Ok(StatementBranch {
condition: inner.next().unwrap().try_into()?,
body: Box::new(inner.next().unwrap().try_into()?),
})
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::statement | Rule::basic_stmt | Rule::control_flow => {
Statement::try_from(inner.next().unwrap())
}
Rule::unsafe_block => Ok(Statement::UnsafeBlock(inner.next().unwrap().try_into()?)),
Rule::block => Ok(Statement::Block(pair.try_into()?)),
Rule::top_level => Ok(Statement::TopLevel(Box::new(pair.try_into()?))),
Rule::var_decl_statement => Ok(Statement::VarDecl(pair.try_into()?)),
Rule::return_stmt => Ok(Statement::Return(
inner.next().map(Expression::try_from).transpose()?,
)),
Rule::break_stmt => Ok(Statement::Break),
Rule::continue_stmt => Ok(Statement::Continue),
Rule::if_stmt => Ok(Statement::If {
initial: inner.next().unwrap().try_into()?,
else_if: collect_recovered(inner.next().unwrap().into_inner())?,
else_branch: inner.next().map(Block::try_from).transpose()?,
}),
Rule::while_stmt => Ok(Statement::While(inner.next().unwrap().try_into()?)),
Rule::loop_stmt => Ok(Statement::Loop(inner.next().unwrap().try_into()?)),
Rule::c_for_stmt => Ok(Statement::CStyleFor {
init: inner.next().unwrap().try_into()?,
condition: inner.next().unwrap().try_into()?,
update: inner.next().unwrap().try_into()?,
body: inner.next().unwrap().try_into()?,
}),
Rule::for_stmt => Ok(Statement::For {
pattern: inner.next().unwrap().try_into()?,
iterator: inner.next().unwrap().try_into()?,
body: inner.next().unwrap().try_into()?,
}),
Rule::match_stmt => Ok(Statement::Match(
inner.next().unwrap().try_into()?,
collect_recovered(inner)?,
)),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for MatchItem {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut match_inner = pair.into_inner();
Ok(MatchItem(
collect_recovered(match_inner.next().unwrap().into_inner())?,
Expression::try_from(match_inner.next().unwrap())?,
))
}
}
+176
View File
@@ -0,0 +1,176 @@
use crate::{
Rule,
ast::*,
ast_ensure,
error::{AstError, collect_recovered},
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::generic => Self::try_from(inner.next().unwrap()),
Rule::type_expr => {
let mut inner = inner;
let mut ty = TypeExpr::try_from(inner.next().unwrap())?;
for ref_pair in inner {
let mut ref_inner = ref_pair.clone().into_inner();
match ref_pair.as_rule() {
Rule::ref_type => {
ty = TypeExpr::Ref {
mutable: listen_rule(&mut ref_inner, Rule::mutable),
lifetime: consume_rule(&mut ref_inner, Rule::lifetime)
.map(|v| v.into_inner().next().map(Identifier::try_from))
.unwrap_or_default()
.transpose()?,
ty: Box::new(ty),
};
}
Rule::unsafe_ref_type => {
ty = TypeExpr::UnsafePtr {
mutable: listen_rule(&mut ref_inner, Rule::mutable),
ty: Box::new(ty),
};
}
Rule::fn_type => {
ty = TypeExpr::Fn {
return_type: Box::new(ty),
kind: ref_inner.next().unwrap().try_into()?,
params: collect_recovered(ref_inner)?,
};
}
Rule::array_type => {
ty = TypeExpr::Array(
Box::new(ty),
ref_inner
.next()
.map(|v| {
v.as_str().parse().map_err(|_| AstError {
span: v.as_span(),
error_code: crate::error::ErrorCode::NumberParse,
error_message: format!(
"Number exceeds isize limits: {}",
v.as_str()
),
})
})
.transpose()?,
)
}
_ => AstError::bug_unimplemented(ref_pair)?,
}
}
Ok(ty)
}
Rule::void_type => Ok(TypeExpr::Void),
Rule::tuple_type => Ok(TypeExpr::Tuple(collect_recovered(inner)?)),
Rule::path_type => Ok(TypeExpr::Path(
Path::try_from(inner.next().unwrap())?,
inner.next().map(Generics::try_from).transpose()?,
)),
Rule::dyn_type => Ok(TypeExpr::Dyn(
TypeExpr::try_from(inner.next().unwrap()).map(Box::new)?,
)),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FnKind {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::fn_kind_fn => Ok(FnKind::Fn),
Rule::fn_kind_unsafe => Ok(FnKind::UnsafeFn),
Rule::fn_kind_closure => Ok(FnKind::FnClosure),
Rule::fn_kind_once => Ok(FnKind::FnOnce),
Rule::fn_kind_mut => Ok(FnKind::FnMut),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericsDecl {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::generics_decl => {
Ok(GenericsDecl(collect_recovered(inner)?))
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for GenericDecl {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::generic_decl => {
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
Ok(GenericDecl::Lifetime(
pair.into_inner().next().unwrap().try_into()?,
collect_recovered(inner)?,
))
} else {
Ok(GenericDecl::Type(
inner.next().unwrap().try_into()?,
collect_recovered(inner)?,
))
}
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::generics => {
Ok(Generics(collect_recovered(inner)?))
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::generic => {
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
Ok(Generic::Lifetime(
pair.into_inner().next().unwrap().try_into()?,
))
} else {
Ok(Generic::Type(
inner.next().unwrap().try_into()?
))
}
})
}
}
@@ -1,11 +1,11 @@
use crate::{
Rule,
ast::*,
error::{AstError, IntoErr, collect_recovered},
error::{AstError, collect_recovered},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
@@ -18,7 +18,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
let mut inner = pair.into_inner();
// first item is always the path
let path = inner.next().unwrap().try_into().get()?;
let path = inner.next().unwrap().try_into()?;
// check what comes next
match inner.next() {
@@ -28,11 +28,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
}
Some(next) => match next.as_rule() {
Rule::primary => {
Rule::literal => {
// #[path = literal]
Ok(Attribute::NameValue {
path,
value: inner.next().unwrap().try_into().get()?,
value: next.try_into()?,
})
}
@@ -40,7 +40,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
// #[path(...)]
Ok(Attribute::List {
path,
items: collect_recovered(next.into_inner()).get()?,
items: collect_recovered(next.into_inner())?,
})
}
+41
View File
@@ -0,0 +1,41 @@
use crate::{Rule, ast::*, error::AstError, parser::consume_rule};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassConstructor {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner();
Ok(Self {
visibility: Visibility::try_from(&mut inner)?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()?
.unwrap_or_default(),
params: consume_rule(&mut inner, Rule::param_list)
.map(ParamList::try_from)
.transpose()?
.unwrap_or_default(),
body: inner.next().unwrap().try_into()?,
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
match rule {
Rule::impl_decl | Rule::impl_for_decl => Ok(ClassItem::ImplDecl(pair.try_into()?)),
Rule::function_decl => Ok(ClassItem::Method(pair.try_into()?)),
_ => AstError::bug_unimplemented(pair),
}
}
}
@@ -1,31 +1,30 @@
use crate::{
Rule,
ast::*,
error::{AstError, IntoErr, collect_recovered},
error::{AstError, collect_recovered},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into().get()?)),
Rule::enum_named => Ok(EnumItem::Named(inner.next().unwrap().try_into()?)),
Rule::enum_tuple => Ok(EnumItem::Tuple(
inner.next().unwrap().try_into().get()?,
collect_recovered(inner.next().unwrap().into_inner()).get()?,
inner.next().unwrap().try_into()?,
collect_recovered(inner.next().unwrap().into_inner())?,
)),
Rule::enum_struct => Ok(EnumItem::Struct(
inner.next().unwrap().try_into().get()?,
inner.next().unwrap().try_into()?,
inner
.next()
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
.transpose()
.get()?
.map(|pair| collect_recovered::<FieldDecl>(pair.into_inner()))
.transpose()?
.unwrap_or_default(),
)),
@@ -0,0 +1,71 @@
use crate::{
Rule,
ast::*,
ast_ensure,
error::{AstError, AstResult},
parser::{consume_rule, consume_rule_map, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
ast_ensure!(pair, Rule::function_decl => {
let mut inner = pair.into_inner();
let visibility = Visibility::try_from(&mut inner)?;
let is_virtual = listen_rule(&mut inner, Rule::virtual_kw);
let return_type = consume_rule(&mut inner, Rule::type_expr)
.map(TypeExpr::try_from)
.transpose()?;
let name = Identifier::try_from(inner.next().unwrap())?;
let generics = consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?;
let self_param = consume_rule_map(&mut inner, Rule::self_param, |param| {
let mut param_inner = param.into_inner();
let is_ref = listen_rule(&mut param_inner, Rule::ref_px);
let lifetime = consume_rule(&mut param_inner, Rule::lifetime);
let mutable = listen_rule(&mut param_inner, Rule::mutable);
Ok((is_ref, lifetime.map(|v| -> AstResult<Identifier> {
Identifier::try_from(v.into_inner().next().unwrap())
}).transpose()?, mutable))
})?;
let params = consume_rule(&mut inner, Rule::param_list).map(ParamList::try_from).transpose()?.unwrap_or_default();
let is_override = consume_rule(&mut inner, Rule::override_kw).map(Override::try_from).transpose()?;
let body = inner.next().map(Block::try_from).transpose()?;
Ok(Self {
visibility: visibility,
is_virtual: is_virtual,
return_type: return_type,
name: name,
generics: generics,
self_param: self_param,
params: params,
is_override: is_override,
body: body,
})
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Override {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
ast_ensure!(pair, Rule::override_kw => {
Ok(Override(pair.into_inner().next().map(ExprPath::try_from).transpose()?))
})
}
}
@@ -1,12 +1,12 @@
use crate::{
Rule,
ast::*,
error::{AstError, IntoErr, collect_recovered},
error::{AstError, collect_recovered},
parser::consume_rule,
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
type Error = AstError<'a, Self>;
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
@@ -14,25 +14,23 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
match rule {
Rule::impl_for_decl => Ok(ImplDecl {
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.get()?
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()?
.unwrap_or_default(),
trait_: Some(inner.next().unwrap().try_into().get()?),
target: inner.next().unwrap().try_into().get()?,
methods: collect_recovered(inner).get()?,
trait_: Some(inner.next().unwrap().try_into()?),
target: inner.next().unwrap().try_into()?,
methods: collect_recovered(inner)?,
}),
Rule::impl_decl => Ok(ImplDecl {
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.get()?
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()?
.unwrap_or_default(),
trait_: None,
target: inner.next().unwrap().try_into().get()?,
methods: collect_recovered(inner).get()?,
target: inner.next().unwrap().try_into()?,
methods: collect_recovered(inner)?,
}),
_ => AstError::bug_unimplemented(pair),
+168
View File
@@ -0,0 +1,168 @@
pub mod attribute;
pub mod class;
pub mod enums;
pub mod function;
pub mod impl_decl;
use crate::{
Rule,
ast::*,
error::{AstError, collect_recovered},
parser::consume_rule,
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
let attributes = collect_recovered(inner.next().unwrap().into_inner())?;
Ok(TopLevel(
inner
.next()
.map(Spanned::try_from)
.unwrap_or_else(move || Ok(Spanned::new_pair(pair, TopLevelKind::ModAttribute)))?,
attributes,
))
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::import => Ok(TopLevelKind::Import(
Visibility::try_from(&mut inner)?,
Path::try_from(inner.next().unwrap())?,
)),
Rule::function_decl => Ok(TopLevelKind::FunctionDecl(pair.try_into()?)),
Rule::struct_decl => Ok(TopLevelKind::StructDecl {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
fields: collect_recovered(inner.next().unwrap().into_inner())?,
}),
Rule::tuple_struct_decl => Ok(TopLevelKind::StructDeclTupleUnit {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
unit: consume_rule(&mut inner, Rule::tuple_type)
.map(|v| collect_recovered(v.into_inner()))
.transpose()?,
}),
Rule::class_decl => Ok(TopLevelKind::ClassDecl {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
inherits: consume_rule(&mut inner, Rule::expr_path)
.map(ExprPath::try_from)
.transpose()?,
fields: collect_recovered(inner.next().unwrap().into_inner())?,
constructor: consume_rule(&mut inner, Rule::class_constructor)
.map(Spanned::try_from)
.transpose()?,
items: collect_recovered(inner)?,
}),
Rule::enum_decl => Ok(TopLevelKind::EnumDecl {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
fields: collect_recovered(inner)?,
}),
Rule::declare_module => Ok(TopLevelKind::DeclareModule(
Visibility::try_from(&mut inner)?,
inner.next().unwrap().try_into()?,
)),
Rule::impl_for_decl | Rule::impl_decl => Ok(TopLevelKind::ImplDecl(pair.try_into()?)),
Rule::trait_decl => Ok(TopLevelKind::TraitDecl {
visibility: Visibility::try_from(&mut inner)?,
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()
.map(|v| v.unwrap_or_default())?,
requirements: consume_rule(&mut inner, Rule::trait_requirements)
.map(|pair| collect_recovered(pair.into_inner()))
.transpose()
.map(|v| v.unwrap_or_default())?,
items: collect_recovered(&mut inner)?,
}),
Rule::const_decl => Ok(TopLevelKind::ConstDecl(inner.next().unwrap().try_into()?)),
Rule::static_decl => Ok(TopLevelKind::StaticDecl(inner.next().unwrap().try_into()?)),
Rule::type_alias => Ok(TopLevelKind::TypeAlias {
name: inner.next().unwrap().try_into()?,
generics: consume_rule(&mut inner, Rule::generics_decl)
.map(GenericsDecl::try_from)
.transpose()?,
ty: inner.next().unwrap().try_into()?,
}),
Rule::include_global => Ok(TopLevelKind::IncludeGlobal(Path(collect_recovered(
&mut inner,
)?))),
Rule::include_use_global => Ok(TopLevelKind::IncludeUse(
Visibility::try_from(&mut inner)?,
Path::try_from(inner.next().unwrap())?,
)),
Rule::include_local => Ok(TopLevelKind::IncludeLocal(
inner
.next()
.unwrap()
.into_inner()
.next()
.unwrap()
.to_string(),
)),
_ => AstError::bug_unimplemented(pair),
}
}
}
+75
View File
@@ -0,0 +1,75 @@
pub mod common;
pub mod items;
use crate::{
Rule,
ast::Spanned,
error::{AstError, AstResult},
};
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
let consumed = pairs
.peek()
.map(|p| p.as_rule() == rule)
.unwrap_or_default();
if consumed {
pairs.next();
}
consumed
}
pub fn consume_rule<'a>(
pairs: &mut pest::iterators::Pairs<'a, Rule>,
rule: Rule,
) -> Option<pest::iterators::Pair<'a, Rule>> {
let consumed = pairs
.peek()
.map(|p| p.as_rule() == rule)
.unwrap_or_default();
if consumed { pairs.next() } else { None }
}
pub fn consume_rule_map<'a, T>(
pairs: &mut pest::iterators::Pairs<'a, Rule>,
rule: Rule,
map: impl Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T>,
) -> AstResult<'a, Option<T>> {
let pair = consume_rule(pairs, rule);
if let Some(pair) = pair {
Some(map(pair)).transpose()
} else {
Ok(None)
}
}
impl<T> Spanned<T> {
fn new_pair(pair: pest::iterators::Pair<'_, Rule>, item: T) -> Self {
let span = pair.as_span().start_pos().line_col();
Self {
line: span.0,
column: span.1,
item,
}
}
}
impl<'a, T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a>>>
TryFrom<pest::iterators::Pair<'a, Rule>> for Spanned<T>
{
type Error = AstError<'a>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let span = pair.as_span().start_pos().line_col();
Ok(Self {
line: span.0,
column: span.1,
item: pair.try_into()?,
})
}
}
+78
View File
@@ -0,0 +1,78 @@
use std::{collections::HashSet, path::PathBuf};
use serde::{Deserialize, Serialize};
#[derive(
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct MistMap(pub usize, pub usize);
#[derive(
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct RustMap(pub usize, pub usize);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Mapping {
pub mist_path: PathBuf,
pub map: HashSet<(RustMap, MistMap)>,
}
impl Mapping {
pub fn new(mist_path: PathBuf) -> Self {
Self {
mist_path,
map: HashSet::new(),
}
}
pub fn find(&self, target: &RustMap) -> Option<(RustMap, MistMap)> {
self.map
.iter()
.copied()
.filter(|(rust, _)| rust <= target)
.max_by_key(|(rust, _)| *rust)
}
pub fn find_by_mist(&self, target: &MistMap) -> Option<(RustMap, MistMap)> {
self.map
.iter()
.copied()
.filter(|(_, mist)| mist <= target)
.max_by_key(|(_, mist)| *mist)
}
pub fn shift_rust(&mut self, lines: isize, cols: isize) {
self.map = self
.map
.iter()
.map(|(rust, mist)| (rust.shifted(lines, cols), *mist))
.collect();
}
pub fn shift_mist(&mut self, lines: isize, cols: isize) {
self.map = self
.map
.iter()
.map(|(rust, mist)| (*rust, mist.shifted(lines, cols)))
.collect();
}
}
impl RustMap {
pub fn shifted(self, lines: isize, cols: isize) -> Self {
Self(
self.0.saturating_add_signed(lines),
self.1.saturating_add_signed(cols),
)
}
}
impl MistMap {
pub fn shifted(self, lines: isize, cols: isize) -> Self {
Self(
self.0.saturating_add_signed(lines),
self.1.saturating_add_signed(cols),
)
}
}
+387
View File
@@ -0,0 +1,387 @@
use crate::ast::{
Block, ClassItem, Expression, FunctionDecl, Identifier, MatchItem, Postfix, Prefix, Spanned,
Statement, StatementBranch, TopLevel, TopLevelKind, VarDeclStmt,
};
pub trait GetMutability {
fn get_mutability(&self) -> Vec<Identifier>;
}
#[derive(Debug, Clone)]
pub struct SemanticError {
pub line: usize,
pub column: usize,
pub error_message: String,
}
/// Class semantics - Ensuring fields are initialized
pub fn find_function_call<'a>(
items: &'a Vec<ClassItem>,
name: &Identifier,
) -> Option<&'a Spanned<FunctionDecl>> {
items.iter().find_map(|v| {
if let ClassItem::Method(m) = v {
if m.item.self_param.is_some() && &m.item.name == name {
Some(m)
} else {
None
}
} else {
None
}
})
}
pub fn check_class_semantics<'a>(top_level: &TopLevel) -> Result<(), Vec<SemanticError>> {
if let TopLevelKind::ClassDecl {
fields,
constructor,
items,
name,
inherits,
..
} = &top_level.0.item
{
if let Some(constructor) = constructor {
let mut fields = fields
.iter()
.filter_map(|field| match field.item.init {
Some(_) => None,
None => Some(Spanned {
item: field.item.decl.name.clone(),
line: field.line,
column: field.column,
}),
})
.collect::<Vec<_>>();
if inherits.is_some() {
fields.push(Spanned {
line: top_level.0.line,
column: top_level.0.column,
item: Identifier("_super".to_string()),
});
}
let mut mutability = constructor.item.body.get_mutability();
let mut i = 0;
while i < mutability.len() {
let name = mutability[i].clone();
if let Some(method) = find_function_call(items, &name) {
if let Some(body) = &method.item.body {
for entry in body.get_mutability() {
if !mutability.contains(&entry) {
mutability.push(entry);
}
}
}
}
i += 1;
}
let mut errs = Vec::new();
for field in &fields {
if !mutability.contains(&field.item) {
errs.push(SemanticError {
line: field.line,
column: field.column,
error_message: format!(
"class field `{}.{}` is uninitialized",
name.0, field.item.0
),
});
}
}
if errs.len() > 0 {
return Err(errs);
}
}
Ok(())
} else if let TopLevelKind::FunctionDecl(decl) = &top_level.0.item {
if decl.is_virtual && decl.is_override.is_some() {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "virtual and override are only used in classes".to_string(),
}])
} else if decl.is_virtual {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "virtual is only used in classes".to_string(),
}])
} else if decl.is_override.is_some() {
Err(vec![SemanticError {
line: top_level.0.line,
column: top_level.0.column,
error_message: "override is only used in classes".to_string(),
}])
} else {
Ok(())
}
} else {
Ok(())
}
}
impl<T: GetMutability> GetMutability for Vec<T> {
fn get_mutability(&self) -> Vec<Identifier> {
self.iter().flat_map(T::get_mutability).collect()
}
}
impl GetMutability for Block {
fn get_mutability(&self) -> Vec<Identifier> {
let mut items: Vec<Identifier> = self
.statements
.iter()
.flat_map(|v| v.item.get_mutability())
.collect();
if let Some(v) = &self.soft_return {
items.append(&mut v.item.get_mutability());
}
items
}
}
impl GetMutability for Statement {
fn get_mutability(&self) -> Vec<Identifier> {
match self {
Statement::TopLevel(_) => Vec::new(),
Statement::Block(body) | Statement::UnsafeBlock(body) => body.get_mutability(),
Statement::If {
initial,
else_if,
else_branch,
} => {
let mut all_sets: Vec<Vec<Identifier>> = Vec::new();
all_sets.push(initial.body.get_mutability());
for branch in else_if {
all_sets.push(branch.body.get_mutability());
}
if let Some(else_block) = else_branch {
all_sets.push(else_block.get_mutability());
} else {
return Vec::new();
}
let mut result = all_sets.remove(0);
for set in all_sets {
result.retain(|id| set.contains(id));
}
result
}
Statement::Loop(body) => body.get_mutability(),
Statement::While(branch) => branch.body.get_mutability(),
Statement::CStyleFor {
body,
init,
condition,
update,
..
} => {
let mut a = init.get_mutability();
a.append(&mut condition.get_mutability());
a.append(&mut update.get_mutability());
a.append(&mut body.get_mutability());
a
}
Statement::For { body, iterator, .. } => {
let mut a = iterator.get_mutability();
a.append(&mut body.get_mutability());
a
}
Statement::Match(_, items) => {
if items.is_empty() {
return Vec::new();
}
let mut all_sets: Vec<Vec<Identifier>> = items
.iter()
.map(|item| item.item.get_mutability())
.collect();
let mut result = all_sets.remove(0);
for set in all_sets {
result.retain(|id| set.contains(id));
}
result
}
Statement::VarDecl(stmt) => stmt
.init
.as_ref()
.map(|e| e.get_mutability())
.unwrap_or_default(),
Statement::Return(expr) => expr
.as_ref()
.map(|e| e.get_mutability())
.unwrap_or_default(),
Statement::Break | Statement::Continue => Vec::new(),
}
}
}
impl GetMutability for StatementBranch {
fn get_mutability(&self) -> Vec<Identifier> {
let mut a = self.condition.get_mutability();
a.append(&mut self.body.get_mutability());
a
}
}
impl GetMutability for MatchItem {
fn get_mutability(&self) -> Vec<Identifier> {
self.1.get_mutability()
}
}
impl GetMutability for VarDeclStmt {
fn get_mutability(&self) -> Vec<Identifier> {
self.init
.as_ref()
.map(|e| e.get_mutability())
.unwrap_or_default()
}
}
fn get_self_ref(initial: &Expression, postfixes: &[Postfix]) -> Option<Identifier> {
match initial {
Expression::Path(v) => {
let ident = v.0.first()?.ident.0.as_str();
if ident == "self" || ident == "super" {
if let Some(Postfix::FieldAccess(field, _)) = postfixes.first() {
if !matches!(postfixes.get(1), Some(Postfix::Call(_))) {
return Some(field.clone());
}
}
}
}
_ => {}
}
None
}
fn get_self_method_call(initial: &Expression, postfixes: &[Postfix]) -> Option<Identifier> {
match initial {
Expression::Path(v) => {
let ident = v.0.first()?.ident.0.as_str();
if ident == "self" || ident == "super" {
if let Some(Postfix::FieldAccess(method, _)) = postfixes.first() {
if matches!(postfixes.get(1), Some(Postfix::Call(_))) {
return Some(method.clone());
}
}
}
}
_ => {}
}
None
}
impl Expression {
fn get_self_ref(&self) -> Option<Identifier> {
match self {
Self::Fix {
initial, postfixes, ..
} => get_self_ref(initial, postfixes),
_ => None,
}
}
}
impl GetMutability for Expression {
fn get_mutability(&self) -> Vec<Identifier> {
match self {
Self::Array(v) => v.get_mutability(),
Self::ArrayRepeat(v, i) => {
let mut a = v.get_mutability();
a.append(&mut i.get_mutability());
a
}
Self::Binary { lhs, op, rhs } => {
if mutates_lhs(op) {
let mut a = if let Some(self_ref) = lhs.get_self_ref() {
vec![self_ref]
} else {
lhs.get_mutability()
};
a.append(&mut rhs.get_mutability());
a
} else {
let mut a = lhs.get_mutability();
a.append(&mut rhs.get_mutability());
a
}
}
Self::Statement(stmt) => stmt.get_mutability(),
Self::Fix {
initial,
prefixes,
postfixes,
} => {
let mut result = Vec::new();
// &mut self.field / &mut super.field / &mut super pattern
if prefixes.iter().any(|p| matches!(p, Prefix::RefMut)) {
if let Some(self_ref) = get_self_ref(initial, postfixes) {
result.push(self_ref);
} else if let Expression::Path(v) = &**initial {
if v.0.first().map_or(false, |s| s.ident.0 == "super") {
result.push(Identifier("_super".to_string()));
}
}
}
// Recurse into all postfix sub-expressions
for postfix in postfixes {
match postfix {
Postfix::Call(args) => {
for arg in args {
result.append(&mut arg.get_mutability());
}
}
Postfix::StructCall(fields) => {
for (_, expr) in fields {
if let Some(expr) = expr {
result.append(&mut expr.get_mutability());
}
}
}
Postfix::Index(expr) => {
result.append(&mut expr.get_mutability());
}
_ => {}
}
}
// Method calls on self: self.method_name(args)
if let Some(method) = get_self_method_call(initial, postfixes) {
result.push(method);
}
result
}
Self::Closure { body, .. } => body.get_mutability(),
Self::Literal(_) => Vec::new(),
Self::Path(v) => {
if v.0.first().map_or(false, |s| s.ident.0 == "super") {
vec![Identifier("_super".to_string())]
} else {
Vec::new()
}
}
}
}
}
pub fn mutates_lhs(op: &str) -> bool {
matches!(op, "=" | "->")
}
+1 -1
View File
@@ -5,6 +5,6 @@ edition = "2024"
[[bin]]
name = "main"
path = "build/main.rs"
path = ".mist/src/main.rs"
[dependencies]
+2
View File
@@ -0,0 +1,2 @@
package = "main.mist"
packages = []
-4
View File
@@ -1,4 +0,0 @@
{
"src": "src",
"output": "build"
}
-95
View File
@@ -1,95 +0,0 @@
use <super::task>;
use <super::logger>;
use <super::event>;
pub class Application {
String name;
Vec<task::Task> tasks;
Vec<String> plugins;
logger::Logger logger;
bool running;
i32 ticks;
pub constructor(str* name) {
self.name = name.to_string();
self.tasks = new Vec();
self.plugins = new Vec();
self.logger = new logger::Logger("app");
self.running = false;
self.ticks = 0;
}
pub void boot(self mut*) {
self.logger.info("booting application");
self.running = true;
self.emit(event::Event::Startup);
}
pub void run(self mut*) {
while(self.running) {
self.tick();
if(self.ticks >= 5) {
self.shutdown();
}
}
}
void tick(self mut*) {
self.logger.info("tick");
self.ticks = self.ticks + 1;
var task = task::create_task("background-job");
self.tasks.push(task);
println!("tasks: {}", self.tasks.len());
}
pub void shutdown(self mut*) {
self.emit(event::Event::Shutdown);
self.logger.warning("shutdown");
self.running = false;
}
pub void register_plugin(self mut*, String name) {
self.plugins.push(name.clone());
self.emit(event::Event::PluginLoaded(name));
}
void emit(self*, event::Event event) {
match(event) {
event::Event::Startup => {
self.logger.info("startup event");
}
event::Event::Shutdown => {
self.logger.info("shutdown event");
}
event::Event::PluginLoaded(name) => {
println!("plugin loaded: {}", name);
}
event::Event::TaskExecuted(name) => {
println!("task executed: {}", name);
}
event::Event::Error(message) => {
self.logger.error(&message);
}
}
}
}
+147
View File
@@ -0,0 +1,147 @@
pub module decl_test;
pub void test_let_basic()
{
let x = 42;
assert_eq!(x, 42);
}
pub void test_let_repeat()
{
let x, y = (42, 67);
assert_eq!(x, 42);
assert_eq!(y, 67);
}
pub void test_let_typed()
{
i32 x = 42;
assert_eq!(x, 42);
str& s = "hello";
assert_eq!(s, "hello");
bool b = true;
assert_eq!(b, true);
f64 f = 3.14;
assert_eq!(f, 3.14);
}
pub void test_let_repeat_typed()
{
i32 x, x1 = (42, 67);
assert_eq!(x, 42);
assert_eq!(x1, 67);
str& s, s1 = ("hello", "world");
assert_eq!(s, "hello");
assert_eq!(s1, "world");
bool b, b1 = (true, false);
assert_eq!(b, true);
assert_eq!(b1, false);
f64 f, f1 = (3.14, 5.5);
assert_eq!(f, 3.14);
assert_eq!(f1, 5.5);
(i32, f64) as a, b = (70, 1.4);
assert_eq!(a, 70);
assert_eq!(b, 1.4);
}
pub void test_let_mut()
{
let mut _x = 42;
_x = 100;
assert_eq!(_x, 100);
}
pub void test_let_tuple_destructure()
{
let (a, b) = (10, "hello");
assert_eq!(a, 10);
assert_eq!(b, "hello");
}
pub void test_let_nested_tuple()
{
let (a, (b, c)) = (1, (2, 3));
assert_eq!(a, 1);
assert_eq!(b, 2);
assert_eq!(c, 3);
}
pub void test_let_pattern_irrefutable()
{
let x = 5;
let (y, z) = (1, 2);
assert_eq!(x, 5);
assert_eq!(y, 1);
assert_eq!(z, 2);
}
pub void test_multiple_decls()
{
let a = 1;
let b = 2;
let c = 3;
assert_eq!(a + b + c, 6);
}
pub void test_let_with_type_and_init()
{
f64 x = 10.0;
assert_eq!(x, 10.0);
}
pub void test_string_literal()
{
let s = "hello, world!";
assert_eq!(s.len(), 13);
}
pub void test_let_bool()
{
let t = true;
let f = false;
assert_eq!(t, !f);
}
pub void test_let_decl_only()
{
let x;
x = 42;
assert_eq!(x, 42);
}
pub void test_let_typed_decl_only()
{
i32 x;
x = 100;
assert_eq!(x, 100);
}
pub void test_let_decl_mut_no_init()
{
let mut x;
x = 5;
assert_eq!(x, 5);
}
pub void run_tests()
{
test_let_basic();
test_let_repeat();
test_let_typed();
test_let_repeat_typed();
test_let_mut();
test_let_tuple_destructure();
test_let_nested_tuple();
test_let_pattern_irrefutable();
test_multiple_decls();
test_let_with_type_and_init();
test_string_literal();
test_let_bool();
test_let_decl_only();
test_let_typed_decl_only();
test_let_decl_mut_no_init();
}
+241
View File
@@ -0,0 +1,241 @@
pub module expr_test;
pub void test_literals()
{
assert_eq!(42, 42);
assert_eq!(3.14, 3.14);
assert_eq!(true, true);
assert_eq!(false, false);
assert_eq!("hello", "hello");
}
pub void test_tuples()
{
let t = (1, true, "three");
assert_eq!(t.0, 1);
assert_eq!(t.1, true);
assert_eq!(t.2, "three");
}
pub void test_arrays()
{
let arr = [1, 2, 3];
assert_eq!(arr[0], 1);
assert_eq!(arr[1], 2);
assert_eq!(arr[2], 3);
}
pub void test_array_repeat()
{
let arr = [0; 5];
assert_eq!(arr[0], 0);
assert_eq!(arr[4], 0);
assert_eq!(arr.len(), 5);
}
pub void test_binary_arith()
{
assert_eq!(10 + 5, 15);
assert_eq!(10 - 5, 5);
assert_eq!(10 * 5, 50);
assert_eq!(10 / 5, 2);
assert_eq!(10 % 3, 1);
}
pub void test_binary_cmp()
{
assert_eq!(5 < 10, true);
assert_eq!(10 <= 10, true);
assert_eq!(10 > 5, true);
assert_eq!(10 >= 10, true);
assert_eq!(5 == 5, true);
assert_eq!(5 != 10, true);
}
pub void test_binary_logic()
{
assert_eq!(true && true, true);
assert_eq!(true && false, false);
assert_eq!(true || false, true);
assert_eq!(false || false, false);
}
pub void test_binary_bit()
{
assert_eq!(5 & 3, 1);
assert_eq!(5 | 3, 7);
assert_eq!(5 ^ 3, 6);
assert_eq!(1 << 2, 4);
assert_eq!(4 >> 1, 2);
}
pub void test_prefix()
{
let x = 42;
assert_eq!(-x, -42);
assert_eq!(!true, false);
assert_eq!(!false, true);
}
pub void test_ref_deref()
{
let x = 42;
let r = &x;
assert_eq!(*r, 42);
}
pub void test_postfix_inc_dec()
{
let mut x = 5;
x++;
assert_eq!(x, 6);
x--;
assert_eq!(x, 5);
}
pub void test_as_cast()
{
let x = 42;
assert_eq!(x as f64, 42.0);
}
pub void test_closure()
{
let add = (a, b) => a + b;
assert_eq!(add(2, 3), 5);
}
pub void test_block_expr()
{
let x = {
let y = 10;
y + 5
};
assert_eq!(x, 15);
}
pub void test_if_expr()
{
let x = if true {
1
} else {
2
};
assert_eq!(x, 1);
let y = if false {
1
} else {
2
};
assert_eq!(y, 2);
}
pub void test_range_expr()
{
let r = 0 .. 5;
let mut count = 0;
for i in r {
count++;
}
assert_eq!(count, 5);
}
pub void test_binary_assign()
{
let mut x = 10;
x += 5;
assert_eq!(x, 15);
x -= 3;
assert_eq!(x, 12);
x *= 2;
assert_eq!(x, 24);
x /= 4;
assert_eq!(x, 6);
x %= 4;
assert_eq!(x, 2);
}
pub void test_binary_assign_bit()
{
let mut x = 10;
x &= 12;
assert_eq!(x, 8);
x |= 1;
assert_eq!(x, 9);
x ^= 3;
assert_eq!(x, 10);
let mut y = 8;
y <<= 2;
assert_eq!(y, 32);
y >>= 1;
assert_eq!(y, 16);
}
pub void test_empty_tuple()
{
let t = ();
assert_eq!(t, ());
}
pub void test_empty_array()
{
let arr = [0; 0];
assert_eq!(arr.len(), 0);
}
pub void test_range_inclusive()
{
let mut sum = 0;
for i in 1 ..= 3 {
sum += i;
}
assert_eq!(sum, 6);
}
pub void test_closure_no_args()
{
let f = () => 42;
assert_eq!(f(), 42);
}
pub void test_closure_with_typed_params()
{
let add = (i32 a, i32 b) => a + b;
assert_eq!(add(3, 4), 7);
}
pub void test_mut_ref()
{
let mut x = 42;
let r = &mut x;
*r = 100;
assert_eq!(x, 100);
}
pub void run_tests()
{
test_literals();
test_tuples();
test_arrays();
test_array_repeat();
test_binary_arith();
test_binary_cmp();
test_binary_logic();
test_binary_bit();
test_prefix();
test_ref_deref();
test_postfix_inc_dec();
test_as_cast();
test_closure();
test_block_expr();
test_if_expr();
test_range_expr();
test_binary_assign();
test_binary_assign_bit();
test_empty_tuple();
test_empty_array();
test_range_inclusive();
test_closure_no_args();
test_closure_with_typed_params();
test_mut_ref();
}
+3
View File
@@ -0,0 +1,3 @@
pub module common;
pub void test_package() {}
+247
View File
@@ -0,0 +1,247 @@
pub module statement_test;
pub void test_var_decl()
{
let x = 42;
assert_eq!(x, 42);
i32 y = 10;
assert_eq!(y, 10);
str& name = "mist";
assert_eq!(name, "mist");
}
pub void test_var_decl_with_init()
{
let mut x = 0;
x = 5;
assert_eq!(x, 5);
}
pub void test_if_statement()
{
let mut x = 0;
if true {
x = 1;
}
assert_eq!(x, 1);
if false {
x = 2;
} else {
x = 3;
}
assert_eq!(x, 3);
}
pub void test_if_else_if()
{
let mut x = 0;
if x == 1 {
x = 10;
} else if x == 0 {
x = 20;
} else {
x = 30;
}
assert_eq!(x, 20);
}
pub void test_while_loop()
{
let mut count = 0;
while count < 5 {
count++;
}
assert_eq!(count, 5);
}
pub void test_for_loop()
{
let mut sum = 0;
for i in 0 .. 4 {
sum += i;
}
assert_eq!(sum, 6);
}
pub void test_loop_stmt()
{
let mut count = 0;
loop {
count++;
if count >= 3 {
break;
}
}
assert_eq!(count, 3);
}
pub void test_break_continue()
{
let mut sum = 0;
for i in 0 .. 10 {
if i % 2 == 0 {
continue;
}
if i >= 7 {
break;
}
sum += i;
}
assert_eq!(sum, 1 + 3 + 5);
}
pub i32 test_return()
{
return 42;
}
pub void test_block_scope()
{
let x = {
let inner = 10;
inner + 5
};
assert_eq!(x, 15);
}
pub void test_match_literal()
{
let x = 2;
let result;
match x {
1 => {
result = 10;
}
2 => result = 20,
3 => result = 30,
_ => panic!(),
}
assert_eq!(result, 20);
}
pub void test_match_or_pattern()
{
let x = 1;
i32 result;
match x {
1 | 2 => {
result = 100;
}
3 => {
result = 200;
}
_ => panic!(),
}
assert_eq!(result, 100);
}
pub void test_match_default()
{
let x = 99;
let result;
match x {
1 => {
result = 10;
}
y => {
result = y;
}
}
assert_eq!(result, 99);
}
pub void test_for_with_pattern_destructure()
{
let pairs = [(1, "a"), (2, "b")];
let mut keys = 0;
for (k, _) in pairs {
keys += k;
}
assert_eq!(keys, 3);
}
pub void test_c_for_loop()
{
let mut sum = 0;
for (let mut i = 0; i < 4; i++) {
sum += i;
}
assert_eq!(sum, 6);
}
pub void test_unsafe_block()
{
let mut x = 42;
unsafe {
let r = &mut x;
*r = 100;
}
assert_eq!(x, 100);
}
pub void test_match_parenthesized()
{
let result;
match (2) {
1 => result = 10,
2 => result = 20,
_ => panic!(),
}
assert_eq!(result, 20);
}
pub void test_if_parenthesized()
{
let mut x = 0;
if (true) {
x = 1;
}
assert_eq!(x, 1);
}
pub void test_while_parenthesized()
{
let mut count = 0;
while (count < 3) {
count++;
}
assert_eq!(count, 3);
}
pub void test_loop_with_break_value()
{
let mut x = 0;
let result;
loop {
if x >= 3 {
result = x;
break;
}
x++;
}
assert_eq!(result, 3);
}
pub void run_tests()
{
test_var_decl();
test_var_decl_with_init();
test_if_statement();
test_if_else_if();
test_while_loop();
test_for_loop();
test_loop_stmt();
test_break_continue();
assert_eq!(test_return(), 42);
test_block_scope();
test_match_literal();
test_match_or_pattern();
test_match_default();
test_for_with_pattern_destructure();
test_c_for_loop();
test_unsafe_block();
test_match_parenthesized();
test_if_parenthesized();
test_while_parenthesized();
test_loop_with_break_value();
}
+93
View File
@@ -0,0 +1,93 @@
pub module types_test;
pub void test_integer_type() {
i32 x = 42;
assert_eq!(x, 42);
}
pub void test_float_type() {
f64 x = 3.14;
assert_eq!(x, 3.14);
}
pub void test_bool_type() {
bool x = true;
assert_eq!(x, true);
bool y = false;
assert_eq!(y, false);
}
pub void test_string_type() {
str& s = "hello";
assert_eq!(s, "hello");
}
pub void test_tuple_type() {
(i32, str&) t = (42, "answer");
assert_eq!(t.0, 42);
assert_eq!(t.1, "answer");
}
pub void test_ref_type() {
i32 x = 42;
i32& r = &x;
assert_eq!(*r, 42);
}
pub void test_mut_ref_type() {
let mut x = 42;
i32 mut& r = &mut x;
*r = 100;
assert_eq!(x, 100);
}
pub void test_void_type() {
}
i32 add(i32 a, i32 b) {
a + b
}
pub void test_fn_return_type() {
assert_eq!(add(3, 4), 7);
}
pub void test_generic_type() {
Option<i32> x = Option::Some(42);
assert_eq!(x.is_some(), true);
}
type MyInt = i32;
pub void test_type_alias() {
MyInt x = 42;
assert_eq!(x, 42);
}
const i32 MY_CONST = 100;
pub void test_const_decl() {
assert_eq!(MY_CONST, 100);
}
static i32 my_static = 200;
pub void test_static_decl() {
assert_eq!(my_static, 200);
}
pub void run_tests() {
test_integer_type();
test_float_type();
test_bool_type();
test_string_type();
test_tuple_type();
test_ref_type();
test_mut_ref_type();
test_void_type();
test_fn_return_type();
test_generic_type();
test_type_alias();
test_const_decl();
test_static_decl();
}
-7
View File
@@ -1,7 +0,0 @@
pub enum Event {
Startup,
Shutdown,
TaskExecuted(String),
PluginLoaded(String),
Error(String),
}
+42
View File
@@ -0,0 +1,42 @@
pub module attribute_test;
#[derive(Debug)]
pub struct Debuggable
{
i32 value;
}
pub void test_derive_attribute()
{
let d = Debuggable {
value: 42,
};
assert_eq!(d.value, 42);
}
#[allow(unused_variables)]
pub void test_allow_attribute()
{
let x = 42;
let y = "unused";
assert_eq!(x, 42);
}
#[allow(dead_code)]
pub struct Tagged
{
i32 id;
}
pub void test_attribute_with_args()
{
Tagged t = Tagged { id: 1 };
assert_eq!(t.id, 1);
}
pub void run_tests()
{
test_derive_attribute();
test_allow_attribute();
test_attribute_with_args();
}
+147
View File
@@ -0,0 +1,147 @@
pub module class_test;
pub enum AnimalType {
Mammal;
}
pub class Animal
{
pub String name;
constructor()
{
self.name = "Rex".to_string();
}
pub virtual AnimalType get_animal_type(&self) {
panic!()
}
pub virtual String speak(&self)
{
"Unknown".to_string()
}
pub virtual void speak_mut(&mut self){}
pub void test_speak<'a>(&'a self)
{
assert_eq!(self.speak(), "Woof!");
}
pub void static_method()
{
}
}
pub class Mammal : Animal
{
constructor()
{
super = Super::new();
}
// override without a target assumes current super
pub AnimalType get_animal_type(&self) override {
AnimalType::Mammal
}
pub void args_test(&self, i32 x, str& y)
{
assert_eq!(x, 10);
assert_eq!(y, "hello");
}
}
pub class Dog : Mammal
{
constructor()
{
super = Super::new();
}
pub String speak(&self) override(Animal)
{
"Woof!".to_string()
}
impl std::fmt::Display
{
Result<(), std::fmt::Error> fmt(&self, std::fmt::Formatter<'_> mut& f)
{
write!(f, "🐾 {}", self.name)
}
}
}
pub class Counter
{
pub i32 count;
constructor()
{
self.count = 42;
}
i32 get_count(&self)
{
self.count
}
pub i32 static_fn()
{
99
}
}
pub void test_class_no_inheritance()
{
Counter c = Counter::new();
assert_eq!(c.get_count(), 42);
}
pub class WithDefault
{
pub String name = "default".to_string();
pub i32 value = 42;
constructor()
{
}
pub String get_name(&self)
{
self.name.clone()
}
}
pub void test_class_field_default()
{
WithDefault w = WithDefault::new();
assert_eq!(w.get_name(), "default");
assert_eq!(w.value, 42);
}
pub class EmptyClass
{
constructor()
{
}
}
pub void test_class_empty()
{
EmptyClass e = EmptyClass::new();
}
pub void run_tests()
{
let dawg = Dog::new();
dawg.args_test(10, "hello");
dawg.test_speak();
dawg.get_animal_type();
assert_eq!(format!("{dawg}"), "🐾 Rex");
test_class_no_inheritance();
test_class_field_default();
test_class_empty();
}
+129
View File
@@ -0,0 +1,129 @@
pub module enum_test;
enum OptionInt
{
None;
Some(i32);
}
pub void test_enum_named()
{
let x = OptionInt::None;
match x {
OptionInt::None => {
assert_eq!(1, 1);
}
OptionInt::Some(_) => {
assert_eq!(0, 1);
}
}
}
pub void test_enum_tuple()
{
let x = OptionInt::Some(42);
match x {
OptionInt::None => {
assert_eq!(0, 1);
}
OptionInt::Some(v) => {
assert_eq!(v, 42);
}
}
}
enum Shape
{
Circle {
i32 radius;
};
Rect {
i32 w;
i32 h;
};
}
pub void test_enum_struct()
{
let c = Shape::Circle {
radius: 5,
};
match c {
Shape::Circle {radius} => {
assert_eq!(radius, 5);
}
Shape::Rect {..} => {
assert_eq!(0, 1);
}
}
let r = Shape::Rect {
w: 3,
h: 4,
};
match r {
Shape::Circle {..} => {
assert_eq!(0, 1);
}
Shape::Rect {w, h} => {
assert_eq!(w * h, 12);
}
}
}
enum Color
{
Red;
Green;
Blue;
}
pub void test_enum_eq()
{
let c = Color::Red;
match c {
Color::Red => {
assert_eq!(1, 1);
}
_ => {
assert_eq!(0, 1);
}
}
}
enum Option<T>
{
None;
Some(T);
}
pub void test_generic_enum()
{
Option<i32> x = Option::Some(42);
match x {
Option::Some(v) => {
assert_eq!(v, 42);
}
_ => {
assert_eq!(0, 1);
}
}
Option<bool> y = Option::None;
match y {
Option::None => {
assert_eq!(1, 1);
}
_ => {
assert_eq!(0, 1);
}
}
}
pub void run_tests()
{
test_enum_named();
test_enum_tuple();
test_enum_struct();
test_enum_eq();
test_generic_enum();
}
+94
View File
@@ -0,0 +1,94 @@
pub module function_test;
void greet()
{
let mut x = 1;
x++;
}
pub void test_basic_function()
{
greet();
}
i32 add(i32 a, i32 b)
{
a + b
}
pub void test_fn_params()
{
assert_eq!(add(2, 3), 5);
}
pub i32 test_fn_return()
{
42
}
pub i32 test_fn_early_return()
{
return 100;
0
}
pub i32 test_fn_mut_param(i32 mut x)
{
x = x + 10;
x
}
pub void test_method_call()
{
let s = "hello";
assert_eq!(s.len(), 5);
assert_eq!(s.to_uppercase(), "HELLO");
}
i32 triple(i32 x)
{
add(x, add(x, x))
}
pub void test_nested_fn_calls()
{
assert_eq!(triple(5), 15);
}
i32 factorial(i32 n)
{
if n <= 1 {
1
} else {
n * factorial(n - 1)
}
}
pub void test_recursive_fn()
{
assert_eq!(factorial(5), 120);
}
T identity<T>(T x)
{
x
}
pub void test_fn_generic()
{
assert_eq!(identity(42), 42);
assert_eq!(identity("hello"), "hello");
}
pub void run_tests()
{
test_basic_function();
test_fn_params();
assert_eq!(test_fn_return(), 42);
assert_eq!(test_fn_early_return(), 100);
assert_eq!(test_fn_mut_param(5), 15);
test_method_call();
test_nested_fn_calls();
test_recursive_fn();
test_fn_generic();
}
+100
View File
@@ -0,0 +1,100 @@
pub module impl_test;
struct Vector2
{
i32 x;
i32 y;
}
impl Vector2
{
pub i32 magnitude(&self)
{
self.x * self.x + self.y * self.y
}
}
pub void test_inherent_impl()
{
let v = Vector2 {
x: 3,
y: 4,
};
assert_eq!(v.magnitude(), 25);
}
trait Display
{
String display(&self);
}
impl Display for Vector2
{
String display(&self)
{
format!("({}, {})", self.x, self.y)
}
}
pub void test_trait_impl_block()
{
let v = Vector2 {
x: 1,
y: 2,
};
let s = v.display();
assert_eq!(s.len() > 0, true);
}
impl Vector2
{
pub Vector2 add(&self, Vector2 other)
{
Vector2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
pub void test_multiple_impls()
{
let a = Vector2 {
x: 1,
y: 2,
};
let b = Vector2 {
x: 3,
y: 4,
};
let c = a.add(b);
assert_eq!(c.x, 4);
assert_eq!(c.y, 6);
}
struct Wrapper<T>
{
T value;
}
impl<T: Copy> Wrapper<T>
{
pub T get(&self)
{
self.value
}
}
pub void test_impl_generic()
{
Wrapper<i32> w = Wrapper { value: 42 };
assert_eq!(w.get(), 42);
}
pub void run_tests()
{
test_inherent_impl();
test_trait_impl_block();
test_multiple_impls();
test_impl_generic();
}
+116
View File
@@ -0,0 +1,116 @@
pub module struct_test;
struct Point
{
i32 x;
i32 y;
}
pub void test_struct_create_access()
{
let p = Point {
x: 10,
y: 20,
};
assert_eq!(p.x, 10);
assert_eq!(p.y, 20);
}
pub void test_struct_mut_field()
{
let mut p = Point {
x: 1,
y: 2,
};
p.x = 100;
assert_eq!(p.x, 100);
}
pub void test_struct_destructure()
{
let p = Point {
x: 3,
y: 4,
};
let Point {x, y} = p;
assert_eq!(x, 3);
assert_eq!(y, 4);
}
struct Line
{
Point start;
Point end;
}
pub void test_struct_nested()
{
let l = Line {
start: Point {
x: 0,
y: 0,
},
end: Point {
x: 5,
y: 10,
},
};
assert_eq!(l.start.x, 0);
assert_eq!(l.end.y, 10);
}
struct Empty {}
pub void test_empty_struct()
{
let e = Empty {};
}
struct Pair<T>
{
T first;
T second;
}
pub void test_generic_struct()
{
Pair<i32> p = Pair<i32> { first: 1, second: 2 };
assert_eq!(p.first, 1);
assert_eq!(p.second, 2);
}
pub void test_struct_partial_destructure()
{
let p = Point {
x: 10,
y: 20,
};
let Point {x, ..} = p;
assert_eq!(x, 10);
}
pub void test_struct_destructure_rename()
{
let p = Point {
x: 5,
y: 15,
};
let Point {x: a, y: b} = p;
assert_eq!(a, 5);
assert_eq!(b, 15);
}
struct TuplePoint(i32, i32);
struct Unit;
pub void run_tests()
{
test_struct_create_access();
test_struct_mut_field();
test_struct_destructure();
test_struct_nested();
test_empty_struct();
test_generic_struct();
test_struct_partial_destructure();
test_struct_destructure_rename();
}
+55
View File
@@ -0,0 +1,55 @@
pub module trait_test;
trait Speak
{
String speak(&self);
}
trait Greet : Speak
{
String greet(&self);
}
struct Dog
{
String name;
}
impl Speak for Dog
{
String speak(&self)
{
"woof".to_string()
}
}
impl Greet for Dog
{
String greet(&self)
{
"hello".to_string()
}
}
pub void test_trait_impl()
{
let d = Dog {
name: "Rex".to_string(),
};
assert_eq!(d.speak(), "woof");
}
pub void test_trait_with_requirement()
{
let d = Dog {
name: "Buddy".to_string(),
};
assert_eq!(d.speak(), "woof");
assert_eq!(d.greet(), "hello");
}
pub void run_tests()
{
test_trait_impl();
test_trait_with_requirement();
}
-72
View File
@@ -1,72 +0,0 @@
use <std::fmt::Formatter>;
use <std::fmt>;
pub trait TestLogging<T: fmt::Display>: fmt::Display {
String get();
}
pub enum LogLevel {
Info,
Warning,
Error,
}
impl fmt::Display for LogLevel {
fmt::Result fmt(self*, Formatter<'_> mut* f) {
match (self) {
LogLevel::Info => {
return write!(f, "[INFO]");
}
LogLevel::Warning => {
return write!(f, "[WARN]");
}
LogLevel::Error => {
return write!(f, "[ERROR]");
}
}
}
}
pub class Logger {
String prefix;
pub constructor(str* prefix) {
self.prefix = prefix.to_string();
}
pub void info(self*, str* message) {
self.log(LogLevel::Info, message);
}
pub void warning(self*, str* message) {
self.log(LogLevel::Warning, message);
}
pub void error(self*, str* message) {
self.log(LogLevel::Error, message);
}
void log(self*, LogLevel level, str* message) {
match(level) {
LogLevel::Info => {
println!("{level} {} {}", self.prefix, message);
}
LogLevel::Warning => {
println!("{level} {} {}", self.prefix, message);
}
LogLevel::Error => {
println!("{level} {} {}", self.prefix, message);
}
}
}
impl fmt::Display {
fmt::Result fmt(self*, Formatter<'_> mut* f) {
return write!(f, "logger ({})", self.prefix);
}
}
}
+18 -15
View File
@@ -1,15 +1,18 @@
pub mod app;
pub mod task;
pub mod plugin;
pub mod logger;
pub mod event;
void main() {
var mut app_instance = new app::Application("mist-app");
// greeting::register(&mut app_instance);
// statistics::register(&mut app_instance);
app_instance.boot();
app_instance.run();
}
void main()
{
println!("running common tests...");
common::test_package();
common::expr_test::run_tests();
common::statement_test::run_tests();
common::decl_test::run_tests();
common::types_test::run_tests();
println!("running items tests...");
items::function_test::run_tests();
items::struct_test::run_tests();
items::enum_test::run_tests();
items::class_test::run_tests();
items::trait_test::run_tests();
items::impl_test::run_tests();
items::attribute_test::run_tests();
println!("\x1b[32m\nAll tests passed!\x1b[0m");
}
-16
View File
@@ -1,16 +0,0 @@
pub struct PluginInfo {
pub String name,
pub String version,
}
pub class PluginRegistry<T> {
T plugins;
pub constructor(T plugins) {
self.plugins = plugins;
}
pub T plugins(self) {
return self.plugins;
}
}
-20
View File
@@ -1,20 +0,0 @@
pub enum TaskState {
Pending,
Running,
Finished,
Failed,
}
pub struct Task {
pub String name,
pub TaskState state,
pub i32 executions,
}
pub Task create_task(str* name) {
return Task {
name: name.to_string(),
state: TaskState::Pending,
executions: 0,
};
}
-280
View File
@@ -1,280 +0,0 @@
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Identifier(pub String);
#[derive(Debug, Clone, Serialize, Default)]
pub struct ParamList(pub Vec<VarDecl>);
#[derive(Debug, Clone, Serialize, Default)]
pub struct Block(pub Vec<Statement>);
#[derive(Debug, Clone, Serialize)]
pub enum TypePostfix {
Ref,
RefMut,
RefLifetime(Identifier),
RefMutLifetime(Identifier),
}
#[derive(Debug, Clone, Serialize)]
pub enum Visibility {
Public,
PublicTarget(Path),
Private,
}
#[derive(Debug, Clone, Serialize)]
pub enum Attribute {
/// #[test]
Path(Path),
/// #[name = "value"]
NameValue { path: Path, value: Literal },
/// #[derive(Clone, Copy)]
List { path: Path, items: Vec<Attribute> },
}
#[derive(Debug, Clone, Serialize)]
pub enum TypeExprKind {
Path(Path),
PathParams(Path, Vec<TypeExpr>),
Tuple(Vec<TypeExpr>),
Lifetime(Identifier),
}
#[derive(Debug, Clone, Serialize)]
pub struct TypeExpr(pub TypeExprKind, pub Vec<TypePostfix>);
#[derive(Debug, Clone, Serialize)]
pub struct Path(pub Vec<Identifier>);
#[derive(Debug, Clone, Serialize)]
pub enum BinaryOp {
Plus,
Minus,
Multiply,
Divide,
Modulo,
Equal,
NotEqual,
LessThan,
GreaterThan,
LessThanOrEqual,
GreaterThanOrEqual,
And,
Or,
}
#[derive(Debug, Clone, Serialize)]
pub struct TopLevel(pub TopLevelKind, pub Vec<Attribute>);
#[derive(Debug, Clone, Serialize)]
pub enum TopLevelKind {
ModAttribute,
Import(Visibility, Path),
Mod(Visibility, Identifier),
ImplDecl(ImplDecl),
TraitDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
requirements: Vec<TypeExpr>,
items: Vec<FunctionDecl>,
},
EnumDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
fields: Vec<EnumItem>,
},
StructDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
fields: Vec<FieldDecl>,
},
FunctionDecl(FunctionDecl),
ClassDecl {
visibility: Visibility,
name: Identifier,
generics: Generics,
fields: Vec<FieldDeclStmt>,
constructor: ClassConstructor,
items: Vec<ClassItem>,
},
}
#[derive(Debug, Clone, Serialize)]
pub enum ClassItem {
Method(FunctionDecl),
ImplDecl(ImplDecl),
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct Generics(pub Vec<Generic>);
#[derive(Debug, Clone, Serialize)]
pub enum Generic {
Lifetime(Identifier),
Type(Identifier, Vec<TypeExpr>),
}
#[derive(Debug, Clone, Serialize)]
pub enum Pattern {
NamedTuple(Path, Vec<Identifier>),
Struct(Path, Vec<Identifier>),
Tuple(Vec<Identifier>),
Literal(Literal),
Path(Path),
Id(Identifier),
}
#[derive(Debug, Clone, Serialize)]
pub enum EnumItem {
Named(Identifier),
Tuple(Identifier, Vec<TypeExpr>),
Struct(Identifier, Vec<FieldDecl>),
}
#[derive(Debug, Clone, Serialize)]
pub struct ClassConstructor {
pub visibility: Visibility,
pub generics: Generics,
pub params: ParamList,
pub body: Block,
}
#[derive(Debug, Clone, Serialize)]
pub struct FunctionDecl {
pub visibility: Visibility,
pub name: Identifier,
pub generics: Generics,
pub params: ParamList,
pub return_type: TypeExpr,
pub body: Option<Block>,
}
#[derive(Debug, Clone, Serialize)]
pub enum Postfix {
FieldAccess(Identifier),
Call(Vec<Expression>),
MacroCall(String),
StructCall(Vec<(Identifier, Expression)>),
Index(Expression),
Binary(BinaryOp, Expression),
}
#[derive(Debug, Clone, Serialize)]
pub enum Prefix {
Ref,
RefMut,
Deref,
New,
Not,
}
#[derive(Debug, Clone, Serialize)]
pub enum Statement {
Expression(Expression),
Block(Block),
VarDecl(VarDeclStmt),
VarAssign(VarAssignStmt),
If {
initial: StatementBranch,
else_if: Vec<StatementBranch>,
else_branch: Option<Box<Statement>>,
},
While(StatementBranch),
CStyleFor {
init: Box<Statement>,
condition: Expression,
update: Box<Statement>,
body: Box<Statement>,
},
For {
mutable: bool,
pattern: Pattern,
iterator: Expression,
body: Box<Statement>,
},
Match(Expression, Vec<(Pattern, Block)>),
Return(Option<Expression>),
Break,
Continue,
}
#[derive(Debug, Clone, Serialize)]
pub struct ImplDecl {
pub generics: Generics,
pub target: TypeExpr,
pub trait_: Option<TypeExpr>,
pub methods: Vec<FunctionDecl>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarDecl {
pub mutable: bool,
pub name: Pattern,
pub type_: Option<TypeExpr>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt {
pub decl: VarDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)]
pub struct FieldDecl {
pub visibility: Visibility,
pub type_: TypeExpr,
pub name: Identifier,
}
#[derive(Debug, Clone, Serialize)]
pub struct FieldDeclStmt {
pub decl: FieldDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarAssignStmt {
pub target: Expression,
pub value: Expression,
}
#[derive(Debug, Clone, Serialize)]
pub struct StatementBranch {
pub condition: Expression,
pub body: Box<Statement>,
}
#[derive(Debug, Clone, Serialize)]
pub enum Expression {
Literal(Literal),
Path(Path),
Fix {
initial: Box<Expression>,
prefixes: Vec<Prefix>,
postfixes: Vec<Postfix>,
},
}
#[derive(Debug, Clone, Serialize)]
pub enum Literal {
String(String),
Int(i64),
Float(f64),
Bool(bool),
Tuple(Vec<Expression>),
}
impl TypeExpr {
pub fn no_px(kind: TypeExprKind) -> Self {
Self(kind, Vec::new())
}
}
-159
View File
@@ -1,159 +0,0 @@
use std::fmt::Debug;
use pest::iterators::Pair;
use crate::Rule;
pub type AstResult<'a, T, ET = T> = Result<T, AstError<'a, ET>>;
#[derive(Debug, Clone)]
pub enum ParseError<'a, T> {
PreAst(pest::error::Error<Rule>),
Ast(AstError<'a, T>),
}
#[derive(Debug, Clone)]
pub struct AstError<'a, T> {
pub span: pest::Span<'a>,
pub error_code: ErrorCode,
pub error_message: String,
pub recovered: Option<T>,
}
#[derive(Debug, Clone)]
pub enum ErrorCode {
InvalidStatement,
AstGenBug,
}
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
fn from(value: pest::error::Error<Rule>) -> Self {
Self::PreAst(value)
}
}
impl<'a, T> From<AstError<'a, T>> for ParseError<'a, T> {
fn from(value: AstError<'a, T>) -> Self {
Self::Ast(value)
}
}
impl<'a, F> AstError<'a, F> {
pub fn get<T>(self) -> AstError<'a, T> {
AstError {
span: self.span,
error_code: self.error_code,
error_message: self.error_message,
recovered: None,
}
}
pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T, F> {
Err(Self {
span: pair.as_span(),
error_code: ErrorCode::AstGenBug,
error_message: format!("Possible bug, unimplemented: {:#?}", pair.as_rule()),
recovered: None,
})
}
}
pub trait IntoErr<T, FA, FR> {
fn get(self) -> T;
fn get_map(self, m: impl Fn(FA) -> FR) -> T;
}
impl<'a, T, TE, TE2> IntoErr<AstResult<'a, T, TE2>, TE, TE2> for AstResult<'a, T, TE> {
fn get(self) -> AstResult<'a, T, TE2> {
self.map_err(AstError::get)
}
fn get_map(self, m: impl Fn(TE) -> TE2) -> AstResult<'a, T, TE2> {
self.map_err(|e| AstError {
span: e.span,
error_code: e.error_code,
error_message: e.error_message,
recovered: e.recovered.map(m),
})
}
}
pub trait GetLength {
fn len(&self) -> usize;
}
impl<T, E> GetLength for Result<Vec<T>, E> {
fn len(&self) -> usize {
if let Ok(v) = self { v.len() } else { 0 }
}
}
pub fn collect_recovered<'a, T: Debug, ET>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
) -> AstResult<'a, Vec<T>, Vec<T>>
where
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, ET>>,
{
collect_recovered_map(pairs, T::try_from)
}
pub fn collect_recovered_map<'a, T: Debug, F, ET>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
f: F,
) -> AstResult<'a, Vec<T>, Vec<T>>
where
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T, ET>,
{
let mut items = Vec::new();
let mut last_error: Option<AstError<'a, ET>> = None;
for pair in pairs {
match f(pair) {
Ok(item) => items.push(item),
Err(e) => {
last_error = Some(e);
}
}
}
match last_error {
Some(ast_err) => Err(AstError {
span: ast_err.span,
error_code: ast_err.error_code,
error_message: ast_err.error_message,
recovered: Some(items),
}),
None => Ok(items),
}
}
pub struct AstErrorAnalyzer<'a, T>(pub Option<AstError<'a, T>>);
impl<'a, T> AstErrorAnalyzer<'a, T> {
pub fn get<V: Clone, V2: Clone + Into<V>>(
&mut self,
r: AstResult<'a, V, V2>,
) -> AstResult<'a, V, V2> {
if let Err(e) = r {
self.0 = Some(e.clone().get());
if let Some(recovered) = e.recovered {
Ok(recovered.into())
} else {
Err(e)
}
} else {
r
}
}
pub fn build(self, v: T) -> AstResult<'a, T> {
if let Some(mut e) = self.0 {
e.recovered = Some(v);
Err(e)
} else {
Ok(v)
}
}
}
-536
View File
@@ -1,536 +0,0 @@
// ======================================================
// LEXICAL
// ======================================================
WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
COMMENT = _{ "//" ~ (!"\n" ~ ANY)* }
// ------------------------------------------------------
// PRIMITIVES
// ------------------------------------------------------
identifier = @{ (ASCII_ALPHA | "_") ~ (ASCII_ALPHANUMERIC | "_")* }
integer = @{ ASCII_DIGIT+ }
float = @{
ASCII_DIGIT+ ~ "." ~ ASCII_DIGIT+
}
boolean = {
"true"
| "false"
}
string_lit = {
"\"" ~ inner_str ~ "\""
}
inner_str = @{
(!"\"" ~ ("\\\"" | ANY))*
}
semicolon = _{ ";" }
static_path = {
identifier ~ ("::" ~ identifier)*
}
// ======================================================
// PROGRAM
// ======================================================
program = {
SOI ~ top_level* ~ EOI
}
// ======================================================
// MODIFIERS
// ======================================================
visibility = { "pub" ~ ("(" ~ static_path ~ ")")? }
mutable = { "mut" }
var = { "var" }
// ======================================================
// ERROR RECOVERY
// ======================================================
unexpected_statement = {
(!(semicolon | "}" | statement) ~ ANY)+
}
// ======================================================
// GENERICS
// ======================================================
generic = { lifetime | (identifier ~ (":" ~ type_expr_param ~ ("+" ~ type_expr_param)*)?) }
generics = { "<" ~ (generic ~ ("," ~ generic)*)? ~ ">" }
// ======================================================
// TYPES
// ======================================================
tuple_type = {
"(" ~ (type_expr ~ ("," ~ type_expr)*)? ~ ")"
}
path_type = {
static_path ~ ("<" ~ (type_expr_param ~ ("," ~ type_expr_param)*)? ~ ">")?
}
ref_type = {
mutable? ~ lifetime? ~ "*"
}
type_expr = {
(path_type | tuple_type) ~ ref_type*
}
lifetime = {
"'" ~ identifier
}
type_expr_param = {
type_expr
| lifetime
}
// ======================================================
// LITERALS
// ======================================================
literal = {
float
| integer
| boolean
| string_lit
}
// ======================================================
// PATTERNS
// ======================================================
tuple_pattern = {
"(" ~ (identifier ~ ("," ~ identifier)*)? ~ ")"
}
named_tuple_pattern = {
static_path ~ "(" ~ (identifier ~ ("," ~ identifier)*)? ~ ")"
}
struct_pattern = {
static_path ~ "{" ~ (identifier ~ ("," ~ identifier)*)? ~ "}"
}
pattern = _{
named_tuple_pattern
| tuple_pattern
| struct_pattern
| literal
| static_path
}
// ======================================================
// ATTRIBUTES / META
// ======================================================
attribute = {
"#" ~ "[" ~ meta ~ "]"
}
mod_attribute = {
"#" ~ "!" ~ "[" ~ meta ~ "]"
}
meta = {
static_path ~ ("=" ~ literal | "(" ~ meta_list? ~ ")")?
}
meta_list = {
meta ~ ("," ~ meta)* ~ ","?
}
attributes = {
attribute*
}
// ======================================================
// DECLARATION HELPERS
// ======================================================
var_decl = {
(var | type_expr) ~ mutable? ~ pattern
}
field = {
visibility? ~ type_expr ~ identifier
}
field_list = {
field ~ ("," ~ field)* ~ ","?
}
param_list = {
var_decl ~ ("," ~ var_decl)* ~ ","?
}
// ======================================================
// IMPORTS / MODULES
// ======================================================
import = {
visibility? ~ "use" ~ "<" ~ static_path ~ ">" ~ semicolon
}
mod_package = {
visibility? ~ "mod" ~ identifier ~ semicolon
}
// ======================================================
// STRUCTS
// ======================================================
struct_decl = {
visibility? ~ "struct" ~ identifier ~ generics? ~ "{" ~ field_list? ~ "}"
}
// ======================================================
// ENUMS
// ======================================================
enum_named = {
identifier
}
enum_tuple = {
identifier ~ tuple_type
}
enum_struct = {
identifier ~ "{" ~ field_list ~ "}"
}
enum_field = _{
enum_tuple
| enum_struct
| enum_named
}
enum_fields = _{
enum_field ~ ("," ~ enum_field)* ~ ","?
}
enum_decl = {
visibility? ~ "enum" ~ identifier ~ generics? ~ "{" ~ enum_fields ~ "}"
}
// ======================================================
// CLASSES
// ======================================================
class_constructor = {
visibility? ~ "constructor" ~ generics? ~ "(" ~ param_list? ~ ")" ~ block
}
class_fields = {
class_field*
}
class_field = {
field ~ ("=" ~ expr)? ~ semicolon
}
self_param = {
"self" ~ mutable? ~ deref_px?
}
method = {
visibility? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ block
}
class_item = _{
impl_decl
| method
}
class_decl = {
visibility? ~ "class" ~ identifier ~ generics? ~ "{" ~ class_fields ~ class_constructor ~ class_item* ~ "}"
}
// ======================================================
// IMPL
// ======================================================
impl_for_decl = {
"impl" ~ generics? ~ type_expr ~ "for" ~ type_expr ~ "{" ~ method* ~ "}"
}
impl_decl = {
"impl" ~ generics? ~ type_expr ~ "{" ~ method* ~ "}"
}
// ======================================================
// Traits
// ======================================================
trait_requirements = { ":" ~ type_expr_param ~ ("+" ~ type_expr_param)* }
method_no_body = {
visibility? ~ type_expr ~ identifier ~ generics? ~ "(" ~ self_param? ~ ("," ~ param_list?)? ~ ")" ~ semicolon
}
trait_item = _{
method
| method_no_body
}
trait_decl = {
visibility? ~ "trait" ~ identifier ~ generics? ~ trait_requirements? ~ "{" ~ trait_item* ~ "}"
}
// ======================================================
// FUNCTIONS
// ======================================================
function_decl = {
visibility? ~ type_expr ~ identifier ~ "(" ~ param_list? ~ ")" ~ block
}
// ======================================================
// TOP LEVEL
// ======================================================
top_level = {
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | mod_package | function_decl))
| mod_attribute
}
// ======================================================
// STATEMENTS
// ======================================================
block = {
"{" ~ (statement | unexpected_statement)* ~ "}"
}
statement = _{
expr_stmt
| match_stmt
| assign_statement
| if_stmt
| while_stmt
| c_for_stmt
| for_stmt
| return_stmt
| break_stmt
| continue_stmt
| block
| var_decl_statement
}
// ------------------------------------------------------
// BASIC STATEMENTS
// ------------------------------------------------------
expr_stmt = {
expr ~ semicolon
}
return_stmt = {
"return" ~ expr? ~ semicolon
}
break_stmt = {
"break" ~ semicolon
}
continue_stmt = {
"continue" ~ semicolon
}
var_decl_statement = {
var_decl ~ ("=" ~ expr)? ~ semicolon
}
assign_statement = {
expr ~ "=" ~ expr ~ semicolon
}
// ------------------------------------------------------
// CONDITIONALS
// ------------------------------------------------------
statement_branch = { "(" ~ expr ~ ")" ~ statement }
else_if = {
"else" ~ "if" ~ statement_branch
}
else_if_list = {
else_if*
}
if_stmt = {
"if" ~ statement_branch ~ else_if_list ~ ("else" ~ statement)?
}
// ------------------------------------------------------
// LOOPS
// ------------------------------------------------------
while_stmt = {
"while" ~ statement_branch
}
c_for_stmt = {
"for" ~ "(" ~ statement ~ expr ~ semicolon ~ statement ~ ")" ~ statement
}
for_stmt = {
"for" ~ "(" ~ mutable? ~ pattern ~ "in" ~ expr ~ ")" ~ statement
}
// ------------------------------------------------------
// MATCH
// ------------------------------------------------------
match_item = {
pattern ~ "=>" ~ block
}
match_stmt = {
"match" ~ "(" ~ expr ~ ")" ~ "{" ~ match_item* ~ "}"
}
// ======================================================
// EXPRESSIONS
// ======================================================
// ------------------------------------------------------
// TUPLES
// ------------------------------------------------------
tuple = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
}
// ------------------------------------------------------
// MACROS
// ------------------------------------------------------
macro_inner_v = {
"(" ~ macro_inner_v* ~ ")"
| (!("(" | ")") ~ ANY)
}
// ------------------------------------------------------
// PRIMARY EXPRESSIONS
// ------------------------------------------------------
primary = {
literal
| static_path
| tuple
}
// ------------------------------------------------------
// POSTFIX EXPRESSIONS
// ------------------------------------------------------
field_px = {
"." ~ identifier
}
call_px = {
"(" ~ (expr ~ ("," ~ expr)*)? ~ ")"
}
macro_call_px = {
"!" ~ "(" ~ macro_inner_v* ~ ")"
}
struct_field_decl = {
identifier ~ ":" ~ expr
}
struct_px = {
"{" ~ (struct_field_decl ~ ("," ~ struct_field_decl)*)? ~ ","? ~ "}"
}
index_px = {
"[" ~ expr ~ "]"
}
binary_px = {
bin_op ~ expr
}
postfix = {
field_px
| call_px
| macro_call_px
| struct_px
| index_px
| binary_px
}
// ------------------------------------------------------
// PREFIX EXPRESSIONS
// ------------------------------------------------------
deref_px = {
"*"
}
mut_ref_px = {
"&" ~ mutable
}
ref_px = {
"&"
}
new_px = {
"new"
}
not_px = {
"!"
}
prefix = {
deref_px
| mut_ref_px
| ref_px
| new_px
| not_px
}
prefix_list = {
prefix*
}
// ------------------------------------------------------
// OPERATORS
// ------------------------------------------------------
bin_op = {
"<="
| ">="
| "=="
| "!="
| "&&"
| "||"
| "+"
| "-"
| "*"
| "/"
| "%"
| "<"
| ">"
}
// ------------------------------------------------------
// EXPRESSIONS
// ------------------------------------------------------
expr = {
prefix_list ~ primary ~ postfix*
}
-72
View File
@@ -1,72 +0,0 @@
use pest::Parser;
use pest_derive::Parser;
pub mod ast;
pub mod error;
pub mod parser;
use ast::*;
use crate::error::{IntoErr, ParseError};
#[derive(Parser)]
#[grammar = "./src/grammar.pest"]
pub struct MistParser;
pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<TopLevel>>> {
let mut pairs = MistParser::parse(Rule::program, source)?;
let mut statements = vec![];
let mut analyzer = error::AstErrorAnalyzer(None);
for pair in pairs.next().unwrap().into_inner() {
if pair.as_rule() != Rule::EOI {
statements.push(analyzer.get(TopLevel::try_from(pair)).get()?);
}
}
match analyzer.build(statements) {
Ok(v) => Ok(v),
Err(e) => Err(ParseError::Ast(e)),
}
}
#[macro_export]
macro_rules! ast_ensure {
($pair:expr, $rule:expr => $body:block) => {
if $pair.as_rule() == $rule
$body
else {
Err(AstError {
span: $pair.as_span(),
error_code: crate::error::ErrorCode::AstGenBug,
error_message: format!("Possible bug: expected {:?}, got {}", $rule, $pair),
recovered: None,
})
}
};
}
#[macro_export]
macro_rules! ast_expr {
($($item:ident)::+ { $($k:ident: $v:expr),* $(,)? }) => {{
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
let v = $($item)::+ { $($k: analyzer.get($v).get()?),* };
analyzer.build(v)
}};
($($item:ident)::+ ( $($v:expr),* $(,)? )) => {{
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
let v = $($item)::+ ( $(analyzer.get($v).get()?),* );
analyzer.build(v)
}};
($($item:ident)::+) => {
$($item)::+
};
}
-117
View File
@@ -1,117 +0,0 @@
use crate::{
Rule,
ast::*,
ast_expr,
error::{AstError, GetLength, IntoErr, collect_recovered, collect_recovered_map},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::expr => {
let prefixes = inner
.next()
.map(|p| collect_recovered::<Prefix, Prefix>(p.into_inner()))
.unwrap_or_else(|| Ok(Vec::new()));
let exp = Expression::try_from(inner.next().unwrap());
if inner.len() > 0 || prefixes.len() > 0 {
ast_expr!(Expression::Fix {
initial: exp.map(Box::new),
prefixes: prefixes,
postfixes: collect_recovered(inner),
})
} else {
exp
}
}
Rule::primary => inner.next().unwrap().try_into(),
Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(match pair.as_rule() {
Rule::prefix => Self::try_from(pair.into_inner().next().unwrap())?,
Rule::deref_px => Self::Deref,
Rule::mut_ref_px => Self::RefMut,
Rule::ref_px => Self::Ref,
Rule::new_px => Self::New,
Rule::not_px => Self::Not,
_ => return AstError::bug_unimplemented(pair),
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::postfix => Postfix::try_from(inner.next().unwrap()),
Rule::field_px => {
ast_expr!(Postfix::FieldAccess(inner.next().unwrap().try_into()))
}
Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
let mut pi = p.into_inner();
Ok((
Identifier::try_from(pi.next().unwrap())?,
Expression::try_from(pi.next().unwrap()).get()?,
))
}))),
Rule::index_px => {
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
}
Rule::binary_px => {
let op_pair = inner.next().unwrap();
let op = match op_pair.as_str() {
"+" => BinaryOp::Plus,
"-" => BinaryOp::Minus,
"*" => BinaryOp::Multiply,
"/" => BinaryOp::Divide,
"%" => BinaryOp::Modulo,
"==" => BinaryOp::Equal,
"!=" => BinaryOp::NotEqual,
"<" => BinaryOp::LessThan,
">" => BinaryOp::GreaterThan,
"<=" => BinaryOp::LessThanOrEqual,
">=" => BinaryOp::GreaterThanOrEqual,
"&&" => BinaryOp::And,
"||" => BinaryOp::Or,
_ => return AstError::bug_unimplemented(op_pair),
};
Ok(Postfix::Binary(op, inner.next().unwrap().try_into().get()?))
}
Rule::macro_call_px => Ok(Postfix::MacroCall(inner.as_str().to_string())),
_ => AstError::bug_unimplemented(pair),
}
}
}
-123
View File
@@ -1,123 +0,0 @@
use crate::{
Rule,
ast::*,
ast_ensure, ast_expr,
error::{AstError, AstResult, ErrorCode, IntoErr, collect_recovered},
parser::listen_rule,
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
ast_ensure!(pair, Rule::block => {
ast_expr!(Block(collect_recovered(pair.into_inner())))
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::statement_branch => {
ast_expr!(StatementBranch {
condition: inner.next().unwrap().try_into(),
body: inner.next().unwrap().try_into().map(Box::new),
})
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::statement => Statement::try_from(inner.next().unwrap()),
Rule::expr_stmt => {
ast_expr!(Statement::Expression(inner.next().unwrap().try_into()))
}
Rule::block => ast_expr!(Statement::Block(pair.try_into())),
Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
Rule::return_stmt => {
ast_expr!(Statement::Return(
inner.next().map(Expression::try_from).transpose()
))
}
Rule::break_stmt => Ok(Statement::Break),
Rule::continue_stmt => Ok(Statement::Continue),
Rule::if_stmt => {
ast_expr!(Statement::If {
initial: inner.next().unwrap().try_into(),
else_if: collect_recovered(inner.next().unwrap().into_inner()),
else_branch: inner
.next()
.map(Statement::try_from)
.transpose()
.map(|v| v.map(Box::new))
.get_map(|v| { Some(Box::new(v)) }),
})
}
Rule::while_stmt => ast_expr!(Statement::While(inner.next().unwrap().try_into())),
Rule::c_for_stmt => ast_expr!(Statement::CStyleFor {
init: inner.next().unwrap().try_into().map(Box::new),
condition: inner.next().unwrap().try_into(),
update: inner.next().unwrap().try_into().map(Box::new),
body: inner.next().unwrap().try_into().map(Box::new),
}),
Rule::for_stmt => ast_expr!(Statement::For {
mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
pattern: inner.next().unwrap().try_into(),
iterator: inner.next().unwrap().try_into(),
body: inner.next().unwrap().try_into().map(Box::new),
}),
Rule::assign_statement => ast_expr!(VarAssignStmt {
target: inner.next().unwrap().try_into(),
value: inner.next().unwrap().try_into(),
})
.map(Statement::VarAssign)
.get_map(Statement::VarAssign),
Rule::match_stmt => ast_expr!(Statement::Match(
inner.next().unwrap().try_into(),
inner
.map(|match_itms| {
let mut match_inner = match_itms.into_inner();
Ok((
Pattern::try_from(match_inner.next().unwrap()).get()?,
Block::try_from(match_inner.next().unwrap()).get()?,
))
})
.collect::<AstResult<'a, Vec<_>>>(),
)),
Rule::unexpected_statement => {
return Err(AstError {
span: pair.as_span(),
error_code: ErrorCode::InvalidStatement,
error_message: "Invalid Statement".to_string(),
recovered: None,
});
}
_ => AstError::bug_unimplemented(pair),
}
}
}
-121
View File
@@ -1,121 +0,0 @@
use crate::{
Rule,
ast::*,
ast_expr,
error::{AstError, GetLength, IntoErr, collect_recovered},
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::ref_type => {
let mutable = listen_rule(&mut inner, Rule::mutable);
let lifetime = consume_rule(&mut inner, Rule::lifetime)
.map(|pair| Identifier::try_from(pair.into_inner().next().unwrap()))
.transpose()
.get()?;
Ok(if mutable {
if let Some(lifetime) = lifetime {
TypePostfix::RefMutLifetime(lifetime)
} else {
TypePostfix::RefMut
}
} else {
if let Some(lifetime) = lifetime {
TypePostfix::RefLifetime(lifetime)
} else {
TypePostfix::Ref
}
})
}
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExprKind {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::tuple_type => ast_expr!(TypeExprKind::Tuple(collect_recovered(inner))),
Rule::path_type => {
let path = Path::try_from(inner.next().unwrap());
let params = collect_recovered(inner);
if params.len() == 0 {
ast_expr!(TypeExprKind::Path(path))
} else {
ast_expr!(TypeExprKind::PathParams(path, params))
}
}
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::type_expr => ast_expr!(TypeExpr(
inner.next().unwrap().try_into(),
collect_recovered(inner),
)),
Rule::type_expr_param => Self::try_from(inner.next().unwrap()),
Rule::lifetime => ast_expr!(TypeExprKind::Lifetime(inner.next().unwrap().try_into()))
.get_map(TypeExpr::no_px)
.map(TypeExpr::no_px),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let inner = pair.clone().into_inner();
match rule {
Rule::generics => ast_expr!(Generics(collect_recovered(inner))),
_ => AstError::bug_unimplemented(pair),
}
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.clone().into_inner();
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
ast_expr!(Generic::Lifetime(
pair.into_inner().next().unwrap().try_into(),
))
} else {
ast_expr!(Generic::Type(
inner.next().unwrap().try_into(),
collect_recovered(inner),
))
}
}
}
-50
View File
@@ -1,50 +0,0 @@
use crate::{
Rule,
ast::*,
error::{AstError, IntoErr},
parser::consume_rule,
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassConstructor {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner();
Ok(Self {
visibility: Visibility::try_from(&mut inner).get()?,
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.get()?
.unwrap_or_default(),
params: consume_rule(&mut inner, Rule::param_list)
.map(ParamList::try_from)
.transpose()
.get()?
.unwrap_or_default(),
body: inner.next().unwrap().try_into().get()?,
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
match rule {
Rule::impl_decl | Rule::impl_for_decl => {
Ok(ClassItem::ImplDecl(pair.try_into().get()?))
}
Rule::method => Ok(ClassItem::Method(pair.try_into().get()?)),
_ => AstError::bug_unimplemented(pair),
}
}
}
-81
View File
@@ -1,81 +0,0 @@
use crate::{
Rule,
ast::*,
ast_expr,
error::{AstError, AstResult, IntoErr, collect_recovered},
parser::{consume_rule, listen_rule},
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner();
let visibility = Visibility::try_from(&mut inner);
let return_type = TypeExpr::try_from(inner.next().unwrap());
let name = Identifier::try_from(inner.next().unwrap());
let generics = consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.map(|v| v.unwrap_or_default());
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
let mut param_inner = param.into_inner();
let name = Pattern::Id(Identifier(String::from("self")));
let mutable = listen_rule(&mut param_inner, Rule::mutable);
let is_ref = listen_rule(&mut param_inner, Rule::deref_px);
VarDecl {
mutable: mutable && !is_ref,
name: name.clone(),
type_: Some(TypeExpr(
TypeExprKind::Path(Path(vec![Identifier("Self".to_string())])),
if is_ref {
vec![if mutable {
TypePostfix::RefMut
} else {
TypePostfix::Ref
}]
} else {
Vec::new()
},
)),
}
});
let params = consume_rule(&mut inner, Rule::param_list)
.map({
let self_param = self_param.clone();
|params_pair| -> AstResult<'a, ParamList> {
let mut params = ParamList::try_from(params_pair)?;
if let Some(x) = self_param {
params.0.insert(0, x);
}
Ok(params)
}
})
.unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
let body = inner.next().map(Block::try_from).transpose();
ast_expr!(Self {
visibility: visibility,
return_type: return_type,
name: name,
generics: generics,
params: params,
body: body,
})
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ParamList {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
Ok(ParamList(collect_recovered(pair.into_inner()).get()?))
}
}
-125
View File
@@ -1,125 +0,0 @@
pub mod attribute;
pub mod class;
pub mod enums;
pub mod function;
pub mod impl_decl;
use crate::{
Rule,
ast::*,
ast_expr,
error::{AstError, IntoErr, collect_recovered},
parser::consume_rule,
};
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner();
let attributes = collect_recovered(inner.next().unwrap().into_inner());
ast_expr!(TopLevel(
inner
.next()
.map(TopLevelKind::try_from)
.unwrap_or(Ok(TopLevelKind::ModAttribute)),
attributes,
))
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let rule = pair.as_rule();
let mut inner = pair.clone().into_inner();
match rule {
Rule::import => ast_expr!(TopLevelKind::Import(
Visibility::try_from(&mut inner),
Path::try_from(inner.next().unwrap()),
)),
Rule::function_decl => ast_expr!(TopLevelKind::FunctionDecl(pair.try_into())),
Rule::struct_decl => ast_expr!(TopLevelKind::StructDecl {
visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.map(|v| v.unwrap_or_default()),
fields: inner
.next()
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
.transpose()
.map(|v| v.unwrap_or_default()),
}),
Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl {
visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.map(|v| v.unwrap_or_default()),
fields: collect_recovered(inner.next().unwrap().into_inner()),
constructor: inner.next().unwrap().try_into(),
items: collect_recovered(inner),
}),
Rule::enum_decl => ast_expr!(TopLevelKind::EnumDecl {
visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.map(|v| v.unwrap_or_default()),
fields: collect_recovered(inner),
}),
Rule::mod_package => ast_expr!(TopLevelKind::Mod(
Visibility::try_from(&mut inner),
inner.next().unwrap().try_into(),
)),
Rule::impl_for_decl | Rule::impl_decl => {
ast_expr!(TopLevelKind::ImplDecl(pair.try_into()))
}
Rule::trait_decl => ast_expr!(TopLevelKind::TraitDecl {
visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from)
.transpose()
.map(|v| v.unwrap_or_default()),
requirements: consume_rule(&mut inner, Rule::trait_requirements)
.map(|pair| collect_recovered::<TypeExpr, TypeExpr>(pair.into_inner()))
.transpose()
.map(|v| v.unwrap_or_default()),
items: collect_recovered(inner),
}),
_ => AstError::bug_unimplemented(pair),
}
}
}
-29
View File
@@ -1,29 +0,0 @@
pub mod common;
pub mod items;
use crate::Rule;
pub fn listen_rule(pairs: &mut pest::iterators::Pairs<'_, Rule>, rule: Rule) -> bool {
let consumed = pairs
.peek()
.map(|p| p.as_rule() == rule)
.unwrap_or_default();
if consumed {
pairs.next();
}
consumed
}
pub fn consume_rule<'a>(
pairs: &mut pest::iterators::Pairs<'a, Rule>,
rule: Rule,
) -> Option<pest::iterators::Pair<'a, Rule>> {
let consumed = pairs
.peek()
.map(|p| p.as_rule() == rule)
.unwrap_or_default();
if consumed { pairs.next() } else { None }
}
+4
View File
@@ -0,0 +1,4 @@
void main()
{
mist_analyzer::start();
}
-883
View File
@@ -1,883 +0,0 @@
use mist_parser::ast::{
Attribute, BinaryOp, Block, ClassItem, EnumItem, Expression, FieldDecl, FunctionDecl, Generic,
Generics, Identifier, ImplDecl, Literal, Path, Pattern, Postfix, Prefix, Statement,
StatementBranch, TopLevel, TopLevelKind, TypeExpr, TypeExprKind, TypePostfix, VarAssignStmt,
VarDecl, VarDeclStmt, Visibility,
};
// ---------------------------------------------------------------------------
// Traits
// ---------------------------------------------------------------------------
/// Implemented by nodes that *write* into the codegen output buffer.
/// Requires `&mut RustCodegen` because it calls `add` / `addln` / indentation helpers.
pub trait ToRust {
fn to_rust(&self, cg: &mut RustCodegen);
}
/// Implemented by nodes that *produce* a `String` without mutating the codegen.
/// Only needs `&RustCodegen` (e.g. for indent level or helper access).
pub trait GetRust {
fn get_rust(&self) -> String;
}
// ---------------------------------------------------------------------------
// Codegen struct
// ---------------------------------------------------------------------------
pub struct RustCodegen {
output: String,
indent: usize,
}
impl RustCodegen {
pub fn new() -> Self {
Self {
output: String::new(),
indent: 0,
}
}
fn indent_str(&self) -> String {
" ".repeat(self.indent)
}
fn add(&mut self, s: &str) {
self.output.push_str(s);
}
fn addln(&mut self, s: &str) {
self.add(s);
self.add("\n");
}
fn add_indentedln(&mut self, s: &str) {
let line = format!("{}{}\n", self.indent_str(), s);
self.add(&line);
}
pub fn generate(&mut self, toplevels: &[TopLevel]) -> String {
for tl in toplevels {
tl.to_rust(self);
}
self.output.clone()
}
pub fn ensure_brackets(&mut self, stmt: &Statement) {
match stmt {
Statement::Block(_) => stmt.to_rust(self),
_ => {
self.add_indentedln("{");
self.indent += 1;
stmt.to_rust(self);
self.indent -= 1;
self.add_indentedln("}");
}
}
}
}
impl Default for RustCodegen {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// GetRust — pure string production (expressions, types)
// ---------------------------------------------------------------------------
impl GetRust for TypeExpr {
fn get_rust(&self) -> String {
get_type_postfixes(&self.1) + &self.0.get_rust()
}
}
impl GetRust for TypeExprKind {
fn get_rust(&self) -> String {
match self {
TypeExprKind::Path(path) => get_static_type_path(path),
TypeExprKind::Lifetime(name) => format!("'{}", name.get_rust()),
TypeExprKind::PathParams(path, params) => {
format!(
"{}<{}>",
get_static_type_path(path),
params
.iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", ")
)
}
TypeExprKind::Tuple(types) => format!(
"({})",
types
.iter()
.map(|t| t.get_rust())
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GetRust for Literal {
fn get_rust(&self) -> String {
match self {
Self::Int(n) => n.to_string(),
Self::Float(n) => format!("{n:?}"),
Self::Bool(b) => b.to_string(),
Self::String(s) => format!("\"{s}\""),
Self::Tuple(t) => {
format!(
"({})",
t.iter()
.map(Expression::get_rust)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
}
impl GetRust for Expression {
fn get_rust(&self) -> String {
match self {
Expression::Path(path) => path.get_rust(),
Expression::Literal(literal) => literal.get_rust(),
Expression::Fix {
initial,
prefixes,
postfixes,
} => {
prefixes.get_rust()
+ &initial.get_rust()
+ &Some(prefixes).get_rust()
+ &postfixes.get_rust()
}
}
}
}
impl GetRust for Prefix {
fn get_rust(&self) -> String {
match self {
Self::Deref => "*",
Self::Ref => "&",
Self::RefMut => "&mut ",
Self::Not => "!",
Self::New => "",
}
.to_string()
}
}
impl GetRust for [Prefix] {
fn get_rust(&self) -> String {
self.iter().map(Prefix::get_rust).collect()
}
}
impl GetRust for Option<&Vec<Prefix>> {
fn get_rust(&self) -> String {
self.map(|prefixes| {
prefixes
.iter()
.last()
.map(|p| match p {
Prefix::New => "::new",
_ => "",
})
.unwrap_or_default()
.to_string()
})
.unwrap_or_default()
}
}
impl GetRust for Postfix {
fn get_rust(&self) -> String {
match self {
Postfix::FieldAccess(field) => format!(".{}", field.get_rust()),
Postfix::Call(args) => {
let args = args
.iter()
.map(|a| a.get_rust())
.collect::<Vec<_>>()
.join(", ");
format!("({})", args)
}
Postfix::MacroCall(inner) => {
format!("!({})", inner)
}
Postfix::StructCall(fields) => {
let fields = fields
.iter()
.map(|(k, v)| format!("{}: {}", k.get_rust(), v.get_rust()))
.collect::<Vec<_>>()
.join(", ");
format!("{{ {} }}", fields)
}
Postfix::Index(idx) => {
format!("[{}]", idx.get_rust())
}
Postfix::Binary(op, rhs) => {
let op_str = match op {
BinaryOp::Plus => "+",
BinaryOp::Minus => "-",
BinaryOp::Multiply => "*",
BinaryOp::Divide => "/",
BinaryOp::Modulo => "%",
BinaryOp::Equal => "==",
BinaryOp::NotEqual => "!=",
BinaryOp::LessThan => "<",
BinaryOp::GreaterThan => ">",
BinaryOp::LessThanOrEqual => "<=",
BinaryOp::GreaterThanOrEqual => ">=",
BinaryOp::And => "&&",
BinaryOp::Or => "||",
};
format!(" {} {}", op_str, rhs.get_rust())
}
}
}
}
impl GetRust for [Postfix] {
fn get_rust(&self) -> String {
self.iter().map(Postfix::get_rust).collect()
}
}
// ---------------------------------------------------------------------------
// ToRust — output-writing (top-level, statements, blocks)
// ---------------------------------------------------------------------------
impl ToRust for Block {
fn to_rust(&self, cg: &mut RustCodegen) {
for stmt in &self.0 {
stmt.to_rust(cg);
}
}
}
impl ToRust for TopLevel {
fn to_rust(&self, cg: &mut RustCodegen) {
match &self.0 {
TopLevelKind::ModAttribute => {
for attr in &self.1 {
cg.addln(&format!("#![{}]", attr.get_rust()));
}
}
_ => {
for attr in &self.1 {
cg.addln(&format!("#[{}]", attr.get_rust()));
}
}
}
self.0.to_rust(cg);
}
}
impl GetRust for Attribute {
fn get_rust(&self) -> String {
match self {
Self::Path(path) => path.get_rust(),
Self::NameValue { path, value } => {
format!("{} = {}", path.get_rust(), value.get_rust())
}
Self::List { path, items } => {
format!(
"{}({})",
path.get_rust(),
items
.iter()
.map(Attribute::get_rust)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
}
impl ToRust for TopLevelKind {
fn to_rust(&self, cg: &mut RustCodegen) {
match self {
Self::ModAttribute => {}
Self::Import(vis, path) => {
cg.addln(&format!("{} use {};", vis.get_rust(), path.get_rust()))
}
Self::Mod(vis, id) => cg.addln(&format!("{} mod {};", vis.get_rust(), id.get_rust())),
Self::FunctionDecl(decl) => decl.to_rust(cg),
Self::ImplDecl(impl_) => impl_.to_rust(cg),
Self::StructDecl {
visibility,
name,
generics,
fields,
} => {
cg.addln(&format!(
"{}struct {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indentedln(&field.get_rust());
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::EnumDecl {
visibility,
name,
generics,
fields,
} => {
cg.addln(&format!(
"{}enum {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indentedln(&(format!("{}", field.get_rust()) + ","));
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::TraitDecl {
visibility,
name,
generics,
requirements,
items,
} => {
cg.addln(&format!(
"{}trait {}{}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust(),
if requirements.len() != 0 {
String::from(": ")
+ &requirements
.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join("+")
} else {
String::new()
},
));
cg.indent += 1;
for item in items {
item.to_rust(cg);
}
cg.indent -= 1;
cg.addln("}\n");
}
Self::ClassDecl {
visibility,
name,
generics,
fields,
constructor,
items,
} => {
// Struct decl
cg.addln(&format!(
"{}struct {}{} {{",
visibility.get_rust(),
name.get_rust(),
generics.get_rust()
));
cg.indent += 1;
for field in fields {
cg.add_indentedln(&field.decl.get_rust());
}
cg.indent -= 1;
cg.addln("}\n");
// Constructor
cg.addln(&format!(
"impl{} {}{} {{",
generics.get_rust(),
name.get_rust(),
format!(
"<{}>",
generics
.0
.iter()
.map(|v| (false, v).get_rust())
.collect::<Vec<_>>()
.join(", ")
)
));
cg.indent += 1;
let params_str = constructor
.params
.0
.iter()
.map(VarDecl::get_rust)
.collect::<Vec<_>>()
.join(", ");
cg.add_indentedln("#[allow(invalid_value)]");
cg.add_indentedln(&format!(
"{}fn new{}({}) -> Self {{",
constructor.visibility.get_rust(),
constructor.generics.get_rust(),
params_str
));
cg.indent += 1;
cg.add_indentedln("let mut this: Self = unsafe { std::mem::MaybeUninit::<Self>::zeroed().assume_init() };");
for field in fields {
if let Some(init) = &field.init {
cg.add_indentedln(&format!(
"this.{} = {};",
field.decl.name.get_rust(),
init.get_rust()
));
}
}
cg.add_indentedln(&format!(
"this.construct_class({});",
constructor
.params
.0
.iter()
.map(|e| e.name.get_rust())
.collect::<Vec<_>>()
.join(", ")
));
cg.add_indentedln("this");
cg.indent -= 1;
cg.add_indentedln("}\n");
// Constructor function
cg.add_indentedln(&format!(
"{}fn construct_class{}(&mut self, {}) {{",
constructor.visibility.get_rust(),
constructor.generics.get_rust(),
params_str
));
cg.indent += 1;
constructor.body.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}\n");
for item in items {
match item {
ClassItem::ImplDecl(_) => {}
ClassItem::Method(method) => method.to_rust(cg),
}
}
cg.indent -= 1;
cg.addln("}\n");
for item in items {
match item {
ClassItem::ImplDecl(impl_) => {
let mut impl_ = impl_.clone();
impl_.trait_ = Some(impl_.target);
impl_.target =
TypeExpr(TypeExprKind::Path(Path(vec![name.clone()])), Vec::new());
impl_.to_rust(cg);
}
ClassItem::Method(_) => {}
}
}
}
}
}
}
impl ToRust for Statement {
fn to_rust(&self, cg: &mut RustCodegen) {
match self {
Statement::Expression(expr) => {
cg.add_indentedln(&format!("{};", expr.get_rust()));
}
Statement::Block(block) => {
cg.add_indentedln("{");
cg.indent += 1;
block.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}");
}
Statement::VarDecl(VarDeclStmt { decl, init }) => {
let init = init
.as_ref()
.map(|e| format!(" = {}", e.get_rust()))
.unwrap_or_default();
cg.add_indentedln(&format!("let {}{};", decl.get_rust(), init));
}
Statement::VarAssign(VarAssignStmt { target, value }) => {
cg.add_indentedln(&format!("{} = {};", target.get_rust(), value.get_rust(),));
}
Statement::Match(expr, match_items) => {
cg.add_indentedln(&format!("match {} {{", expr.get_rust()));
cg.indent += 1;
for itm in match_items {
cg.add_indentedln(&format!("{} =>", itm.0.get_rust()));
cg.add_indentedln("{");
cg.indent += 1;
itm.1.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}");
}
cg.indent -= 1;
cg.add_indentedln("}");
}
Statement::If {
initial,
else_if,
else_branch,
} => {
cg.add_indentedln(&format!("if {}", initial.condition.get_rust()));
cg.ensure_brackets(&initial.body);
for else_if_branch in else_if {
cg.add_indentedln(&format!("else if {}", else_if_branch.condition.get_rust()));
cg.ensure_brackets(&else_if_branch.body);
}
if let Some(else_br) = else_branch {
cg.add_indentedln("else");
cg.ensure_brackets(else_br);
}
}
Statement::While(StatementBranch { condition, body }) => {
cg.add_indentedln(&format!("while {}", condition.get_rust()));
cg.ensure_brackets(body);
}
Statement::CStyleFor {
init,
condition,
update,
body,
} => {
cg.add_indentedln("{");
cg.indent += 1;
init.to_rust(cg);
cg.add_indentedln(&format!("while {}", condition.get_rust()));
cg.add_indentedln("{");
cg.indent += 1;
cg.ensure_brackets(body);
update.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}");
cg.indent -= 1;
cg.add_indentedln("}");
}
Statement::For {
mutable,
pattern,
iterator,
body,
} => {
cg.add_indentedln(&format!(
"for {}{} in {}",
get_mutable(*mutable),
pattern.get_rust(),
iterator.get_rust()
));
cg.ensure_brackets(body);
}
Statement::Return(expr) => {
let val = expr.as_ref().map(|e| e.get_rust()).unwrap_or_default();
cg.add_indentedln(&format!("return {};", val));
}
Statement::Break => cg.add_indentedln("break;"),
Statement::Continue => cg.add_indentedln("continue;"),
}
}
}
impl ToRust for FunctionDecl {
fn to_rust(&self, cg: &mut RustCodegen) {
let params_str = self
.params
.0
.iter()
.map(VarDecl::get_rust)
.collect::<Vec<_>>()
.join(", ");
cg.add_indentedln(&format!(
"{}fn {}{}({}) -> {}",
self.visibility.get_rust(),
self.name.get_rust(),
self.generics.get_rust(),
params_str,
self.return_type.get_rust()
));
if let Some(body) = &self.body {
cg.add_indentedln("{\n");
cg.indent += 1;
body.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}\n");
} else {
cg.add(";");
}
}
}
impl ToRust for ImplDecl {
fn to_rust(&self, cg: &mut RustCodegen) {
if let Some(trait_) = &self.trait_ {
cg.add_indentedln(&format!(
"impl{} {} for {} {{",
self.generics.get_rust(),
trait_.get_rust(),
self.target.get_rust()
));
} else {
cg.add_indentedln(&format!(
"impl{} {} {{",
self.generics.get_rust(),
self.target.get_rust()
));
}
cg.indent += 1;
for method in &self.methods {
method.to_rust(cg);
}
cg.indent -= 1;
cg.add_indentedln("}");
}
}
impl GetRust for VarDecl {
fn get_rust(&self) -> String {
let ty = self
.type_
.as_ref()
.map(|t| format!(": {}", t.get_rust()))
.unwrap_or_default();
format!(
"{}{}{}",
get_mutable(self.mutable),
self.name.get_rust(),
ty
)
}
}
impl GetRust for Path {
fn get_rust(&self) -> String {
self.0
.iter()
.map(Identifier::get_rust)
.collect::<Vec<String>>()
.join("::")
}
}
impl GetRust for TypePostfix {
fn get_rust(&self) -> String {
match self {
TypePostfix::Ref => format!("&"),
TypePostfix::RefMut => format!("&mut "),
TypePostfix::RefLifetime(lifetime) => format!("&'{} ", lifetime.get_rust()),
TypePostfix::RefMutLifetime(lifetime) => format!("&'{} mut ", lifetime.get_rust()),
}
}
}
impl GetRust for Visibility {
fn get_rust(&self) -> String {
match self {
Visibility::Public => "pub ".to_string(),
Visibility::PublicTarget(path) => format!("pub({}) ", path.get_rust()),
Visibility::Private => "".to_string(),
}
}
}
impl GetRust for Identifier {
fn get_rust(&self) -> String {
self.0.clone()
}
}
impl GetRust for EnumItem {
fn get_rust(&self) -> String {
match self {
Self::Named(id) => id.get_rust(),
Self::Struct(id, s) => format!(
"{} {{{}}}",
id.get_rust(),
s.iter()
.map(|field| format!("{}: {}", field.name.get_rust(), field.type_.get_rust()))
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(id, t) => format!(
"{} ({})",
id.get_rust(),
t.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
impl GetRust for Pattern {
fn get_rust(&self) -> String {
match self {
Self::Id(id) => id.get_rust(),
Self::Path(path) => path.get_rust(),
Self::Literal(lit) => lit.get_rust(),
Self::Struct(path, ids) => format!(
"{} {{{}}}",
path.get_rust(),
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
Self::Tuple(ids) => format!(
"({})",
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
),
Self::NamedTuple(path, ids) => {
format!(
"{} ({})",
path.get_rust(),
ids.iter()
.map(Identifier::get_rust)
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
}
impl GetRust for Generics {
fn get_rust(&self) -> String {
if self.0.len() == 0 {
String::new()
} else {
format!(
"<{}>",
self.0
.iter()
.map(|v| (true, v).get_rust())
.collect::<Vec<_>>()
.join(", ")
)
}
}
}
impl GetRust for (bool, &Generic) {
fn get_rust(&self) -> String {
match &self.1 {
Generic::Lifetime(name) => format!("'{}", name.get_rust()),
Generic::Type(name, requirements) => {
name.get_rust()
+ &(if !self.0 && requirements.len() == 0 {
String::new()
} else {
format!(
": {}",
requirements
.iter()
.map(TypeExpr::get_rust)
.collect::<Vec<_>>()
.join("+")
)
})
}
}
}
}
impl GetRust for FieldDecl {
fn get_rust(&self) -> String {
format!(
"{}{}: {},",
self.visibility.get_rust(),
self.name.get_rust(),
self.type_.get_rust()
)
}
}
pub fn get_static_type_path(path: &Path) -> String {
let rust_path = path.get_rust();
if rust_path == "void" {
format!("()")
} else {
rust_path
}
}
pub fn get_type_postfixes(postfixes: &[TypePostfix]) -> String {
postfixes.iter().map(TypePostfix::get_rust).collect()
}
pub fn get_mutable(mutable: bool) -> String {
if mutable { "mut " } else { "" }.to_string()
}
-168
View File
@@ -1,168 +0,0 @@
use std::{
fs,
path::{Path, PathBuf},
process,
time::Instant,
};
use mist_parser::error::ParseError;
use serde::Deserialize;
#[derive(Deserialize)]
struct Config {
src: String,
output: String,
}
pub fn build() {
let start = Instant::now();
// 1. find project root
let root = find_project_root().unwrap_or_else(|| {
panic!("error: could not find project root (mist.json)");
});
println!("mistc build ({})", root.display());
// 2. load config
let config = load_config(&root);
let src_dir = root.join(&config.src);
let out_dir = root.join(&config.output);
build_dir(&root, &src_dir, &src_dir, &out_dir);
let elapsed = start.elapsed();
println!("build finished in {:.2?}", elapsed);
}
fn build_dir(root: &Path, base_src: &Path, current_dir: &Path, out_dir: &Path) {
let entries = match fs::read_dir(current_dir) {
Ok(entries) => entries,
Err(e) => {
eprintln!(
"error: failed to read directory {}\n {}",
current_dir.display(),
e
);
process::exit(1);
}
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) => {
eprintln!("error: failed to read directory entry\n {}", e);
process::exit(1);
}
};
let path = entry.path();
// recurse into nested directories
if path.is_dir() {
build_dir(root, base_src, &path, out_dir);
continue;
}
// skip non-mist files
if path.extension().and_then(|e| e.to_str()) != Some("mist") {
continue;
}
let relative = path.strip_prefix(base_src).unwrap();
let output_path = out_dir.join(relative).with_extension("rs");
// create parent directories
if let Some(parent) = output_path.parent() {
if let Err(e) = fs::create_dir_all(parent) {
eprintln!(
"error: failed to create output directory {}\n {}",
parent.display(),
e
);
process::exit(1);
}
}
// read source
let source = match fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
eprintln!("error: failed to read file {}\n {}", path.display(), e);
process::exit(1);
}
};
let parser_result = mist_parser::parse(&source).map_err(|e| match e {
ParseError::Ast(e) => {
let start_pos = e.span.start_pos().line_col();
let span = e.span.as_str();
format!(
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
path.as_os_str().display(),
start_pos.0,
start_pos.1,
e.error_message,
span,
if span.ends_with("\n") { "" } else { "\n" },
"^".repeat(span.trim().len()),
)
}
ParseError::PreAst(e) => format!("{e}"),
});
let ast = match parser_result {
Ok(ast) => ast,
Err(e) => {
eprintln!("error: parse failed in {}\n{}", path.display(), e);
process::exit(1);
}
};
// semantic::walk_ast(semantic::scope::Scope::from_top(root, &ast), &mut ast);
let mut gc = crate::codegen::RustCodegen::new();
let output = gc.generate(&ast);
if let Err(e) = fs::write(&output_path, output) {
eprintln!(
"error: failed to write output {}\n {}",
output_path.display(),
e
);
process::exit(1);
}
}
}
pub fn find_project_root() -> Option<PathBuf> {
let mut dir = std::env::current_dir().ok()?;
loop {
if dir.join("mist.json").exists() {
return Some(dir);
}
if !dir.pop() {
return None;
}
}
}
fn load_config(root: &Path) -> Config {
let content = fs::read_to_string(root.join("mist.json")).expect("failed to read mist.json");
serde_json::from_str(&content).expect("invalid mist.json format")
}
+195
View File
@@ -0,0 +1,195 @@
use std::process;
use std::env;
use std::fs;
use mist_api::builder;
use mist_api::transpiler;
void main()
{
Vec<String> mut args = env::args().collect();
if args.len() < 2 {
print_usage();
process::exit(1);
}
match args[1].as_str() {
"run" | "build" | "check" | "test" | "bench" | "doc" | "fix" | "clippy" | "r" | "b" | "c" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);
transpiler::transpile(&root);
println!("");
if builder::build(args, root) {
println!("\x1b[32m\nBuild successful\x1b[0m");
} else {
println!("\x1b[31m\nBuild failed\x1b[0m");
}
}
"publish" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);
transpiler::transpile(&root);
let status = std::process::Command::new("cargo")
.args(args)
.status()
.expect("Failed to run cargo");
if status.success() {
println!("\x1b[32m\nPublished successfully\x1b[0m");
} else {
println!("\x1b[31m\nFailed to publish\x1b[0m");
}
}
"transpile" | "t" => {
let mut root = env::current_dir().expect("Unable to find project root");
modify_args(&mut args, &mut root);
transpiler::transpile(&root);
}
"clean" => {
args.remove(0);
process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
}
"init" => {
init_project(args);
}
"new" => {
new_project(args);
}
"version" | "--version" | "-v" => {
println!("mist {}", env!("CARGO_PKG_VERSION"));
}
"help" | "--help" | "-h" => {
print_usage();
}
unknown => {
eprintln!("error: unknown command '{}'\n", unknown);
print_usage();
process::exit(1);
}
}
}
void modify_args(Vec<String> mut& args, std::path::PathBuf mut& root)
{
if let Some(path_arg) = args.get(2) {
if path_arg == "--path" {
if args.len() > 3 {
let path_arg = args[3].clone();
*root = root.join(&path_arg);
args.remove(2);
args.remove(2);
args.push(format!("--manifest-path={}/Cargo.toml", root.display()));
}
}
}
}
void print_usage()
{
println!("Mist - the mist compiler\n");
println!("󰖟 View our documentation! \x1b[95mhttps://mist.selimaj.dev\x1b[0m");
println!(" Follow us on github! \x1b[95mhttps://github.com/mist-go\x1b[0m\n");
println!("usage:");
println!(" \x1b[96m mist run\x1b[0m,\x1b[96m r\x1b[0m run the project\n");
println!(" \x1b[96m mist build\x1b[0m,\x1b[96m b\x1b[0m build the project\n");
println!(" \x1b[96m mist test\x1b[0m test the project\n");
println!(" \x1b[96m mist publish\x1b[0m publish the project\n");
println!(" \x1b[96m mist bench\x1b[0m benchmark the project\n");
println!(" \x1b[96m mist doc\x1b[0m build documentation\n");
println!(" \x1b[96m mist fix\x1b[0m automatically fix warnings\n");
println!(" \x1b[96m mist clippy\x1b[0m lint the project\n");
println!(" \x1b[96m mist check\x1b[0m,\x1b[96m c\x1b[0m check the project\n");
println!(" \x1b[96m mist clean\x1b[0m clean build artifacts\n");
println!(" \x1b[96m mist transpile\x1b[0m,\x1b[96m t\x1b[0m transpile the project\n");
println!(" \x1b[96m mist init\x1b[0m initialize a project in the current folder\n");
println!(" \x1b[96m mist new\x1b[0m create a new project\n");
println!(" \x1b[96m mist version \x1b[0m print the compiler version\n");
println!(" \x1b[96m mist help\x1b[0m print this message\n");
}
void init_project(Vec<String> mut args)
{
args.remove(0);
let status = process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
if !status.success() {
return;
}
bool is_lib = fs::metadata("src/lib.rs").is_ok();
if is_lib {
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
fs::write("src/lib.mist", "void test() {\n}").expect("Failed to create src/lib.mist");
} else {
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
fs::write("src/main.mist", "void main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
}
inject_mist_target(is_lib);
add_mist_toml(is_lib);
add_gitignore();
println!("Thank you for using Mist!\n");
}
void new_project(Vec<String> mut args)
{
args.remove(0);
if args.len() < 2 {
eprintln!("error: missing project name\n");
print_usage();
process::exit(1);
}
String project_name = args[1].clone();
let status = process::Command::new("cargo").args(args).stdout(process::Stdio::inherit()).stderr(process::Stdio::inherit()).stdin(process::Stdio::inherit()).spawn().expect("Failed to run cargo").wait().expect("Unable to wait");
if !status.success() {
return;
}
std::path::PathBuf project_path = env::current_dir().expect("Unable to find project root").join(&project_name);
env::set_current_dir(&project_path).expect("Failed to change to project directory");
bool is_lib = fs::metadata("src/lib.rs").is_ok();
if is_lib {
fs::remove_file("src/lib.rs").expect("Failed to remove src/lib.rs");
fs::write("src/lib.mist", "void test() {\n}").expect("Failed to create src/lib.mist");
} else {
fs::remove_file("src/main.rs").expect("Failed to remove src/main.rs");
fs::write("src/main.mist", "void main() {\n println!(\"Hello, World!\");\n}\n").expect("Failed to create src/main.mist");
}
inject_mist_target(is_lib);
add_mist_toml(is_lib);
add_gitignore();
println!("Thank you for using Mist!\n");
}
void inject_mist_target(bool is_lib)
{
String toml_content = fs::read_to_string("Cargo.toml").expect("Failed to read Cargo.toml");
toml::Value parsed = toml::from_str(&toml_content).expect("Failed to parse Cargo.toml");
String name = parsed["package"]["name"].as_str().expect("Missing package.name in Cargo.toml").to_string();
String inject = if is_lib {
format!("\n[lib]\nname = \"{name}\"\npath = \".mist/src/lib.rs\"\n")
} else {
format!("\n[[bin]]\nname = \"{name}\"\npath = \".mist/src/main.rs\"\n")
};
fs::write("Cargo.toml", toml_content + &inject).expect("Failed to inject to Cargo.toml");
}
void add_mist_toml(bool is_lib)
{
str& content = if is_lib {
"package = \"lib.mist\"\npackages = []\ninclude = []\n"
} else {
"package = \"main.mist\"\npackages = []\ninclude = []\n"
};
fs::write("Mist.toml", content).expect("Failed to add Mist.toml");
}
void add_gitignore()
{
if fs::metadata(".gitignore").is_ok() {
String content = fs::read_to_string(".gitignore").expect("Failed to read .gitignore");
if !content.contains(".mist") {
fs::write(".gitignore", content + "\n.mist\n").expect("Failed to write .gitignore");
}
}
}
-48
View File
@@ -1,48 +0,0 @@
use std::process::{self, Command};
pub mod codegen;
pub mod compiler;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
print_usage();
process::exit(1);
}
match args[1].as_str() {
"run" | "build" | "r" | "b" => {
compiler::build();
Command::new("cargo").args(&args[1..]).status().unwrap();
}
"transpile" | "t" => compiler::build(),
"version" | "--version" | "-v" => {
println!("mist {}", env!("CARGO_PKG_VERSION"));
}
"help" | "--help" | "-h" => {
print_usage();
}
unknown => {
eprintln!("error: unknown command '{}'\n", unknown);
print_usage();
process::exit(1);
}
}
}
fn print_usage() {
println!("Mist - the mist compiler\n");
println!("󰖟 View our documentation! \x1b[35mhttps://mist.selimaj.dev\x1b[0m");
println!(" Follow us on github! \x1b[35mhttps://github.com/mist-go\x1b[0m\n");
println!("usage:");
println!(" \x1b[36m mist run\x1b[0m run the project in the current directory\n");
println!(
" \x1b[36m mist build\x1b[0m build the project in the current directory\n"
);
println!(
" \x1b[36m mist transpile\x1b[0m transpile the project in the current directory\n"
);
println!(" \x1b[36m mist version \x1b[0m print the compiler version\n");
println!(" \x1b[36m mist help\x1b[0m print this message\n");
}