From 9e1ba442a948d9efc4b7740acc0dca15ba0f457c Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 21 Dec 2023 10:52:27 +0100 Subject: [PATCH 001/195] tree-sitter experiment --- packages/haskell/.gitignore | 26 ++++ packages/haskell/README.md | 25 ++++ packages/haskell/index.html | 13 ++ packages/haskell/main.js | 7 ++ packages/haskell/package.json | 20 +++ pnpm-lock.yaml | 231 ++++++++++++++++++++++++++++++++++ 6 files changed, 322 insertions(+) create mode 100644 packages/haskell/.gitignore create mode 100644 packages/haskell/README.md create mode 100644 packages/haskell/index.html create mode 100644 packages/haskell/main.js create mode 100644 packages/haskell/package.json diff --git a/packages/haskell/.gitignore b/packages/haskell/.gitignore new file mode 100644 index 00000000..30378b91 --- /dev/null +++ b/packages/haskell/.gitignore @@ -0,0 +1,26 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +public/tree-sitter.wasm \ No newline at end of file diff --git a/packages/haskell/README.md b/packages/haskell/README.md new file mode 100644 index 00000000..2769a416 --- /dev/null +++ b/packages/haskell/README.md @@ -0,0 +1,25 @@ +# @strudel/haskell + +This is an experiment in implementing tree-sitter for parsing haskell. + +So far, I have just set up a vite project that imports and inits `web-tree-sitter`, which works after + +- +- + +Running: + +```sh +cd haskell && pnpm i +pnpm dev +``` + +will start the vite dev server, loading tree sitter on `http://localhost:5174/`. + +The next step is be to generate `tree-sitter-haskell.wasm` file following . + +I've tried to generate it using but it failed, due to some versioning conflicts involving node / v8 / node-gyp. + +It seems a lot of work has gone into this package in , without a new npm package version being released, which is why I've written this comment: . + +So either someone authorized releases a new version of the package or we might need to pull the changes and try to build it from the tree-sitter master branch. diff --git a/packages/haskell/index.html b/packages/haskell/index.html new file mode 100644 index 00000000..18355039 --- /dev/null +++ b/packages/haskell/index.html @@ -0,0 +1,13 @@ + + + + + + + Tree sitter test + + +
+ + + diff --git a/packages/haskell/main.js b/packages/haskell/main.js new file mode 100644 index 00000000..e7d2c78b --- /dev/null +++ b/packages/haskell/main.js @@ -0,0 +1,7 @@ +import Parser from 'web-tree-sitter'; + +console.log('Parser', Parser); + +Parser.init().then(() => { + console.log('init done..'); +}); diff --git a/packages/haskell/package.json b/packages/haskell/package.json new file mode 100644 index 00000000..bcc05169 --- /dev/null +++ b/packages/haskell/package.json @@ -0,0 +1,20 @@ +{ + "name": "haskell", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public" + }, + "devDependencies": { + "tree-sitter-cli": "^0.20.8", + "tree-sitter-javascript": "^0.20.1", + "vite": "^5.0.8" + }, + "dependencies": { + "web-tree-sitter": "^0.20.8" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 98f6441f..db0a9dce 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,5 +1,9 @@ lockfileVersion: '6.0' +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + importers: .: @@ -187,6 +191,22 @@ importers: packages/embed: {} + packages/haskell: + dependencies: + web-tree-sitter: + specifier: ^0.20.8 + version: 0.20.8 + devDependencies: + tree-sitter-cli: + specifier: ^0.20.8 + version: 0.20.8 + tree-sitter-javascript: + specifier: ^0.20.1 + version: 0.20.1 + vite: + specifier: ^5.0.8 + version: 5.0.10 + packages/hydra: dependencies: '@strudel.cycles/core': @@ -4053,6 +4073,110 @@ packages: rollup: 2.79.1 dev: true + /@rollup/rollup-android-arm-eabi@4.9.1: + resolution: {integrity: sha512-6vMdBZqtq1dVQ4CWdhFwhKZL6E4L1dV6jUjuBvsavvNJSppzi6dLBbuV+3+IyUREaj9ZFvQefnQm28v4OCXlig==} + cpu: [arm] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-android-arm64@4.9.1: + resolution: {integrity: sha512-Jto9Fl3YQ9OLsTDWtLFPtaIMSL2kwGyGoVCmPC8Gxvym9TCZm4Sie+cVeblPO66YZsYH8MhBKDMGZ2NDxuk/XQ==} + cpu: [arm64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-darwin-arm64@4.9.1: + resolution: {integrity: sha512-LtYcLNM+bhsaKAIGwVkh5IOWhaZhjTfNOkGzGqdHvhiCUVuJDalvDxEdSnhFzAn+g23wgsycmZk1vbnaibZwwA==} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-darwin-x64@4.9.1: + resolution: {integrity: sha512-KyP/byeXu9V+etKO6Lw3E4tW4QdcnzDG/ake031mg42lob5tN+5qfr+lkcT/SGZaH2PdW4Z1NX9GHEkZ8xV7og==} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm-gnueabihf@4.9.1: + resolution: {integrity: sha512-Yqz/Doumf3QTKplwGNrCHe/B2p9xqDghBZSlAY0/hU6ikuDVQuOUIpDP/YcmoT+447tsZTmirmjgG3znvSCR0Q==} + cpu: [arm] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm64-gnu@4.9.1: + resolution: {integrity: sha512-u3XkZVvxcvlAOlQJ3UsD1rFvLWqu4Ef/Ggl40WAVCuogf4S1nJPHh5RTgqYFpCOvuGJ7H5yGHabjFKEZGExk5Q==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm64-musl@4.9.1: + resolution: {integrity: sha512-0XSYN/rfWShW+i+qjZ0phc6vZ7UWI8XWNz4E/l+6edFt+FxoEghrJHjX1EY/kcUGCnZzYYRCl31SNdfOi450Aw==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-riscv64-gnu@4.9.1: + resolution: {integrity: sha512-LmYIO65oZVfFt9t6cpYkbC4d5lKHLYv5B4CSHRpnANq0VZUQXGcCPXHzbCXCz4RQnx7jvlYB1ISVNCE/omz5cw==} + cpu: [riscv64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-x64-gnu@4.9.1: + resolution: {integrity: sha512-kr8rEPQ6ns/Lmr/hiw8sEVj9aa07gh1/tQF2Y5HrNCCEPiCBGnBUt9tVusrcBBiJfIt1yNaXN6r1CCmpbFEDpg==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-x64-musl@4.9.1: + resolution: {integrity: sha512-t4QSR7gN+OEZLG0MiCgPqMWZGwmeHhsM4AkegJ0Kiy6TnJ9vZ8dEIwHw1LcZKhbHxTY32hp9eVCMdR3/I8MGRw==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-arm64-msvc@4.9.1: + resolution: {integrity: sha512-7XI4ZCBN34cb+BH557FJPmh0kmNz2c25SCQeT9OiFWEgf8+dL6ZwJ8f9RnUIit+j01u07Yvrsuu1rZGxJCc51g==} + cpu: [arm64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-ia32-msvc@4.9.1: + resolution: {integrity: sha512-yE5c2j1lSWOH5jp+Q0qNL3Mdhr8WuqCNVjc6BxbVfS5cAS6zRmdiw7ktb8GNpDCEUJphILY6KACoFoRtKoqNQg==} + cpu: [ia32] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-x64-msvc@4.9.1: + resolution: {integrity: sha512-PyJsSsafjmIhVgaI1Zdj7m8BB8mMckFah/xbpplObyHfiXzKcI5UOUXRyOdHW7nz4DpMCuzLnF7v5IWHenCwYA==} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: true + optional: true + /@sigstore/protobuf-specs@0.1.0: resolution: {integrity: sha512-a31EnjuIDSX8IXBUib3cYLDRlPMU36AWX4xS8ysLaNu4ZzUesDiPt83pgrW2X1YLMe5L2HbDyaKK5BrL4cNKaQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -5572,6 +5696,7 @@ packages: /b4a@1.6.4: resolution: {integrity: sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==} + requiresBuild: true optional: true /babel-plugin-add-module-exports@0.2.1: @@ -6154,6 +6279,7 @@ packages: /color-string@1.9.1: resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} + requiresBuild: true dependencies: color-name: 1.1.4 simple-swizzle: 0.2.2 @@ -6166,6 +6292,7 @@ packages: /color@4.2.3: resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} engines: {node: '>=12.5.0'} + requiresBuild: true dependencies: color-convert: 2.0.1 color-string: 1.9.1 @@ -6629,6 +6756,7 @@ packages: /detect-libc@2.0.2: resolution: {integrity: sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==} engines: {node: '>=8'} + requiresBuild: true optional: true /detective-amd@4.0.1: @@ -7472,6 +7600,7 @@ packages: /fast-fifo@1.3.2: resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==} + requiresBuild: true optional: true /fast-glob@3.2.12: @@ -7743,6 +7872,14 @@ packages: requiresBuild: true optional: true + /fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + requiresBuild: true + dev: true + optional: true + /function-bind@1.1.1: resolution: {integrity: sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==} @@ -10521,6 +10658,12 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true + /nanoid@3.3.7: + resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + dev: true + /nanoid@4.0.2: resolution: {integrity: sha512-7ZtY5KTCNheRGfEFxnedV5zFiORN1+Y1N6zvPTnHQd8ENUvfaDBeuJDZb2bN/oXwXxu3qkTXDzy57W5vAmDTBw==} engines: {node: ^14 || ^16 || >=18} @@ -10579,6 +10722,7 @@ packages: /node-addon-api@6.1.0: resolution: {integrity: sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==} + requiresBuild: true optional: true /node-domexception@1.0.0: @@ -11675,6 +11819,15 @@ packages: picocolors: 1.0.0 source-map-js: 1.0.2 + /postcss@8.4.32: + resolution: {integrity: sha512-D/kj5JNu6oo2EIy+XL/26JEDTlIbB8hw85G8StOE6L74RQAVVP5rej6wxCNqyMbR4RkPfqvezVbPw81Ngd6Kcw==} + engines: {node: ^10 || ^12 || >=14} + dependencies: + nanoid: 3.3.7 + picocolors: 1.0.0 + source-map-js: 1.0.2 + dev: true + /prebuild-install@7.1.1: resolution: {integrity: sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==} engines: {node: '>=10'} @@ -11875,6 +12028,7 @@ packages: /queue-tick@1.0.1: resolution: {integrity: sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==} + requiresBuild: true optional: true /quick-lru@4.0.1: @@ -12522,6 +12676,27 @@ packages: optionalDependencies: fsevents: 2.3.2 + /rollup@4.9.1: + resolution: {integrity: sha512-pgPO9DWzLoW/vIhlSoDByCzcpX92bKEorbgXuZrqxByte3JFk2xSW2JEeAcyLc9Ru9pqcNNW+Ob7ntsk2oT/Xw==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.9.1 + '@rollup/rollup-android-arm64': 4.9.1 + '@rollup/rollup-darwin-arm64': 4.9.1 + '@rollup/rollup-darwin-x64': 4.9.1 + '@rollup/rollup-linux-arm-gnueabihf': 4.9.1 + '@rollup/rollup-linux-arm64-gnu': 4.9.1 + '@rollup/rollup-linux-arm64-musl': 4.9.1 + '@rollup/rollup-linux-riscv64-gnu': 4.9.1 + '@rollup/rollup-linux-x64-gnu': 4.9.1 + '@rollup/rollup-linux-x64-musl': 4.9.1 + '@rollup/rollup-win32-arm64-msvc': 4.9.1 + '@rollup/rollup-win32-ia32-msvc': 4.9.1 + '@rollup/rollup-win32-x64-msvc': 4.9.1 + fsevents: 2.3.3 + dev: true + /run-async@2.4.1: resolution: {integrity: sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==} engines: {node: '>=0.12.0'} @@ -12730,6 +12905,7 @@ packages: /simple-swizzle@0.2.2: resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==} + requiresBuild: true dependencies: is-arrayish: 0.3.2 optional: true @@ -12943,6 +13119,7 @@ packages: /streamx@2.15.2: resolution: {integrity: sha512-b62pAV/aeMjUoRN2C/9F0n+G8AfcJjNC0zw/ZmOHeFsIe4m4GzjVW9m6VHXVjk536NbdU9JRwKMJRfkc+zUFTg==} + requiresBuild: true dependencies: fast-fifo: 1.3.2 queue-tick: 1.0.1 @@ -13220,6 +13397,7 @@ packages: /tar-fs@3.0.4: resolution: {integrity: sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==} + requiresBuild: true dependencies: mkdirp-classic: 0.5.3 pump: 3.0.0 @@ -13238,6 +13416,7 @@ packages: /tar-stream@3.1.6: resolution: {integrity: sha512-B/UyjYwPpMBv+PaFSWAmtYjwdrlEaZQEhMIBFNC5oEG8lpiW8XjcSdmEaClj28ArfKScKHs2nshz3k2le6crsg==} + requiresBuild: true dependencies: b4a: 1.6.4 fast-fifo: 1.3.2 @@ -13429,6 +13608,19 @@ packages: punycode: 2.3.0 dev: true + /tree-sitter-cli@0.20.8: + resolution: {integrity: sha512-XjTcS3wdTy/2cc/ptMLc/WRyOLECRYcMTrSWyhZnj1oGSOWbHLTklgsgRICU3cPfb0vy+oZCC33M43u6R1HSCA==} + hasBin: true + requiresBuild: true + dev: true + + /tree-sitter-javascript@0.20.1: + resolution: {integrity: sha512-2LNRAw6vd6NDGf5DvAZTaIJDv0j7519bbDsQQ9jnT7uC91efvbn2BxOagNs7u41LSbmsuScjkM8VeN0mnya1iw==} + requiresBuild: true + dependencies: + nan: 2.17.0 + dev: true + /treeverse@3.0.0: resolution: {integrity: sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -14141,6 +14333,41 @@ packages: optionalDependencies: fsevents: 2.3.2 + /vite@5.0.10: + resolution: {integrity: sha512-2P8J7WWgmc355HUMlFrwofacvr98DAjoE52BfdbwQtyLH06XKwaL/FMnmKM2crF0iX4MpmMKoDlNCB1ok7zHCw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + dependencies: + esbuild: 0.19.5 + postcss: 8.4.32 + rollup: 4.9.1 + optionalDependencies: + fsevents: 2.3.3 + dev: true + /vitefu@0.2.4(vite@4.5.0): resolution: {integrity: sha512-fanAXjSaf9xXtOOeno8wZXIhgia+CZury481LsDaV++lSvcU2R9Ch2bPh3PYFyoHW+w9LqAeYRISVQjUIew14g==} peerDependencies: @@ -14267,6 +14494,10 @@ packages: engines: {node: '>= 8'} dev: true + /web-tree-sitter@0.20.8: + resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} + dev: false + /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} From 756f37e265d50003b1371f962e7200fba09930d1 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 21 Dec 2023 10:54:12 +0100 Subject: [PATCH 002/195] format --- packages/haskell/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/haskell/index.html b/packages/haskell/index.html index 18355039..c6b59eed 100644 --- a/packages/haskell/index.html +++ b/packages/haskell/index.html @@ -1,4 +1,4 @@ - + From 64dbdd97baaefbc02d1558320bdcc00345ea7376 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 29 Dec 2023 21:27:54 +0100 Subject: [PATCH 003/195] little update --- packages/haskell/.gitignore | 3 ++- packages/haskell/README.md | 6 ++++++ packages/haskell/main.js | 8 ++++++-- packages/haskell/public/README.md | 3 +++ 4 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 packages/haskell/public/README.md diff --git a/packages/haskell/.gitignore b/packages/haskell/.gitignore index 30378b91..213c8054 100644 --- a/packages/haskell/.gitignore +++ b/packages/haskell/.gitignore @@ -23,4 +23,5 @@ dist-ssr *.sln *.sw? -public/tree-sitter.wasm \ No newline at end of file +public/tree-sitter.wasm +public/tree-sitter-haskell.wasm \ No newline at end of file diff --git a/packages/haskell/README.md b/packages/haskell/README.md index 2769a416..0143b93e 100644 --- a/packages/haskell/README.md +++ b/packages/haskell/README.md @@ -23,3 +23,9 @@ I've tried to generate it using , without a new npm package version being released, which is why I've written this comment: . So either someone authorized releases a new version of the package or we might need to pull the changes and try to build it from the tree-sitter master branch. + +## Update 1 + +I've managed to make it work by using [this tree-sitter-haskell.wasm](https://github.com/tree-sitter/tree-sitter-haskell/blob/master/tree-sitter-haskell.wasm), instead of using the version on npm! Make sure both `tree-sitter.wasm` and `tree-sitter-haskell.wasm` are in the public dir, then run `pnpm dev`. The console should log a tree sitter AST string. + +Next step: understand how the ast works to then transform it into JS function calls! diff --git a/packages/haskell/main.js b/packages/haskell/main.js index e7d2c78b..dd96e32f 100644 --- a/packages/haskell/main.js +++ b/packages/haskell/main.js @@ -2,6 +2,10 @@ import Parser from 'web-tree-sitter'; console.log('Parser', Parser); -Parser.init().then(() => { - console.log('init done..'); +Parser.init().then(async () => { + const parser = new Parser(); + const Lang = await Parser.Language.load('tree-sitter-haskell.wasm'); + parser.setLanguage(Lang); + const tree = parser.parse('d1 $ s "hh*3"'); + console.log(tree.rootNode.toString()); }); diff --git a/packages/haskell/public/README.md b/packages/haskell/public/README.md new file mode 100644 index 00000000..6f8ff001 --- /dev/null +++ b/packages/haskell/public/README.md @@ -0,0 +1,3 @@ +# public + +this file is just here to make sure the public folder exists From a39b4c1637bfb048e6175280171c9aaa8530d1cb Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sat, 30 Dec 2023 16:43:08 +0100 Subject: [PATCH 004/195] parser viz --- packages/haskell/.gitignore | 3 +- packages/haskell/index.html | 5 +- packages/haskell/main.js | 50 ++++++++++++++-- packages/haskell/package.json | 6 +- pnpm-lock.yaml | 110 +++++++++++++++++++++++++++++++++- 5 files changed, 162 insertions(+), 12 deletions(-) diff --git a/packages/haskell/.gitignore b/packages/haskell/.gitignore index 213c8054..aa33e831 100644 --- a/packages/haskell/.gitignore +++ b/packages/haskell/.gitignore @@ -24,4 +24,5 @@ dist-ssr *.sw? public/tree-sitter.wasm -public/tree-sitter-haskell.wasm \ No newline at end of file +public/tree-sitter-haskell.wasm +public/tree-sitter-haskell_mine.wasm \ No newline at end of file diff --git a/packages/haskell/index.html b/packages/haskell/index.html index c6b59eed..23d1c4a6 100644 --- a/packages/haskell/index.html +++ b/packages/haskell/index.html @@ -6,8 +6,9 @@ Tree sitter test - -
+ + +
diff --git a/packages/haskell/main.js b/packages/haskell/main.js index dd96e32f..df11110a 100644 --- a/packages/haskell/main.js +++ b/packages/haskell/main.js @@ -1,11 +1,51 @@ import Parser from 'web-tree-sitter'; +import toDot from 'jgf-dot'; +import { Graphviz } from '@hpcc-js/wasm'; -console.log('Parser', Parser); +const graphvizLoaded = Graphviz.load(); +const parserLoaded = loadParser(); +const graphContainer = document.getElementById('graph'); -Parser.init().then(async () => { +const textarea = document.getElementById('code'); +textarea.value = 'd1 $ s "hh(3,8)"'; +textarea.addEventListener('input', (e) => renderGraph(e.target.value, graphContainer)); +renderGraph(textarea.value, graphContainer); + +function walk(node, branch = [0], parent) { + let nodes = []; + let edges = []; + const current = { id: branch.join('-'), label: node.type }; + nodes.push(current); + parent && edges.push({ source: parent.id, target: current.id }); + if (node.children.length) { + node.children.forEach((child, j) => { + const { nodes: childNodes, edges: childEdges } = walk(child, branch.concat([j]), current); + nodes = nodes.concat(childNodes || []); + edges = edges.concat(childEdges || []); + }); + } + return { nodes, edges }; +} + +async function renderGraph(code, container) { + const parser = await parserLoaded; + const tree = parser.parse(code); + const { nodes, edges } = walk(tree.rootNode); + const graphviz = await graphvizLoaded; + const dot = toDot({ + graph: { + nodes, + edges, + }, + }); + const svg = await graphviz.layout(dot, 'svg', 'dot'); + container.innerHTML = svg; +} + +async function loadParser() { + await Parser.init(); const parser = new Parser(); const Lang = await Parser.Language.load('tree-sitter-haskell.wasm'); parser.setLanguage(Lang); - const tree = parser.parse('d1 $ s "hh*3"'); - console.log(tree.rootNode.toString()); -}); + return parser; +} diff --git a/packages/haskell/package.json b/packages/haskell/package.json index bcc05169..46039e25 100644 --- a/packages/haskell/package.json +++ b/packages/haskell/package.json @@ -7,14 +7,18 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public" + "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public", + "parse": "tree-sitter parse -D ./test.hs" }, "devDependencies": { + "tree-sitter": "^0.20.6", "tree-sitter-cli": "^0.20.8", "tree-sitter-javascript": "^0.20.1", "vite": "^5.0.8" }, "dependencies": { + "@hpcc-js/wasm": "^2.15.3", + "jgf-dot": "^1.1.1", "web-tree-sitter": "^0.20.8" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 44efa683..5f77b9ad 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -240,10 +240,19 @@ importers: packages/haskell: dependencies: + '@hpcc-js/wasm': + specifier: ^2.15.3 + version: 2.15.3 + jgf-dot: + specifier: ^1.1.1 + version: 1.1.1 web-tree-sitter: specifier: ^0.20.8 version: 0.20.8 devDependencies: + tree-sitter: + specifier: ^0.20.6 + version: 0.20.6 tree-sitter-cli: specifier: ^0.20.8 version: 0.20.8 @@ -2914,6 +2923,13 @@ packages: react: 18.2.0 dev: false + /@hpcc-js/wasm@2.15.3: + resolution: {integrity: sha512-enmVW4APrv6jBCRP5V/WdIjYvxidNgBbgdWOdLpiygoE0g0ZurM1qsysBo4TbZfdS81SCdkjRSU/URWf+gpQUA==} + hasBin: true + dependencies: + yargs: 17.7.2 + dev: false + /@humanwhocodes/config-array@0.11.8: resolution: {integrity: sha512-UybHIJzJnR5Qc/MsD9Kr+RpO2h+/P1GhOwdiLPXK5TWk5sgTdu88bTD9UP+CKbPPh5Rni1u0GjAdYQLemG8g+g==} engines: {node: '>=10.10.0'} @@ -6423,7 +6439,6 @@ packages: resolution: {integrity: sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==} engines: {node: '>=8'} requiresBuild: true - optional: true /detective-amd@4.0.1: resolution: {integrity: sha512-bDo22IYbJ8yzALB0Ow5CQLtyhU1BpDksLB9dsWHI9Eh0N3OQR6aQqhjPsNDd69ncYwRfL1sTo7OA9T3VRVSe2Q==} @@ -6593,6 +6608,10 @@ packages: engines: {node: '>=10'} dev: true + /dotty@0.0.1: + resolution: {integrity: sha512-eDT0hfJEnQbGaZcTuCfj2igPkQ7qa/n9K2pGGDxhEqKhARLq+xE1TonvpOPHq+7KeG+D6A/V8BwCcsdPom2TQg==} + dev: false + /dset@3.1.2: resolution: {integrity: sha512-g/M9sqy3oHe477Ar4voQxWtaPIFw1jTdKZuomOjhCcBx9nHUNn0pu6NopuFFrTh/TRZIKEj+76vLWFu9BNKk+Q==} engines: {node: '>=4'} @@ -7560,6 +7579,10 @@ packages: resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} dev: true + /gather-stream@1.0.0: + resolution: {integrity: sha512-NspYMi3rN3EKmMdejUXbtluDYrcRlTEBBFhWzVRZVsOx94OPxlXp0AzyPKyLiT7iaurcoTE/KcHsHP/PowNEaA==} + dev: false + /gauge@3.0.2: resolution: {integrity: sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==} engines: {node: '>=10'} @@ -7898,6 +7921,33 @@ packages: /grapheme-splitter@1.0.4: resolution: {integrity: sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==} + /graphlib-dot@0.6.4: + resolution: {integrity: sha512-rdhDTu0mBlloTpFMfkQq+e3y4yL22OqP5MhQbkw6QUURqa+4YLgv3XZy2fA64wdEcJNZ+waI76URemVgdFtzng==} + dependencies: + graphlib: 2.1.8 + lodash: 4.17.21 + dev: false + + /graphlib-json-graph@1.0.0: + resolution: {integrity: sha512-sJsFuthZnSL5knaDDZhDx8fg1Zy5t/7ZqVHiytoeSzezGhMoSFD3T3K5YQakKFEyXtYjOzbnvsyr2qo+6/qq/Q==} + dependencies: + graphlib: 1.0.7 + par: 0.3.0 + prop: 0.1.1 + dev: false + + /graphlib@1.0.7: + resolution: {integrity: sha512-jNb7RbqTIRyZRmcVCxGefOlGWjNdbjcT2tFj36zhnRa8yhAlOvydh9nBixfLQIqSU+DwCx47tg3ysw8NIYhpsA==} + dependencies: + lodash: 3.10.1 + dev: false + + /graphlib@2.1.8: + resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==} + dependencies: + lodash: 4.17.21 + dev: false + /gray-matter@4.0.3: resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==} engines: {node: '>=6.0'} @@ -8794,6 +8844,15 @@ packages: supports-color: 7.2.0 dev: true + /jgf-dot@1.1.1: + resolution: {integrity: sha512-/aw9bwVfn67A+lvjxtbocBuhB2rNdL5UY5rlHhKVh9ValvVJETU5lQ0jitDxiIjIPAEeuR4B1aFNA7E3wKNV1A==} + hasBin: true + dependencies: + graphlib-dot: 0.6.4 + graphlib-json-graph: 1.0.0 + read-file-stdin: 0.2.1 + dev: false + /jiti@1.18.2: resolution: {integrity: sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg==} hasBin: true @@ -9257,9 +9316,12 @@ packages: resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==} dev: true + /lodash@3.10.1: + resolution: {integrity: sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==} + dev: false + /lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} - dev: true /log-symbols@4.1.0: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} @@ -10316,6 +10378,10 @@ packages: /nan@2.17.0: resolution: {integrity: sha512-2ZTgtl0nJsO0KQCjEpxcIr5D+Yv90plTitZt9JBfQvVJDS5seMl3FOvsh3+9CoYWXf/1l5OaZzzF6nDm4cagaQ==} + /nan@2.18.0: + resolution: {integrity: sha512-W7tfG7vMOGtD30sHoZSSc/JVYiyDPEyQVso/Zz+/uQd0B0L46gtC+pHha5FFMRpil6fm/AoEcRWyOVi4+E/f8w==} + dev: true + /nanoid@3.3.6: resolution: {integrity: sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -11118,6 +11184,11 @@ packages: - supports-color dev: true + /par@0.3.0: + resolution: {integrity: sha512-6V910zFAoHnxjX6ILkwbQcpIkD3KI2gBAPfCtZQNaJTvTxgIoKXSwDQIE3ty0zbOGdBXHRnl6rd66a5jj12pfw==} + engines: {node: '>=0.6'} + dev: false + /parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -11499,7 +11570,7 @@ packages: engines: {node: '>=10'} hasBin: true dependencies: - detect-libc: 2.0.1 + detect-libc: 2.0.2 expand-template: 2.0.3 github-from-package: 0.0.0 minimist: 1.2.7 @@ -11659,6 +11730,12 @@ packages: read: 1.0.7 dev: true + /prop@0.1.1: + resolution: {integrity: sha512-hf5DdgiPkcoVxBfuSknP918U0lDC+7lArIjIB2U4Gh79p1Xtc0JP6W5DW3c0wC0x9/A6CsAISh3202I1GlMgkw==} + dependencies: + dotty: 0.0.1 + dev: false + /property-information@6.2.0: resolution: {integrity: sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==} @@ -11792,6 +11869,12 @@ packages: engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} dev: true + /read-file-stdin@0.2.1: + resolution: {integrity: sha512-dAqysQ4kfj9m5aejZOPr+aRGXZJXdLkMOLZ3BXMwMBQHiO+aylGBFJPh88AYPQrOf+D43F4Uc2oUIW9kBlItLA==} + dependencies: + gather-stream: 1.0.0 + dev: false + /read-package-json-fast@2.0.3: resolution: {integrity: sha512-W/BKtbL+dUjTuRL2vziuYhp76s5HZ9qQhd/dKfWIZveD0O40453QNyZhC0e63lqZrAQ4jiOapVoeJ7JrszenQQ==} engines: {node: '>=10'} @@ -13294,6 +13377,14 @@ packages: nan: 2.17.0 dev: true + /tree-sitter@0.20.6: + resolution: {integrity: sha512-GxJodajVpfgb3UREzzIbtA1hyRnTxVbWVXrbC6sk4xTMH5ERMBJk9HJNq4c8jOJeUaIOmLcwg+t6mez/PDvGqg==} + requiresBuild: true + dependencies: + nan: 2.18.0 + prebuild-install: 7.1.1 + dev: true + /treeverse@3.0.0: resolution: {integrity: sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -14592,6 +14683,19 @@ packages: y18n: 5.0.8 yargs-parser: 21.1.1 + /yargs@17.7.2: + resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} + engines: {node: '>=12'} + dependencies: + cliui: 8.0.1 + escalade: 3.1.1 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + dev: false + /yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} From 89ae241bf7f74ca77b0ad03b38c8a45e6aaa0470 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sat, 30 Dec 2023 16:45:03 +0100 Subject: [PATCH 005/195] some styling --- packages/haskell/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/haskell/index.html b/packages/haskell/index.html index 23d1c4a6..9883b1b9 100644 --- a/packages/haskell/index.html +++ b/packages/haskell/index.html @@ -7,8 +7,8 @@ Tree sitter test - -
+ +
From eefd8b37b11b3b2f2b74ecafbb86a6a85795175f Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sat, 30 Dec 2023 16:48:21 +0100 Subject: [PATCH 006/195] ignore their wasm file --- packages/haskell/.gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/haskell/.gitignore b/packages/haskell/.gitignore index aa33e831..75d4123f 100644 --- a/packages/haskell/.gitignore +++ b/packages/haskell/.gitignore @@ -25,4 +25,5 @@ dist-ssr public/tree-sitter.wasm public/tree-sitter-haskell.wasm -public/tree-sitter-haskell_mine.wasm \ No newline at end of file +public/tree-sitter-haskell_mine.wasm +public/tree-sitter-haskell_theirs.wasm \ No newline at end of file From 8f06bc4b57dd7b6610c2766e428597483c726d72 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Mon, 1 Apr 2024 02:59:17 +0200 Subject: [PATCH 007/195] add swing + swingBy --- packages/core/pattern.mjs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index daacc946..8ab308e4 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -2110,6 +2110,24 @@ export const segment = register('segment', function (rate, pat) { return pat.struct(pure(true)._fast(rate)).setTactus(rate); }); +/** + * The function `swingBy x n` breaks each cycle into `n` slices, and then delays events in the second half of each slice by the amount `x`, which is relative to the size of the (half) slice. So if `x` is 0 it does nothing, `0.5` delays for half the note duration, and 1 will wrap around to doing nothing again. The end result is a shuffle or swing-like rhythm + * @param {number} subdivision + * @param {number} offset + * @example + * s("hh*8").swingBy(1/3, 4) + */ +export const swingBy = register('swingBy', (swing, n, pat) => pat.inside(n, late(seq(0, swing / 2)))); + +/** + * Shorthand for swingBy with 1/3: + * @param {number} subdivision + * @example + * s("hh*8").swing(4) + * // s("hh*8").swingBy(1/3, 4) + */ +export const swing = register('swing', (n, pat) => pat.swingBy(1 / 3, n)); + /** * Swaps 1s and 0s in a binary pattern. * @name invert From 16851cf8f8a4411c54261c505bfd0c5e09691a4b Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Mon, 1 Apr 2024 03:01:04 +0200 Subject: [PATCH 008/195] snap --- test/__snapshots__/examples.test.mjs.snap | 106 ++++++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index 27074590..1d2af9de 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -7298,6 +7298,112 @@ exports[`runs examples > example "sustain" example index 0 1`] = ` ] `; +exports[`runs examples > example "swing" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | s:hh ]", + "[ 1/24 ⇜ (1/8 → 1/6) | s:hh ]", + "[ (1/6 → 1/4) ⇝ 7/24 | s:hh ]", + "[ 1/4 → 3/8 | s:hh ]", + "[ 7/24 ⇜ (3/8 → 5/12) | s:hh ]", + "[ (5/12 → 1/2) ⇝ 13/24 | s:hh ]", + "[ 1/2 → 5/8 | s:hh ]", + "[ 13/24 ⇜ (5/8 → 2/3) | s:hh ]", + "[ (2/3 → 3/4) ⇝ 19/24 | s:hh ]", + "[ 3/4 → 7/8 | s:hh ]", + "[ 19/24 ⇜ (7/8 → 11/12) | s:hh ]", + "[ (11/12 → 1/1) ⇝ 25/24 | s:hh ]", + "[ 1/1 → 9/8 | s:hh ]", + "[ 25/24 ⇜ (9/8 → 7/6) | s:hh ]", + "[ (7/6 → 5/4) ⇝ 31/24 | s:hh ]", + "[ 5/4 → 11/8 | s:hh ]", + "[ 31/24 ⇜ (11/8 → 17/12) | s:hh ]", + "[ (17/12 → 3/2) ⇝ 37/24 | s:hh ]", + "[ 3/2 → 13/8 | s:hh ]", + "[ 37/24 ⇜ (13/8 → 5/3) | s:hh ]", + "[ (5/3 → 7/4) ⇝ 43/24 | s:hh ]", + "[ 7/4 → 15/8 | s:hh ]", + "[ 43/24 ⇜ (15/8 → 23/12) | s:hh ]", + "[ (23/12 → 2/1) ⇝ 49/24 | s:hh ]", + "[ 2/1 → 17/8 | s:hh ]", + "[ 49/24 ⇜ (17/8 → 13/6) | s:hh ]", + "[ (13/6 → 9/4) ⇝ 55/24 | s:hh ]", + "[ 9/4 → 19/8 | s:hh ]", + "[ 55/24 ⇜ (19/8 → 29/12) | s:hh ]", + "[ (29/12 → 5/2) ⇝ 61/24 | s:hh ]", + "[ 5/2 → 21/8 | s:hh ]", + "[ 61/24 ⇜ (21/8 → 8/3) | s:hh ]", + "[ (8/3 → 11/4) ⇝ 67/24 | s:hh ]", + "[ 11/4 → 23/8 | s:hh ]", + "[ 67/24 ⇜ (23/8 → 35/12) | s:hh ]", + "[ (35/12 → 3/1) ⇝ 73/24 | s:hh ]", + "[ 3/1 → 25/8 | s:hh ]", + "[ 73/24 ⇜ (25/8 → 19/6) | s:hh ]", + "[ (19/6 → 13/4) ⇝ 79/24 | s:hh ]", + "[ 13/4 → 27/8 | s:hh ]", + "[ 79/24 ⇜ (27/8 → 41/12) | s:hh ]", + "[ (41/12 → 7/2) ⇝ 85/24 | s:hh ]", + "[ 7/2 → 29/8 | s:hh ]", + "[ 85/24 ⇜ (29/8 → 11/3) | s:hh ]", + "[ (11/3 → 15/4) ⇝ 91/24 | s:hh ]", + "[ 15/4 → 31/8 | s:hh ]", + "[ 91/24 ⇜ (31/8 → 47/12) | s:hh ]", + "[ (47/12 → 4/1) ⇝ 97/24 | s:hh ]", +] +`; + +exports[`runs examples > example "swingBy" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | s:hh ]", + "[ 1/24 ⇜ (1/8 → 1/6) | s:hh ]", + "[ (1/6 → 1/4) ⇝ 7/24 | s:hh ]", + "[ 1/4 → 3/8 | s:hh ]", + "[ 7/24 ⇜ (3/8 → 5/12) | s:hh ]", + "[ (5/12 → 1/2) ⇝ 13/24 | s:hh ]", + "[ 1/2 → 5/8 | s:hh ]", + "[ 13/24 ⇜ (5/8 → 2/3) | s:hh ]", + "[ (2/3 → 3/4) ⇝ 19/24 | s:hh ]", + "[ 3/4 → 7/8 | s:hh ]", + "[ 19/24 ⇜ (7/8 → 11/12) | s:hh ]", + "[ (11/12 → 1/1) ⇝ 25/24 | s:hh ]", + "[ 1/1 → 9/8 | s:hh ]", + "[ 25/24 ⇜ (9/8 → 7/6) | s:hh ]", + "[ (7/6 → 5/4) ⇝ 31/24 | s:hh ]", + "[ 5/4 → 11/8 | s:hh ]", + "[ 31/24 ⇜ (11/8 → 17/12) | s:hh ]", + "[ (17/12 → 3/2) ⇝ 37/24 | s:hh ]", + "[ 3/2 → 13/8 | s:hh ]", + "[ 37/24 ⇜ (13/8 → 5/3) | s:hh ]", + "[ (5/3 → 7/4) ⇝ 43/24 | s:hh ]", + "[ 7/4 → 15/8 | s:hh ]", + "[ 43/24 ⇜ (15/8 → 23/12) | s:hh ]", + "[ (23/12 → 2/1) ⇝ 49/24 | s:hh ]", + "[ 2/1 → 17/8 | s:hh ]", + "[ 49/24 ⇜ (17/8 → 13/6) | s:hh ]", + "[ (13/6 → 9/4) ⇝ 55/24 | s:hh ]", + "[ 9/4 → 19/8 | s:hh ]", + "[ 55/24 ⇜ (19/8 → 29/12) | s:hh ]", + "[ (29/12 → 5/2) ⇝ 61/24 | s:hh ]", + "[ 5/2 → 21/8 | s:hh ]", + "[ 61/24 ⇜ (21/8 → 8/3) | s:hh ]", + "[ (8/3 → 11/4) ⇝ 67/24 | s:hh ]", + "[ 11/4 → 23/8 | s:hh ]", + "[ 67/24 ⇜ (23/8 → 35/12) | s:hh ]", + "[ (35/12 → 3/1) ⇝ 73/24 | s:hh ]", + "[ 3/1 → 25/8 | s:hh ]", + "[ 73/24 ⇜ (25/8 → 19/6) | s:hh ]", + "[ (19/6 → 13/4) ⇝ 79/24 | s:hh ]", + "[ 13/4 → 27/8 | s:hh ]", + "[ 79/24 ⇜ (27/8 → 41/12) | s:hh ]", + "[ (41/12 → 7/2) ⇝ 85/24 | s:hh ]", + "[ 7/2 → 29/8 | s:hh ]", + "[ 85/24 ⇜ (29/8 → 11/3) | s:hh ]", + "[ (11/3 → 15/4) ⇝ 91/24 | s:hh ]", + "[ 15/4 → 31/8 | s:hh ]", + "[ 91/24 ⇜ (31/8 → 47/12) | s:hh ]", + "[ (47/12 → 4/1) ⇝ 97/24 | s:hh ]", +] +`; + exports[`runs examples > example "timecat" example index 0 1`] = ` [ "[ 0/1 → 3/4 | note:e3 ]", From 97d292adbbdc2bebab832926d16d5bd89e124735 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 21:32:39 +0200 Subject: [PATCH 009/195] add swing / swingBy to time modifiers page --- website/src/pages/learn/time-modifiers.mdx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/website/src/pages/learn/time-modifiers.mdx b/website/src/pages/learn/time-modifiers.mdx index 1baef9ea..7419bcfa 100644 --- a/website/src/pages/learn/time-modifiers.mdx +++ b/website/src/pages/learn/time-modifiers.mdx @@ -106,4 +106,12 @@ Some of these have equivalent operators in the Mini Notation: +## swingBy + + + +## swing + + + Apart from modifying time, there are ways to [Control Parameters](/functions/value-modifiers/). From fde0da3b195c0c2863aca24668fc3e2198504376 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 22:43:35 +0200 Subject: [PATCH 010/195] dont ignore hydra.mjs in eslint + fix lint --- .eslintignore | 1 - packages/hydra/hydra.mjs | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.eslintignore b/.eslintignore index 7d807b65..9f6d5035 100644 --- a/.eslintignore +++ b/.eslintignore @@ -20,5 +20,4 @@ vite.config.js **/dist /src-tauri/target/**/* reverbGen.mjs -hydra.mjs jsdoc-synonyms.js \ No newline at end of file diff --git a/packages/hydra/hydra.mjs b/packages/hydra/hydra.mjs index 13d08de6..91401034 100644 --- a/packages/hydra/hydra.mjs +++ b/packages/hydra/hydra.mjs @@ -1,5 +1,5 @@ import { getDrawContext } from '@strudel/draw'; -import { controls } from '@strudel/core'; +import { controls, getTime } from '@strudel/core'; let latestOptions; let hydra; @@ -27,6 +27,7 @@ export async function initHydra(options = {}) { hydraConfig.canvas = canvas; await import(/* @vite-ignore */ src); + /* eslint-disable-next-line */ hydra = new Hydra(hydraConfig); if (feedStrudel) { const { canvas } = getDrawContext(); From d06b70c28d3e153a727653c38c3f0b56884e1cba Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 23:02:42 +0200 Subject: [PATCH 011/195] fix: call setTime in initStrudel + return promise with scheduler --- packages/web/web.mjs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/web/web.mjs b/packages/web/web.mjs index 660acf26..2c07d2a6 100644 --- a/packages/web/web.mjs +++ b/packages/web/web.mjs @@ -5,7 +5,7 @@ export * from '@strudel/transpiler'; export * from '@strudel/mini'; export * from '@strudel/tonal'; export * from '@strudel/webaudio'; -import { Pattern, evalScope } from '@strudel/core'; +import { Pattern, evalScope, setTime } from '@strudel/core'; import { initAudioOnFirstClick, registerSynthSounds, webaudioScheduler } from '@strudel/webaudio'; // import { registerSoundfonts } from '@strudel/soundfonts'; import { evaluate as _evaluate } from '@strudel/transpiler'; @@ -33,11 +33,14 @@ export function initStrudel(options = {}) { miniAllStrings(); const { prebake, ...schedulerOptions } = options; + scheduler = webaudioScheduler(schedulerOptions); initDone = (async () => { await defaultPrebake(); await prebake?.(); + return scheduler; })(); - scheduler = webaudioScheduler(schedulerOptions); + setTime(() => scheduler.now()); + return initDone; } window.initStrudel = initStrudel; From 610c848ff4632b1924f5b78b8651d190e21ae906 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 23:06:02 +0200 Subject: [PATCH 012/195] fix: reify hydra pattern --- packages/hydra/hydra.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/hydra/hydra.mjs b/packages/hydra/hydra.mjs index 91401034..8f6d9d8e 100644 --- a/packages/hydra/hydra.mjs +++ b/packages/hydra/hydra.mjs @@ -47,4 +47,4 @@ export function clearHydra() { globalThis.shape = controls.shape; } -export const H = (p) => () => p.queryArc(getTime(), getTime())[0].value; +export const H = (p) => () => reify(p).queryArc(getTime(), getTime())[0].value; From 3a4ffb13ad6b7d6f2b394ee3ce72316e57e08e05 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 23:48:08 +0200 Subject: [PATCH 013/195] add more info on using strings for patterns in web package --- packages/web/README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/web/README.md b/packages/web/README.md index 8b567729..659c8271 100644 --- a/packages/web/README.md +++ b/packages/web/README.md @@ -72,7 +72,13 @@ document.getElementById('play').addEventListener('stop', There is a tiny difference between the [Strudel REPL](https://strudel.cc/) and `@strudel/web`. In the REPL you can use 'single quotes' for regular JS strings and "double quotes" for mini notation patterns. In `@strudel/web`, it does not matter which types of quotes you're using. -There will probably be an escapte hatch for that in the future. + +This difference means that you cannot call pattern methods on raw strings, for example `"1 2 3".slow(2)`. +To make it work you can either: + +1. Use the `evaluate` function, which behaves exactly like the Strudel REPL, interpreting double quoted strings as mini notation. +2. wrap the string with `m`: `m("1 2 3").slow(2)` +3. wrap the string in a control function: `n("1 2 3").slow(2)` depending on your context. ## More Examples From 915a4d2149ca33943e22ef752088e06cfe6ceb2f Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 3 Apr 2024 23:53:25 +0200 Subject: [PATCH 014/195] fix: example encoding for testing builds locally without server --- examples/buildless/headless-simple.html | 25 ++++++++---- examples/buildless/headless-with-samples.html | 38 +++++++++++-------- 2 files changed, 40 insertions(+), 23 deletions(-) diff --git a/examples/buildless/headless-simple.html b/examples/buildless/headless-simple.html index 15a56161..768765d6 100644 --- a/examples/buildless/headless-simple.html +++ b/examples/buildless/headless-simple.html @@ -1,9 +1,18 @@ - - - - + + + + + + + + + + + + + diff --git a/examples/buildless/headless-with-samples.html b/examples/buildless/headless-with-samples.html index 18b5e379..1915cd54 100644 --- a/examples/buildless/headless-with-samples.html +++ b/examples/buildless/headless-with-samples.html @@ -1,16 +1,24 @@ - - - - - - + + + + + + + + + + + + + + From 6ff7697cfda05188caabf575fbdc68f425cfc59a Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 4 Apr 2024 00:03:32 +0200 Subject: [PATCH 015/195] fix: use foreground color for pianoroll playhead --- packages/draw/pianoroll.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/draw/pianoroll.mjs b/packages/draw/pianoroll.mjs index 1bdf81c4..247213b4 100644 --- a/packages/draw/pianoroll.mjs +++ b/packages/draw/pianoroll.mjs @@ -108,7 +108,7 @@ export function pianoroll({ active = getTheme().foreground, background = 'transparent', smear = 0, - playheadColor = 'white', + playheadColor = getTheme().foreground, minMidi = 10, maxMidi = 90, autorange = 0, From 18abcaccbb844438b9948f4700079471255e1a9f Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 4 Apr 2024 00:03:43 +0200 Subject: [PATCH 016/195] add fallback theme --- packages/draw/draw.mjs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/draw/draw.mjs b/packages/draw/draw.mjs index cfd2ce75..81123f46 100644 --- a/packages/draw/draw.mjs +++ b/packages/draw/draw.mjs @@ -191,7 +191,16 @@ export function getComputedPropertyValue(name) { return getComputedStyle(document.documentElement).getPropertyValue(name); } -let theme = {}; +let theme = { + background: '#222', + foreground: '#75baff', + caret: '#ffcc00', + selection: 'rgba(128, 203, 196, 0.5)', + selectionMatch: '#036dd626', + lineHighlight: '#00000050', + gutterBackground: 'transparent', + gutterForeground: '#8a919966', +}; export function getTheme() { return theme; } From ca8707f32a626d250a498987937400cd2bfe9420 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 4 Apr 2024 00:13:37 +0200 Subject: [PATCH 017/195] cooler example --- examples/buildless/headless-simple.html | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/examples/buildless/headless-simple.html b/examples/buildless/headless-simple.html index 768765d6..61533447 100644 --- a/examples/buildless/headless-simple.html +++ b/examples/buildless/headless-simple.html @@ -2,16 +2,29 @@ - - - + + From 0ba4be0571834b7d0729ca2715238f76df7bcd0d Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 4 Apr 2024 00:13:43 +0200 Subject: [PATCH 018/195] bg --- examples/buildless/headless-with-samples.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/buildless/headless-with-samples.html b/examples/buildless/headless-with-samples.html index 1915cd54..3ac6d42e 100644 --- a/examples/buildless/headless-with-samples.html +++ b/examples/buildless/headless-with-samples.html @@ -2,10 +2,10 @@ - - + + From a4897adb831b9ad0e4ed0c53bead73a497b90e52 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 4 Apr 2024 00:38:08 +0200 Subject: [PATCH 019/195] fix: import --- packages/hydra/hydra.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/hydra/hydra.mjs b/packages/hydra/hydra.mjs index 8f6d9d8e..2cb265c2 100644 --- a/packages/hydra/hydra.mjs +++ b/packages/hydra/hydra.mjs @@ -1,5 +1,5 @@ import { getDrawContext } from '@strudel/draw'; -import { controls, getTime } from '@strudel/core'; +import { controls, getTime, reify } from '@strudel/core'; let latestOptions; let hydra; From 93d151b943872f2c8f14dd51ea6aca55b828fdcb Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Wed, 17 Apr 2024 12:37:19 +0200 Subject: [PATCH 020/195] anonymous patterns + muting with _ --- packages/core/repl.mjs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/core/repl.mjs b/packages/core/repl.mjs index 3a2e6bd6..5b7bcd71 100644 --- a/packages/core/repl.mjs +++ b/packages/core/repl.mjs @@ -54,10 +54,12 @@ export function repl({ const scheduler = sync && typeof SharedWorker != 'undefined' ? new NeoCyclist(schedulerOptions) : new Cyclist(schedulerOptions); let pPatterns = {}; + let anonymousIndex = 0; let allTransform; const hush = function () { pPatterns = {}; + anonymousIndex = 0; allTransform = undefined; return silence; }; @@ -82,6 +84,15 @@ export function repl({ // set pattern methods that use this repl via closure const injectPatternMethods = () => { Pattern.prototype.p = function (id) { + if (id.startsWith('_') || id.endsWith('_')) { + // allows muting a pattern x with x_ or _x + return silence; + } + if (id === '$') { + // allows adding anonymous patterns with $: + id = `$${anonymousIndex}`; + anonymousIndex++; + } pPatterns[id] = this; return this; }; From a194180130e83bf330a56794376bab594af7fcb4 Mon Sep 17 00:00:00 2001 From: "Alexandre G.-Raymond" Date: Sun, 21 Apr 2024 11:03:55 +0200 Subject: [PATCH 021/195] Fix wchooseCycles not picking the whole pattern (#1061) --- packages/core/signal.mjs | 4 +- test/__snapshots__/examples.test.mjs.snap | 59 +++++++++++++++++++++-- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/packages/core/signal.mjs b/packages/core/signal.mjs index 7c931aff..375c4f67 100644 --- a/packages/core/signal.mjs +++ b/packages/core/signal.mjs @@ -486,8 +486,10 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs); * @returns {Pattern} * @example * wchooseCycles(["bd",10], ["hh",1], ["sd",1]).s().fast(8) + * @example + * wchooseCycles(["bd bd bd",5], ["hh hh hh",3], ["sd sd sd",1]).fast(4).s() */ -export const wchooseCycles = (...pairs) => _wchooseWith(rand, ...pairs).innerJoin(); +export const wchooseCycles = (...pairs) => _wchooseWith(rand.segment(1), ...pairs).innerJoin(); export const wrandcat = wchooseCycles; diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index 1d2af9de..94c390b6 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -7985,12 +7985,12 @@ exports[`runs examples > example "wchooseCycles" example index 0 1`] = ` "[ 3/8 → 1/2 | s:bd ]", "[ 1/2 → 5/8 | s:bd ]", "[ 5/8 → 3/4 | s:bd ]", - "[ 3/4 → 7/8 | s:bd ]", + "[ 3/4 → 7/8 | s:sd ]", "[ 7/8 → 1/1 | s:bd ]", "[ 1/1 → 9/8 | s:bd ]", "[ 9/8 → 5/4 | s:bd ]", "[ 5/4 → 11/8 | s:bd ]", - "[ 11/8 → 3/2 | s:bd ]", + "[ 11/8 → 3/2 | s:sd ]", "[ 3/2 → 13/8 | s:bd ]", "[ 13/8 → 7/4 | s:bd ]", "[ 7/4 → 15/8 | s:bd ]", @@ -8001,7 +8001,7 @@ exports[`runs examples > example "wchooseCycles" example index 0 1`] = ` "[ 19/8 → 5/2 | s:bd ]", "[ 5/2 → 21/8 | s:bd ]", "[ 21/8 → 11/4 | s:bd ]", - "[ 11/4 → 23/8 | s:bd ]", + "[ 11/4 → 23/8 | s:hh ]", "[ 23/8 → 3/1 | s:bd ]", "[ 3/1 → 25/8 | s:bd ]", "[ 25/8 → 13/4 | s:bd ]", @@ -8014,6 +8014,59 @@ exports[`runs examples > example "wchooseCycles" example index 0 1`] = ` ] `; +exports[`runs examples > example "wchooseCycles" example index 1 1`] = ` +[ + "[ 0/1 → 1/12 | s:bd ]", + "[ 1/12 → 1/6 | s:bd ]", + "[ 1/6 → 1/4 | s:bd ]", + "[ 1/4 → 1/3 | s:hh ]", + "[ 1/3 → 5/12 | s:hh ]", + "[ 5/12 → 1/2 | s:hh ]", + "[ 1/2 → 7/12 | s:bd ]", + "[ 7/12 → 2/3 | s:bd ]", + "[ 2/3 → 3/4 | s:bd ]", + "[ 3/4 → 5/6 | s:bd ]", + "[ 5/6 → 11/12 | s:bd ]", + "[ 11/12 → 1/1 | s:bd ]", + "[ 1/1 → 13/12 | s:bd ]", + "[ 13/12 → 7/6 | s:bd ]", + "[ 7/6 → 5/4 | s:bd ]", + "[ 5/4 → 4/3 | s:bd ]", + "[ 4/3 → 17/12 | s:bd ]", + "[ 17/12 → 3/2 | s:bd ]", + "[ 3/2 → 19/12 | s:sd ]", + "[ 19/12 → 5/3 | s:sd ]", + "[ 5/3 → 7/4 | s:sd ]", + "[ 7/4 → 11/6 | s:bd ]", + "[ 11/6 → 23/12 | s:bd ]", + "[ 23/12 → 2/1 | s:bd ]", + "[ 2/1 → 25/12 | s:hh ]", + "[ 25/12 → 13/6 | s:hh ]", + "[ 13/6 → 9/4 | s:hh ]", + "[ 9/4 → 7/3 | s:hh ]", + "[ 7/3 → 29/12 | s:hh ]", + "[ 29/12 → 5/2 | s:hh ]", + "[ 5/2 → 31/12 | s:hh ]", + "[ 31/12 → 8/3 | s:hh ]", + "[ 8/3 → 11/4 | s:hh ]", + "[ 11/4 → 17/6 | s:sd ]", + "[ 17/6 → 35/12 | s:sd ]", + "[ 35/12 → 3/1 | s:sd ]", + "[ 3/1 → 37/12 | s:bd ]", + "[ 37/12 → 19/6 | s:bd ]", + "[ 19/6 → 13/4 | s:bd ]", + "[ 13/4 → 10/3 | s:bd ]", + "[ 10/3 → 41/12 | s:bd ]", + "[ 41/12 → 7/2 | s:bd ]", + "[ 7/2 → 43/12 | s:hh ]", + "[ 43/12 → 11/3 | s:hh ]", + "[ 11/3 → 15/4 | s:hh ]", + "[ 15/4 → 23/6 | s:bd ]", + "[ 23/6 → 47/12 | s:bd ]", + "[ 47/12 → 4/1 | s:bd ]", +] +`; + exports[`runs examples > example "when" example index 0 1`] = ` [ "[ 0/1 → 1/3 | note:c3 ]", From 0a3694fb825c2dfc08fa77502eb0c59db8729002 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Sun, 21 Apr 2024 21:17:07 +0100 Subject: [PATCH 022/195] Stepwise functions from Tidal (#1060) * rename new stepwise functions to match tidal, adding s_expand and s_contract * created a `stepJoin` for stepwise patternification --- packages/core/fraction.mjs | 4 + packages/core/pattern.mjs | 200 +++++++++++++++------- packages/core/test/pattern.test.mjs | 38 ++-- packages/core/util.mjs | 30 ++++ test/__snapshots__/examples.test.mjs.snap | 150 ++++++++++++++++ 5 files changed, 344 insertions(+), 78 deletions(-) diff --git a/packages/core/fraction.mjs b/packages/core/fraction.mjs index 43dc84ef..ce614246 100644 --- a/packages/core/fraction.mjs +++ b/packages/core/fraction.mjs @@ -47,6 +47,10 @@ Fraction.prototype.eq = function (other) { return this.compare(other) == 0; }; +Fraction.prototype.ne = function (other) { + return this.compare(other) != 0; +}; + Fraction.prototype.max = function (other) { return this.gt(other) ? this : other; }; diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 4762ab85..8f2c4362 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -10,7 +10,18 @@ import Hap from './hap.mjs'; import State from './state.mjs'; import { unionWithObj } from './value.mjs'; -import { compose, removeUndefineds, flatten, id, listRange, curry, _mod, numeralArgs, parseNumeral } from './util.mjs'; +import { + uniqsortr, + removeUndefineds, + flatten, + id, + listRange, + curry, + _mod, + numeralArgs, + parseNumeral, + pairs, +} from './util.mjs'; import drawLine from './drawLine.mjs'; import { logger } from './logger.mjs'; @@ -48,6 +59,10 @@ export class Pattern { return this; } + withTactus(f) { + return new Pattern(this.query, this.tactus === undefined ? undefined : f(this.tactus)); + } + ////////////////////////////////////////////////////////////////////// // Haskell-style functor, applicative and monadic operations @@ -1137,24 +1152,24 @@ function _composeOp(a, b, func) { export const polyrhythm = stack; export const pr = stack; -export const pm = polymeter; +export const pm = s_polymeter; // methods that create patterns, which are added to patternified Pattern methods // TODO: remove? this is only used in old transpiler (shapeshifter) -Pattern.prototype.factories = { - pure, - stack, - slowcat, - fastcat, - cat, - timecat, - sequence, - seq, - polymeter, - pm, - polyrhythm, - pr, -}; +// Pattern.prototype.factories = { +// pure, +// stack, +// slowcat, +// fastcat, +// cat, +// timecat, +// sequence, +// seq, +// polymeter, +// pm, +// polyrhythm, +// pr, +// }; // the magic happens in Pattern constructor. Keeping this in prototype enables adding methods from the outside (e.g. see tonal.ts) // Elemental patterns @@ -1254,14 +1269,14 @@ function _stackWith(func, pats) { export function stackLeft(...pats) { return _stackWith( - (tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : timecat(pat, gap(tactus.sub(pat.tactus))))), + (tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : s_cat(pat, gap(tactus.sub(pat.tactus))))), pats, ); } export function stackRight(...pats) { return _stackWith( - (tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : timecat(gap(tactus.sub(pat.tactus)), pat))), + (tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : s_cat(gap(tactus.sub(pat.tactus)), pat))), pats, ); } @@ -1274,7 +1289,7 @@ export function stackCentre(...pats) { return pat; } const g = gap(tactus.sub(pat.tactus).div(2)); - return timecat(g, pat, g); + return s_cat(g, pat, g); }), pats, ); @@ -1288,7 +1303,7 @@ export function stackBy(by, ...pats) { left: stackLeft, right: stackRight, expand: stack, - repeat: (...args) => polymeterSteps(tactus, ...args), + repeat: (...args) => s_polymeterSteps(tactus, ...args), }; return by .inhabit(lookup) @@ -1374,7 +1389,7 @@ export function cat(...pats) { export function arrange(...sections) { const total = sections.reduce((sum, [cycles]) => sum + cycles, 0); sections = sections.map(([cycles, section]) => [cycles, section.fast(cycles)]); - return timecat(...sections).slow(total); + return s_cat(...sections).slow(total); } export function fastcat(...pats) { @@ -1454,7 +1469,7 @@ export const func = curry((a, b) => reify(b).func(a)); * @noAutocomplete * */ -export function register(name, func, patternify = true, preserveTactus = false) { +export function register(name, func, patternify = true, preserveTactus = false, join = (x) => x.innerJoin()) { if (Array.isArray(name)) { const result = {}; for (const name_item of name) { @@ -1491,7 +1506,7 @@ export function register(name, func, patternify = true, preserveTactus = false) return func(...args, pat); }; mapFn = curry(mapFn, null, arity - 1); - result = right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)).innerJoin(); + result = join(right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn))); } } if (preserveTactus) { @@ -1535,6 +1550,11 @@ export function register(name, func, patternify = true, preserveTactus = false) return curry(pfunc, null, arity); } +// Like register, but defaults to stepJoin +function stepRegister(name, func, patternify = true, preserveTactus = false, join = (x) => x.stepJoin()) { + return register(name, func, patternify, preserveTactus, join); +} + ////////////////////////////////////////////////////////////////////// // Numerical transformations @@ -2375,13 +2395,62 @@ Pattern.prototype.tag = function (tag) { // Tactus-related functions, i.e. ones that do stepwise // transformations +Pattern.prototype.stepJoin = function () { + const pp = this; + const first_t = s_cat(..._retime(_slices(pp.queryArc(0, 1)))).tactus; + const q = function (state) { + const shifted = pp.early(state.span.begin.sam()); + const haps = shifted.query(state.setSpan(new TimeSpan(Fraction(0), Fraction(1)))); + const pat = s_cat(..._retime(_slices(haps))); + return pat.query(state); + }; + return new Pattern(q, first_t); +}; + +export function _retime(timedHaps) { + const occupied_perc = timedHaps.filter((t, pat) => pat.tactus != undefined).reduce((a, b) => a.add(b), Fraction(0)); + const occupied_tactus = removeUndefineds(timedHaps.map((t, pat) => pat.tactus)).reduce( + (a, b) => a.add(b), + Fraction(0), + ); + const total_tactus = occupied_perc.eq(0) ? 0 : occupied_tactus.div(occupied_perc); + function adjust(dur, pat) { + if (pat.tactus === undefined) { + return [dur.mul(total_tactus), pat]; + } + return [pat.tactus, pat]; + } + return timedHaps.map((x) => adjust(...x)); +} + +export function _slices(haps) { + // slices evs = map (\s -> ((snd s - fst s), stack $ map value $ fit s evs)) + // $ pairs $ sort $ nubOrd $ 0:1:concatMap (\ev -> start (part ev):stop (part ev):[]) evs + const breakpoints = flatten(haps.map((hap) => [hap.part.begin, hap.part.end])); + const unique = uniqsortr([Fraction(0), Fraction(1), ...breakpoints]); + const slicespans = pairs(unique); + return slicespans.map((s) => [s[1].sub(s[0]), stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value))]); +} + +export function _fitslice(span, haps) { + return removeUndefineds(haps.map((hap) => _match(span, hap))); +} + +export function _match(span, hap_p) { + const subspan = span.intersection(hap_p.part); + if (subspan == undefined) { + return undefined; + } + return new Hap(hap_p.whole, subspan, hap_p.value, hap_p.context); +} + /** - * *EXPERIMENTAL* - Speeds a pattern up or down, to fit to the given metrical 'tactus'. + * *EXPERIMENTAL* - Speeds a pattern up or down, to fit to the given number of steps per cycle (aka tactus). * @example - * s("bd sd cp").toTactus(4) + * s("bd sd cp").steps(4) * // The same as s("{bd sd cp}%4") */ -export const toTactus = register('toTactus', function (targetTactus, pat) { +export const steps = register('steps', function (targetTactus, pat) { if (pat.tactus.eq(0)) { // avoid divide by zero.. return nothing; @@ -2415,14 +2484,14 @@ export function _polymeterListSteps(steps, ...args) { * Aligns one or more given patterns to the given number of steps per cycle. * This relies on patterns having coherent number of steps per cycle, * - * @name polymeterSteps + * @name s_polymeterSteps * @param {number} steps how many items are placed in one cycle * @param {any[]} patterns one or more patterns * @example * // the same as "{c d, e f g}%4" - * polymeterSteps(4, "c d", "e f g") + * s_polymeterSteps(4, "c d", "e f g") */ -export function polymeterSteps(steps, ...args) { +export function s_polymeterSteps(steps, ...args) { if (args.length == 0) { return silence; } @@ -2431,7 +2500,7 @@ export function polymeterSteps(steps, ...args) { return _polymeterListSteps(steps, ...args); } - return polymeter(...args).toTactus(steps); + return s_polymeter(...args).steps(steps); } /** @@ -2439,10 +2508,10 @@ export function polymeterSteps(steps, ...args) { * @synonyms pm * @example * // The same as "{c eb g, c2 g2}" - * polymeter("c eb g", "c2 g2") + * s_polymeter("c eb g", "c2 g2") * */ -export function polymeter(...args) { +export function s_polymeter(...args) { if (Array.isArray(args[0])) { // Support old behaviour return _polymeterListSteps(0, ...args); @@ -2461,16 +2530,16 @@ export function polymeter(...args) { /** Sequences patterns like `seq`, but each pattern has a length, relative to the whole. * This length can either be provided as a [length, pattern] pair, or inferred from - * the pattern's 'tactus', generally inferred by the mininotation. + * the pattern's 'tactus', generally inferred by the mininotation. Has the alias `timecat`. * @return {Pattern} * @example - * timecat([3,"e3"],[1, "g3"]).note() + * s_cat([3,"e3"],[1, "g3"]).note() * // the same as "e3@3 g3".note() * @example - * timecat("bd sd cp","hh hh").sound() + * s_cat("bd sd cp","hh hh").sound() * // the same as "bd sd cp hh hh".sound() */ -export function timecat(...timepats) { +export function s_cat(...timepats) { const findtactus = (x) => (Array.isArray(x) ? x : [x.tactus, x]); timepats = timepats.map(findtactus); if (timepats.length == 1) { @@ -2495,18 +2564,19 @@ export function timecat(...timepats) { return result; } -/** Deprecated alias for `timecat` */ -export const timeCat = timecat; +/** Aliases for `s_cat` */ +export const timecat = s_cat; +export const timeCat = s_cat; /** * *EXPERIMENTAL* - Concatenates patterns stepwise, according to their 'tactus'. - * Similar to `timecat`, but if an argument is a list, the whole pattern will be repeated for each element in the list. + * Similar to `s_cat`, but if an argument is a list, the whole pattern will alternate between the elements in the list. * * @return {Pattern} * @example - * stepcat(["bd cp", "mt"], "bd").sound() + * s_alt(["bd cp", "mt"], "bd").sound() */ -export function stepcat(...groups) { +export function s_alt(...groups) { groups = groups.map((a) => (Array.isArray(a) ? a.map(reify) : [reify(a)])); const cycles = lcm(...groups.map((x) => Fraction(x.length))); @@ -2517,7 +2587,7 @@ export function stepcat(...groups) { } result = result.filter((x) => x.tactus > 0); const tactus = result.reduce((a, b) => a.add(b.tactus), Fraction(0)); - result = timecat(...result); + result = s_cat(...result); result.tactus = tactus; return result; } @@ -2525,7 +2595,7 @@ export function stepcat(...groups) { /** * *EXPERIMENTAL* - Retains the given number of steps in a pattern (and dropping the rest), according to its 'tactus'. */ -export const stepwax = register('stepwax', function (i, pat) { +export const s_add = stepRegister('s_add', function (i, pat) { if (pat.tactus.lte(0)) { return nothing; } @@ -2553,18 +2623,26 @@ export const stepwax = register('stepwax', function (i, pat) { /** * *EXPERIMENTAL* - Removes the given number of steps from a pattern, according to its 'tactus'. */ -export const stepwane = register('stepwane', function (i, pat) { +export const s_sub = stepRegister('s_sub', function (i, pat) { i = Fraction(i); if (i.lt(0)) { - return pat.stepwax(Fraction(0).sub(pat.tactus.add(i))); + return pat.s_add(Fraction(0).sub(pat.tactus.add(i))); } - return pat.stepwax(pat.tactus.sub(i)); + return pat.s_add(pat.tactus.sub(i)); +}); + +export const s_expand = stepRegister('s_expand', function (factor, pat) { + return pat.withTactus((t) => t.mul(Fraction(factor))); +}); + +export const s_contract = stepRegister('s_contract', function (factor, pat) { + return pat.withTactus((t) => t.div(Fraction(factor))); }); /** * *EXPERIMENTAL* */ -Pattern.prototype.taperlist = function (amount, times) { +Pattern.prototype.s_taperlist = function (amount, times) { const pat = this; times = times - 1; @@ -2586,23 +2664,29 @@ Pattern.prototype.taperlist = function (amount, times) { } return list; }; -export const taperlist = (amount, times, pat) => pat.taperlist(amount, times); +export const s_taperlist = (amount, times, pat) => pat.s_taperlist(amount, times); /** * *EXPERIMENTAL* */ -export const steptaper = register('steptaper', function (amount, times, pat) { - const list = pat.taperlist(amount, times); - const result = timecat(...list); - result.tactus = list.reduce((a, b) => a.add(b.tactus), Fraction(0)); - return result; -}); +export const s_taper = register( + 's_taper', + function (amount, times, pat) { + const list = pat.s_taperlist(amount, times); + const result = s_cat(...list); + result.tactus = list.reduce((a, b) => a.add(b.tactus), Fraction(0)); + return result; + }, + true, + false, + (x) => x.stepJoin(), +); /** * *EXPERIMENTAL* */ -Pattern.prototype.steptour = function (...many) { - return stepcat( +Pattern.prototype.s_tour = function (...many) { + return s_cat( ...[].concat( ...many.map((x, i) => [...many.slice(0, many.length - i), this, ...many.slice(many.length - i)]), this, @@ -2611,8 +2695,8 @@ Pattern.prototype.steptour = function (...many) { ); }; -export const steptour = function (pat, ...many) { - return pat.steptour(...many); +export const s_tour = function (pat, ...many) { + return pat.s_tour(...many); }; ////////////////////////////////////////////////////////////////////// diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index 1ef90f73..b9848885 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -21,8 +21,8 @@ import { cat, sequence, palindrome, - polymeter, - polymeterSteps, + s_polymeter, + s_polymeterSteps, polyrhythm, silence, fast, @@ -603,18 +603,18 @@ describe('Pattern', () => { ); }); }); - describe('polymeter()', () => { + describe('s_polymeter()', () => { it('Can layer up cycles, stepwise, with lists', () => { - expect(polymeterSteps(3, ['d', 'e']).firstCycle()).toStrictEqual( + expect(s_polymeterSteps(3, ['d', 'e']).firstCycle()).toStrictEqual( fastcat(pure('d'), pure('e'), pure('d')).firstCycle(), ); - expect(polymeter(['a', 'b', 'c'], ['d', 'e']).fast(2).firstCycle()).toStrictEqual( + expect(s_polymeter(['a', 'b', 'c'], ['d', 'e']).fast(2).firstCycle()).toStrictEqual( stack(sequence('a', 'b', 'c', 'a', 'b', 'c'), sequence('d', 'e', 'd', 'e', 'd', 'e')).firstCycle(), ); }); it('Can layer up cycles, stepwise, with weighted patterns', () => { - sameFirst(polymeterSteps(3, sequence('a', 'b')).fast(2), sequence('a', 'b', 'a', 'b', 'a', 'b')); + sameFirst(s_polymeterSteps(3, sequence('a', 'b')).fast(2), sequence('a', 'b', 'a', 'b', 'a', 'b')); }); }); @@ -1138,28 +1138,26 @@ describe('Pattern', () => { ); }); }); - describe('steptaper', () => { + describe('s_taper', () => { it('can taper', () => { - expect(sameFirst(sequence(0, 1, 2, 3, 4).steptaper(1, 5), sequence(0, 1, 2, 3, 4, 0, 1, 2, 3, 0, 1, 2, 0, 1, 0))); + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_taper(1, 5), sequence(0, 1, 2, 3, 4, 0, 1, 2, 3, 0, 1, 2, 0, 1, 0))); }); it('can taper backwards', () => { - expect( - sameFirst(sequence(0, 1, 2, 3, 4).steptaper(-1, 5), sequence(0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4)), - ); + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_taper(-1, 5), sequence(0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4))); }); }); - describe('wax and wane, left', () => { - it('can wax from the left', () => { - expect(sameFirst(sequence(0, 1, 2, 3, 4).stepwax(2), sequence(0, 1))); + describe('s_add and s_sub, left', () => { + it('can add from the left', () => { + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_add(2), sequence(0, 1))); }); - it('can wane to the left', () => { - expect(sameFirst(sequence(0, 1, 2, 3, 4).stepwane(2), sequence(0, 1, 2))); + it('can sub to the left', () => { + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_sub(2), sequence(0, 1, 2))); }); - it('can wax from the right', () => { - expect(sameFirst(sequence(0, 1, 2, 3, 4).stepwax(-2), sequence(3, 4))); + it('can add from the right', () => { + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_add(-2), sequence(3, 4))); }); - it('can wane to the right', () => { - expect(sameFirst(sequence(0, 1, 2, 3, 4).stepwane(-2), sequence(2, 3, 4))); + it('can sub to the right', () => { + expect(sameFirst(sequence(0, 1, 2, 3, 4).s_sub(-2), sequence(2, 3, 4))); }); }); }); diff --git a/packages/core/util.mjs b/packages/core/util.mjs index 2c7b3d71..ff59cc90 100644 --- a/packages/core/util.mjs +++ b/packages/core/util.mjs @@ -231,6 +231,14 @@ export const splitAt = function (index, value) { export const zipWith = (f, xs, ys) => xs.map((n, i) => f(n, ys[i])); +export const pairs = function (xs) { + const result = []; + for (let i = 0; i < xs.length - 1; ++i) { + result.push([xs[i], xs[i + 1]]); + } + return result; +}; + export const clamp = (num, min, max) => Math.min(Math.max(num, min), max); /* solmization, not used yet */ @@ -289,6 +297,28 @@ export const sol2note = (n, notation = 'letters') => { return note + oct; }; +// Remove duplicates from list +export function uniq(a) { + var seen = {}; + return a.filter(function (item) { + return seen.hasOwn(item) ? false : (seen[item] = true); + }); +} + +// Remove duplicates from list, sorting in the process. Mutates argument! +export function uniqsort(a) { + return a.sort().filter(function (item, pos, ary) { + return !pos || item != ary[pos - 1]; + }); +} + +// rational version +export function uniqsortr(a) { + return a.sort().filter(function (item, pos, ary) { + return !pos || item.ne(ary[pos - 1]); + }); +} + // code hashing helpers export function unicodeToBase64(text) { diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index 94c390b6..30db05a2 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -5972,6 +5972,135 @@ exports[`runs examples > example "s" example index 1 1`] = ` ] `; +exports[`runs examples > example "s_alt" example index 0 1`] = ` +[ + "[ 0/1 → 1/5 | s:bd ]", + "[ 1/5 → 2/5 | s:cp ]", + "[ 2/5 → 3/5 | s:bd ]", + "[ 3/5 → 4/5 | s:mt ]", + "[ 4/5 → 1/1 | s:bd ]", + "[ 1/1 → 6/5 | s:bd ]", + "[ 6/5 → 7/5 | s:cp ]", + "[ 7/5 → 8/5 | s:bd ]", + "[ 8/5 → 9/5 | s:mt ]", + "[ 9/5 → 2/1 | s:bd ]", + "[ 2/1 → 11/5 | s:bd ]", + "[ 11/5 → 12/5 | s:cp ]", + "[ 12/5 → 13/5 | s:bd ]", + "[ 13/5 → 14/5 | s:mt ]", + "[ 14/5 → 3/1 | s:bd ]", + "[ 3/1 → 16/5 | s:bd ]", + "[ 16/5 → 17/5 | s:cp ]", + "[ 17/5 → 18/5 | s:bd ]", + "[ 18/5 → 19/5 | s:mt ]", + "[ 19/5 → 4/1 | s:bd ]", +] +`; + +exports[`runs examples > example "s_cat" example index 0 1`] = ` +[ + "[ 0/1 → 3/4 | note:e3 ]", + "[ 3/4 → 1/1 | note:g3 ]", + "[ 1/1 → 7/4 | note:e3 ]", + "[ 7/4 → 2/1 | note:g3 ]", + "[ 2/1 → 11/4 | note:e3 ]", + "[ 11/4 → 3/1 | note:g3 ]", + "[ 3/1 → 15/4 | note:e3 ]", + "[ 15/4 → 4/1 | note:g3 ]", +] +`; + +exports[`runs examples > example "s_cat" example index 1 1`] = ` +[ + "[ 0/1 → 1/5 | s:bd ]", + "[ 1/5 → 2/5 | s:sd ]", + "[ 2/5 → 3/5 | s:cp ]", + "[ 3/5 → 4/5 | s:hh ]", + "[ 4/5 → 1/1 | s:hh ]", + "[ 1/1 → 6/5 | s:bd ]", + "[ 6/5 → 7/5 | s:sd ]", + "[ 7/5 → 8/5 | s:cp ]", + "[ 8/5 → 9/5 | s:hh ]", + "[ 9/5 → 2/1 | s:hh ]", + "[ 2/1 → 11/5 | s:bd ]", + "[ 11/5 → 12/5 | s:sd ]", + "[ 12/5 → 13/5 | s:cp ]", + "[ 13/5 → 14/5 | s:hh ]", + "[ 14/5 → 3/1 | s:hh ]", + "[ 3/1 → 16/5 | s:bd ]", + "[ 16/5 → 17/5 | s:sd ]", + "[ 17/5 → 18/5 | s:cp ]", + "[ 18/5 → 19/5 | s:hh ]", + "[ 19/5 → 4/1 | s:hh ]", +] +`; + +exports[`runs examples > example "s_polymeter" example index 0 1`] = ` +[ + "[ 0/1 → 1/3 | c ]", + "[ 0/1 → 1/3 | c2 ]", + "[ 1/3 → 2/3 | eb ]", + "[ 1/3 → 2/3 | g2 ]", + "[ 2/3 → 1/1 | g ]", + "[ 2/3 → 1/1 | c2 ]", + "[ 1/1 → 4/3 | c ]", + "[ 1/1 → 4/3 | g2 ]", + "[ 4/3 → 5/3 | eb ]", + "[ 4/3 → 5/3 | c2 ]", + "[ 5/3 → 2/1 | g ]", + "[ 5/3 → 2/1 | g2 ]", + "[ 2/1 → 7/3 | c ]", + "[ 2/1 → 7/3 | c2 ]", + "[ 7/3 → 8/3 | eb ]", + "[ 7/3 → 8/3 | g2 ]", + "[ 8/3 → 3/1 | g ]", + "[ 8/3 → 3/1 | c2 ]", + "[ 3/1 → 10/3 | c ]", + "[ 3/1 → 10/3 | g2 ]", + "[ 10/3 → 11/3 | eb ]", + "[ 10/3 → 11/3 | c2 ]", + "[ 11/3 → 4/1 | g ]", + "[ 11/3 → 4/1 | g2 ]", +] +`; + +exports[`runs examples > example "s_polymeterSteps" example index 0 1`] = ` +[ + "[ 0/1 → 1/4 | c ]", + "[ 0/1 → 1/4 | e ]", + "[ 1/4 → 1/2 | d ]", + "[ 1/4 → 1/2 | f ]", + "[ 1/2 → 3/4 | c ]", + "[ 1/2 → 3/4 | g ]", + "[ 3/4 → 1/1 | d ]", + "[ 3/4 → 1/1 | e ]", + "[ 1/1 → 5/4 | c ]", + "[ 1/1 → 5/4 | f ]", + "[ 5/4 → 3/2 | d ]", + "[ 5/4 → 3/2 | g ]", + "[ 3/2 → 7/4 | c ]", + "[ 3/2 → 7/4 | e ]", + "[ 7/4 → 2/1 | d ]", + "[ 7/4 → 2/1 | f ]", + "[ 2/1 → 9/4 | c ]", + "[ 2/1 → 9/4 | g ]", + "[ 9/4 → 5/2 | d ]", + "[ 9/4 → 5/2 | e ]", + "[ 5/2 → 11/4 | c ]", + "[ 5/2 → 11/4 | f ]", + "[ 11/4 → 3/1 | d ]", + "[ 11/4 → 3/1 | g ]", + "[ 3/1 → 13/4 | c ]", + "[ 3/1 → 13/4 | e ]", + "[ 13/4 → 7/2 | d ]", + "[ 13/4 → 7/2 | f ]", + "[ 7/2 → 15/4 | c ]", + "[ 7/2 → 15/4 | g ]", + "[ 15/4 → 4/1 | d ]", + "[ 15/4 → 4/1 | e ]", +] +`; + exports[`runs examples > example "samples" example index 0 1`] = ` [ "[ 0/1 → 1/4 | s:bd ]", @@ -7112,6 +7241,27 @@ exports[`runs examples > example "stepcat" example index 0 1`] = ` ] `; +exports[`runs examples > example "steps" example index 0 1`] = ` +[ + "[ 0/1 → 1/4 | s:bd ]", + "[ 1/4 → 1/2 | s:sd ]", + "[ 1/2 → 3/4 | s:cp ]", + "[ 3/4 → 1/1 | s:bd ]", + "[ 1/1 → 5/4 | s:sd ]", + "[ 5/4 → 3/2 | s:cp ]", + "[ 3/2 → 7/4 | s:bd ]", + "[ 7/4 → 2/1 | s:sd ]", + "[ 2/1 → 9/4 | s:cp ]", + "[ 9/4 → 5/2 | s:bd ]", + "[ 5/2 → 11/4 | s:sd ]", + "[ 11/4 → 3/1 | s:cp ]", + "[ 3/1 → 13/4 | s:bd ]", + "[ 13/4 → 7/2 | s:sd ]", + "[ 7/2 → 15/4 | s:cp ]", + "[ 15/4 → 4/1 | s:bd ]", +] +`; + exports[`runs examples > example "striate" example index 0 1`] = ` [ "[ 0/1 → 1/6 | s:numbers n:0 begin:0 end:0.16666666666666666 ]", From 5d8eea72998986302a98a0ffd779145ad3fefa65 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Sun, 21 Apr 2024 17:29:29 -0400 Subject: [PATCH 023/195] fixed --- packages/core/util.mjs | 5 + packages/desktopbridge/oscbridge.mjs | 6 +- packages/midi/midi.mjs | 6 +- packages/osc/osc.mjs | 7 +- src-tauri/src/oscbridge.rs | 236 ++++++++++++++------------- 5 files changed, 137 insertions(+), 123 deletions(-) diff --git a/packages/core/util.mjs b/packages/core/util.mjs index 2c7b3d71..9ab9bc7c 100644 --- a/packages/core/util.mjs +++ b/packages/core/util.mjs @@ -61,6 +61,11 @@ export const valueToMidi = (value, fallbackValue) => { return fallbackValue; }; +// used to schedule external event like midi and osc out +export const getEventOffsetMs = (targetTime, currentTime) => { + return (targetTime - currentTime) * 1000; +}; + /** * @deprecated does not appear to be referenced or invoked anywhere in the codebase * @noAutocomplete diff --git a/packages/desktopbridge/oscbridge.mjs b/packages/desktopbridge/oscbridge.mjs index 935ec9ff..81366367 100644 --- a/packages/desktopbridge/oscbridge.mjs +++ b/packages/desktopbridge/oscbridge.mjs @@ -1,8 +1,8 @@ -import { parseNumeral, Pattern } from '@strudel/core'; +import { parseNumeral, Pattern, getEventOffsetMs } from '@strudel/core'; import { Invoke } from './utils.mjs'; Pattern.prototype.osc = function () { - return this.onTrigger(async (time, hap, currentTime, cps = 1) => { + return this.onTrigger(async (time, hap, currentTime, cps = 1, targetTime) => { hap.ensureObjectValue(); const cycle = hap.wholeOrPart().begin.valueOf(); const delta = hap.duration.valueOf(); @@ -13,7 +13,7 @@ Pattern.prototype.osc = function () { const params = []; - const timestamp = Math.round(Date.now() + (time - currentTime) * 1000); + const timestamp = Math.round(Date.now() + getEventOffsetMs(targetTime, currentTime)); Object.keys(controls).forEach((key) => { const val = controls[key]; diff --git a/packages/midi/midi.mjs b/packages/midi/midi.mjs index 89812b86..ef5c792a 100644 --- a/packages/midi/midi.mjs +++ b/packages/midi/midi.mjs @@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th */ import * as _WebMidi from 'webmidi'; -import { Pattern, isPattern, logger, ref } from '@strudel/core'; +import { Pattern, getEventOffsetMs, isPattern, logger, ref } from '@strudel/core'; import { noteToMidi } from '@strudel/core'; import { Note } from 'webmidi'; // if you use WebMidi from outside of this package, make sure to import that instance: @@ -120,9 +120,9 @@ Pattern.prototype.midi = function (output) { const device = getDevice(output, WebMidi.outputs); hap.ensureObjectValue(); //magic number to get audio engine to line up, can probably be calculated somehow - const latency = 0.034; + const latencyMs = 34; // passing a string with a +num into the webmidi api adds an offset to the current time https://webmidijs.org/api/classes/Output - const timeOffsetString = `+${(targetTime - currentTime + latency) * 1000}`; + const timeOffsetString = `${getEventOffsetMs(targetTime, currentTime) + latencyMs}`; // destructure value let { note, nrpnn, nrpv, ccn, ccv, midichan = 1, midicmd, gain = 1, velocity = 0.9 } = hap.value; diff --git a/packages/osc/osc.mjs b/packages/osc/osc.mjs index 14206e1d..5552a1c1 100644 --- a/packages/osc/osc.mjs +++ b/packages/osc/osc.mjs @@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th import OSC from 'osc-js'; -import { logger, parseNumeral, Pattern } from '@strudel/core'; +import { logger, parseNumeral, Pattern, getEventOffsetMs } from '@strudel/core'; let connection; // Promise function connect() { @@ -44,7 +44,7 @@ function connect() { * @returns Pattern */ Pattern.prototype.osc = function () { - return this.onTrigger(async (time, hap, currentTime, cps = 1) => { + return this.onTrigger(async (time, hap, currentTime, cps = 1, targetTime) => { hap.ensureObjectValue(); const osc = await connect(); const cycle = hap.wholeOrPart().begin.valueOf(); @@ -56,7 +56,8 @@ Pattern.prototype.osc = function () { const keyvals = Object.entries(controls).flat(); // time should be audio time of onset // currentTime should be current time of audio context (slightly before time) - const offset = (time - currentTime) * 1000; + const offset = getEventOffsetMs(targetTime, currentTime); + // timestamp in milliseconds used to trigger the osc bundle at a precise moment const ts = Math.floor(Date.now() + offset); const message = new OSC.Message('/dirt/play', ...keyvals); diff --git a/src-tauri/src/oscbridge.rs b/src-tauri/src/oscbridge.rs index 6060cd9d..c8dcf03a 100644 --- a/src-tauri/src/oscbridge.rs +++ b/src-tauri/src/oscbridge.rs @@ -1,22 +1,22 @@ -use rosc::{ encoder, OscTime }; -use rosc::{ OscMessage, OscPacket, OscType, OscBundle }; +use rosc::{encoder, OscTime}; +use rosc::{OscBundle, OscMessage, OscPacket, OscType}; use std::net::UdpSocket; -use std::time::Duration; -use std::sync::Arc; -use tokio::sync::{ mpsc, Mutex }; use serde::Deserialize; +use std::sync::Arc; use std::thread::sleep; +use std::time::Duration; +use tokio::sync::{mpsc, Mutex}; use crate::loggerbridge::Logger; pub struct OscMsg { - pub msg_buf: Vec, - pub timestamp: u64, + pub msg_buf: Vec, + pub timestamp: u64, } pub struct AsyncInputTransmit { - pub inner: Mutex>>, + pub inner: Mutex>>, } const UNIX_OFFSET: u64 = 2_208_988_800; // 70 years in seconds @@ -25,133 +25,141 @@ const NANOS_PER_SECOND: f64 = 1.0e9; const SECONDS_PER_NANO: f64 = 1.0 / NANOS_PER_SECOND; pub fn init( - logger: Logger, - async_input_receiver: mpsc::Receiver>, - mut async_output_receiver: mpsc::Receiver>, - async_output_transmitter: mpsc::Sender> + logger: Logger, + async_input_receiver: mpsc::Receiver>, + mut async_output_receiver: mpsc::Receiver>, + async_output_transmitter: mpsc::Sender>, ) { - tauri::async_runtime::spawn(async move { async_process_model(async_input_receiver, async_output_transmitter).await }); - let message_queue: Arc>> = Arc::new(Mutex::new(Vec::new())); - /* ........................................................... - Listen For incoming messages and add to queue - ............................................................*/ - let message_queue_clone = Arc::clone(&message_queue); - tauri::async_runtime::spawn(async move { - loop { - if let Some(package) = async_output_receiver.recv().await { - let mut message_queue = message_queue_clone.lock().await; - let messages = package; - for message in messages { - (*message_queue).push(message); - } - } - } - }); - - let message_queue_clone = Arc::clone(&message_queue); - tauri::async_runtime::spawn(async move { + tauri::async_runtime::spawn(async move { + async_process_model(async_input_receiver, async_output_transmitter).await + }); + let message_queue: Arc>> = Arc::new(Mutex::new(Vec::new())); /* ........................................................... - Open OSC Ports + Listen For incoming messages and add to queue ............................................................*/ - let sock = UdpSocket::bind("127.0.0.1:57122").unwrap(); - let to_addr = String::from("127.0.0.1:57120"); - sock.set_nonblocking(true).unwrap(); - sock.connect(to_addr).expect("could not connect to OSC address"); - - /* ........................................................... - Process queued messages - ............................................................*/ - - loop { - let mut message_queue = message_queue_clone.lock().await; - - message_queue.retain(|message| { - let result = sock.send(&message.msg_buf); - if result.is_err() { - logger.log( - format!("OSC Message failed to send, the server might no longer be available"), - "error".to_string() - ); + let message_queue_clone = Arc::clone(&message_queue); + tauri::async_runtime::spawn(async move { + loop { + if let Some(package) = async_output_receiver.recv().await { + let mut message_queue = message_queue_clone.lock().await; + let messages = package; + for message in messages { + (*message_queue).push(message); + } + } } - return false; - }); + }); - sleep(Duration::from_millis(1)); - } - }); + let message_queue_clone = Arc::clone(&message_queue); + tauri::async_runtime::spawn(async move { + /* ........................................................... + Open OSC Ports + ............................................................*/ + let sock = UdpSocket::bind("127.0.0.1:57122").unwrap(); + let to_addr = String::from("127.0.0.1:57120"); + sock.set_nonblocking(true).unwrap(); + sock.connect(to_addr) + .expect("could not connect to OSC address"); + + /* ........................................................... + Process queued messages + ............................................................*/ + + loop { + let mut message_queue = message_queue_clone.lock().await; + + message_queue.retain(|message| { + let result = sock.send(&message.msg_buf); + if result.is_err() { + logger.log( + format!( + "OSC Message failed to send, the server might no longer be available" + ), + "error".to_string(), + ); + } + return false; + }); + + sleep(Duration::from_millis(1)); + } + }); } pub async fn async_process_model( - mut input_reciever: mpsc::Receiver>, - output_transmitter: mpsc::Sender> + mut input_reciever: mpsc::Receiver>, + output_transmitter: mpsc::Sender>, ) -> Result<(), Box> { - while let Some(input) = input_reciever.recv().await { - let output = input; - output_transmitter.send(output).await?; - } - Ok(()) + while let Some(input) = input_reciever.recv().await { + let output = input; + output_transmitter.send(output).await?; + } + Ok(()) } #[derive(Deserialize)] pub struct Param { - name: String, - value: String, - valueisnumber: bool, + name: String, + value: String, + valueisnumber: bool, } #[derive(Deserialize)] pub struct MessageFromJS { - params: Vec, - timestamp: u64, - target: String, + params: Vec, + timestamp: u64, + target: String, } // Called from JS #[tauri::command] pub async fn sendosc( - messagesfromjs: Vec, - state: tauri::State<'_, AsyncInputTransmit> + messagesfromjs: Vec, + state: tauri::State<'_, AsyncInputTransmit>, ) -> Result<(), String> { - let async_proc_input_tx = state.inner.lock().await; - let mut messages_to_process: Vec = Vec::new(); - for m in messagesfromjs { - let mut args = Vec::new(); - for p in m.params { - args.push(OscType::String(p.name)); - if p.valueisnumber { - args.push(OscType::Float(p.value.parse().unwrap())); - } else { - args.push(OscType::String(p.value)); - } + let async_proc_input_tx = state.inner.lock().await; + let mut messages_to_process: Vec = Vec::new(); + for m in messagesfromjs { + let mut args = Vec::new(); + for p in m.params { + args.push(OscType::String(p.name)); + if p.valueisnumber { + args.push(OscType::Float(p.value.parse().unwrap())); + } else { + args.push(OscType::String(p.value)); + } + } + + let duration_since_epoch = + Duration::from_millis(m.timestamp) + Duration::new(UNIX_OFFSET, 0); + + let seconds = u32::try_from(duration_since_epoch.as_secs()) + .map_err(|_| "bit conversion failed for osc message timetag")?; + + let nanos = duration_since_epoch.subsec_nanos() as f64; + let fractional = (nanos * SECONDS_PER_NANO * TWO_POW_32).round() as u32; + + let timetag = OscTime::from((seconds, fractional)); + + let packet = OscPacket::Message(OscMessage { + addr: m.target, + args, + }); + + let bundle = OscBundle { + content: vec![packet], + timetag, + }; + + let msg_buf = encoder::encode(&OscPacket::Bundle(bundle)).unwrap(); + + let message_to_process = OscMsg { + msg_buf, + timestamp: m.timestamp, + }; + messages_to_process.push(message_to_process); } - let duration_since_epoch = Duration::from_millis(m.timestamp) + Duration::new(UNIX_OFFSET, 0); - - let seconds = u32 - ::try_from(duration_since_epoch.as_secs()) - .map_err(|_| "bit conversion failed for osc message timetag")?; - - let nanos = duration_since_epoch.subsec_nanos() as f64; - let fractional = (nanos * SECONDS_PER_NANO * TWO_POW_32).round() as u32; - - let timetag = OscTime::from((seconds, fractional)); - - let packet = OscPacket::Message(OscMessage { - addr: m.target, - args, - }); - - let bundle = OscBundle { - content: vec![packet], - timetag, - }; - - let msg_buf = encoder::encode(&OscPacket::Bundle(bundle)).unwrap(); - - let message_to_process = OscMsg { - msg_buf, - timestamp: m.timestamp, - }; - messages_to_process.push(message_to_process); - } - - async_proc_input_tx.send(messages_to_process).await.map_err(|e| e.to_string()) + async_proc_input_tx + .send(messages_to_process) + .await + .map_err(|e| e.to_string()) } From 57ad278137f4797fe8dfbd5666b5451a806529b5 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Sun, 21 Apr 2024 17:52:22 -0400 Subject: [PATCH 024/195] fixed osc server --- packages/core/util.mjs | 4 ++-- packages/desktopbridge/midibridge.mjs | 6 +++--- packages/midi/midi.mjs | 3 +-- packages/osc/server.js | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/core/util.mjs b/packages/core/util.mjs index 9ab9bc7c..e8e40398 100644 --- a/packages/core/util.mjs +++ b/packages/core/util.mjs @@ -62,8 +62,8 @@ export const valueToMidi = (value, fallbackValue) => { }; // used to schedule external event like midi and osc out -export const getEventOffsetMs = (targetTime, currentTime) => { - return (targetTime - currentTime) * 1000; +export const getEventOffsetMs = (targetTimeSeconds, currentTimeSeconds) => { + return (targetTimeSeconds - currentTimeSeconds) * 1000; }; /** diff --git a/packages/desktopbridge/midibridge.mjs b/packages/desktopbridge/midibridge.mjs index 07a5f963..471c826e 100644 --- a/packages/desktopbridge/midibridge.mjs +++ b/packages/desktopbridge/midibridge.mjs @@ -1,5 +1,5 @@ import { Invoke } from './utils.mjs'; -import { Pattern, noteToMidi } from '@strudel/core'; +import { Pattern, getEventOffsetMs, noteToMidi } from '@strudel/core'; const ON_MESSAGE = 0x90; const OFF_MESSAGE = 0x80; @@ -9,8 +9,8 @@ Pattern.prototype.midi = function (output) { return this.onTrigger((time_deprecate, hap, currentTime, cps, targetTime) => { let { note, nrpnn, nrpv, ccn, ccv, velocity = 0.9, gain = 1 } = hap.value; //magic number to get audio engine to line up, can probably be calculated somehow - const latency = 0.034; - const offset = (targetTime - currentTime + latency) * 1000; + const latencyMs = 34; + const offset = getEventOffsetMs(targetTime, currentTime) + latencyMs; velocity = Math.floor(gain * velocity * 100); const duration = Math.floor((hap.duration.valueOf() / cps) * 1000 - 10); const roundedOffset = Math.round(offset); diff --git a/packages/midi/midi.mjs b/packages/midi/midi.mjs index ef5c792a..3ce894d6 100644 --- a/packages/midi/midi.mjs +++ b/packages/midi/midi.mjs @@ -122,8 +122,7 @@ Pattern.prototype.midi = function (output) { //magic number to get audio engine to line up, can probably be calculated somehow const latencyMs = 34; // passing a string with a +num into the webmidi api adds an offset to the current time https://webmidijs.org/api/classes/Output - const timeOffsetString = `${getEventOffsetMs(targetTime, currentTime) + latencyMs}`; - + const timeOffsetString = `+${getEventOffsetMs(targetTime, currentTime) + latencyMs}`; // destructure value let { note, nrpnn, nrpv, ccn, ccv, midichan = 1, midicmd, gain = 1, velocity = 0.9 } = hap.value; diff --git a/packages/osc/server.js b/packages/osc/server.js index 42722d28..7e0b9059 100644 --- a/packages/osc/server.js +++ b/packages/osc/server.js @@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see . */ -const OSC = require('osc-js'); +import OSC from 'osc-js'; const config = { receiver: 'ws', // @param {string} Where messages sent via 'send' method will be delivered to, 'ws' for Websocket clients, 'udp' for udp client From 267f58b7be4c4399fd7a319baa9650a584fa3ed2 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Tue, 23 Apr 2024 14:14:30 +0100 Subject: [PATCH 025/195] Tactus tweaks - fixes for maintaining tactus and highlight locations (#1065) * outer bind/join should keep outer tactus * keep locations of outer pattern in stepJoin --- packages/core/pattern.mjs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 8f2c4362..439050d8 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -257,12 +257,12 @@ export class Pattern { } outerBind(func) { - return this.bindWhole((a) => a, func); + return this.bindWhole((a) => a, func).setTactus(this.tactus); } outerJoin() { // Flattens a pattern of patterns into a pattern, where wholes are - // taken from inner haps. + // taken from outer haps. return this.outerBind(id); } @@ -2429,7 +2429,10 @@ export function _slices(haps) { const breakpoints = flatten(haps.map((hap) => [hap.part.begin, hap.part.end])); const unique = uniqsortr([Fraction(0), Fraction(1), ...breakpoints]); const slicespans = pairs(unique); - return slicespans.map((s) => [s[1].sub(s[0]), stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value))]); + return slicespans.map((s) => [ + s[1].sub(s[0]), + stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value.withHap((h) => h.setContext(h.combineContext(x))))), + ]); } export function _fitslice(span, haps) { From 6a1fa7e67fead7a9cc070ff8a7f8e6b760991464 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Tue, 23 Apr 2024 22:32:00 +0100 Subject: [PATCH 026/195] clarify license (#1064) --- website/src/repl/panel/WelcomeTab.jsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/website/src/repl/panel/WelcomeTab.jsx b/website/src/repl/panel/WelcomeTab.jsx index bda6c3f5..fb41b471 100644 --- a/website/src/repl/panel/WelcomeTab.jsx +++ b/website/src/repl/panel/WelcomeTab.jsx @@ -36,7 +36,12 @@ export function WelcomeTab({ context }) { tidalcycles - , which is a popular live coding language for music, written in Haskell. You can find the source code at{' '} + , which is a popular live coding language for music, written in Haskell. Strudel is free/open source software: + you can redistribute and/or modify it under the terms of the{' '} + + GNU Affero General Public License + + . You can find the source code at{' '} github From a189626e8b4f482d2e6b9abb09fa8f87dd1bef6c Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Tue, 23 Apr 2024 22:37:21 +0100 Subject: [PATCH 027/195] Fix stepjoin (#1067) * sort fractions properly - fixes #1066 --- packages/core/pattern.mjs | 2 +- packages/core/test/pattern.test.mjs | 11 ++++++++++- packages/core/util.mjs | 8 +++++--- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 439050d8..91174857 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -43,7 +43,7 @@ export class Pattern { constructor(query, tactus = undefined) { this.query = query; this._Pattern = true; // this property is used to detect if a pattern that fails instanceof Pattern is an instance of another Pattern - this.__tactus = tactus; // in terms of number of beats per cycle + this.__tactus = Fraction(tactus); // in terms of number of steps per cycle } get tactus() { diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index b9848885..9c17d8be 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -1146,7 +1146,7 @@ describe('Pattern', () => { expect(sameFirst(sequence(0, 1, 2, 3, 4).s_taper(-1, 5), sequence(0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4))); }); }); - describe('s_add and s_sub, left', () => { + describe('s_add and s_sub', () => { it('can add from the left', () => { expect(sameFirst(sequence(0, 1, 2, 3, 4).s_add(2), sequence(0, 1))); }); @@ -1159,5 +1159,14 @@ describe('Pattern', () => { it('can sub to the right', () => { expect(sameFirst(sequence(0, 1, 2, 3, 4).s_sub(-2), sequence(2, 3, 4))); }); + it('can subtract nothing', () => { + expect(sameFirst(pure('a').s_sub(0), pure('a'))); + }); + it('can subtract nothing, repeatedly', () => { + expect(sameFirst(pure('a').s_sub(0, 0), fastcat('a', 'a'))); + for (var i = 0; i < 100; ++i) { + expect(sameFirst(pure('a').s_sub(...Array(i).fill(0)), fastcat(...Array(i).fill('a')))); + } + }); }); }); diff --git a/packages/core/util.mjs b/packages/core/util.mjs index e3ec1617..03f8b410 100644 --- a/packages/core/util.mjs +++ b/packages/core/util.mjs @@ -319,9 +319,11 @@ export function uniqsort(a) { // rational version export function uniqsortr(a) { - return a.sort().filter(function (item, pos, ary) { - return !pos || item.ne(ary[pos - 1]); - }); + return a + .sort((x, y) => x.compare(y)) + .filter(function (item, pos, ary) { + return !pos || item.ne(ary[pos - 1]); + }); } // code hashing helpers From 5c01760b28a9235b830eaf7e8283ae82567f63af Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Thu, 25 Apr 2024 06:01:49 +1000 Subject: [PATCH 028/195] fix cr typo on first-sounds.mdx --- website/src/pages/workshop/first-sounds.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index 0cb69a34..14a2da1c 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -93,7 +93,7 @@ These letter combinations stand for different parts of a drum set: - `mt` = **m**iddle tom - `ht` = **h**igh tom - `rd` = **r**i**d**e cymbal -- `rd` = **cr**ash cymbal +- `cr` = **cr**ash cymbal Try out different drum sounds! From 54829bd28c04063020a3854a4d3511cbca564905 Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Thu, 25 Apr 2024 06:24:56 +1000 Subject: [PATCH 029/195] fix first sounds typo --- website/src/pages/workshop/first-sounds.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index 0cb69a34..25b5c2bc 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -268,7 +268,7 @@ This is shorter and more readable than: ## Recap Now we've learned the basics of the so called Mini-Notation, the rhythm language of Tidal. -This is what we've leared so far: +This is what we've learned so far: | Concept | Syntax | Example | | ----------------- | -------- | ----------------------------------------------------------------------- | From d8eb186ee49d8b0bc2d0ca53f466e3da86fbdc81 Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Thu, 25 Apr 2024 06:35:34 +1000 Subject: [PATCH 030/195] add `<...>` to recap --- website/src/pages/workshop/first-sounds.mdx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index 0cb69a34..e456048c 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -270,15 +270,16 @@ This is shorter and more readable than: Now we've learned the basics of the so called Mini-Notation, the rhythm language of Tidal. This is what we've leared so far: -| Concept | Syntax | Example | -| ----------------- | -------- | ----------------------------------------------------------------------- | -| Sequence | space | | -| Sample Number | :x | | -| Rests | - or ~ | | -| Sub-Sequences | \[\] | | -| Sub-Sub-Sequences | \[\[\]\] | | -| Speed up | \* | | -| Parallel | , | | +| Concept | Syntax | Example | +| ------------------- | -------- | ----------------------------------------------------------------------- | +| Sequence | space | | +| Sample Number | :x | | +| Rests | - or ~ | | +| Per Cycle Sequences | \<\> | ")`} /> | +| Sub-Sequences | \[\] | | +| Sub-Sub-Sequences | \[\[\]\] | | +| Speed up | \* | | +| Parallel | , | | The Mini-Notation is usually used inside some function. These are the functions we've seen so far: From bbf8577f859859c741d7883dd74d6f2f2b903af9 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Fri, 26 Apr 2024 15:12:30 +0200 Subject: [PATCH 031/195] More tactus tidying (#1071) * preserve tactus for register (only non-formatting change is adding args to register) * support undefined tactus values --- packages/core/fraction.mjs | 32 +++++++- packages/core/pattern.mjs | 77 +++++++++++++++---- packages/core/test/pattern.test.mjs | 39 ++++++++++ packages/tonal/tonal.mjs | 115 +++++++++++++++------------- 4 files changed, 192 insertions(+), 71 deletions(-) diff --git a/packages/core/fraction.mjs b/packages/core/fraction.mjs index ce614246..a339567f 100644 --- a/packages/core/fraction.mjs +++ b/packages/core/fraction.mjs @@ -6,6 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th import Fraction from 'fraction.js'; import { TimeSpan } from './timespan.mjs'; +import { removeUndefineds } from './util.mjs'; // Returns the start of the cycle. Fraction.prototype.sam = function () { @@ -64,6 +65,22 @@ Fraction.prototype.min = function (other) { return this.lt(other) ? this : other; }; +Fraction.prototype.mulmaybe = function (other) { + return other !== undefined ? this.mul(other) : undefined; +}; + +Fraction.prototype.divmaybe = function (other) { + return other !== undefined ? this.div(other) : undefined; +}; + +Fraction.prototype.addmaybe = function (other) { + return other !== undefined ? this.add(other) : undefined; +}; + +Fraction.prototype.submaybe = function (other) { + return other !== undefined ? this.sub(other) : undefined; +}; + Fraction.prototype.show = function (/* excludeWhole = false */) { // return this.toFraction(excludeWhole); return this.s * this.n + '/' + this.d; @@ -89,11 +106,24 @@ const fraction = (n) => { }; export const gcd = (...fractions) => { + fractions = removeUndefineds(fractions); + if (fractions.length === 0) { + return undefined; + } + return fractions.reduce((gcd, fraction) => gcd.gcd(fraction), fraction(1)); }; export const lcm = (...fractions) => { - return fractions.reduce((lcm, fraction) => lcm.lcm(fraction), fraction(1)); + fractions = removeUndefineds(fractions); + if (fractions.length === 0) { + return undefined; + } + + return fractions.reduce( + (lcm, fraction) => (lcm === undefined || fraction === undefined ? undefined : lcm.lcm(fraction)), + fraction(1), + ); }; fraction._original = Fraction; diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 91174857..7291c12f 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -42,16 +42,16 @@ export class Pattern { */ constructor(query, tactus = undefined) { this.query = query; - this._Pattern = true; // this property is used to detect if a pattern that fails instanceof Pattern is an instance of another Pattern - this.__tactus = Fraction(tactus); // in terms of number of steps per cycle + this._Pattern = true; // this property is used to detectinstance of another Pattern + this.tactus = tactus; // in terms of number of steps per cycle } get tactus() { - return this.__tactus ?? Fraction(1); + return this.__tactus; } set tactus(tactus) { - this.__tactus = Fraction(tactus); + this.__tactus = tactus === undefined ? undefined : Fraction(tactus); } setTactus(tactus) { @@ -63,6 +63,10 @@ export class Pattern { return new Pattern(this.query, this.tactus === undefined ? undefined : f(this.tactus)); } + get hasTactus() { + return this.tactus !== undefined; + } + ////////////////////////////////////////////////////////////////////// // Haskell-style functor, applicative and monadic operations @@ -1181,7 +1185,7 @@ export const pm = s_polymeter; * @example * gap(3) // "~@3" */ -export const gap = (tactus) => new Pattern(() => [], Fraction(tactus)); +export const gap = (tactus) => new Pattern(() => [], tactus); /** * Does absolutely nothing.. @@ -1762,7 +1766,7 @@ export const { focusSpan, focusspan } = register(['focusSpan', 'focusspan'], fun */ export const ply = register('ply', function (factor, pat) { const result = pat.fmap((x) => pure(x)._fast(factor)).squeezeJoin(); - result.tactus = pat.tactus.mul(factor); + result.tactus = Fraction(factor).mulmaybe(pat.tactus); return result; }); @@ -1784,7 +1788,7 @@ export const { fast, density } = register(['fast', 'density'], function (factor, factor = Fraction(factor); const fastQuery = pat.withQueryTime((t) => t.mul(factor)); const result = fastQuery.withHapTime((t) => t.div(factor)); - result.tactus = factor.mul(pat.tactus); + result.tactus = factor.mulmaybe(pat.tactus); return result; }); @@ -1954,7 +1958,7 @@ export const zoom = register('zoom', function (s, e, pat) { return nothing; } const d = e.sub(s); - const tactus = pat.tactus.mul(d); + const tactus = pat.tactus.mulmaybe(d); return pat .withQuerySpan((span) => span.withCycle((t) => t.mul(d).add(s))) .withHapSpan((span) => span.withCycle((t) => t.sub(s).div(d))) @@ -2408,15 +2412,15 @@ Pattern.prototype.stepJoin = function () { }; export function _retime(timedHaps) { - const occupied_perc = timedHaps.filter((t, pat) => pat.tactus != undefined).reduce((a, b) => a.add(b), Fraction(0)); + const occupied_perc = timedHaps.filter((t, pat) => pat.hasTactus).reduce((a, b) => a.add(b), Fraction(0)); const occupied_tactus = removeUndefineds(timedHaps.map((t, pat) => pat.tactus)).reduce( (a, b) => a.add(b), Fraction(0), ); - const total_tactus = occupied_perc.eq(0) ? 0 : occupied_tactus.div(occupied_perc); + const total_tactus = occupied_perc.eq(0) ? undefined : occupied_tactus.div(occupied_perc); function adjust(dur, pat) { if (pat.tactus === undefined) { - return [dur.mul(total_tactus), pat]; + return [dur.mulmaybe(total_tactus), pat]; } return [pat.tactus, pat]; } @@ -2454,7 +2458,10 @@ export function _match(span, hap_p) { * // The same as s("{bd sd cp}%4") */ export const steps = register('steps', function (targetTactus, pat) { - if (pat.tactus.eq(0)) { + if (pat.tactus === undefined) { + return pat; + } + if (pat.tactus.eq(Fraction(0))) { // avoid divide by zero.. return nothing; } @@ -2520,10 +2527,16 @@ export function s_polymeter(...args) { return _polymeterListSteps(0, ...args); } + // TODO currently ignoring arguments without tactus... + args = args.filter((arg) => arg.hasTactus); + if (args.length == 0) { return silence; } const tactus = args[0].tactus; + if (tactus.eq(Fraction(0))) { + return nothing; + } const [head, ...tail] = args; const result = stack(head, ...tail.map((pat) => pat._slow(pat.tactus.div(tactus)))); @@ -2543,8 +2556,26 @@ export function s_polymeter(...args) { * // the same as "bd sd cp hh hh".sound() */ export function s_cat(...timepats) { + if (timepats.length === 0) { + return nothing; + } const findtactus = (x) => (Array.isArray(x) ? x : [x.tactus, x]); timepats = timepats.map(findtactus); + if (timepats.find((x) => x[0] === undefined)) { + const times = timepats.map((a) => a[0]).filter((x) => x !== undefined); + if (times.length === 0) { + return fastcat(...timepats.map((x) => x[1])); + } + if (times.length === timepats.length) { + return nothing; + } + const avg = times.reduce((a, b) => a.add(b), Fraction(0)).div(times.length); + for (let timepat of timepats) { + if (timepat[0] === undefined) { + timepat[0] = avg; + } + } + } if (timepats.length == 1) { const result = reify(timepats[0][1]); result.tactus = timepats[0][0]; @@ -2588,7 +2619,7 @@ export function s_alt(...groups) { for (let cycle = 0; cycle < cycles; ++cycle) { result.push(...groups.map((x) => (x.length == 0 ? silence : x[cycle % x.length]))); } - result = result.filter((x) => x.tactus > 0); + result = result.filter((x) => x.hasTactus && x.tactus > 0); const tactus = result.reduce((a, b) => a.add(b.tactus), Fraction(0)); result = s_cat(...result); result.tactus = tactus; @@ -2599,6 +2630,9 @@ export function s_alt(...groups) { * *EXPERIMENTAL* - Retains the given number of steps in a pattern (and dropping the rest), according to its 'tactus'. */ export const s_add = stepRegister('s_add', function (i, pat) { + if (!pat.hasTactus) { + return nothing; + } if (pat.tactus.lte(0)) { return nothing; } @@ -2627,6 +2661,10 @@ export const s_add = stepRegister('s_add', function (i, pat) { * *EXPERIMENTAL* - Removes the given number of steps from a pattern, according to its 'tactus'. */ export const s_sub = stepRegister('s_sub', function (i, pat) { + if (!pat.hasTactus) { + return nothing; + } + i = Fraction(i); if (i.lt(0)) { return pat.s_add(Fraction(0).sub(pat.tactus.add(i))); @@ -2647,10 +2685,15 @@ export const s_contract = stepRegister('s_contract', function (factor, pat) { */ Pattern.prototype.s_taperlist = function (amount, times) { const pat = this; + + if (!pat.hasTactus) { + return [pat]; + } + times = times - 1; if (times === 0) { - return pat; + return [pat]; } const list = []; @@ -2675,6 +2718,10 @@ export const s_taperlist = (amount, times, pat) => pat.s_taperlist(amount, times export const s_taper = register( 's_taper', function (amount, times, pat) { + if (!pat.hasTactus) { + return nothing; + } + const list = pat.s_taperlist(amount, times); const result = s_cat(...list); result.tactus = list.reduce((a, b) => a.add(b.tactus), Fraction(0)); @@ -2726,7 +2773,7 @@ export const chop = register('chop', function (n, pat) { const func = function (o) { return sequence(slice_objects.map((slice_o) => Object.assign({}, o, slice_o))); }; - return pat.squeezeBind(func).setTactus(pat.tactus.mul(n)); + return pat.squeezeBind(func).setTactus(Fraction(n).mulmaybe(pat.tactus)); }); /** diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index 9c17d8be..4bed34cb 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -47,6 +47,10 @@ import { time, run, pick, + stackLeft, + stackRight, + stackCentre, + s_cat, } from '../index.mjs'; import { steady } from '../signal.mjs'; @@ -1136,6 +1140,41 @@ describe('Pattern', () => { expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3)).tactus).toStrictEqual( Fraction(4), ); + expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4).tactus).toStrictEqual(Fraction(12)); + expect( + pure((x) => x + 1) + .setTactus(3) + .appBoth(pure(1).setTactus(2)).tactus, + ).toStrictEqual(Fraction(6)); + expect( + pure((x) => x + 1) + .setTactus(undefined) + .appBoth(pure(1).setTactus(2)).tactus, + ).toStrictEqual(Fraction(2)); + expect( + pure((x) => x + 1) + .setTactus(3) + .appBoth(pure(1).setTactus(undefined)).tactus, + ).toStrictEqual(Fraction(3)); + expect(stack(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(6)); + expect(stack(fastcat(0, 1, 2), fastcat(3, 4).setTactus(undefined)).tactus).toStrictEqual(Fraction(3)); + expect(stackLeft(fastcat(0, 1, 2, 3), fastcat(3, 4)).tactus).toStrictEqual(Fraction(4)); + expect(stackRight(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(3)); + // maybe this should double when they are either all even or all odd + expect(stackCentre(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(3)); + expect(fastcat(0, 1).ply(3).tactus).toStrictEqual(Fraction(6)); + expect(fastcat(0, 1).setTactus(undefined).ply(3).tactus).toStrictEqual(undefined); + expect(fastcat(0, 1).fast(3).tactus).toStrictEqual(Fraction(6)); + expect(fastcat(0, 1).setTactus(undefined).fast(3).tactus).toStrictEqual(undefined); + }); + }); + describe('s_cat', () => { + it('can cat', () => { + expect(sameFirst(s_cat(fastcat(0, 1, 2, 3), fastcat(4, 5)), fastcat(0, 1, 2, 3, 4, 5))); + expect(sameFirst(s_cat(pure(1), pure(2), pure(3)), fastcat(1, 2, 3))); + }); + it('calculates undefined tactuses as the average', () => { + expect(sameFirst(s_cat(pure(1), pure(2), pure(3).setTactus(undefined)), fastcat(1, 2, 3))); }); }); describe('s_taper', () => { diff --git a/packages/tonal/tonal.mjs b/packages/tonal/tonal.mjs index a2e01092..4c25d23e 100644 --- a/packages/tonal/tonal.mjs +++ b/packages/tonal/tonal.mjs @@ -188,61 +188,66 @@ export const scaleTranspose = register('scaleTranspose', function (offset /* : n * .s("piano") */ -export const scale = register('scale', function (scale, pat) { - // Supports ':' list syntax in mininotation - if (Array.isArray(scale)) { - scale = scale.flat().join(' '); - } - return ( - pat - .fmap((value) => { - const isObject = typeof value === 'object'; - let step = isObject ? value.n : value; - if (isObject) { - delete value.n; // remove n so it won't cause trouble - } - if (isNote(step)) { - // legacy.. - return pure(step); - } - let asNumber = Number(step); - let semitones = 0; - if (isNaN(asNumber)) { - step = String(step); - if (!/^[-+]?\d+(#*|b*){1}$/.test(step)) { - logger( - `[tonal] invalid scale step "${step}", expected number or integer with optional # b suffixes`, - 'error', - ); - return silence; +export const scale = register( + 'scale', + function (scale, pat) { + // Supports ':' list syntax in mininotation + if (Array.isArray(scale)) { + scale = scale.flat().join(' '); + } + return ( + pat + .fmap((value) => { + const isObject = typeof value === 'object'; + let step = isObject ? value.n : value; + if (isObject) { + delete value.n; // remove n so it won't cause trouble } - const isharp = step.indexOf('#'); - if (isharp >= 0) { - asNumber = Number(step.substring(0, isharp)); - semitones = step.length - isharp; - } else { - const iflat = step.indexOf('b'); - asNumber = Number(step.substring(0, iflat)); - semitones = iflat - step.length; + if (isNote(step)) { + // legacy.. + return pure(step); } - } - try { - let note; - if (isObject && value.anchor) { - note = stepInNamedScale(asNumber, scale, value.anchor); - } else { - note = scaleStep(asNumber, scale); + let asNumber = Number(step); + let semitones = 0; + if (isNaN(asNumber)) { + step = String(step); + if (!/^[-+]?\d+(#*|b*){1}$/.test(step)) { + logger( + `[tonal] invalid scale step "${step}", expected number or integer with optional # b suffixes`, + 'error', + ); + return silence; + } + const isharp = step.indexOf('#'); + if (isharp >= 0) { + asNumber = Number(step.substring(0, isharp)); + semitones = step.length - isharp; + } else { + const iflat = step.indexOf('b'); + asNumber = Number(step.substring(0, iflat)); + semitones = iflat - step.length; + } } - if (semitones != 0) note = Note.transpose(note, Interval.fromSemitones(semitones)); - value = pure(isObject ? { ...value, note } : note); - } catch (err) { - logger(`[tonal] ${err.message}`, 'error'); - value = silence; - } - return value; - }) - .outerJoin() - // legacy: - .withHap((hap) => hap.setContext({ ...hap.context, scale })) - ); -}); + try { + let note; + if (isObject && value.anchor) { + note = stepInNamedScale(asNumber, scale, value.anchor); + } else { + note = scaleStep(asNumber, scale); + } + if (semitones != 0) note = Note.transpose(note, Interval.fromSemitones(semitones)); + value = pure(isObject ? { ...value, note } : note); + } catch (err) { + logger(`[tonal] ${err.message}`, 'error'); + value = silence; + } + return value; + }) + .outerJoin() + // legacy: + .withHap((hap) => hap.setContext({ ...hap.context, scale })) + ); + }, + true, + true, // preserve tactus +); From 0be5f77247ec6eee09bdee085b7ba6a16a68ecbc Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Sat, 27 Apr 2024 10:15:55 +1000 Subject: [PATCH 032/195] fix translation issue in first-effects.mdx --- website/src/pages/workshop/first-effects.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/workshop/first-effects.mdx b/website/src/pages/workshop/first-effects.mdx index e7251624..82f7def8 100644 --- a/website/src/pages/workshop/first-effects.mdx +++ b/website/src/pages/workshop/first-effects.mdx @@ -168,7 +168,7 @@ What happens if you use `.delay(".8:.06:.8")` ? Can you guess what the third num - + `delay("a:b:c")`: From 5c4ad5730997dc4e4f03ef695a8c45823d7d8169 Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Sat, 27 Apr 2024 10:47:30 +1000 Subject: [PATCH 033/195] add signals to recap in first-effects.mdx --- website/src/pages/workshop/first-effects.mdx | 21 ++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/website/src/pages/workshop/first-effects.mdx b/website/src/pages/workshop/first-effects.mdx index e7251624..d49ac0c9 100644 --- a/website/src/pages/workshop/first-effects.mdx +++ b/website/src/pages/workshop/first-effects.mdx @@ -307,15 +307,16 @@ The whole automation will now take 8 cycles to repeat. ## Recap -| name | example | -| ----- | ---------------------------------------------------------------------------------------- | -| lpf | ")`} /> | -| vowel | ")`} /> | -| gain | | -| delay | | -| room | | -| pan | | -| speed | ")`} /> | -| range | | +| name | example | +| ------- | ---------------------------------------------------------------------------------------------------------------- | +| lpf | ")`} /> | +| vowel | ")`} /> | +| gain | | +| delay | | +| room | | +| pan | | +| speed | ")`} /> | +| signals | `sine`, `saw`, `square`, `tri`, `rand`, `perlin`
| +| range | | Let us now take a look at some of Tidal's typical [pattern effects](/workshop/pattern-effects). From 6b919132aad0a220fec4c3ec57a2adc40e216207 Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Sat, 27 Apr 2024 11:18:51 +1000 Subject: [PATCH 034/195] clarify `off` in pattern-effects.mdx I had a bit of difficulty understanding `off` as it was presented, so I've attempted to simplify it: 1. take out the `delay` effect which is obscuring things (since we're using a delayed `off` pattern) 2. add a more complete explanation of the syntax --- website/src/pages/workshop/pattern-effects.mdx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/website/src/pages/workshop/pattern-effects.mdx b/website/src/pages/workshop/pattern-effects.mdx index f4ced454..d9b65c4f 100644 --- a/website/src/pages/workshop/pattern-effects.mdx +++ b/website/src/pages/workshop/pattern-effects.mdx @@ -145,13 +145,16 @@ Try patterning the `ply` function, for example using `"<1 2 1 3>"` .off(1/16, x=>x.add(4)) //.off(1/8, x=>x.add(7)) ).scale("/2") -.s("triangle").room(.5).ds(".1:0").delay(.5)`} +.s("triangle").room(.5).ds("0.1:0")`} punchcard /> -In the notation `x=>x.`, the `x` is the shifted pattern, which where modifying. +In the notation `.off(1/16, x=>x.add(4))`, says: + - take the original pattern named as `x` + - modify `x` with `.add(4)`, and + - play it offset to the original pattern by `1/16` of a cycle. From 975eb684b9163af3dd9ee4e2c5644cd36720613c Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Sat, 27 Apr 2024 11:35:08 +1000 Subject: [PATCH 035/195] add nesting to `off` example variation in pattern-effects.mdx I was immediately curious whether `off` could be nested - it turns out it can, so I added an example of it in action. This example should also add clarity to the flexibility of pattern naming inside `off` arguments as well --- website/src/pages/workshop/pattern-effects.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/website/src/pages/workshop/pattern-effects.mdx b/website/src/pages/workshop/pattern-effects.mdx index f4ced454..e9587d73 100644 --- a/website/src/pages/workshop/pattern-effects.mdx +++ b/website/src/pages/workshop/pattern-effects.mdx @@ -155,14 +155,16 @@ In the notation `x=>x.`, the `x` is the shifted pattern, which where modifying. -off is also useful for sounds: +off is also useful for modifying other sounds, and can even be nested: x.speed(1.5).gain(.25))`} + .off(2/16, x=>x.speed(1.5).gain(.25) + .off(3/16, y=>y.vowel("*8")))`} /> + | name | description | example | | ---- | ------------------------------ | ------------------------------------------------------------------------------------------- | | rev | reverse | | From 69f8498d4b65614ce19f678a541d5ba5e83bd858 Mon Sep 17 00:00:00 2001 From: Bernard Gray Date: Sat, 27 Apr 2024 14:20:26 +1000 Subject: [PATCH 036/195] Use "Alternate" for `<...>`, consistent with recap page in first-sounds.mdx --- website/src/pages/workshop/first-sounds.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index e456048c..05273ebe 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -275,7 +275,7 @@ This is what we've leared so far: | Sequence | space | | | Sample Number | :x | | | Rests | - or ~ | | -| Per Cycle Sequences | \<\> | ")`} /> | +| Alternate | \<\> | ")`} /> | | Sub-Sequences | \[\] | | | Sub-Sub-Sequences | \[\[\]\] | | | Speed up | \* | | From d253e35b6cf71b28e279dd41b3b7264f74646c8a Mon Sep 17 00:00:00 2001 From: Diego Dorado Date: Sun, 28 Apr 2024 10:53:53 -0300 Subject: [PATCH 037/195] fix docs on alignment.mdx --- website/src/pages/technical-manual/alignment.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/website/src/pages/technical-manual/alignment.mdx b/website/src/pages/technical-manual/alignment.mdx index f372baff..dd3a6db5 100644 --- a/website/src/pages/technical-manual/alignment.mdx +++ b/website/src/pages/technical-manual/alignment.mdx @@ -23,7 +23,7 @@ following example: ```js '0 1 2'.add('10 20'); -('10 [11 21] 20'); +('10 [11 21] 22'); ``` They are similar to the previous example in that the number `1` is split in two, with its two halves added to `10` and `20` respectively. However, the `11` 'remembers' that it is a fragment of that original `1` event, and so is treated as having a duration of a third of a cycle, despite only being active for a sixth of a cycle. Likewise, the `21` is also a fragment of that original `1` event, but a fragment of its second half. Because the start of its event is missing, it wouldn't actually trigger a sound (unless it underwent further pattern transformations/combinations). @@ -41,7 +41,7 @@ This makes way for other ways to align the pattern, and several are already defi - `mix` - structures from both patterns are combined, so that the new events are not fragments but are created at intersections of events from both sides. - `squeeze` - cycles from the pattern on the right are squeezed into events on the left. So that e.g. `"0 1 2".add.squeeze("10 20")` is equivalent to `"[10 20] [11 21] [12 22]"`. - `squeezeout` - as with `squeeze`, but cycles from the left are squeezed into events on the right. So, `"0 1 2".add.squeezeout("10 20")` is equivalent to `[10 11 12] [20 21 22]`. -- `reset` is similar to `squeezeout` in that cycles from the right are aligned with events on the left. However those cycles are not 'squeezed', rather they are truncated to fit the event. So `"0 1 2 3 4 5 6 7".add.trig("10 [20 30]")` would be equivalent to `10 11 12 13 20 21 30 31`. In effect, events on the right 'trigger' cycles on the left. +- `reset` is similar to `squeezeout` in that cycles from the right are aligned with events on the left. However those cycles are not 'squeezed', rather they are truncated to fit the event. So `"0 1 2 3 4 5 6 7".add.reset("10 [20 30]")` would be equivalent to `10 11 12 13 20 21 30 31`. In effect, events on the right 'reset' cycles on the left. - `restart` is similar to `reset`, but the pattern is 'restarted' from its very first cycle, rather than from the current cycle. `reset` and `restart` therefore only give different results where the leftmost pattern differs from one cycle to the next. We will save going deeper into the background, design and practicalities of these alignment functions for future publications. However in the next section, we take them as a case study for looking at the different design affordances offered by Haskell to Tidal, and JavaScript to Strudel. From ce79a44848562974d2debda42ab914a614a3c7b1 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Sun, 28 Apr 2024 14:36:52 -0400 Subject: [PATCH 038/195] fix failing format test --- website/src/pages/workshop/first-effects.mdx | 60 ++++++++++---------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/website/src/pages/workshop/first-effects.mdx b/website/src/pages/workshop/first-effects.mdx index e7251624..d3dd80ba 100644 --- a/website/src/pages/workshop/first-effects.mdx +++ b/website/src/pages/workshop/first-effects.mdx @@ -83,15 +83,15 @@ Let's combine all of the above into a little tune: ") - .sound("sawtooth").lpf("200 1000 200 1000"), - note("<[c3,g3,e4] [bb2,f3,d4] [a2,f3,c4] [bb2,g3,eb4]>") - .sound("sawtooth").vowel("") -) `} +stack( +sound("hh*8").gain("[.25 1]*4"), +sound("bd*4,[~ sd:1]*2") +), +note("<[c2 c3]*4 [bb1 bb2]*4 [f2 f3]*4 [eb2 eb3]*4>") +.sound("sawtooth").lpf("200 1000 200 1000"), +note("<[c3,g3,e4] [bb2,f3,d4] [a2,f3,c4] [bb2,g3,eb4]>") +.sound("sawtooth").vowel("") +)`} /> @@ -152,9 +152,9 @@ Can you guess what they do? ~]]*2") - .sound("gm_electric_guitar_muted"), - sound("").bank("RolandTR707") +note("[~ [<[d3,a3,f4]!2 [d3,bb3,g4]!2> ~]]*2") +.sound("gm_electric_guitar_muted"), +sound("").bank("RolandTR707") ).delay(".5")`} /> @@ -200,12 +200,12 @@ Add a delay too! ~]]*2") - .sound("gm_electric_guitar_muted").delay(.5), - sound("").bank("RolandTR707").delay(.5), - n("<4 [3@3 4] [<2 0> ~@16] ~>") - .scale("D4:minor").sound("gm_accordion:2") - .room(2).gain(.5) +note("[~ [<[d3,a3,f4]!2 [d3,bb3,g4]!2> ~]]*2") +.sound("gm_electric_guitar_muted").delay(.5), +sound("").bank("RolandTR707").delay(.5), +n("<4 [3@3 4] [<2 0> ~@16] ~>") +.scale("D4:minor").sound("gm_accordion:2") +room(2).gain(.5) )`} /> @@ -214,15 +214,15 @@ Let's add a bass to make this complete: ~]]*2") - .sound("gm_electric_guitar_muted").delay(.5), - sound("").bank("RolandTR707").delay(.5), - n("<4 [3@3 4] [<2 0> ~@16] ~>") - .scale("D4:minor").sound("gm_accordion:2") - .room(2).gain(.4), - n("[0 [~ 0] 4 [3 2] [0 ~] [0 ~] <0 2> ~]/2") - .scale("D2:minor") - .sound("sawtooth,triangle").lpf(800) +note("[~ [<[d3,a3,f4]!2 [d3,bb3,g4]!2> ~]]*2") +.sound("gm_electric_guitar_muted").delay(.5), +sound("").bank("RolandTR707").delay(.5), +n("<4 [3@3 4] [<2 0> ~@16] ~>") +.scale("D4:minor").sound("gm_accordion:2") +.room(2).gain(.4), +n("[0 [~ 0] 4 [3 2] [0 ~] [0 ~] <0 2> ~]/2") +.scale("D2:minor") +.sound("sawtooth,triangle").lpf(800) )`} /> @@ -237,7 +237,7 @@ Try adding `.hush()` at the end of one of the patterns in the stack... **speed** @@ -295,8 +295,8 @@ We can change the automation speed with slow / fast: ") -.sound("sawtooth") -.lpf(sine.range(100, 2000).slow(4))`} + .sound("sawtooth") + .lpf(sine.range(100, 2000).slow(4))`} /> From 15f16006d012c6d68a688e4903533b639c7915ad Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Sun, 28 Apr 2024 14:43:35 -0400 Subject: [PATCH 039/195] ran prettier again? --- website/src/pages/workshop/first-sounds.mdx | 20 +++++++++---------- .../src/pages/workshop/pattern-effects.mdx | 1 - 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index 4e374001..9c33cdc3 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -270,16 +270,16 @@ This is shorter and more readable than: Now we've learned the basics of the so called Mini-Notation, the rhythm language of Tidal. This is what we've learned so far: -| Concept | Syntax | Example | -| ------------------- | -------- | ----------------------------------------------------------------------- | -| Sequence | space | | -| Sample Number | :x | | -| Rests | - or ~ | | -| Alternate | \<\> | ")`} /> | -| Sub-Sequences | \[\] | | -| Sub-Sub-Sequences | \[\[\]\] | | -| Speed up | \* | | -| Parallel | , | | +| Concept | Syntax | Example | +| ----------------- | -------- | ----------------------------------------------------------------------- | +| Sequence | space | | +| Sample Number | :x | | +| Rests | - or ~ | | +| Alternate | \<\> | ")`} /> | +| Sub-Sequences | \[\] | | +| Sub-Sub-Sequences | \[\[\]\] | | +| Speed up | \* | | +| Parallel | , | | The Mini-Notation is usually used inside some function. These are the functions we've seen so far: diff --git a/website/src/pages/workshop/pattern-effects.mdx b/website/src/pages/workshop/pattern-effects.mdx index e9587d73..5afe862c 100644 --- a/website/src/pages/workshop/pattern-effects.mdx +++ b/website/src/pages/workshop/pattern-effects.mdx @@ -164,7 +164,6 @@ off is also useful for modifying other sounds, and can even be nested: .off(3/16, y=>y.vowel("*8")))`} /> - | name | description | example | | ---- | ------------------------------ | ------------------------------------------------------------------------------------------- | | rev | reverse | | From 91bb0a1d36e4f2400946f14c770492e5022a4af4 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Mon, 29 Apr 2024 11:36:10 +0100 Subject: [PATCH 040/195] Add calculateTactus() for turning off calculation of tactus in (#1081) core functions. Also while I'm here stop fast/slow from manipulating tactus. --- packages/core/pattern.mjs | 59 +++++++++++++++++++---------- packages/core/test/pattern.test.mjs | 7 ++-- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 7291c12f..0e378d78 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -27,6 +27,12 @@ import { logger } from './logger.mjs'; let stringParser; +let __tactus = true; + +export const calculateTactus = function (x) { + __tactus = x ? true : false; +}; + // parser is expected to turn a string into a pattern // if set, the reify function will parse all strings with it // intended to use with mini to automatically interpret all strings as mini notation @@ -60,6 +66,9 @@ export class Pattern { } withTactus(f) { + if (!__tactus) { + return this; + } return new Pattern(this.query, this.tactus === undefined ? undefined : f(this.tactus)); } @@ -149,7 +158,9 @@ export class Pattern { return span_a.intersection_e(span_b); }; const result = pat_func.appWhole(whole_func, pat_val); - result.tactus = lcm(pat_val.tactus, pat_func.tactus); + if (__tactus) { + result.tactus = lcm(pat_val.tactus, pat_func.tactus); + } return result; } @@ -1254,7 +1265,9 @@ export function stack(...pats) { pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat))); const query = (state) => flatten(pats.map((pat) => pat.query(state))); const result = new Pattern(query); - result.tactus = lcm(...pats.map((pat) => pat.tactus)); + if (__tactus) { + result.tactus = lcm(...pats.map((pat) => pat.tactus)); + } return result; } @@ -1267,7 +1280,7 @@ function _stackWith(func, pats) { return pats[0]; } const [left, ...right] = pats.map((pat) => pat.tactus); - const tactus = left.maximum(...right); + const tactus = __tactus ? left.maximum(...right) : undefined; return stack(...func(tactus, pats)); } @@ -1347,7 +1360,7 @@ export function slowcat(...pats) { const offset = span.begin.floor().sub(span.begin.div(pats.length).floor()); return pat.withHapTime((t) => t.add(offset)).query(state.setSpan(span.withTime((t) => t.sub(offset)))); }; - const tactus = lcm(...pats.map((x) => x.tactus)); + const tactus = __tactus ? lcm(...pats.map((x) => x.tactus)) : undefined; return new Pattern(query).splitQueries().setTactus(tactus); } @@ -1766,7 +1779,9 @@ export const { focusSpan, focusspan } = register(['focusSpan', 'focusspan'], fun */ export const ply = register('ply', function (factor, pat) { const result = pat.fmap((x) => pure(x)._fast(factor)).squeezeJoin(); - result.tactus = Fraction(factor).mulmaybe(pat.tactus); + if (__tactus) { + result.tactus = Fraction(factor).mulmaybe(pat.tactus); + } return result; }); @@ -1781,16 +1796,19 @@ export const ply = register('ply', function (factor, pat) { * @example * s("bd hh sd hh").fast(2) // s("[bd hh sd hh]*2") */ -export const { fast, density } = register(['fast', 'density'], function (factor, pat) { - if (factor === 0) { - return silence; - } - factor = Fraction(factor); - const fastQuery = pat.withQueryTime((t) => t.mul(factor)); - const result = fastQuery.withHapTime((t) => t.div(factor)); - result.tactus = factor.mulmaybe(pat.tactus); - return result; -}); +export const { fast, density } = register( + ['fast', 'density'], + function (factor, pat) { + if (factor === 0) { + return silence; + } + factor = Fraction(factor); + const fastQuery = pat.withQueryTime((t) => t.mul(factor)); + return fastQuery.withHapTime((t) => t.div(factor)).setTactus(pat.tactus); + }, + true, + true, +); /** * Both speeds up the pattern (like 'fast') and the sample playback (like 'speed'). @@ -1958,7 +1976,7 @@ export const zoom = register('zoom', function (s, e, pat) { return nothing; } const d = e.sub(s); - const tactus = pat.tactus.mulmaybe(d); + const tactus = __tactus ? pat.tactus.mulmaybe(d) : undefined; return pat .withQuerySpan((span) => span.withCycle((t) => t.mul(d).add(s))) .withHapSpan((span) => span.withCycle((t) => t.sub(s).div(d))) @@ -2173,7 +2191,7 @@ export const { juxBy, juxby } = register(['juxBy', 'juxby'], function (by, func, const left = pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) - by })); const right = func(pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) + by }))); - return stack(left, right).setTactus(lcm(left.tactus, right.tactus)); + return stack(left, right).setTactus(__tactus ? lcm(left.tactus, right.tactus) : undefined); }); /** @@ -2773,7 +2791,7 @@ export const chop = register('chop', function (n, pat) { const func = function (o) { return sequence(slice_objects.map((slice_o) => Object.assign({}, o, slice_o))); }; - return pat.squeezeBind(func).setTactus(Fraction(n).mulmaybe(pat.tactus)); + return pat.squeezeBind(func).setTactus(__tactus ? Fraction(n).mulmaybe(pat.tactus) : undefined); }); /** @@ -2788,7 +2806,10 @@ export const striate = register('striate', function (n, pat) { const slices = Array.from({ length: n }, (x, i) => i); const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n })); const slicePat = slowcat(...slice_objects); - return pat.set(slicePat)._fast(n); + return pat + .set(slicePat) + ._fast(n) + .setTactus(__tactus ? Fraction(n).mulmaybe(pat.tactus) : undefined); }); /** diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index 4bed34cb..845ed00a 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -51,6 +51,7 @@ import { stackRight, stackCentre, s_cat, + calculateTactus, } from '../index.mjs'; import { steady } from '../signal.mjs'; @@ -1127,8 +1128,8 @@ describe('Pattern', () => { it('Is correctly preserved/calculated through transformations', () => { expect(sequence(0, 1, 2, 3).linger(4).tactus).toStrictEqual(Fraction(4)); expect(sequence(0, 1, 2, 3).iter(4).tactus).toStrictEqual(Fraction(4)); - expect(sequence(0, 1, 2, 3).fast(4).tactus).toStrictEqual(Fraction(16)); - expect(sequence(0, 1, 2, 3).hurry(4).tactus).toStrictEqual(Fraction(16)); + expect(sequence(0, 1, 2, 3).fast(4).tactus).toStrictEqual(Fraction(4)); + expect(sequence(0, 1, 2, 3).hurry(4).tactus).toStrictEqual(Fraction(4)); expect(sequence(0, 1, 2, 3).rev().tactus).toStrictEqual(Fraction(4)); expect(sequence(1).segment(10).tactus).toStrictEqual(Fraction(10)); expect(sequence(1, 0, 1).invert().tactus).toStrictEqual(Fraction(3)); @@ -1164,7 +1165,7 @@ describe('Pattern', () => { expect(stackCentre(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(3)); expect(fastcat(0, 1).ply(3).tactus).toStrictEqual(Fraction(6)); expect(fastcat(0, 1).setTactus(undefined).ply(3).tactus).toStrictEqual(undefined); - expect(fastcat(0, 1).fast(3).tactus).toStrictEqual(Fraction(6)); + expect(fastcat(0, 1).fast(3).tactus).toStrictEqual(Fraction(2)); expect(fastcat(0, 1).setTactus(undefined).fast(3).tactus).toStrictEqual(undefined); }); }); From 5b4322c9648fa5da98e6053f85a6f38ec5a70366 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 2 May 2024 22:39:39 +0200 Subject: [PATCH 041/195] fix: url parsing with extra params --- website/src/repl/util.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/website/src/repl/util.mjs b/website/src/repl/util.mjs index 6dba7dab..3147ae38 100644 --- a/website/src/repl/util.mjs +++ b/website/src/repl/util.mjs @@ -26,13 +26,13 @@ export async function initCode() { // load code from url hash (either short hash from database or decode long hash) try { const initialUrl = window.location.href; - const hash = initialUrl.split('?')[1]?.split('#')?.[0]; + const hash = initialUrl.split('?')[1]?.split('#')?.[0]?.split('&')[0]; const codeParam = window.location.href.split('#')[1] || ''; - // looking like https://strudel.cc/?J01s5i1J0200 (fixed hash length) if (codeParam) { // looking like https://strudel.cc/#ImMzIGUzIg%3D%3D (hash length depends on code length) return hash2code(codeParam); } else if (hash) { + // looking like https://strudel.cc/?J01s5i1J0200 (fixed hash length) return supabase .from('code_v1') .select('code') From 34e9d73908b37a657081ae90e10a24568dd79fe4 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Thu, 2 May 2024 23:37:32 +0100 Subject: [PATCH 042/195] Improve performance of ! (replicate) (#1084) * Implement ! with weighted repeatCycles * reimplement repeatCycles without array filling --- packages/core/pattern.mjs | 8 +++++++- packages/mini/krill-parser.js | 10 +++++++++- packages/mini/krill.pegjs | 9 ++++++++- packages/mini/mini.mjs | 21 +++++++-------------- 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 0e378d78..03ce2e2d 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -2310,7 +2310,13 @@ export const { iterBack, iterback } = register( export const { repeatCycles } = register( 'repeatCycles', function (n, pat) { - return slowcat(...Array(n).fill(pat)); + return new Pattern(function (state) { + const cycle = state.span.begin.sam(); + const source_cycle = cycle.div(n).sam(); + const delta = cycle.sub(source_cycle); + state = state.withSpan((span) => span.withTime((spant) => spant.sub(delta))); + return pat.query(state).map((hap) => hap.withSpan((span) => span.withTime((spant) => spant.add(delta)))); + }).splitQueries(); }, true, true, diff --git a/packages/mini/krill-parser.js b/packages/mini/krill-parser.js index 7762242d..1cdd3486 100644 --- a/packages/mini/krill-parser.js +++ b/packages/mini/krill-parser.js @@ -295,7 +295,15 @@ function peg$parse(input, options) { var peg$f6 = function(a) { return a }; var peg$f7 = function(s) { s.arguments_.alignment = 'polymeter_slowcat'; return s; }; var peg$f8 = function(a) { return x => x.options_['weight'] = (x.options_['weight'] ?? 1) + (a ?? 2) - 1 }; - var peg$f9 = function(a) { return x => x.options_['reps'] = (x.options_['reps'] ?? 1) + (a ?? 2) - 1 }; + var peg$f9 = function(a) { return x => {const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1; + x.options_['reps'] = reps; + console.log("reps: ", reps) + x.options_['ops'] = x.options_['ops'].filter(x => x.type_ !== "replicate"); + x.options_['ops'].push({ type_: "replicate", arguments_ :{ amount:reps }}); + x.options_['weight'] = reps; + console.log("options: ", x.options_); + } + }; var peg$f10 = function(p, s, r) { return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) }; var peg$f11 = function(a) { return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'slow' }}) }; var peg$f12 = function(a) { return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'fast' }}) }; diff --git a/packages/mini/krill.pegjs b/packages/mini/krill.pegjs index 35d7bdc4..c1349ca5 100644 --- a/packages/mini/krill.pegjs +++ b/packages/mini/krill.pegjs @@ -135,7 +135,14 @@ op_weight = ws ("@" / "_") a:number? { return x => x.options_['weight'] = (x.options_['weight'] ?? 1) + (a ?? 2) - 1 } op_replicate = ws "!" a:number? - { return x => x.options_['reps'] = (x.options_['reps'] ?? 1) + (a ?? 2) - 1 } + { return x => {// A bit fiddly, to support both x!4 and x!!! as equivalent.. + const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1; + x.options_['reps'] = reps; + x.options_['ops'] = x.options_['ops'].filter(x => x.type_ !== "replicate"); + x.options_['ops'].push({ type_: "replicate", arguments_ :{ amount:reps }}); + x.options_['weight'] = reps; + } + } op_bjorklund = "(" ws p:slice_with_ops ws comma ws s:slice_with_ops ws comma? ws r:slice_with_ops? ws ")" { return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) } diff --git a/packages/mini/mini.mjs b/packages/mini/mini.mjs index 8c893273..8d2276fb 100644 --- a/packages/mini/mini.mjs +++ b/packages/mini/mini.mjs @@ -27,6 +27,12 @@ const applyOptions = (parent, enter) => (pat, i) => { pat = strudel.reify(pat)[type](enter(amount)); break; } + case 'replicate': { + const { amount } = op.arguments_; + pat = strudel.reify(pat); + pat = pat._repeatCycles(amount)._fast(amount); + break; + } case 'bjorklund': { if (op.arguments_.rotation) { pat = pat.euclidRot(enter(op.arguments_.pulse), enter(op.arguments_.step), enter(op.arguments_.rotation)); @@ -67,26 +73,13 @@ const applyOptions = (parent, enter) => (pat, i) => { return pat; }; -function resolveReplications(ast) { - ast.source_ = strudel.flatten( - ast.source_.map((child) => { - const { reps } = child.options_ || {}; - if (!reps) { - return [child]; - } - delete child.options_.reps; - return Array(reps).fill(child); - }), - ); -} - // expects ast from mini2ast + quoted mini string + optional callback when a node is entered export function patternifyAST(ast, code, onEnter, offset = 0) { onEnter?.(ast); const enter = (node) => patternifyAST(node, code, onEnter, offset); switch (ast.type_) { case 'pattern': { - resolveReplications(ast); + // resolveReplications(ast); const children = ast.source_.map((child) => enter(child)).map(applyOptions(ast, enter)); const alignment = ast.arguments_.alignment; const with_tactus = children.filter((child) => child.__tactus_source); From 8db443ba265f2b08bba4f0ba9ab5c28bc8555a54 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 3 May 2024 00:42:13 +0200 Subject: [PATCH 043/195] fix: csound + dough timing --- packages/csound/index.mjs | 6 ++++-- packages/superdough/dspworklet.mjs | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/csound/index.mjs b/packages/csound/index.mjs index a00be74f..1eeaf6fa 100644 --- a/packages/csound/index.mjs +++ b/packages/csound/index.mjs @@ -23,7 +23,7 @@ export const csound = register('csound', (instrument, pat) => { instrument = instrument || 'triangle'; init(); // not async to support csound inside other patterns + to be able to call pattern methods after it // TODO: find a alternative way to wait for csound to load (to wait with first time playback) - return pat.onTrigger((time, hap) => { + return pat.onTrigger((time_deprecate, hap, currentTime, _cps, targetTime) => { if (!_csound) { logger('[csound] not loaded yet', 'warning'); return; @@ -38,9 +38,11 @@ export const csound = register('csound', (instrument, pat) => { .join('/'); // TODO: find out how to send a precise ctx based time // http://www.csounds.com/manual/html/i.html + const timeOffset = targetTime - currentTime; // latency ? + //const timeOffset = time_deprecate - getAudioContext().currentTime const params = [ `"${instrument}"`, // p1: instrument name - time - getAudioContext().currentTime, //.toFixed(precision), // p2: starting time in arbitrary unit called beats + timeOffset, // p2: starting time in arbitrary unit called beats hap.duration + 0, // p3: duration in beats // instrument specific params: freq, //.toFixed(precision), // p4: frequency diff --git a/packages/superdough/dspworklet.mjs b/packages/superdough/dspworklet.mjs index deff485a..ed5c1e7e 100644 --- a/packages/superdough/dspworklet.mjs +++ b/packages/superdough/dspworklet.mjs @@ -74,6 +74,6 @@ export const dough = async (code) => { worklet.node.connect(ac.destination); }; -export function doughTrigger(t, hap, currentTime, duration, cps) { - window.postMessage({ time: t, dough: hap.value, currentTime, duration, cps }); +export function doughTrigger(time_deprecate, hap, currentTime, cps, targetTime) { + window.postMessage({ time: targetTime, dough: hap.value, currentTime, duration: hap.duration, cps }); } From e47d67a9da1db57108d05b8db09824ac0d5271a7 Mon Sep 17 00:00:00 2001 From: Alex McLean Date: Fri, 3 May 2024 10:52:56 +0100 Subject: [PATCH 044/195] Benchmarks (#1079) * tactus-oriented benchmarks * add benchmarks for individual example tunes --- bench/tunes.bench.mjs | 22 +++++++++++++ package.json | 1 + packages/core/bench/pattern.bench.mjs | 46 +++++++++++++++++++++++++++ packages/core/package.json | 1 + packages/mini/bench/mini.bench.mjs | 25 +++++++++++++++ packages/mini/package.json | 1 + 6 files changed, 96 insertions(+) create mode 100644 bench/tunes.bench.mjs create mode 100644 packages/core/bench/pattern.bench.mjs create mode 100644 packages/mini/bench/mini.bench.mjs diff --git a/bench/tunes.bench.mjs b/bench/tunes.bench.mjs new file mode 100644 index 00000000..cd381873 --- /dev/null +++ b/bench/tunes.bench.mjs @@ -0,0 +1,22 @@ +import { queryCode, testCycles } from '../test/runtime.mjs'; +import * as tunes from '../website/src/repl/tunes.mjs'; +import { describe, bench } from 'vitest'; +import { calculateTactus } from '../packages/core/index.mjs'; + +const tuneKeys = Object.keys(tunes); + +describe('renders tunes', () => { + tuneKeys.forEach((key) => { + describe(key, () => { + calculateTactus(true); + bench(`+tactus`, async () => { + await queryCode(tunes[key], testCycles[key] || 1); + }); + calculateTactus(false); + bench(`-tactus`, async () => { + await queryCode(tunes[key], testCycles[key] || 1); + }); + calculateTactus(true); + }); + }); +}); diff --git a/package.json b/package.json index 97900913..8aefa102 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "test": "npm run pretest && vitest run --version", "test-ui": "npm run pretest && vitest --ui", "test-coverage": "npm run pretest && vitest --coverage", + "bench": "npm run pretest && vitest bench", "snapshot": "npm run pretest && vitest run -u --silent", "repl": "npm run prestart && cd website && npm run dev", "start": "npm run prestart && cd website && npm run dev", diff --git a/packages/core/bench/pattern.bench.mjs b/packages/core/bench/pattern.bench.mjs new file mode 100644 index 00000000..12644800 --- /dev/null +++ b/packages/core/bench/pattern.bench.mjs @@ -0,0 +1,46 @@ +import { describe, bench } from 'vitest'; + +import { calculateTactus, sequence, stack } from '../index.mjs'; + +const pat64 = sequence(...Array(64).keys()); + +describe('tactus', () => { + calculateTactus(true); + bench( + '+tactus', + () => { + pat64.iter(64).fast(64).firstCycle(); + }, + { time: 1000 }, + ); + + calculateTactus(false); + bench( + '-tactus', + () => { + pat64.iter(64).fast(64).firstCycle(); + }, + { time: 1000 }, + ); +}); + +describe('stack', () => { + calculateTactus(true); + bench( + '+tactus', + () => { + stack(pat64, pat64, pat64, pat64, pat64, pat64, pat64, pat64).fast(64).firstCycle(); + }, + { time: 1000 }, + ); + + calculateTactus(false); + bench( + '-tactus', + () => { + stack(pat64, pat64, pat64, pat64, pat64, pat64, pat64, pat64).fast(64).firstCycle(); + }, + { time: 1000 }, + ); +}); +calculateTactus(true); diff --git a/packages/core/package.json b/packages/core/package.json index 7f59ed41..6c95d049 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -9,6 +9,7 @@ }, "scripts": { "test": "vitest run", + "bench": "vitest bench", "build": "vite build", "prepublishOnly": "pnpm build" }, diff --git a/packages/mini/bench/mini.bench.mjs b/packages/mini/bench/mini.bench.mjs new file mode 100644 index 00000000..782ac86b --- /dev/null +++ b/packages/mini/bench/mini.bench.mjs @@ -0,0 +1,25 @@ +import { describe, bench } from 'vitest'; + +import { calculateTactus } from '../../core/index.mjs'; +import { mini } from '../index.mjs'; + +describe('mini', () => { + calculateTactus(true); + bench( + '+tactus', + () => { + mini('a b c*3 [c d e, f g] ').fast(64).firstCycle(); + }, + { time: 1000 }, + ); + + calculateTactus(false); + bench( + '-tactus', + () => { + mini('a b c*3 [c d e, f g] ').fast(64).firstCycle(); + }, + { time: 1000 }, + ); + calculateTactus(true); +}); diff --git a/packages/mini/package.json b/packages/mini/package.json index cb4f459c..7bd73011 100644 --- a/packages/mini/package.json +++ b/packages/mini/package.json @@ -9,6 +9,7 @@ }, "scripts": { "test": "vitest run", + "bench": "vitest bench", "build:parser": "peggy -o krill-parser.js --format es ./krill.pegjs", "build": "vite build", "prepublishOnly": "npm run build" From 956ceb8aa495c0a002e197a1028abd12ae90dd76 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Mon, 6 May 2024 21:29:15 +0200 Subject: [PATCH 045/195] fix: missing events due to premature worklet cleanup --- packages/superdough/worklets.mjs | 46 ++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index bab28987..a1f524ca 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -1,6 +1,7 @@ // coarse, crush, and shape processors adapted from dktr0's webdirt: https://github.com/dktr0/WebDirt/blob/5ce3d698362c54d6e1b68acc47eb2955ac62c793/dist/AudioWorklets.js // LICENSE GNU General Public License v3.0 see https://github.com/dktr0/WebDirt/blob/main/LICENSE +const blockSize = 128; class CoarseProcessor extends AudioWorkletProcessor { static get parameterDescriptors() { return [{ name: 'coarse', defaultValue: 1 }]; @@ -8,19 +9,21 @@ class CoarseProcessor extends AudioWorkletProcessor { constructor() { super(); + this.started = false; } process(inputs, outputs, parameters) { const input = inputs[0]; const output = outputs[0]; - const blockSize = 128; + + const hasInput = !(input[0] === undefined); + if (this.started && !hasInput) { + return false; + } + this.started = hasInput; let coarse = parameters.coarse[0] ?? 0; coarse = Math.max(1, coarse); - - if (input[0] == null || output[0] == null) { - return false; - } for (let n = 0; n < blockSize; n++) { for (let i = 0; i < input.length; i++) { output[i][n] = n % coarse === 0 ? input[i][n] : output[i][n - 1]; @@ -38,19 +41,22 @@ class CrushProcessor extends AudioWorkletProcessor { constructor() { super(); + this.started = false; } process(inputs, outputs, parameters) { const input = inputs[0]; const output = outputs[0]; - const blockSize = 128; + + const hasInput = !(input[0] === undefined); + if (this.started && !hasInput) { + return false; + } + this.started = hasInput; let crush = parameters.crush[0] ?? 8; crush = Math.max(1, crush); - if (input[0] == null || output[0] == null) { - return false; - } for (let n = 0; n < blockSize; n++) { for (let i = 0; i < input.length; i++) { const x = Math.pow(2, crush - 1); @@ -72,21 +78,24 @@ class ShapeProcessor extends AudioWorkletProcessor { constructor() { super(); + this.started = false; } process(inputs, outputs, parameters) { const input = inputs[0]; const output = outputs[0]; - const blockSize = 128; + + const hasInput = !(input[0] === undefined); + if (this.started && !hasInput) { + return false; + } + this.started = hasInput; let shape = parameters.shape[0]; shape = shape < 1 ? shape : 1.0 - 4e-10; shape = (2.0 * shape) / (1.0 - shape); const postgain = Math.max(0.001, Math.min(1, parameters.postgain[0])); - if (input[0] == null || output[0] == null) { - return false; - } for (let n = 0; n < blockSize; n++) { for (let i = 0; i < input.length; i++) { output[i][n] = (((1 + shape) * input[i][n]) / (1 + shape * Math.abs(input[i][n]))) * postgain; @@ -107,19 +116,22 @@ class DistortProcessor extends AudioWorkletProcessor { constructor() { super(); + this.started = false; } process(inputs, outputs, parameters) { const input = inputs[0]; const output = outputs[0]; - const blockSize = 128; + + const hasInput = !(input[0] === undefined); + if (this.started && !hasInput) { + return false; + } + this.started = hasInput; const shape = Math.expm1(parameters.distort[0]); const postgain = Math.max(0.001, Math.min(1, parameters.postgain[0])); - if (input[0] == null || output[0] == null) { - return false; - } for (let n = 0; n < blockSize; n++) { for (let i = 0; i < input.length; i++) { output[i][n] = (((1 + shape) * input[i][n]) / (1 + shape * Math.abs(input[i][n]))) * postgain; From 7f22040a0c4b2e723f316e8635bba3691e25a8c0 Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 10:44:58 +0200 Subject: [PATCH 046/195] use sessionStorage instead of localStorage --- website/src/user_pattern_utils.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index 19cba84b..cf849d3a 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -1,5 +1,5 @@ import { atom } from 'nanostores'; -import { persistentAtom } from '@nanostores/persistent'; +import { persistentAtom, setPersistentEngine } from '@nanostores/persistent'; import { useStore } from '@nanostores/react'; import { logger } from '@strudel/core'; import { nanoid } from 'nanoid'; @@ -21,6 +21,10 @@ export const patternFilterName = { user: 'user', }; +if (typeof sessionStorage !== 'undefined') { + setPersistentEngine(sessionStorage); +} + export let $viewingPatternData = persistentAtom( 'viewingPatternData', { From b69b9c37cd7f380db11a05287478356beae28c4d Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 11:01:02 +0200 Subject: [PATCH 047/195] fix events, add comment --- website/src/user_pattern_utils.mjs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index cf849d3a..b0a19e6a 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -1,5 +1,5 @@ import { atom } from 'nanostores'; -import { persistentAtom, setPersistentEngine } from '@nanostores/persistent'; +import { persistentAtom, setPersistentEngine, windowPersistentEvents } from '@nanostores/persistent'; import { useStore } from '@nanostores/react'; import { logger } from '@strudel/core'; import { nanoid } from 'nanoid'; @@ -22,7 +22,10 @@ export const patternFilterName = { }; if (typeof sessionStorage !== 'undefined') { - setPersistentEngine(sessionStorage); + // NB: this switches storageEngine of all persistent atoms + // ideally we would switch the engine per atom + // (like in this abandoned pr: https://github.com/nanostores/persistent/pull/30) + setPersistentEngine(sessionStorage, windowPersistentEvents); } export let $viewingPatternData = persistentAtom( From 6249631a722da0222a689ae2e595d85371f0b7a5 Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 11:40:09 +0200 Subject: [PATCH 048/195] implement sessionAtom function (same api as persistenAtom, just used sessionStorage instead of localStorage) --- website/src/user_pattern_utils.mjs | 60 ++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 8 deletions(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index b0a19e6a..4ce1e7d9 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -1,5 +1,5 @@ -import { atom } from 'nanostores'; -import { persistentAtom, setPersistentEngine, windowPersistentEvents } from '@nanostores/persistent'; +import {atom, onMount} from 'nanostores'; +import { persistentAtom, windowPersistentEvents } from '@nanostores/persistent'; import { useStore } from '@nanostores/react'; import { logger } from '@strudel/core'; import { nanoid } from 'nanoid'; @@ -21,14 +21,58 @@ export const patternFilterName = { user: 'user', }; +export let sessionAtom = persistentAtom; + if (typeof sessionStorage !== 'undefined') { - // NB: this switches storageEngine of all persistent atoms - // ideally we would switch the engine per atom - // (like in this abandoned pr: https://github.com/nanostores/persistent/pull/30) - setPersistentEngine(sessionStorage, windowPersistentEvents); + const identity = a => a; + const eventsEngine = windowPersistentEvents; + sessionAtom = (name, initial = undefined, opts = {}) => { + let encode = opts.encode || identity + let decode = opts.decode || identity + + let store = atom(initial) + + let set = store.set + store.set = newValue => { + if (typeof newValue === 'undefined') { + delete sessionStorage[name] + } else { + sessionStorage[name] = encode(newValue) + } + set(newValue) + } + + function listener(e) { + if (e.key === name) { + if (e.newValue === null) { + set(undefined) + } else { + set(decode(e.newValue)) + } + } else if (!sessionStorage[name]) { + set(undefined) + } + } + + function restore() { + store.set(sessionStorage[name] ? decode(sessionStorage[name]) : initial) + } + + onMount(store, () => { + restore() + if (opts.listen !== false) { + eventsEngine.addEventListener(name, listener, restore) + return () => { + eventsEngine.removeEventListener(name, listener, restore) + } + } + }) + + return store + } } -export let $viewingPatternData = persistentAtom( +export let $viewingPatternData = sessionAtom( 'viewingPatternData', { id: '', @@ -75,7 +119,7 @@ export async function loadDBPatterns() { } // reason: https://github.com/tidalcycles/strudel/issues/857 -const $activePattern = persistentAtom('activePattern', '', { listen: false }); +const $activePattern = sessionAtom('activePattern', '', { listen: false }); export function setActivePattern(key) { $activePattern.set(key); From 6e6a2439c3bfa9f75a0406a3c4ae7febcaf1f9ce Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 12:54:33 +0200 Subject: [PATCH 049/195] simplify implementation --- website/src/user_pattern_utils.mjs | 54 +++++++----------------------- 1 file changed, 13 insertions(+), 41 deletions(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index 4ce1e7d9..08e1ffc6 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -1,5 +1,5 @@ -import {atom, onMount} from 'nanostores'; -import { persistentAtom, windowPersistentEvents } from '@nanostores/persistent'; +import { atom, onMount } from 'nanostores'; +import { persistentAtom } from '@nanostores/persistent'; import { useStore } from '@nanostores/react'; import { logger } from '@strudel/core'; import { nanoid } from 'nanoid'; @@ -24,52 +24,24 @@ export const patternFilterName = { export let sessionAtom = persistentAtom; if (typeof sessionStorage !== 'undefined') { - const identity = a => a; - const eventsEngine = windowPersistentEvents; + const identity = (a) => a; sessionAtom = (name, initial = undefined, opts = {}) => { - let encode = opts.encode || identity - let decode = opts.decode || identity + let encode = opts.encode || identity; + let decode = opts.decode || identity; + if (opts.listen) console.error('sessionAtom does not support "listen" option'); - let store = atom(initial) + let store = atom(sessionStorage[name] ? decode(sessionStorage[name]) : initial); - let set = store.set - store.set = newValue => { + store.listen((newValue) => { if (typeof newValue === 'undefined') { - delete sessionStorage[name] + delete sessionStorage[name]; } else { - sessionStorage[name] = encode(newValue) + sessionStorage[name] = encode(newValue); } - set(newValue) - } + }); - function listener(e) { - if (e.key === name) { - if (e.newValue === null) { - set(undefined) - } else { - set(decode(e.newValue)) - } - } else if (!sessionStorage[name]) { - set(undefined) - } - } - - function restore() { - store.set(sessionStorage[name] ? decode(sessionStorage[name]) : initial) - } - - onMount(store, () => { - restore() - if (opts.listen !== false) { - eventsEngine.addEventListener(name, listener, restore) - return () => { - eventsEngine.removeEventListener(name, listener, restore) - } - } - }) - - return store - } + return store; + }; } export let $viewingPatternData = sessionAtom( From 5dc2ecd741619b91e470daa03e1ba9b47181fb08 Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 12:55:52 +0200 Subject: [PATCH 050/195] cleanup --- website/src/user_pattern_utils.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index 08e1ffc6..a76cf0e5 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -1,4 +1,4 @@ -import { atom, onMount } from 'nanostores'; +import { atom } from 'nanostores'; import { persistentAtom } from '@nanostores/persistent'; import { useStore } from '@nanostores/react'; import { logger } from '@strudel/core'; From 02ea4d111629c8be199ac09a9ed259c4f4e17cda Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 14:52:06 +0200 Subject: [PATCH 051/195] bug fix --- website/src/user_pattern_utils.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index a76cf0e5..9ab23fab 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -30,7 +30,7 @@ if (typeof sessionStorage !== 'undefined') { let decode = opts.decode || identity; if (opts.listen) console.error('sessionAtom does not support "listen" option'); - let store = atom(sessionStorage[name] ? decode(sessionStorage[name]) : initial); + let store = atom(typeof sessionStorage[name] !== 'undefined' ? decode(sessionStorage[name]) : initial); store.listen((newValue) => { if (typeof newValue === 'undefined') { From 33ebf08e81a1373b4b56fecae8ec716f7f296e20 Mon Sep 17 00:00:00 2001 From: Kaspars Date: Tue, 7 May 2024 15:20:59 +0200 Subject: [PATCH 052/195] simplify more --- website/src/user_pattern_utils.mjs | 52 +++++++++++------------------- 1 file changed, 19 insertions(+), 33 deletions(-) diff --git a/website/src/user_pattern_utils.mjs b/website/src/user_pattern_utils.mjs index 9ab23fab..ab2b5f35 100644 --- a/website/src/user_pattern_utils.mjs +++ b/website/src/user_pattern_utils.mjs @@ -21,39 +21,25 @@ export const patternFilterName = { user: 'user', }; -export let sessionAtom = persistentAtom; +const sessionAtom = (name, initial = undefined) => { + const storage = typeof sessionStorage !== 'undefined' ? sessionStorage : {}; + const store = atom(typeof storage[name] !== 'undefined' ? storage[name] : initial); + store.listen((newValue) => { + if (typeof newValue === 'undefined') { + delete storage[name]; + } else { + storage[name] = newValue; + } + }); + return store; +}; -if (typeof sessionStorage !== 'undefined') { - const identity = (a) => a; - sessionAtom = (name, initial = undefined, opts = {}) => { - let encode = opts.encode || identity; - let decode = opts.decode || identity; - if (opts.listen) console.error('sessionAtom does not support "listen" option'); - - let store = atom(typeof sessionStorage[name] !== 'undefined' ? decode(sessionStorage[name]) : initial); - - store.listen((newValue) => { - if (typeof newValue === 'undefined') { - delete sessionStorage[name]; - } else { - sessionStorage[name] = encode(newValue); - } - }); - - return store; - }; -} - -export let $viewingPatternData = sessionAtom( - 'viewingPatternData', - { - id: '', - code: '', - collection: collectionName.user, - created_at: Date.now(), - }, - { listen: false }, -); +export let $viewingPatternData = sessionAtom('viewingPatternData', { + id: '', + code: '', + collection: collectionName.user, + created_at: Date.now(), +}); export const getViewingPatternData = () => { return parseJSON($viewingPatternData.get()); @@ -91,7 +77,7 @@ export async function loadDBPatterns() { } // reason: https://github.com/tidalcycles/strudel/issues/857 -const $activePattern = sessionAtom('activePattern', '', { listen: false }); +const $activePattern = sessionAtom('activePattern', ''); export function setActivePattern(key) { $activePattern.set(key); From a69563cb9ba1f9104c1099a205052c5c783b580f Mon Sep 17 00:00:00 2001 From: Kaspars Jaudzems Date: Sun, 12 May 2024 19:23:08 +0300 Subject: [PATCH 053/195] repl: set document.title from @title (#1090) * fixes #811 set document.title from @title --- website/src/repl/Repl.jsx | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/website/src/repl/Repl.jsx b/website/src/repl/Repl.jsx index 9c472eb4..d709d058 100644 --- a/website/src/repl/Repl.jsx +++ b/website/src/repl/Repl.jsx @@ -38,6 +38,7 @@ import { getRandomTune, initCode, loadModules, shareCode, ReplContext } from './ import PlayCircleIcon from '@heroicons/react/20/solid/PlayCircleIcon'; import './Repl.css'; import { setInterval, clearInterval } from 'worker-timers'; +import { getMetadata } from '../metadata_parser'; const { latestCode } = settingsMap.get(); @@ -91,6 +92,7 @@ export function Repl({ embedded = false }) { const { code } = all; setLatestCode(code); window.location.hash = '#' + code2hash(code); + setDocumentTitle(code); const viewingPatternData = getViewingPatternData(); const data = { ...viewingPatternData, code }; let id = data.id; @@ -116,18 +118,20 @@ export function Repl({ embedded = false }) { // init settings initCode().then(async (decoded) => { - let msg; + let code, msg; if (decoded) { - editor.setCode(decoded); + code = decoded; msg = `I have loaded the code from the URL.`; } else if (latestCode) { - editor.setCode(latestCode); + code = latestCode; msg = `Your last session has been loaded!`; } else { const { code: randomTune, name } = await getRandomTune(); - editor.setCode(randomTune); + code = randomTune; msg = `A random code snippet named "${name}" has been loaded!`; } + editor.setCode(code); + setDocumentTitle(code); logger(`Welcome to Strudel! ${msg} Press play or hit ctrl+enter to run it!`, 'highlight'); }); @@ -170,6 +174,11 @@ export function Repl({ embedded = false }) { // UI Actions // + const setDocumentTitle = (code) => { + const meta = getMetadata(code); + document.title = (meta.title ? `${meta.title} - ` : '') + 'Strudel REPL'; + }; + const handleTogglePlay = async () => { editorRef.current?.toggle(); }; From e268802f3cb268cf6cdec6aa7fd60abd61522b1d Mon Sep 17 00:00:00 2001 From: Kaspars Jaudzems Date: Mon, 13 May 2024 11:10:34 +0300 Subject: [PATCH 054/195] OSC/SuperDirt fixes (#1093) * If note is a midi note, and it's sent together with octave to SuperDirt, then that will be wrong. instead we should to midinote whenever sure that it's a midi note. * mapbank to work like tidal's drumFrom * roomsize is size in SuperDirt * fix tidal-sniffer * export `registerControl` (but see #1098) --- packages/core/controls.mjs | 2 +- packages/osc/osc.mjs | 12 ++++++++++-- packages/osc/tidal-sniffer.js | 2 +- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 166f0ac2..d5dbef13 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -47,7 +47,7 @@ export function createParam(names) { return func; } -function registerControl(names, ...aliases) { +export function registerControl(names, ...aliases) { const name = Array.isArray(names) ? names[0] : names; let bag = {}; bag[name] = createParam(names); diff --git a/packages/osc/osc.mjs b/packages/osc/osc.mjs index 5552a1c1..422e56da 100644 --- a/packages/osc/osc.mjs +++ b/packages/osc/osc.mjs @@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th import OSC from 'osc-js'; -import { logger, parseNumeral, Pattern, getEventOffsetMs } from '@strudel/core'; +import { logger, parseNumeral, Pattern, getEventOffsetMs, isNote, noteToMidi } from '@strudel/core'; let connection; // Promise function connect() { @@ -52,7 +52,15 @@ Pattern.prototype.osc = function () { const controls = Object.assign({}, { cps, cycle, delta }, hap.value); // make sure n and note are numbers controls.n && (controls.n = parseNumeral(controls.n)); - controls.note && (controls.note = parseNumeral(controls.note)); + if (typeof controls.note !== 'undefined') { + if (isNote(controls.note)) { + controls.midinote = noteToMidi(controls.note, controls.octave || 3); + } else { + controls.note = parseNumeral(controls.note); + } + } + controls.bank && (controls.s = controls.bank + controls.s); + controls.roomsize && (controls.size = parseNumeral(controls.roomsize)); const keyvals = Object.entries(controls).flat(); // time should be audio time of onset // currentTime should be current time of audio context (slightly before time) diff --git a/packages/osc/tidal-sniffer.js b/packages/osc/tidal-sniffer.js index 2cbb15e6..10bf0ad0 100644 --- a/packages/osc/tidal-sniffer.js +++ b/packages/osc/tidal-sniffer.js @@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see . */ -const OSC = require('osc-js'); +import OSC from 'osc-js'; const config = { receiver: 'ws', // @param {string} Where messages sent via 'send' method will be delivered to, 'ws' for Websocket clients, 'udp' for udp client From 4ade86f75ce012ea6eff0617d07108ee058bb037 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 10:59:57 +0200 Subject: [PATCH 055/195] hotfix: rebuild parser to remove logs --- packages/mini/krill-parser.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/mini/krill-parser.js b/packages/mini/krill-parser.js index 1cdd3486..0a062f46 100644 --- a/packages/mini/krill-parser.js +++ b/packages/mini/krill-parser.js @@ -295,13 +295,12 @@ function peg$parse(input, options) { var peg$f6 = function(a) { return a }; var peg$f7 = function(s) { s.arguments_.alignment = 'polymeter_slowcat'; return s; }; var peg$f8 = function(a) { return x => x.options_['weight'] = (x.options_['weight'] ?? 1) + (a ?? 2) - 1 }; - var peg$f9 = function(a) { return x => {const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1; + var peg$f9 = function(a) { return x => {// A bit fiddly, to support both x!4 and x!!! as equivalent.. + const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1; x.options_['reps'] = reps; - console.log("reps: ", reps) x.options_['ops'] = x.options_['ops'].filter(x => x.type_ !== "replicate"); x.options_['ops'].push({ type_: "replicate", arguments_ :{ amount:reps }}); x.options_['weight'] = reps; - console.log("options: ", x.options_); } }; var peg$f10 = function(p, s, r) { return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) }; From 179931be88056cac4cb4d35579637a2e37c1eec4 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:10:42 +0200 Subject: [PATCH 056/195] fix lockfile: reset to main one --- pnpm-lock.yaml | 98 ++------------------------------------------------ 1 file changed, 3 insertions(+), 95 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0a085314..de4f9185 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -251,31 +251,6 @@ importers: packages/embed: {} - packages/haskell: - dependencies: - '@hpcc-js/wasm': - specifier: ^2.15.3 - version: 2.15.3 - jgf-dot: - specifier: ^1.1.1 - version: 1.1.1 - web-tree-sitter: - specifier: ^0.20.8 - version: 0.20.8 - devDependencies: - tree-sitter: - specifier: ^0.20.6 - version: 0.20.6 - tree-sitter-cli: - specifier: ^0.20.8 - version: 0.20.8 - tree-sitter-javascript: - specifier: ^0.20.1 - version: 0.20.1 - vite: - specifier: ^5.0.8 - version: 5.0.10 - packages/hydra: dependencies: '@strudel/core': @@ -8228,33 +8203,6 @@ packages: /graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} - /graphlib-dot@0.6.4: - resolution: {integrity: sha512-rdhDTu0mBlloTpFMfkQq+e3y4yL22OqP5MhQbkw6QUURqa+4YLgv3XZy2fA64wdEcJNZ+waI76URemVgdFtzng==} - dependencies: - graphlib: 2.1.8 - lodash: 4.17.21 - dev: false - - /graphlib-json-graph@1.0.0: - resolution: {integrity: sha512-sJsFuthZnSL5knaDDZhDx8fg1Zy5t/7ZqVHiytoeSzezGhMoSFD3T3K5YQakKFEyXtYjOzbnvsyr2qo+6/qq/Q==} - dependencies: - graphlib: 1.0.7 - par: 0.3.0 - prop: 0.1.1 - dev: false - - /graphlib@1.0.7: - resolution: {integrity: sha512-jNb7RbqTIRyZRmcVCxGefOlGWjNdbjcT2tFj36zhnRa8yhAlOvydh9nBixfLQIqSU+DwCx47tg3ysw8NIYhpsA==} - dependencies: - lodash: 3.10.1 - dev: false - - /graphlib@2.1.8: - resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==} - dependencies: - lodash: 4.17.21 - dev: false - /gray-matter@4.0.3: resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==} engines: {node: '>=6.0'} @@ -9610,12 +9558,9 @@ packages: resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==} dev: true - /lodash@3.10.1: - resolution: {integrity: sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==} - dev: false - /lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} + dev: true /log-symbols@4.1.0: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} @@ -11321,11 +11266,6 @@ packages: - supports-color dev: true - /par@0.3.0: - resolution: {integrity: sha512-6V910zFAoHnxjX6ILkwbQcpIkD3KI2gBAPfCtZQNaJTvTxgIoKXSwDQIE3ty0zbOGdBXHRnl6rd66a5jj12pfw==} - engines: {node: '>=0.6'} - dev: false - /parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -11661,21 +11601,12 @@ packages: picocolors: 1.0.0 source-map-js: 1.2.0 - /postcss@8.4.32: - resolution: {integrity: sha512-D/kj5JNu6oo2EIy+XL/26JEDTlIbB8hw85G8StOE6L74RQAVVP5rej6wxCNqyMbR4RkPfqvezVbPw81Ngd6Kcw==} - engines: {node: ^10 || ^12 || >=14} - dependencies: - nanoid: 3.3.7 - picocolors: 1.0.0 - source-map-js: 1.0.2 - dev: true - /prebuild-install@7.1.1: resolution: {integrity: sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==} engines: {node: '>=10'} hasBin: true dependencies: - detect-libc: 2.0.2 + detect-libc: 2.0.1 expand-template: 2.0.3 github-from-package: 0.0.0 minimist: 1.2.7 @@ -11805,12 +11736,6 @@ packages: read: 2.1.0 dev: true - /prop@0.1.1: - resolution: {integrity: sha512-hf5DdgiPkcoVxBfuSknP918U0lDC+7lArIjIB2U4Gh79p1Xtc0JP6W5DW3c0wC0x9/A6CsAISh3202I1GlMgkw==} - dependencies: - dotty: 0.0.1 - dev: false - /property-information@6.2.0: resolution: {integrity: sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==} @@ -14261,10 +14186,6 @@ packages: engines: {node: '>= 8'} dev: true - /web-tree-sitter@0.20.8: - resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} - dev: false - /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} @@ -14738,19 +14659,6 @@ packages: yargs-parser: 21.1.1 dev: true - /yargs@17.7.2: - resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} - engines: {node: '>=12'} - dependencies: - cliui: 8.0.1 - escalade: 3.1.1 - get-caller-file: 2.0.5 - require-directory: 2.1.1 - string-width: 4.2.3 - y18n: 5.0.8 - yargs-parser: 21.1.1 - dev: false - /yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} @@ -14763,4 +14671,4 @@ packages: resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==} /zwitch@2.0.4: - resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} + resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} \ No newline at end of file From 733d6ec67369985a994e41ef7c384af05b032053 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:12:11 +0200 Subject: [PATCH 057/195] pnpm i --- pnpm-lock.yaml | 133 ++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 127 insertions(+), 6 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index de4f9185..e3395c25 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -251,6 +251,31 @@ importers: packages/embed: {} + packages/haskell: + dependencies: + '@hpcc-js/wasm': + specifier: ^2.15.3 + version: 2.16.2 + jgf-dot: + specifier: ^1.1.1 + version: 1.1.1 + web-tree-sitter: + specifier: ^0.20.8 + version: 0.20.8 + devDependencies: + tree-sitter: + specifier: ^0.20.6 + version: 0.20.6 + tree-sitter-cli: + specifier: ^0.20.8 + version: 0.20.8 + tree-sitter-javascript: + specifier: ^0.20.1 + version: 0.20.4 + vite: + specifier: ^5.0.8 + version: 5.2.2(@types/node@20.10.6) + packages/hydra: dependencies: '@strudel/core': @@ -3034,6 +3059,13 @@ packages: react: 18.2.0 dev: false + /@hpcc-js/wasm@2.16.2: + resolution: {integrity: sha512-THiidUMYR8/cIfFT3MVcWuRE7bQKh295nrFBxGvUNc4Nq8e2uU1LtiplHs7AUkJ0GxgvZoR+8TQ1/E3Qb/uE2g==} + hasBin: true + dependencies: + yargs: 17.7.2 + dev: false + /@humanwhocodes/config-array@0.11.13: resolution: {integrity: sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==} engines: {node: '>=10.10.0'} @@ -6227,7 +6259,6 @@ packages: string-width: 4.2.3 strip-ansi: 6.0.1 wrap-ansi: 7.0.0 - dev: true /clone-buffer@1.0.0: resolution: {integrity: sha512-KLLTJWrvwIP+OPfMn0x2PheDEP20RPUcGXj/ERegTgdmPEZylALQldygiqrPPu8P45uNuPs7ckmReLY6v/iA5g==} @@ -6945,6 +6976,10 @@ packages: engines: {node: '>=12'} dev: true + /dotty@0.0.1: + resolution: {integrity: sha512-eDT0hfJEnQbGaZcTuCfj2igPkQ7qa/n9K2pGGDxhEqKhARLq+xE1TonvpOPHq+7KeG+D6A/V8BwCcsdPom2TQg==} + dev: false + /dset@3.1.3: resolution: {integrity: sha512-20TuZZHCEZ2O71q9/+8BwKwZ0QtD9D8ObhrihJPr+vLLYlSuAU3/zL4cSlgbfeoGHTjCSJBa7NGcrF9/Bx/WJQ==} engines: {node: '>=4'} @@ -7866,6 +7901,10 @@ packages: resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} dev: true + /gather-stream@1.0.0: + resolution: {integrity: sha512-NspYMi3rN3EKmMdejUXbtluDYrcRlTEBBFhWzVRZVsOx94OPxlXp0AzyPKyLiT7iaurcoTE/KcHsHP/PowNEaA==} + dev: false + /gauge@4.0.4: resolution: {integrity: sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -8203,6 +8242,33 @@ packages: /graphemer@1.4.0: resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + /graphlib-dot@0.6.4: + resolution: {integrity: sha512-rdhDTu0mBlloTpFMfkQq+e3y4yL22OqP5MhQbkw6QUURqa+4YLgv3XZy2fA64wdEcJNZ+waI76URemVgdFtzng==} + dependencies: + graphlib: 2.1.8 + lodash: 4.17.21 + dev: false + + /graphlib-json-graph@1.0.0: + resolution: {integrity: sha512-sJsFuthZnSL5knaDDZhDx8fg1Zy5t/7ZqVHiytoeSzezGhMoSFD3T3K5YQakKFEyXtYjOzbnvsyr2qo+6/qq/Q==} + dependencies: + graphlib: 1.0.7 + par: 0.3.0 + prop: 0.1.1 + dev: false + + /graphlib@1.0.7: + resolution: {integrity: sha512-jNb7RbqTIRyZRmcVCxGefOlGWjNdbjcT2tFj36zhnRa8yhAlOvydh9nBixfLQIqSU+DwCx47tg3ysw8NIYhpsA==} + dependencies: + lodash: 3.10.1 + dev: false + + /graphlib@2.1.8: + resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==} + dependencies: + lodash: 4.17.21 + dev: false + /gray-matter@4.0.3: resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==} engines: {node: '>=6.0'} @@ -9102,6 +9168,15 @@ packages: supports-color: 7.2.0 dev: true + /jgf-dot@1.1.1: + resolution: {integrity: sha512-/aw9bwVfn67A+lvjxtbocBuhB2rNdL5UY5rlHhKVh9ValvVJETU5lQ0jitDxiIjIPAEeuR4B1aFNA7E3wKNV1A==} + hasBin: true + dependencies: + graphlib-dot: 0.6.4 + graphlib-json-graph: 1.0.0 + read-file-stdin: 0.2.1 + dev: false + /jiti@1.21.0: resolution: {integrity: sha512-gFqAIbuKyyso/3G2qhiO2OM6shY6EPP/R0+mkDbyspxKazh8BXDC5FiFsUjlczgdNz/vfra0da2y+aHrusLG/Q==} hasBin: true @@ -9558,9 +9633,12 @@ packages: resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==} dev: true + /lodash@3.10.1: + resolution: {integrity: sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==} + dev: false + /lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} - dev: true /log-symbols@4.1.0: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} @@ -10582,6 +10660,10 @@ packages: thenify-all: 1.6.0 dev: false + /nan@2.19.0: + resolution: {integrity: sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw==} + dev: true + /nanoid@3.3.7: resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -11266,6 +11348,11 @@ packages: - supports-color dev: true + /par@0.3.0: + resolution: {integrity: sha512-6V910zFAoHnxjX6ILkwbQcpIkD3KI2gBAPfCtZQNaJTvTxgIoKXSwDQIE3ty0zbOGdBXHRnl6rd66a5jj12pfw==} + engines: {node: '>=0.6'} + dev: false + /parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -11736,6 +11823,12 @@ packages: read: 2.1.0 dev: true + /prop@0.1.1: + resolution: {integrity: sha512-hf5DdgiPkcoVxBfuSknP918U0lDC+7lArIjIB2U4Gh79p1Xtc0JP6W5DW3c0wC0x9/A6CsAISh3202I1GlMgkw==} + dependencies: + dotty: 0.0.1 + dev: false + /property-information@6.2.0: resolution: {integrity: sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==} @@ -11867,6 +11960,12 @@ packages: engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} dev: true + /read-file-stdin@0.2.1: + resolution: {integrity: sha512-dAqysQ4kfj9m5aejZOPr+aRGXZJXdLkMOLZ3BXMwMBQHiO+aylGBFJPh88AYPQrOf+D43F4Uc2oUIW9kBlItLA==} + dependencies: + gather-stream: 1.0.0 + dev: false + /read-package-json-fast@3.0.2: resolution: {integrity: sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} @@ -13392,6 +13491,27 @@ packages: punycode: 2.3.1 dev: true + /tree-sitter-cli@0.20.8: + resolution: {integrity: sha512-XjTcS3wdTy/2cc/ptMLc/WRyOLECRYcMTrSWyhZnj1oGSOWbHLTklgsgRICU3cPfb0vy+oZCC33M43u6R1HSCA==} + hasBin: true + requiresBuild: true + dev: true + + /tree-sitter-javascript@0.20.4: + resolution: {integrity: sha512-7IUgGkZQROI7MmX2ErKhE3YP4+rM2qwBy5JeukE7fJQMEYP9nHpxvuQpa+eOX+hE1im2pWVc1yDCfVKKCBtxww==} + requiresBuild: true + dependencies: + nan: 2.19.0 + dev: true + + /tree-sitter@0.20.6: + resolution: {integrity: sha512-GxJodajVpfgb3UREzzIbtA1hyRnTxVbWVXrbC6sk4xTMH5ERMBJk9HJNq4c8jOJeUaIOmLcwg+t6mez/PDvGqg==} + requiresBuild: true + dependencies: + nan: 2.19.0 + prebuild-install: 7.1.1 + dev: true + /trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -14186,6 +14306,10 @@ packages: engines: {node: '>= 8'} dev: true + /web-tree-sitter@0.20.8: + resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} + dev: false + /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} @@ -14494,7 +14618,6 @@ packages: ansi-styles: 4.3.0 string-width: 4.2.3 strip-ansi: 6.0.1 - dev: true /wrap-ansi@8.1.0: resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} @@ -14586,7 +14709,6 @@ packages: /y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} - dev: true /yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -14657,7 +14779,6 @@ packages: string-width: 4.2.3 y18n: 5.0.8 yargs-parser: 21.1.1 - dev: true /yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} @@ -14671,4 +14792,4 @@ packages: resolution: {integrity: sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==} /zwitch@2.0.4: - resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} \ No newline at end of file + resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} From 2aac085bb8ac623e3dd91a36feb596f54b73cab7 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:12:30 +0200 Subject: [PATCH 058/195] lint fix --- packages/haskell/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/haskell/index.html b/packages/haskell/index.html index 9883b1b9..c371ec39 100644 --- a/packages/haskell/index.html +++ b/packages/haskell/index.html @@ -1,4 +1,4 @@ - + From 09e455e17e2972239afd0f82e3d09c24fb59ede4 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:30:00 +0200 Subject: [PATCH 059/195] move haskell-tree-sitter-playground --- packages/haskell/.gitignore | 2 - packages/haskell/README.md | 28 ++------ packages/haskell/graph.mjs | 43 +++++++++++ packages/haskell/hs2js.mjs | 131 ++++++++++++++++++++++++++++++++++ packages/haskell/index.html | 23 ++++-- packages/haskell/main.js | 120 ++++++++++++++++++++----------- packages/haskell/package.json | 38 +++++++--- packages/haskell/parser.mjs | 22 ++++++ pnpm-lock.yaml | 58 +++++++++------ 9 files changed, 362 insertions(+), 103 deletions(-) create mode 100644 packages/haskell/graph.mjs create mode 100644 packages/haskell/hs2js.mjs create mode 100644 packages/haskell/parser.mjs diff --git a/packages/haskell/.gitignore b/packages/haskell/.gitignore index 75d4123f..ce99c129 100644 --- a/packages/haskell/.gitignore +++ b/packages/haskell/.gitignore @@ -25,5 +25,3 @@ dist-ssr public/tree-sitter.wasm public/tree-sitter-haskell.wasm -public/tree-sitter-haskell_mine.wasm -public/tree-sitter-haskell_theirs.wasm \ No newline at end of file diff --git a/packages/haskell/README.md b/packages/haskell/README.md index 0143b93e..24f3efc3 100644 --- a/packages/haskell/README.md +++ b/packages/haskell/README.md @@ -1,31 +1,11 @@ -# @strudel/haskell +# @strudel/tidal This is an experiment in implementing tree-sitter for parsing haskell. -So far, I have just set up a vite project that imports and inits `web-tree-sitter`, which works after - -- -- - -Running: - ```sh -cd haskell && pnpm i +pnpm i +cd haskell pnpm dev ``` -will start the vite dev server, loading tree sitter on `http://localhost:5174/`. - -The next step is be to generate `tree-sitter-haskell.wasm` file following . - -I've tried to generate it using but it failed, due to some versioning conflicts involving node / v8 / node-gyp. - -It seems a lot of work has gone into this package in , without a new npm package version being released, which is why I've written this comment: . - -So either someone authorized releases a new version of the package or we might need to pull the changes and try to build it from the tree-sitter master branch. - -## Update 1 - -I've managed to make it work by using [this tree-sitter-haskell.wasm](https://github.com/tree-sitter/tree-sitter-haskell/blob/master/tree-sitter-haskell.wasm), instead of using the version on npm! Make sure both `tree-sitter.wasm` and `tree-sitter-haskell.wasm` are in the public dir, then run `pnpm dev`. The console should log a tree sitter AST string. - -Next step: understand how the ast works to then transform it into JS function calls! +This \ No newline at end of file diff --git a/packages/haskell/graph.mjs b/packages/haskell/graph.mjs new file mode 100644 index 00000000..bac3d135 --- /dev/null +++ b/packages/haskell/graph.mjs @@ -0,0 +1,43 @@ +import { Graphviz } from '@hpcc-js/wasm'; +import toDot from 'jgf-dot'; + +const graphvizLoaded = Graphviz.load(); + +function walk(node, branch = [0], parent) { + let nodes = []; + let edges = []; + const color = 'white'; + const current = { + id: branch.join('-'), + color, + fontcolor: color, + label: node.type.replace('\\', 'lambda'), // backslash kills graphviz.. + }; + nodes.push(current); + parent && edges.push({ source: parent.id, target: current.id, color }); + if (node.children.length) { + node.children.forEach((child, j) => { + const { nodes: childNodes, edges: childEdges } = walk(child, branch.concat([j]), current); + nodes = nodes.concat(childNodes || []); + edges = edges.concat(childEdges || []); + }); + } + return { nodes, edges }; +} + +export async function renderGraph(tree, container) { + const { nodes, edges } = walk(tree.rootNode); + const graphviz = await graphvizLoaded; + let dot = toDot({ + graph: { + nodes, + edges, + }, + }); + dot = dot.split('\n'); + dot.splice(1, 0, 'bgcolor="transparent"'); + dot.splice(1, 0, 'color="white"'); + dot = dot.join('\n'); + const svg = await graphviz.layout(dot, 'svg', 'dot', {}); + container.innerHTML = svg; +} diff --git a/packages/haskell/hs2js.mjs b/packages/haskell/hs2js.mjs new file mode 100644 index 00000000..3a507112 --- /dev/null +++ b/packages/haskell/hs2js.mjs @@ -0,0 +1,131 @@ +function runApply(node, scope, ops) { + if (node.children.length !== 2) + throw new Error(`expected 2 children for node type apply, got ${node.children.length}`); + const [fn, arg] = node.children.map((child) => run(child, scope, ops)); + if (typeof fn !== 'function') { + throw new Error(`${node.children[0].text} is not a function`); + } + // only works if fn is curried! + return fn(arg); +} + +function runInfix(left, symbol, right, ops) { + const customOp = ops[symbol]; + if (customOp) { + return customOp(left, right); + } + switch (symbol) { + case '+': + return left + right; + case '-': + return left - right; + case '*': + return left * right; + case '/': + return left / right; + case '$': + return left(right); + case '&': + console.log('right', right); + return right(left); + case '.': + return (x) => left(right(x)); + default: + throw new Error('unexpected infix operator ' + symbol); + } +} + +function curry(patterns, body, scope, ops) { + const [variable, ...rest] = patterns; + return (arg) => { + let _scope = { ...scope, [variable.text]: arg }; + if (patterns.length === 1) { + const result = run(body, _scope, ops); + return result; + } + return curry(rest, body, _scope, ops); + }; +} + +export function run(node, scope, ops = {}) { + let runInScope = (node, scp = scope) => run(node, scp, ops); + //console.log("node", node.type, node.text); + switch (node.type) { + case 'ERROR': + throw new Error(`invalid syntax: "${node.text}"`); + case 'declarations': + let result; + node.children.forEach((declaration) => { + result = runInScope(declaration); + }); + return result; + case 'integer': + return Number(node.text); + case 'float': + return Number(node.text); + case 'string': + const str = node.text.slice(1, -1); + return String(str); + case 'lambda': + const [_, lpatterns, __, lbody] = node.children; + return curry(lpatterns.children, lbody, scope, ops); + case 'function': + const [fvariable, fpatterns, fbody] = node.children; + scope[fvariable.text] = curry(fpatterns.children, fbody, scope, ops); + return scope[fvariable.text]; + case 'list': { + return node.children + .filter((_, i) => i % 2 === 1) // elements are at odd indices + .map((node) => runInScope(node)); + } + case 'match': + if (node.children[0].text !== '=' || node.children.length !== 2) { + throw new Error('match node so far only support simple assignments'); + } + return runInScope(node.children[1]); + case 'bind': + if (node.children.length !== 2) throw new Error('expected 2 children for node type bind'); + if (node.children[0].type !== 'variable') throw new Error('expected variable as first child of bind node'); + if (node.children[1].type !== 'match') throw new Error('expected match as first child of bind node'); + const [bvariable, bmatch] = node.children; + const value = runInScope(bmatch); + scope[bvariable.text] = value; + return value; + case 'variable': + return scope[node.text]; + case 'infix': { + const [a, op, b] = node.children; + const symbol = op.text; + const [left, right] = [runInScope(a), runInScope(b)]; + return runInfix(left, symbol, right, ops); + } + case 'apply': + return runApply(node, scope, ops); + case 'left_section': { + const [_, b, op] = node.children; + const right = runInScope(b); + return (left) => runInfix(left, op.text, right, ops); + } + case 'right_section': { + const [_, op, b] = node.children; + const right = runInScope(b); + return (left) => runInfix(left, op.text, right, ops); + } + case 'parens': + if (node.children.length !== 3) throw new Error('expected 3 children for node type parens'); + return runInScope(node.children[1]); + default: + if (node.children.length === 0) { + throw new Error('unhandled leaf type ' + node.type); + } + if (node.children.length > 1) { + throw new Error('unhandled branch type ' + node.type); + } + return runInScope(node.children[0]); + } +} + +export async function evaluate(haskellCode, scope = globalThis, ops) { + const ast = await parse(haskellCode); + return run(ast.rootNode, scope, ops); +} diff --git a/packages/haskell/index.html b/packages/haskell/index.html index c371ec39..532bce3d 100644 --- a/packages/haskell/index.html +++ b/packages/haskell/index.html @@ -2,13 +2,28 @@ - Tree sitter test + - - -
+ + +

+    
diff --git a/packages/haskell/main.js b/packages/haskell/main.js index df11110a..bd9c2702 100644 --- a/packages/haskell/main.js +++ b/packages/haskell/main.js @@ -1,51 +1,89 @@ -import Parser from 'web-tree-sitter'; -import toDot from 'jgf-dot'; -import { Graphviz } from '@hpcc-js/wasm'; +import { run } from './hs2js.mjs'; +import { renderGraph } from './graph.mjs'; +import { parse } from './parser.mjs'; +import { initStrudel, reify, late } from '@strudel/web'; +initStrudel({ + prebake: () => samples('github:tidalcycles/dirt-samples'), +}); -const graphvizLoaded = Graphviz.load(); -const parserLoaded = loadParser(); const graphContainer = document.getElementById('graph'); const textarea = document.getElementById('code'); -textarea.value = 'd1 $ s "hh(3,8)"'; -textarea.addEventListener('input', (e) => renderGraph(e.target.value, graphContainer)); -renderGraph(textarea.value, graphContainer); +if (window.location.hash) { + textarea.value = atob(window.location.hash.slice(1)); +} else { + textarea.value = 'd1 $ s "jvbass(3,8)"'; +} +textarea.addEventListener('input', (e) => { + window.location.hash = btoa(e.target.value); + update(); +}); +update(); -function walk(node, branch = [0], parent) { - let nodes = []; - let edges = []; - const current = { id: branch.join('-'), label: node.type }; - nodes.push(current); - parent && edges.push({ source: parent.id, target: current.id }); - if (node.children.length) { - node.children.forEach((child, j) => { - const { nodes: childNodes, edges: childEdges } = walk(child, branch.concat([j]), current); - nodes = nodes.concat(childNodes || []); - edges = edges.concat(childEdges || []); +function getInfixOperators() { + let operators = { + '>': 'set', + '#': 'set', + '+': 'add', + '-': 'sub', + '*': 'mul', + '/': 'div', + }; + let alignments = { + in: (s) => '|' + s, + out: (s) => s + '|', + mix: (s) => '|' + s + '|', + }; + let ops = {}; + Object.entries(operators).forEach(([o, name]) => { + // operator without alignment + ops[o] = (l, r) => reify(l)[name](reify(r)); + Object.entries(alignments).forEach(([a, getSymbol]) => { + // get symbol with alignment + let symbol = getSymbol(o); + ops[symbol] = (l, r) => reify(l)[name][a](reify(r)); }); - } - return { nodes, edges }; -} - -async function renderGraph(code, container) { - const parser = await parserLoaded; - const tree = parser.parse(code); - const { nodes, edges } = walk(tree.rootNode); - const graphviz = await graphvizLoaded; - const dot = toDot({ - graph: { - nodes, - edges, - }, }); - const svg = await graphviz.layout(dot, 'svg', 'dot'); - container.innerHTML = svg; + ops['~>'] = (l, r) => reify(l).late(reify(r)); + ops['<~'] = (l, r) => reify(l).early(reify(r)); + ops['<$>'] = (l, r) => reify(r).fmap(l).outerJoin(); // is this right? + return ops; } +const ops = getInfixOperators(); -async function loadParser() { - await Parser.init(); - const parser = new Parser(); - const Lang = await Parser.Language.load('tree-sitter-haskell.wasm'); - parser.setLanguage(Lang); - return parser; +async function update() { + let result, tree; + try { + tree = await parse(textarea.value); + } catch (err) { + console.warn('parse error'); + console.error(err); + } + console.log('parsed tree'); + console.log(tree.rootNode.toString()); + try { + renderGraph(tree, graphContainer); + } catch (err) { + console.warn('could not render graph'); + console.error(err); + } + try { + let patterns = {}; + window.p = (name, pattern) => { + patterns[name] = pattern; + }; + window.d1 = (pat) => window.p(1, pat); + window.d2 = (pat) => window.p(2, pat); + window.d3 = (pat) => window.p(3, pat); + window.rot = late; + result = run(tree.rootNode, window, ops); + if (Object.values(patterns).length) { + stack(...Object.values(patterns)).play(); + } + } catch (err) { + console.warn('eval error'); + console.error(err); + result = 'ERROR: ' + err.message; + } + document.getElementById('result').innerHTML = 'Result: ' + result; } diff --git a/packages/haskell/package.json b/packages/haskell/package.json index 46039e25..7d8b72e4 100644 --- a/packages/haskell/package.json +++ b/packages/haskell/package.json @@ -1,24 +1,42 @@ { - "name": "haskell", + "name": "@strudel/tidal", "private": true, - "version": "0.0.0", + "version": "0.0.1", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", - "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public", - "parse": "tree-sitter parse -D ./test.hs" + "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public && npm run build:parser", + "build:parser": "tree-sitter build-wasm node_modules/tree-sitter-haskell && mv tree-sitter-haskell.wasm public" }, - "devDependencies": { - "tree-sitter": "^0.20.6", - "tree-sitter-cli": "^0.20.8", - "tree-sitter-javascript": "^0.20.1", - "vite": "^5.0.8" + "repository": { + "type": "git", + "url": "git+https://github.com/tidalcycles/strudel.git" }, + "keywords": [ + "titdalcycles", + "strudel", + "pattern", + "livecoding", + "algorave" + ], + "author": "Felix Roos ", + "license": "AGPL-3.0-or-later", + "bugs": { + "url": "https://github.com/tidalcycles/strudel/issues" + }, + "homepage": "https://github.com/tidalcycles/strudel#readme", "dependencies": { "@hpcc-js/wasm": "^2.15.3", "jgf-dot": "^1.1.1", - "web-tree-sitter": "^0.20.8" + "web-tree-sitter": "^0.22.6", + "tree-sitter-haskell": "^0.21.0", + "@strudel/web": "workspace:*" + }, + "devDependencies": { + "tree-sitter": "^0.21.1", + "tree-sitter-cli": "^0.20.8", + "vite": "^5.0.8" } } diff --git a/packages/haskell/parser.mjs b/packages/haskell/parser.mjs new file mode 100644 index 00000000..1b1f8a03 --- /dev/null +++ b/packages/haskell/parser.mjs @@ -0,0 +1,22 @@ +import Parser from 'web-tree-sitter'; + +const base = import.meta.env.BASE_URL; + +async function loadParser() { + await Parser.init({ + locateFile(scriptName, scriptDirectory) { + return `${base}${scriptName}`; + }, + }); + const parser = new Parser(); + const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`); + parser.setLanguage(Lang); + return parser; +} + +let parserLoaded = loadParser(); +export async function parse(code) { + const parser = await parserLoaded; + // for some reason, the parser doesn't like new lines.. + return parser.parse(code.replaceAll('\n\n', '~~~~').replaceAll('\n', '').replaceAll('~~~~', '\n')); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e3395c25..76947b5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -256,22 +256,25 @@ importers: '@hpcc-js/wasm': specifier: ^2.15.3 version: 2.16.2 + '@strudel/web': + specifier: workspace:* + version: link:../web jgf-dot: specifier: ^1.1.1 version: 1.1.1 + tree-sitter-haskell: + specifier: ^0.21.0 + version: 0.21.0(tree-sitter@0.21.1) web-tree-sitter: - specifier: ^0.20.8 - version: 0.20.8 + specifier: ^0.22.6 + version: 0.22.6 devDependencies: tree-sitter: - specifier: ^0.20.6 - version: 0.20.6 + specifier: ^0.21.1 + version: 0.21.1 tree-sitter-cli: specifier: ^0.20.8 version: 0.20.8 - tree-sitter-javascript: - specifier: ^0.20.1 - version: 0.20.4 vite: specifier: ^5.0.8 version: 5.2.2(@types/node@20.10.6) @@ -10660,10 +10663,6 @@ packages: thenify-all: 1.6.0 dev: false - /nan@2.19.0: - resolution: {integrity: sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw==} - dev: true - /nanoid@3.3.7: resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -10719,6 +10718,10 @@ packages: semver: 7.5.4 dev: true + /node-addon-api@8.0.0: + resolution: {integrity: sha512-ipO7rsHEBqa9STO5C5T10fj732ml+5kLN1cAG8/jdHd56ldQeGj3Q7+scUS+VHK/qy1zLEwC4wMK5+yM0btPvw==} + engines: {node: ^18 || ^20 || >= 21} + /node-domexception@1.0.0: resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} engines: {node: '>=10.5.0'} @@ -10762,6 +10765,10 @@ packages: engines: {node: '>= 0.6.0'} dev: false + /node-gyp-build@4.8.1: + resolution: {integrity: sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==} + hasBin: true + /node-gyp@10.0.1: resolution: {integrity: sha512-gg3/bHehQfZivQVfqIyy8wTdSymF9yTyP4CJifK73imyNMU8AIGQE2pUa7dNWfmMeG9cDVF2eehiRMv0LC1iAg==} engines: {node: ^16.14.0 || >=18.0.0} @@ -13497,20 +13504,27 @@ packages: requiresBuild: true dev: true - /tree-sitter-javascript@0.20.4: - resolution: {integrity: sha512-7IUgGkZQROI7MmX2ErKhE3YP4+rM2qwBy5JeukE7fJQMEYP9nHpxvuQpa+eOX+hE1im2pWVc1yDCfVKKCBtxww==} + /tree-sitter-haskell@0.21.0(tree-sitter@0.21.1): + resolution: {integrity: sha512-b2RLegPHuYPh7nJ3YKWgkWnFYxmYlQDE8TDJuNH+iuNuBcCMYyaA9JlJlMHfCvf7DmJNPtqqbO9Kh9NXEmbatQ==} requiresBuild: true + peerDependencies: + tree-sitter: ^0.21.0 + tree_sitter: '*' + peerDependenciesMeta: + tree_sitter: + optional: true dependencies: - nan: 2.19.0 - dev: true + node-addon-api: 8.0.0 + node-gyp-build: 4.8.1 + tree-sitter: 0.21.1 + dev: false - /tree-sitter@0.20.6: - resolution: {integrity: sha512-GxJodajVpfgb3UREzzIbtA1hyRnTxVbWVXrbC6sk4xTMH5ERMBJk9HJNq4c8jOJeUaIOmLcwg+t6mez/PDvGqg==} + /tree-sitter@0.21.1: + resolution: {integrity: sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==} requiresBuild: true dependencies: - nan: 2.19.0 - prebuild-install: 7.1.1 - dev: true + node-addon-api: 8.0.0 + node-gyp-build: 4.8.1 /trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -14306,8 +14320,8 @@ packages: engines: {node: '>= 8'} dev: true - /web-tree-sitter@0.20.8: - resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} + /web-tree-sitter@0.22.6: + resolution: {integrity: sha512-hS87TH71Zd6mGAmYCvlgxeGDjqd9GTeqXNqTT+u0Gs51uIozNIaaq/kUAbV/Zf56jb2ZOyG8BxZs2GG9wbLi6Q==} dev: false /webidl-conversions@3.0.1: From eba7dec1a516d8ee3149ec911917d398b8a7267e Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:31:00 +0200 Subject: [PATCH 060/195] rename haskell -> tidal --- packages/{haskell => tidal}/.gitignore | 0 packages/{haskell => tidal}/README.md | 0 packages/{haskell => tidal}/graph.mjs | 0 packages/{haskell => tidal}/hs2js.mjs | 0 packages/{haskell => tidal}/index.html | 0 packages/{haskell => tidal}/main.js | 0 packages/{haskell => tidal}/package.json | 0 packages/{haskell => tidal}/parser.mjs | 0 packages/{haskell => tidal}/public/README.md | 0 pnpm-lock.yaml | 56 ++++++++++---------- 10 files changed, 28 insertions(+), 28 deletions(-) rename packages/{haskell => tidal}/.gitignore (100%) rename packages/{haskell => tidal}/README.md (100%) rename packages/{haskell => tidal}/graph.mjs (100%) rename packages/{haskell => tidal}/hs2js.mjs (100%) rename packages/{haskell => tidal}/index.html (100%) rename packages/{haskell => tidal}/main.js (100%) rename packages/{haskell => tidal}/package.json (100%) rename packages/{haskell => tidal}/parser.mjs (100%) rename packages/{haskell => tidal}/public/README.md (100%) diff --git a/packages/haskell/.gitignore b/packages/tidal/.gitignore similarity index 100% rename from packages/haskell/.gitignore rename to packages/tidal/.gitignore diff --git a/packages/haskell/README.md b/packages/tidal/README.md similarity index 100% rename from packages/haskell/README.md rename to packages/tidal/README.md diff --git a/packages/haskell/graph.mjs b/packages/tidal/graph.mjs similarity index 100% rename from packages/haskell/graph.mjs rename to packages/tidal/graph.mjs diff --git a/packages/haskell/hs2js.mjs b/packages/tidal/hs2js.mjs similarity index 100% rename from packages/haskell/hs2js.mjs rename to packages/tidal/hs2js.mjs diff --git a/packages/haskell/index.html b/packages/tidal/index.html similarity index 100% rename from packages/haskell/index.html rename to packages/tidal/index.html diff --git a/packages/haskell/main.js b/packages/tidal/main.js similarity index 100% rename from packages/haskell/main.js rename to packages/tidal/main.js diff --git a/packages/haskell/package.json b/packages/tidal/package.json similarity index 100% rename from packages/haskell/package.json rename to packages/tidal/package.json diff --git a/packages/haskell/parser.mjs b/packages/tidal/parser.mjs similarity index 100% rename from packages/haskell/parser.mjs rename to packages/tidal/parser.mjs diff --git a/packages/haskell/public/README.md b/packages/tidal/public/README.md similarity index 100% rename from packages/haskell/public/README.md rename to packages/tidal/public/README.md diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 76947b5a..53cf7207 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -251,34 +251,6 @@ importers: packages/embed: {} - packages/haskell: - dependencies: - '@hpcc-js/wasm': - specifier: ^2.15.3 - version: 2.16.2 - '@strudel/web': - specifier: workspace:* - version: link:../web - jgf-dot: - specifier: ^1.1.1 - version: 1.1.1 - tree-sitter-haskell: - specifier: ^0.21.0 - version: 0.21.0(tree-sitter@0.21.1) - web-tree-sitter: - specifier: ^0.22.6 - version: 0.22.6 - devDependencies: - tree-sitter: - specifier: ^0.21.1 - version: 0.21.1 - tree-sitter-cli: - specifier: ^0.20.8 - version: 0.20.8 - vite: - specifier: ^5.0.8 - version: 5.2.2(@types/node@20.10.6) - packages/hydra: dependencies: '@strudel/core': @@ -437,6 +409,34 @@ importers: specifier: ^5.0.10 version: 5.0.10 + packages/tidal: + dependencies: + '@hpcc-js/wasm': + specifier: ^2.15.3 + version: 2.16.2 + '@strudel/web': + specifier: workspace:* + version: link:../web + jgf-dot: + specifier: ^1.1.1 + version: 1.1.1 + tree-sitter-haskell: + specifier: ^0.21.0 + version: 0.21.0(tree-sitter@0.21.1) + web-tree-sitter: + specifier: ^0.22.6 + version: 0.22.6 + devDependencies: + tree-sitter: + specifier: ^0.21.1 + version: 0.21.1 + tree-sitter-cli: + specifier: ^0.20.8 + version: 0.20.8 + vite: + specifier: ^5.0.8 + version: 5.2.2(@types/node@20.10.6) + packages/tonal: dependencies: '@strudel/core': From 29598d1744f7dd06f5994af93c9e1658be8e4ab9 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Thu, 16 May 2024 14:32:45 +0200 Subject: [PATCH 061/195] fix: lint --- .eslintignore | 3 ++- packages/tidal/hs2js.mjs | 1 - packages/tidal/main.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.eslintignore b/.eslintignore index 7d807b65..a16bd3cd 100644 --- a/.eslintignore +++ b/.eslintignore @@ -21,4 +21,5 @@ vite.config.js /src-tauri/target/**/* reverbGen.mjs hydra.mjs -jsdoc-synonyms.js \ No newline at end of file +jsdoc-synonyms.js +packages/tidal/hs2js.mjs \ No newline at end of file diff --git a/packages/tidal/hs2js.mjs b/packages/tidal/hs2js.mjs index 3a507112..733b7aeb 100644 --- a/packages/tidal/hs2js.mjs +++ b/packages/tidal/hs2js.mjs @@ -26,7 +26,6 @@ function runInfix(left, symbol, right, ops) { case '$': return left(right); case '&': - console.log('right', right); return right(left); case '.': return (x) => left(right(x)); diff --git a/packages/tidal/main.js b/packages/tidal/main.js index bd9c2702..b1d40198 100644 --- a/packages/tidal/main.js +++ b/packages/tidal/main.js @@ -1,7 +1,7 @@ import { run } from './hs2js.mjs'; import { renderGraph } from './graph.mjs'; import { parse } from './parser.mjs'; -import { initStrudel, reify, late } from '@strudel/web'; +import { initStrudel, reify, late, samples, stack } from '@strudel/web'; initStrudel({ prebake: () => samples('github:tidalcycles/dirt-samples'), }); From 803b5e56fcd6c1326687837e7fb9025853ac1901 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Thu, 16 May 2024 16:49:28 -0400 Subject: [PATCH 062/195] working --- website/src/repl/idbutils.mjs | 13 +++++++++---- website/src/repl/panel/ImportSoundsButton.jsx | 3 ++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/website/src/repl/idbutils.mjs b/website/src/repl/idbutils.mjs index 40219c9a..959dc7d1 100644 --- a/website/src/repl/idbutils.mjs +++ b/website/src/repl/idbutils.mjs @@ -40,8 +40,10 @@ export const registerSamplesFromDB = (config = userSamplesDBConfig, onComplete = if (!isAudioFile(title)) { return; } - const splitRelativePath = soundFile.id?.split('/'); - const parentDirectory = splitRelativePath[splitRelativePath.length - 2]; + const splitRelativePath = soundFile.id.split('/'); + const parentDirectory = + //fallback to file name before period and seperator if no parent directory + splitRelativePath[splitRelativePath.length - 2] ?? soundFile.id.split(/\W+/)[0] ?? 'user'; const soundPath = soundFile.blob; const soundPaths = sounds.get(parentDirectory) ?? new Set(); soundPaths.add(soundPath); @@ -114,6 +116,7 @@ const processFilesForIDB = async (files) => { Array.from(files) .map(async (s) => { const title = s.name; + if (!isAudioFile(title)) { return; } @@ -121,12 +124,14 @@ const processFilesForIDB = async (files) => { const sUrl = URL.createObjectURL(s); //fetch the sound and turn it into a buffer array const buf = await fetch(sUrl).then((res) => res.arrayBuffer()); - //create a url blob containing all of the buffer data + //create a url base64 containing all of the buffer data const base64 = await bufferToDataUrl(buf); + const path = s.webkitRelativePath; + const id = path?.length ? path : title; return { title, blob: base64, - id: s.webkitRelativePath, + id, }; }) .filter(Boolean), diff --git a/website/src/repl/panel/ImportSoundsButton.jsx b/website/src/repl/panel/ImportSoundsButton.jsx index 20a1d5e3..7a97b9e0 100644 --- a/website/src/repl/panel/ImportSoundsButton.jsx +++ b/website/src/repl/panel/ImportSoundsButton.jsx @@ -10,6 +10,7 @@ export default function ImportSoundsButton({ onComplete }) { return; } setIsUploading(true); + await uploadSamplesToDB(userSamplesDBConfig, fileUploadRef.current.files).then(() => { registerSamplesFromDB(userSamplesDBConfig, () => { onComplete(); @@ -32,7 +33,7 @@ export default function ImportSoundsButton({ onComplete }) { directory="" webkitdirectory="" multiple - accept="audio/*" + accept="audio/*, .wav, .mp3, .m4a, .flac" onChange={() => { onChange(); }} From 16ad27406d57073980646a4c5d4a408154261e00 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Thu, 16 May 2024 17:10:41 -0400 Subject: [PATCH 063/195] sort samples in tabs --- website/src/repl/panel/SoundsTab.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/website/src/repl/panel/SoundsTab.jsx b/website/src/repl/panel/SoundsTab.jsx index d4b52ee5..9b35d04b 100644 --- a/website/src/repl/panel/SoundsTab.jsx +++ b/website/src/repl/panel/SoundsTab.jsx @@ -13,7 +13,9 @@ export function SoundsTab() { const sounds = useStore(soundMap); const { soundsFilter } = useSettings(); const soundEntries = useMemo(() => { - let filtered = Object.entries(sounds).filter(([key]) => !key.startsWith('_')); + let filtered = Object.entries(sounds) + .filter(([key]) => !key.startsWith('_')) + .sort((a, b) => a[0].localeCompare(b[0])); if (!sounds) { return []; } @@ -43,7 +45,7 @@ export function SoundsTab() { }); return (
-
+
settingsMap.setKey('soundsFilter', value)} From d49c9dce4fccb5df67e60577352a7bcb997cfc49 Mon Sep 17 00:00:00 2001 From: "Jade (Rose) Rowland" Date: Fri, 17 May 2024 00:27:34 -0400 Subject: [PATCH 064/195] working --- packages/superdough/superdough.mjs | 2 + packages/superdough/worklets.mjs | 64 ++++++++++++++++++++++++++++++ website/src/repl/panel/Forms.jsx | 5 +-- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index c0ba96e0..cd9fcfeb 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -471,6 +471,8 @@ export const superdough = async (value, t, hapDuration) => { shape !== undefined && chain.push(getWorklet(ac, 'shape-processor', { shape, postgain: shapevol })); distort !== undefined && chain.push(getWorklet(ac, 'distort-processor', { distort, postgain: distortvol })); + chain.push(getWorklet(ac, 'ladder-processor', { cutoff: 500, q: 1 })); + compressorThreshold !== undefined && chain.push( getCompressor(ac, compressorThreshold, compressorRatio, compressorKnee, compressorAttack, compressorRelease), diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index a1f524ca..152e51d6 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -106,6 +106,70 @@ class ShapeProcessor extends AudioWorkletProcessor { } registerProcessor('shape-processor', ShapeProcessor); +function fast_tanh(x) { + const x2 = x * x; + return (x * (27.0 + x2)) / (27.0 + 9.0 * x2); +} +const _PI = 3.14159265359; + +class LadderProcessor extends AudioWorkletProcessor { + static get parameterDescriptors() { + return [ + { name: 'cutoff', defaultValue: 500 }, + { name: 'q', defaultValue: 1 }, + ]; + } + + constructor() { + super(); + this.started = false; + this.p0 = 0; + this.p1 = 0; + this.p2 = 0; + this.p3 = 0; + this.p32 = 0; + this.p33 = 0; + this.p34 = 0; + } + + process(inputs, outputs, parameters) { + const input = inputs[0]; + const output = outputs[0]; + + const hasInput = !(input[0] === undefined); + if (this.started && !hasInput) { + return false; + } + this.started = hasInput; + + const resonance = parameters.q[0]; + let cutoff = parameters.cutoff[0]; + cutoff = (cutoff * 2 * _PI) / sampleRate; + cutoff = cutoff > 1 ? 1 : cutoff; + + const k = resonance * 4; + + for (let n = 0; n < blockSize; n++) { + for (let i = 0; i < input.length; i++) { + const out = this.p3 * 0.360891 + this.p32 * 0.41729 + this.p33 * 0.177896 + this.p34 * 0.0439725; + + this.p34 = this.p33; + this.p33 = this.p32; + this.p32 = this.p3; + + this.p0 += (fast_tanh(input[i][n] - k * out) - fast_tanh(this.p0)) * cutoff; + this.p1 += (fast_tanh(this.p0) - fast_tanh(this.p1)) * cutoff; + this.p2 += (fast_tanh(this.p1) - fast_tanh(this.p2)) * cutoff; + this.p3 += (fast_tanh(this.p2) - fast_tanh(this.p3)) * cutoff; + + output[i][n] = out; + } + } + return true; + } +} +registerProcessor('ladder-processor', LadderProcessor); + class DistortProcessor extends AudioWorkletProcessor { static get parameterDescriptors() { return [ diff --git a/website/src/repl/panel/Forms.jsx b/website/src/repl/panel/Forms.jsx index c5b22002..b9172e91 100644 --- a/website/src/repl/panel/Forms.jsx +++ b/website/src/repl/panel/Forms.jsx @@ -2,16 +2,13 @@ import cx from '@src/cx.mjs'; export function ButtonGroup({ value, onChange, items }) { return ( -
+
{Object.entries(items).map(([key, label], i, arr) => ( diff --git a/packages/hs2js/LICENSE b/packages/hs2js/LICENSE new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/packages/hs2js/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/hs2js/README.md b/packages/hs2js/README.md new file mode 100644 index 00000000..f4ca3ed5 --- /dev/null +++ b/packages/hs2js/README.md @@ -0,0 +1,49 @@ +# hs2js + +Experimental haskell in javascript interpreter. + +## Usage + +### Via Script Tag + +You can load the library directly from a script tag via unpkg: + +```html + + + +``` + +### Via npm + +You need to add `postinstall` to your `package.json` script to copy the parser to your `public` folder: + +```json +{ + "scripts": { + "postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" + } +} +``` + +Depending on your setup, replace `public` with the folder that will serve your assets to `/`. Then install the package: + +```sh +npm i hs2js +``` + +and use it: + +```js +import * as hs2js from 'hs2js'; +hs2js.loadParser(); +document.getElementById('hello').addEventListener('click', () => { + hs2js.evaluate('alert "hello from haskell!"'); +}); +``` diff --git a/packages/hs2js/package.json b/packages/hs2js/package.json new file mode 100644 index 00000000..d0cd0f62 --- /dev/null +++ b/packages/hs2js/package.json @@ -0,0 +1,33 @@ +{ + "name": "hs2js", + "version": "0.0.4", + "description": "Experimental Haskell in JavaScript interpreter", + "main": "dist/index.js", + "module": "dist/index.mjs", + "scripts": { + "build-wasm": "tree-sitter build-wasm node_modules/tree-sitter-haskell && mv tree-sitter-haskell.wasm ./dist/ && cp node_modules/web-tree-sitter/tree-sitter.wasm ./dist/", + "build": "vite build && npm run build-wasm", + "prepublishOnly": "npm run build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/felixroos/hs2js.git" + }, + "keywords": [ + "haskell", + "javascript" + ], + "author": "Felix Roos ", + "license": "AGPL-3.0-or-later", + "bugs": { + "url": "https://github.com/tidalcycles/strudel/issues" + }, + "homepage": "https://github.com/tidalcycles/strudel/tree/main/packages/hs2js", + "dependencies": { + "web-tree-sitter": "^0.20.8" + }, + "devDependencies": { + "vite": "^5.0.10", + "tree-sitter-haskell": "^0.21.0" + } +} diff --git a/packages/hs2js/pnpm-lock.yaml b/packages/hs2js/pnpm-lock.yaml new file mode 100644 index 00000000..9043fd41 --- /dev/null +++ b/packages/hs2js/pnpm-lock.yaml @@ -0,0 +1,520 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +dependencies: + web-tree-sitter: + specifier: ^0.20.8 + version: 0.20.8 + +devDependencies: + tree-sitter-haskell: + specifier: ^0.21.0 + version: 0.21.0(tree-sitter@0.21.1) + vite: + specifier: ^5.0.10 + version: 5.2.11 + +packages: + + /@esbuild/aix-ppc64@0.20.2: + resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-arm64@0.20.2: + resolution: {integrity: sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-arm@0.20.2: + resolution: {integrity: sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-x64@0.20.2: + resolution: {integrity: sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/darwin-arm64@0.20.2: + resolution: {integrity: sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@esbuild/darwin-x64@0.20.2: + resolution: {integrity: sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@esbuild/freebsd-arm64@0.20.2: + resolution: {integrity: sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/freebsd-x64@0.20.2: + resolution: {integrity: sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-arm64@0.20.2: + resolution: {integrity: sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-arm@0.20.2: + resolution: {integrity: sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-ia32@0.20.2: + resolution: {integrity: sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-loong64@0.20.2: + resolution: {integrity: sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-mips64el@0.20.2: + resolution: {integrity: sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-ppc64@0.20.2: + resolution: {integrity: sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-riscv64@0.20.2: + resolution: {integrity: sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-s390x@0.20.2: + resolution: {integrity: sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-x64@0.20.2: + resolution: {integrity: sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/netbsd-x64@0.20.2: + resolution: {integrity: sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/openbsd-x64@0.20.2: + resolution: {integrity: sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/sunos-x64@0.20.2: + resolution: {integrity: sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-arm64@0.20.2: + resolution: {integrity: sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-ia32@0.20.2: + resolution: {integrity: sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-x64@0.20.2: + resolution: {integrity: sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-android-arm-eabi@4.17.2: + resolution: {integrity: sha512-NM0jFxY8bB8QLkoKxIQeObCaDlJKewVlIEkuyYKm5An1tdVZ966w2+MPQ2l8LBZLjR+SgyV+nRkTIunzOYBMLQ==} + cpu: [arm] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-android-arm64@4.17.2: + resolution: {integrity: sha512-yeX/Usk7daNIVwkq2uGoq2BYJKZY1JfyLTaHO/jaiSwi/lsf8fTFoQW/n6IdAsx5tx+iotu2zCJwz8MxI6D/Bw==} + cpu: [arm64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-darwin-arm64@4.17.2: + resolution: {integrity: sha512-kcMLpE6uCwls023+kknm71ug7MZOrtXo+y5p/tsg6jltpDtgQY1Eq5sGfHcQfb+lfuKwhBmEURDga9N0ol4YPw==} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-darwin-x64@4.17.2: + resolution: {integrity: sha512-AtKwD0VEx0zWkL0ZjixEkp5tbNLzX+FCqGG1SvOu993HnSz4qDI6S4kGzubrEJAljpVkhRSlg5bzpV//E6ysTQ==} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm-gnueabihf@4.17.2: + resolution: {integrity: sha512-3reX2fUHqN7sffBNqmEyMQVj/CKhIHZd4y631duy0hZqI8Qoqf6lTtmAKvJFYa6bhU95B1D0WgzHkmTg33In0A==} + cpu: [arm] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm-musleabihf@4.17.2: + resolution: {integrity: sha512-uSqpsp91mheRgw96xtyAGP9FW5ChctTFEoXP0r5FAzj/3ZRv3Uxjtc7taRQSaQM/q85KEKjKsZuiZM3GyUivRg==} + cpu: [arm] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm64-gnu@4.17.2: + resolution: {integrity: sha512-EMMPHkiCRtE8Wdk3Qhtciq6BndLtstqZIroHiiGzB3C5LDJmIZcSzVtLRbwuXuUft1Cnv+9fxuDtDxz3k3EW2A==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-arm64-musl@4.17.2: + resolution: {integrity: sha512-NMPylUUZ1i0z/xJUIx6VUhISZDRT+uTWpBcjdv0/zkp7b/bQDF+NfnfdzuTiB1G6HTodgoFa93hp0O1xl+/UbA==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-powerpc64le-gnu@4.17.2: + resolution: {integrity: sha512-T19My13y8uYXPw/L/k0JYaX1fJKFT/PWdXiHr8mTbXWxjVF1t+8Xl31DgBBvEKclw+1b00Chg0hxE2O7bTG7GQ==} + cpu: [ppc64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-riscv64-gnu@4.17.2: + resolution: {integrity: sha512-BOaNfthf3X3fOWAB+IJ9kxTgPmMqPPH5f5k2DcCsRrBIbWnaJCgX2ll77dV1TdSy9SaXTR5iDXRL8n7AnoP5cg==} + cpu: [riscv64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-s390x-gnu@4.17.2: + resolution: {integrity: sha512-W0UP/x7bnn3xN2eYMql2T/+wpASLE5SjObXILTMPUBDB/Fg/FxC+gX4nvCfPBCbNhz51C+HcqQp2qQ4u25ok6g==} + cpu: [s390x] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-x64-gnu@4.17.2: + resolution: {integrity: sha512-Hy7pLwByUOuyaFC6mAr7m+oMC+V7qyifzs/nW2OJfC8H4hbCzOX07Ov0VFk/zP3kBsELWNFi7rJtgbKYsav9QQ==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-linux-x64-musl@4.17.2: + resolution: {integrity: sha512-h1+yTWeYbRdAyJ/jMiVw0l6fOOm/0D1vNLui9iPuqgRGnXA0u21gAqOyB5iHjlM9MMfNOm9RHCQ7zLIzT0x11Q==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-arm64-msvc@4.17.2: + resolution: {integrity: sha512-tmdtXMfKAjy5+IQsVtDiCfqbynAQE/TQRpWdVataHmhMb9DCoJxp9vLcCBjEQWMiUYxO1QprH/HbY9ragCEFLA==} + cpu: [arm64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-ia32-msvc@4.17.2: + resolution: {integrity: sha512-7II/QCSTAHuE5vdZaQEwJq2ZACkBpQDOmQsE6D6XUbnBHW8IAhm4eTufL6msLJorzrHDFv3CF8oCA/hSIRuZeQ==} + cpu: [ia32] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@rollup/rollup-win32-x64-msvc@4.17.2: + resolution: {integrity: sha512-TGGO7v7qOq4CYmSBVEYpI1Y5xDuCEnbVC5Vth8mOsW0gDSzxNrVERPc790IGHsrT2dQSimgMr9Ub3Y1Jci5/8w==} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@types/estree@1.0.5: + resolution: {integrity: sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==} + dev: true + + /esbuild@0.20.2: + resolution: {integrity: sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==} + engines: {node: '>=12'} + hasBin: true + requiresBuild: true + optionalDependencies: + '@esbuild/aix-ppc64': 0.20.2 + '@esbuild/android-arm': 0.20.2 + '@esbuild/android-arm64': 0.20.2 + '@esbuild/android-x64': 0.20.2 + '@esbuild/darwin-arm64': 0.20.2 + '@esbuild/darwin-x64': 0.20.2 + '@esbuild/freebsd-arm64': 0.20.2 + '@esbuild/freebsd-x64': 0.20.2 + '@esbuild/linux-arm': 0.20.2 + '@esbuild/linux-arm64': 0.20.2 + '@esbuild/linux-ia32': 0.20.2 + '@esbuild/linux-loong64': 0.20.2 + '@esbuild/linux-mips64el': 0.20.2 + '@esbuild/linux-ppc64': 0.20.2 + '@esbuild/linux-riscv64': 0.20.2 + '@esbuild/linux-s390x': 0.20.2 + '@esbuild/linux-x64': 0.20.2 + '@esbuild/netbsd-x64': 0.20.2 + '@esbuild/openbsd-x64': 0.20.2 + '@esbuild/sunos-x64': 0.20.2 + '@esbuild/win32-arm64': 0.20.2 + '@esbuild/win32-ia32': 0.20.2 + '@esbuild/win32-x64': 0.20.2 + dev: true + + /fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /nanoid@3.3.7: + resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + dev: true + + /node-addon-api@8.0.0: + resolution: {integrity: sha512-ipO7rsHEBqa9STO5C5T10fj732ml+5kLN1cAG8/jdHd56ldQeGj3Q7+scUS+VHK/qy1zLEwC4wMK5+yM0btPvw==} + engines: {node: ^18 || ^20 || >= 21} + dev: true + + /node-gyp-build@4.8.1: + resolution: {integrity: sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==} + hasBin: true + dev: true + + /picocolors@1.0.1: + resolution: {integrity: sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==} + dev: true + + /postcss@8.4.38: + resolution: {integrity: sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==} + engines: {node: ^10 || ^12 || >=14} + dependencies: + nanoid: 3.3.7 + picocolors: 1.0.1 + source-map-js: 1.2.0 + dev: true + + /rollup@4.17.2: + resolution: {integrity: sha512-/9ClTJPByC0U4zNLowV1tMBe8yMEAxewtR3cUNX5BoEpGH3dQEWpJLr6CLp0fPdYRF/fzVOgvDb1zXuakwF5kQ==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + dependencies: + '@types/estree': 1.0.5 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.17.2 + '@rollup/rollup-android-arm64': 4.17.2 + '@rollup/rollup-darwin-arm64': 4.17.2 + '@rollup/rollup-darwin-x64': 4.17.2 + '@rollup/rollup-linux-arm-gnueabihf': 4.17.2 + '@rollup/rollup-linux-arm-musleabihf': 4.17.2 + '@rollup/rollup-linux-arm64-gnu': 4.17.2 + '@rollup/rollup-linux-arm64-musl': 4.17.2 + '@rollup/rollup-linux-powerpc64le-gnu': 4.17.2 + '@rollup/rollup-linux-riscv64-gnu': 4.17.2 + '@rollup/rollup-linux-s390x-gnu': 4.17.2 + '@rollup/rollup-linux-x64-gnu': 4.17.2 + '@rollup/rollup-linux-x64-musl': 4.17.2 + '@rollup/rollup-win32-arm64-msvc': 4.17.2 + '@rollup/rollup-win32-ia32-msvc': 4.17.2 + '@rollup/rollup-win32-x64-msvc': 4.17.2 + fsevents: 2.3.3 + dev: true + + /source-map-js@1.2.0: + resolution: {integrity: sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==} + engines: {node: '>=0.10.0'} + dev: true + + /tree-sitter-haskell@0.21.0(tree-sitter@0.21.1): + resolution: {integrity: sha512-b2RLegPHuYPh7nJ3YKWgkWnFYxmYlQDE8TDJuNH+iuNuBcCMYyaA9JlJlMHfCvf7DmJNPtqqbO9Kh9NXEmbatQ==} + requiresBuild: true + peerDependencies: + tree-sitter: ^0.21.0 + tree_sitter: '*' + peerDependenciesMeta: + tree_sitter: + optional: true + dependencies: + node-addon-api: 8.0.0 + node-gyp-build: 4.8.1 + tree-sitter: 0.21.1 + dev: true + + /tree-sitter@0.21.1: + resolution: {integrity: sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==} + requiresBuild: true + dependencies: + node-addon-api: 8.0.0 + node-gyp-build: 4.8.1 + dev: true + + /vite@5.2.11: + resolution: {integrity: sha512-HndV31LWW05i1BLPMUCE1B9E9GFbOu1MbenhS58FuK6owSO5qHm7GiCotrNY1YE5rMeQSFBGmT5ZaLEjFizgiQ==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + dependencies: + esbuild: 0.20.2 + postcss: 8.4.38 + rollup: 4.17.2 + optionalDependencies: + fsevents: 2.3.3 + dev: true + + /web-tree-sitter@0.20.8: + resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} + dev: false diff --git a/packages/hs2js/src/hs2js.mjs b/packages/hs2js/src/hs2js.mjs new file mode 100644 index 00000000..1f894d14 --- /dev/null +++ b/packages/hs2js/src/hs2js.mjs @@ -0,0 +1,139 @@ +import { parse } from "./parser.mjs"; + +function runApply(node, scope, ops) { + if (node.children.length !== 2) + throw new Error( + `expected 2 children for node type apply, got ${node.children.length}` + ); + const [fn, arg] = node.children.map((child) => run(child, scope, ops)); + if (typeof fn !== "function") { + throw new Error(`${node.children[0].text} is not a function`); + } + // only works if fn is curried! + return fn(arg); +} + +function runInfix(left, symbol, right, ops) { + const customOp = ops[symbol]; + if (customOp) { + return customOp(left, right); + } + switch (symbol) { + case "+": + return left + right; + case "-": + return left - right; + case "*": + return left * right; + case "/": + return left / right; + case "$": + return left(right); + case "&": + console.log("right", right); + return right(left); + case ".": + return (x) => left(right(x)); + default: + throw new Error("unexpected infix operator " + symbol); + } +} + +function curry(patterns, body, scope, ops) { + const [variable, ...rest] = patterns; + return (arg) => { + let _scope = { ...scope, [variable.text]: arg }; + if (patterns.length === 1) { + const result = run(body, _scope, ops); + return result; + } + return curry(rest, body, _scope, ops); + }; +} + +export function run(node, scope, ops = {}) { + let runInScope = (node, scp = scope) => run(node, scp, ops); + //console.log("node", node.type, node.text); + switch (node.type) { + case "ERROR": + throw new Error(`invalid syntax: "${node.text}"`); + case "declarations": + let result; + node.children.forEach((declaration) => { + result = runInScope(declaration); + }); + return result; + case "integer": + return Number(node.text); + case "float": + return Number(node.text); + case "string": + const str = node.text.slice(1, -1); + return String(str); + case "lambda": + const [_, lpatterns, __, lbody] = node.children; + return curry(lpatterns.children, lbody, scope, ops); + case "function": + const [fvariable, fpatterns, fbody] = node.children; + scope[fvariable.text] = curry(fpatterns.children, fbody, scope, ops); + return scope[fvariable.text]; + case "list": { + return node.children + .filter((_, i) => i % 2 === 1) // elements are at odd indices + .map((node) => runInScope(node)); + } + case "match": + if (node.children[0].text !== "=" || node.children.length !== 2) { + throw new Error("match node so far only support simple assignments"); + } + return runInScope(node.children[1]); + case "bind": + if (node.children.length !== 2) + throw new Error("expected 2 children for node type bind"); + if (node.children[0].type !== "variable") + throw new Error("expected variable as first child of bind node"); + if (node.children[1].type !== "match") + throw new Error("expected match as first child of bind node"); + const [bvariable, bmatch] = node.children; + const value = runInScope(bmatch); + scope[bvariable.text] = value; + return value; + case "variable": + return scope[node.text]; + case "infix": { + const [a, op, b] = node.children; + const symbol = op.text; + const [left, right] = [runInScope(a), runInScope(b)]; + return runInfix(left, symbol, right, ops); + } + case "apply": + return runApply(node, scope, ops); + case "left_section": { + const [_, b, op] = node.children; + const right = runInScope(b); + return (left) => runInfix(left, op.text, right, ops); + } + case "right_section": { + const [_, op, b] = node.children; + const right = runInScope(b); + return (left) => runInfix(left, op.text, right, ops); + } + case "parens": + if (node.children.length !== 3) + throw new Error("expected 3 children for node type parens"); + return runInScope(node.children[1]); + default: + if (node.children.length === 0) { + throw new Error("unhandled leaf type " + node.type); + } + if (node.children.length > 1) { + throw new Error("unhandled branch type " + node.type); + } + return runInScope(node.children[0]); + } +} + +export async function evaluate(haskellCode, scope = globalThis, ops) { + const ast = await parse(haskellCode); + return run(ast.rootNode, scope, ops); +} diff --git a/packages/hs2js/src/index.mjs b/packages/hs2js/src/index.mjs new file mode 100644 index 00000000..170ef1b6 --- /dev/null +++ b/packages/hs2js/src/index.mjs @@ -0,0 +1,2 @@ +export * from "./hs2js.mjs"; +export * from "./parser.mjs"; diff --git a/packages/hs2js/src/parser.mjs b/packages/hs2js/src/parser.mjs new file mode 100644 index 00000000..829a5da3 --- /dev/null +++ b/packages/hs2js/src/parser.mjs @@ -0,0 +1,37 @@ +import Parser from "web-tree-sitter"; + +let base = "/"; +export function setBase(path) { + base = path; +} + +async function _loadParser() { + await Parser.init({ + locateFile(scriptName, scriptDirectory) { + return `${base}${scriptName}`; + }, + }); + const parser = new Parser(); + const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`); + parser.setLanguage(Lang); + return parser; +} + +let parserLoaded; +export function loadParser() { + if (!parserLoaded) { + parserLoaded = _loadParser(); + } + return parserLoaded; +} + +export async function parse(code) { + const parser = await loadParser(); + // for some reason, the parser doesn't like new lines.. + return parser.parse( + code + .replaceAll("\n\n", "~~~~") + .replaceAll("\n", "") + .replaceAll("~~~~", "\n") + ); +} diff --git a/packages/hs2js/vite.config.mjs b/packages/hs2js/vite.config.mjs new file mode 100644 index 00000000..9eb4a07a --- /dev/null +++ b/packages/hs2js/vite.config.mjs @@ -0,0 +1,20 @@ +import { defineConfig } from "vite"; +import { resolve } from "path"; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [], + build: { + lib: { + entry: resolve(__dirname, "src", "index.mjs"), + name: "hs2js", + formats: ["es", "iife"], + fileName: (ext) => ({ es: "index.mjs", iife: "index.js" }[ext]), + }, + rollupOptions: { + // external: [...Object.keys(dependencies)], + plugins: [], + }, + target: "esnext", + }, +}); diff --git a/packages/tidal/main.js b/packages/tidal/main.js index b1d40198..0b2ac7d5 100644 --- a/packages/tidal/main.js +++ b/packages/tidal/main.js @@ -1,6 +1,5 @@ -import { run } from './hs2js.mjs'; +import { run, parse } from 'hs2js'; import { renderGraph } from './graph.mjs'; -import { parse } from './parser.mjs'; import { initStrudel, reify, late, samples, stack } from '@strudel/web'; initStrudel({ prebake: () => samples('github:tidalcycles/dirt-samples'), diff --git a/packages/tidal/package.json b/packages/tidal/package.json index 7d8b72e4..7c12cbb6 100644 --- a/packages/tidal/package.json +++ b/packages/tidal/package.json @@ -7,8 +7,7 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public && npm run build:parser", - "build:parser": "tree-sitter build-wasm node_modules/tree-sitter-haskell && mv tree-sitter-haskell.wasm public" + "postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" }, "repository": { "type": "git", @@ -30,13 +29,10 @@ "dependencies": { "@hpcc-js/wasm": "^2.15.3", "jgf-dot": "^1.1.1", - "web-tree-sitter": "^0.22.6", - "tree-sitter-haskell": "^0.21.0", - "@strudel/web": "workspace:*" + "@strudel/web": "workspace:*", + "hs2js": "workspace:*" }, "devDependencies": { - "tree-sitter": "^0.21.1", - "tree-sitter-cli": "^0.20.8", "vite": "^5.0.8" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 577954cb..8ac9adb0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -251,6 +251,19 @@ importers: packages/embed: {} + packages/hs2js: + dependencies: + web-tree-sitter: + specifier: ^0.20.8 + version: 0.20.8 + devDependencies: + tree-sitter-haskell: + specifier: ^0.21.0 + version: 0.21.0(tree-sitter@0.21.1) + vite: + specifier: ^5.0.10 + version: 5.2.2(@types/node@20.10.6) + packages/hydra: dependencies: '@strudel/core': @@ -417,22 +430,13 @@ importers: '@strudel/web': specifier: workspace:* version: link:../web + hs2js: + specifier: workspace:* + version: link:../hs2js jgf-dot: specifier: ^1.1.1 version: 1.1.1 - tree-sitter-haskell: - specifier: ^0.21.0 - version: 0.21.0(tree-sitter@0.21.1) - web-tree-sitter: - specifier: ^0.22.6 - version: 0.22.6 devDependencies: - tree-sitter: - specifier: ^0.21.1 - version: 0.21.1 - tree-sitter-cli: - specifier: ^0.20.8 - version: 0.20.8 vite: specifier: ^5.0.8 version: 5.2.2(@types/node@20.10.6) @@ -10730,6 +10734,7 @@ packages: /node-addon-api@8.0.0: resolution: {integrity: sha512-ipO7rsHEBqa9STO5C5T10fj732ml+5kLN1cAG8/jdHd56ldQeGj3Q7+scUS+VHK/qy1zLEwC4wMK5+yM0btPvw==} engines: {node: ^18 || ^20 || >= 21} + dev: true /node-domexception@1.0.0: resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} @@ -10777,6 +10782,7 @@ packages: /node-gyp-build@4.8.1: resolution: {integrity: sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==} hasBin: true + dev: true /node-gyp@10.0.1: resolution: {integrity: sha512-gg3/bHehQfZivQVfqIyy8wTdSymF9yTyP4CJifK73imyNMU8AIGQE2pUa7dNWfmMeG9cDVF2eehiRMv0LC1iAg==} @@ -13507,12 +13513,6 @@ packages: punycode: 2.3.1 dev: true - /tree-sitter-cli@0.20.8: - resolution: {integrity: sha512-XjTcS3wdTy/2cc/ptMLc/WRyOLECRYcMTrSWyhZnj1oGSOWbHLTklgsgRICU3cPfb0vy+oZCC33M43u6R1HSCA==} - hasBin: true - requiresBuild: true - dev: true - /tree-sitter-haskell@0.21.0(tree-sitter@0.21.1): resolution: {integrity: sha512-b2RLegPHuYPh7nJ3YKWgkWnFYxmYlQDE8TDJuNH+iuNuBcCMYyaA9JlJlMHfCvf7DmJNPtqqbO9Kh9NXEmbatQ==} requiresBuild: true @@ -13526,7 +13526,7 @@ packages: node-addon-api: 8.0.0 node-gyp-build: 4.8.1 tree-sitter: 0.21.1 - dev: false + dev: true /tree-sitter@0.21.1: resolution: {integrity: sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==} @@ -13534,6 +13534,7 @@ packages: dependencies: node-addon-api: 8.0.0 node-gyp-build: 4.8.1 + dev: true /trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -14333,10 +14334,6 @@ packages: resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==} dev: false - /web-tree-sitter@0.22.6: - resolution: {integrity: sha512-hS87TH71Zd6mGAmYCvlgxeGDjqd9GTeqXNqTT+u0Gs51uIozNIaaq/kUAbV/Zf56jb2ZOyG8BxZs2GG9wbLi6Q==} - dev: false - /webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} From 0123f4e5f3c5abf2871c6a61de51d4d0865d7ec9 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 17 May 2024 10:02:14 +0200 Subject: [PATCH 067/195] fix lint errors + cleanup --- .eslintignore | 2 +- packages/hs2js/src/hs2js.mjs | 78 +++++++++----------- packages/hs2js/src/index.mjs | 4 +- packages/hs2js/src/parser.mjs | 11 +-- packages/hs2js/vite.config.js | 20 +++++ packages/hs2js/vite.config.mjs | 20 ----- packages/tidal/hs2js.mjs | 130 --------------------------------- packages/tidal/parser.mjs | 22 ------ 8 files changed, 62 insertions(+), 225 deletions(-) create mode 100644 packages/hs2js/vite.config.js delete mode 100644 packages/hs2js/vite.config.mjs delete mode 100644 packages/tidal/hs2js.mjs delete mode 100644 packages/tidal/parser.mjs diff --git a/.eslintignore b/.eslintignore index a16bd3cd..30e8a0ff 100644 --- a/.eslintignore +++ b/.eslintignore @@ -22,4 +22,4 @@ vite.config.js reverbGen.mjs hydra.mjs jsdoc-synonyms.js -packages/tidal/hs2js.mjs \ No newline at end of file +packages/hs2js/src/hs2js.mjs \ No newline at end of file diff --git a/packages/hs2js/src/hs2js.mjs b/packages/hs2js/src/hs2js.mjs index 1f894d14..e7b7cf46 100644 --- a/packages/hs2js/src/hs2js.mjs +++ b/packages/hs2js/src/hs2js.mjs @@ -1,12 +1,10 @@ -import { parse } from "./parser.mjs"; +import { parse } from './parser.mjs'; function runApply(node, scope, ops) { if (node.children.length !== 2) - throw new Error( - `expected 2 children for node type apply, got ${node.children.length}` - ); + throw new Error(`expected 2 children for node type apply, got ${node.children.length}`); const [fn, arg] = node.children.map((child) => run(child, scope, ops)); - if (typeof fn !== "function") { + if (typeof fn !== 'function') { throw new Error(`${node.children[0].text} is not a function`); } // only works if fn is curried! @@ -19,23 +17,23 @@ function runInfix(left, symbol, right, ops) { return customOp(left, right); } switch (symbol) { - case "+": + case '+': return left + right; - case "-": + case '-': return left - right; - case "*": + case '*': return left * right; - case "/": + case '/': return left / right; - case "$": + case '$': return left(right); - case "&": - console.log("right", right); + case '&': + console.log('right', right); return right(left); - case ".": + case '.': return (x) => left(right(x)); default: - throw new Error("unexpected infix operator " + symbol); + throw new Error('unexpected infix operator ' + symbol); } } @@ -55,79 +53,75 @@ export function run(node, scope, ops = {}) { let runInScope = (node, scp = scope) => run(node, scp, ops); //console.log("node", node.type, node.text); switch (node.type) { - case "ERROR": + case 'ERROR': throw new Error(`invalid syntax: "${node.text}"`); - case "declarations": + case 'declarations': let result; node.children.forEach((declaration) => { result = runInScope(declaration); }); return result; - case "integer": + case 'integer': return Number(node.text); - case "float": + case 'float': return Number(node.text); - case "string": + case 'string': const str = node.text.slice(1, -1); return String(str); - case "lambda": + case 'lambda': const [_, lpatterns, __, lbody] = node.children; return curry(lpatterns.children, lbody, scope, ops); - case "function": + case 'function': const [fvariable, fpatterns, fbody] = node.children; scope[fvariable.text] = curry(fpatterns.children, fbody, scope, ops); return scope[fvariable.text]; - case "list": { + case 'list': { return node.children .filter((_, i) => i % 2 === 1) // elements are at odd indices .map((node) => runInScope(node)); } - case "match": - if (node.children[0].text !== "=" || node.children.length !== 2) { - throw new Error("match node so far only support simple assignments"); + case 'match': + if (node.children[0].text !== '=' || node.children.length !== 2) { + throw new Error('match node so far only support simple assignments'); } return runInScope(node.children[1]); - case "bind": - if (node.children.length !== 2) - throw new Error("expected 2 children for node type bind"); - if (node.children[0].type !== "variable") - throw new Error("expected variable as first child of bind node"); - if (node.children[1].type !== "match") - throw new Error("expected match as first child of bind node"); + case 'bind': + if (node.children.length !== 2) throw new Error('expected 2 children for node type bind'); + if (node.children[0].type !== 'variable') throw new Error('expected variable as first child of bind node'); + if (node.children[1].type !== 'match') throw new Error('expected match as first child of bind node'); const [bvariable, bmatch] = node.children; const value = runInScope(bmatch); scope[bvariable.text] = value; return value; - case "variable": + case 'variable': return scope[node.text]; - case "infix": { + case 'infix': { const [a, op, b] = node.children; const symbol = op.text; const [left, right] = [runInScope(a), runInScope(b)]; return runInfix(left, symbol, right, ops); } - case "apply": + case 'apply': return runApply(node, scope, ops); - case "left_section": { + case 'left_section': { const [_, b, op] = node.children; const right = runInScope(b); return (left) => runInfix(left, op.text, right, ops); } - case "right_section": { + case 'right_section': { const [_, op, b] = node.children; const right = runInScope(b); return (left) => runInfix(left, op.text, right, ops); } - case "parens": - if (node.children.length !== 3) - throw new Error("expected 3 children for node type parens"); + case 'parens': + if (node.children.length !== 3) throw new Error('expected 3 children for node type parens'); return runInScope(node.children[1]); default: if (node.children.length === 0) { - throw new Error("unhandled leaf type " + node.type); + throw new Error('unhandled leaf type ' + node.type); } if (node.children.length > 1) { - throw new Error("unhandled branch type " + node.type); + throw new Error('unhandled branch type ' + node.type); } return runInScope(node.children[0]); } diff --git a/packages/hs2js/src/index.mjs b/packages/hs2js/src/index.mjs index 170ef1b6..c3aab230 100644 --- a/packages/hs2js/src/index.mjs +++ b/packages/hs2js/src/index.mjs @@ -1,2 +1,2 @@ -export * from "./hs2js.mjs"; -export * from "./parser.mjs"; +export * from './hs2js.mjs'; +export * from './parser.mjs'; diff --git a/packages/hs2js/src/parser.mjs b/packages/hs2js/src/parser.mjs index 829a5da3..6fbd9ae2 100644 --- a/packages/hs2js/src/parser.mjs +++ b/packages/hs2js/src/parser.mjs @@ -1,6 +1,6 @@ -import Parser from "web-tree-sitter"; +import Parser from 'web-tree-sitter'; -let base = "/"; +let base = '/'; export function setBase(path) { base = path; } @@ -28,10 +28,5 @@ export function loadParser() { export async function parse(code) { const parser = await loadParser(); // for some reason, the parser doesn't like new lines.. - return parser.parse( - code - .replaceAll("\n\n", "~~~~") - .replaceAll("\n", "") - .replaceAll("~~~~", "\n") - ); + return parser.parse(code.replaceAll('\n\n', '~~~~').replaceAll('\n', '').replaceAll('~~~~', '\n')); } diff --git a/packages/hs2js/vite.config.js b/packages/hs2js/vite.config.js new file mode 100644 index 00000000..ce715712 --- /dev/null +++ b/packages/hs2js/vite.config.js @@ -0,0 +1,20 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [], + build: { + lib: { + entry: resolve(__dirname, 'src', 'index.mjs'), + name: 'hs2js', + formats: ['es', 'iife'], + fileName: (ext) => ({ es: 'index.mjs', iife: 'index.js' })[ext], + }, + rollupOptions: { + // external: [...Object.keys(dependencies)], + plugins: [], + }, + target: 'esnext', + }, +}); diff --git a/packages/hs2js/vite.config.mjs b/packages/hs2js/vite.config.mjs deleted file mode 100644 index 9eb4a07a..00000000 --- a/packages/hs2js/vite.config.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig } from "vite"; -import { resolve } from "path"; - -// https://vitejs.dev/config/ -export default defineConfig({ - plugins: [], - build: { - lib: { - entry: resolve(__dirname, "src", "index.mjs"), - name: "hs2js", - formats: ["es", "iife"], - fileName: (ext) => ({ es: "index.mjs", iife: "index.js" }[ext]), - }, - rollupOptions: { - // external: [...Object.keys(dependencies)], - plugins: [], - }, - target: "esnext", - }, -}); diff --git a/packages/tidal/hs2js.mjs b/packages/tidal/hs2js.mjs deleted file mode 100644 index 733b7aeb..00000000 --- a/packages/tidal/hs2js.mjs +++ /dev/null @@ -1,130 +0,0 @@ -function runApply(node, scope, ops) { - if (node.children.length !== 2) - throw new Error(`expected 2 children for node type apply, got ${node.children.length}`); - const [fn, arg] = node.children.map((child) => run(child, scope, ops)); - if (typeof fn !== 'function') { - throw new Error(`${node.children[0].text} is not a function`); - } - // only works if fn is curried! - return fn(arg); -} - -function runInfix(left, symbol, right, ops) { - const customOp = ops[symbol]; - if (customOp) { - return customOp(left, right); - } - switch (symbol) { - case '+': - return left + right; - case '-': - return left - right; - case '*': - return left * right; - case '/': - return left / right; - case '$': - return left(right); - case '&': - return right(left); - case '.': - return (x) => left(right(x)); - default: - throw new Error('unexpected infix operator ' + symbol); - } -} - -function curry(patterns, body, scope, ops) { - const [variable, ...rest] = patterns; - return (arg) => { - let _scope = { ...scope, [variable.text]: arg }; - if (patterns.length === 1) { - const result = run(body, _scope, ops); - return result; - } - return curry(rest, body, _scope, ops); - }; -} - -export function run(node, scope, ops = {}) { - let runInScope = (node, scp = scope) => run(node, scp, ops); - //console.log("node", node.type, node.text); - switch (node.type) { - case 'ERROR': - throw new Error(`invalid syntax: "${node.text}"`); - case 'declarations': - let result; - node.children.forEach((declaration) => { - result = runInScope(declaration); - }); - return result; - case 'integer': - return Number(node.text); - case 'float': - return Number(node.text); - case 'string': - const str = node.text.slice(1, -1); - return String(str); - case 'lambda': - const [_, lpatterns, __, lbody] = node.children; - return curry(lpatterns.children, lbody, scope, ops); - case 'function': - const [fvariable, fpatterns, fbody] = node.children; - scope[fvariable.text] = curry(fpatterns.children, fbody, scope, ops); - return scope[fvariable.text]; - case 'list': { - return node.children - .filter((_, i) => i % 2 === 1) // elements are at odd indices - .map((node) => runInScope(node)); - } - case 'match': - if (node.children[0].text !== '=' || node.children.length !== 2) { - throw new Error('match node so far only support simple assignments'); - } - return runInScope(node.children[1]); - case 'bind': - if (node.children.length !== 2) throw new Error('expected 2 children for node type bind'); - if (node.children[0].type !== 'variable') throw new Error('expected variable as first child of bind node'); - if (node.children[1].type !== 'match') throw new Error('expected match as first child of bind node'); - const [bvariable, bmatch] = node.children; - const value = runInScope(bmatch); - scope[bvariable.text] = value; - return value; - case 'variable': - return scope[node.text]; - case 'infix': { - const [a, op, b] = node.children; - const symbol = op.text; - const [left, right] = [runInScope(a), runInScope(b)]; - return runInfix(left, symbol, right, ops); - } - case 'apply': - return runApply(node, scope, ops); - case 'left_section': { - const [_, b, op] = node.children; - const right = runInScope(b); - return (left) => runInfix(left, op.text, right, ops); - } - case 'right_section': { - const [_, op, b] = node.children; - const right = runInScope(b); - return (left) => runInfix(left, op.text, right, ops); - } - case 'parens': - if (node.children.length !== 3) throw new Error('expected 3 children for node type parens'); - return runInScope(node.children[1]); - default: - if (node.children.length === 0) { - throw new Error('unhandled leaf type ' + node.type); - } - if (node.children.length > 1) { - throw new Error('unhandled branch type ' + node.type); - } - return runInScope(node.children[0]); - } -} - -export async function evaluate(haskellCode, scope = globalThis, ops) { - const ast = await parse(haskellCode); - return run(ast.rootNode, scope, ops); -} diff --git a/packages/tidal/parser.mjs b/packages/tidal/parser.mjs deleted file mode 100644 index 1b1f8a03..00000000 --- a/packages/tidal/parser.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import Parser from 'web-tree-sitter'; - -const base = import.meta.env.BASE_URL; - -async function loadParser() { - await Parser.init({ - locateFile(scriptName, scriptDirectory) { - return `${base}${scriptName}`; - }, - }); - const parser = new Parser(); - const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`); - parser.setLanguage(Lang); - return parser; -} - -let parserLoaded = loadParser(); -export async function parse(code) { - const parser = await parserLoaded; - // for some reason, the parser doesn't like new lines.. - return parser.parse(code.replaceAll('\n\n', '~~~~').replaceAll('\n', '').replaceAll('~~~~', '\n')); -} From bbeb243cea02f2a9da9b532a04d953a859c95d71 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 17 May 2024 10:05:18 +0200 Subject: [PATCH 068/195] replace postinstall with prepare for dev only --- packages/tidal/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/tidal/package.json b/packages/tidal/package.json index 7c12cbb6..e2f94c56 100644 --- a/packages/tidal/package.json +++ b/packages/tidal/package.json @@ -7,7 +7,7 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" + "prepare": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" }, "repository": { "type": "git", From 8c480807d280f0dc4cdd4b8b1d8b9fc6bdd1f53c Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 17 May 2024 10:11:22 +0200 Subject: [PATCH 069/195] remove prepare script for now --- packages/tidal/README.md | 3 +-- packages/tidal/package.json | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/tidal/README.md b/packages/tidal/README.md index 24f3efc3..8b07ac19 100644 --- a/packages/tidal/README.md +++ b/packages/tidal/README.md @@ -5,7 +5,6 @@ This is an experiment in implementing tree-sitter for parsing haskell. ```sh pnpm i cd haskell +pnpm copy-wasm pnpm dev ``` - -This \ No newline at end of file diff --git a/packages/tidal/package.json b/packages/tidal/package.json index e2f94c56..3cab8182 100644 --- a/packages/tidal/package.json +++ b/packages/tidal/package.json @@ -5,9 +5,9 @@ "type": "module", "scripts": { "dev": "vite", - "build": "vite build", + "build": "pnpm copy-wasm && vite build", "preview": "vite preview", - "prepare": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" + "copy-wasm": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public" }, "repository": { "type": "git", From f54f80e698b9c95f9be5d7b641fcefa44e01a0eb Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 17 May 2024 10:14:26 +0200 Subject: [PATCH 070/195] bump version --- examples/buildless/hs2js.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/buildless/hs2js.html b/examples/buildless/hs2js.html index 5ffb6cf0..96b53c53 100644 --- a/examples/buildless/hs2js.html +++ b/examples/buildless/hs2js.html @@ -1,7 +1,7 @@ - + + + + + diff --git a/packages/tidal/graph.mjs b/packages/tidal/graph.mjs deleted file mode 100644 index bac3d135..00000000 --- a/packages/tidal/graph.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { Graphviz } from '@hpcc-js/wasm'; -import toDot from 'jgf-dot'; - -const graphvizLoaded = Graphviz.load(); - -function walk(node, branch = [0], parent) { - let nodes = []; - let edges = []; - const color = 'white'; - const current = { - id: branch.join('-'), - color, - fontcolor: color, - label: node.type.replace('\\', 'lambda'), // backslash kills graphviz.. - }; - nodes.push(current); - parent && edges.push({ source: parent.id, target: current.id, color }); - if (node.children.length) { - node.children.forEach((child, j) => { - const { nodes: childNodes, edges: childEdges } = walk(child, branch.concat([j]), current); - nodes = nodes.concat(childNodes || []); - edges = edges.concat(childEdges || []); - }); - } - return { nodes, edges }; -} - -export async function renderGraph(tree, container) { - const { nodes, edges } = walk(tree.rootNode); - const graphviz = await graphvizLoaded; - let dot = toDot({ - graph: { - nodes, - edges, - }, - }); - dot = dot.split('\n'); - dot.splice(1, 0, 'bgcolor="transparent"'); - dot.splice(1, 0, 'color="white"'); - dot = dot.join('\n'); - const svg = await graphviz.layout(dot, 'svg', 'dot', {}); - container.innerHTML = svg; -} diff --git a/packages/tidal/index.html b/packages/tidal/index.html index 532bce3d..cfa818b0 100644 --- a/packages/tidal/index.html +++ b/packages/tidal/index.html @@ -23,7 +23,6 @@

-    
diff --git a/packages/tidal/main.js b/packages/tidal/main.js index 0b2ac7d5..0d948504 100644 --- a/packages/tidal/main.js +++ b/packages/tidal/main.js @@ -1,12 +1,9 @@ import { run, parse } from 'hs2js'; -import { renderGraph } from './graph.mjs'; import { initStrudel, reify, late, samples, stack } from '@strudel/web'; initStrudel({ prebake: () => samples('github:tidalcycles/dirt-samples'), }); -const graphContainer = document.getElementById('graph'); - const textarea = document.getElementById('code'); if (window.location.hash) { textarea.value = atob(window.location.hash.slice(1)); @@ -60,12 +57,6 @@ async function update() { } console.log('parsed tree'); console.log(tree.rootNode.toString()); - try { - renderGraph(tree, graphContainer); - } catch (err) { - console.warn('could not render graph'); - console.error(err); - } try { let patterns = {}; window.p = (name, pattern) => { diff --git a/packages/tidal/package.json b/packages/tidal/package.json index 3cab8182..0e2d8aa5 100644 --- a/packages/tidal/package.json +++ b/packages/tidal/package.json @@ -27,8 +27,6 @@ }, "homepage": "https://github.com/tidalcycles/strudel#readme", "dependencies": { - "@hpcc-js/wasm": "^2.15.3", - "jgf-dot": "^1.1.1", "@strudel/web": "workspace:*", "hs2js": "workspace:*" }, From d108de40d05b1a6968566cd2feb7d287bb7de0a0 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Fri, 17 May 2024 18:41:43 +0200 Subject: [PATCH 075/195] rename --- packages/tidal/index.html | 2 +- packages/tidal/{main.js => tidal.mjs} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename packages/tidal/{main.js => tidal.mjs} (100%) diff --git a/packages/tidal/index.html b/packages/tidal/index.html index cfa818b0..7f88bf0a 100644 --- a/packages/tidal/index.html +++ b/packages/tidal/index.html @@ -23,6 +23,6 @@

-    
+    
   
 
diff --git a/packages/tidal/main.js b/packages/tidal/tidal.mjs
similarity index 100%
rename from packages/tidal/main.js
rename to packages/tidal/tidal.mjs

From fd950d4476da7650936bc2be9f6325b15de21260 Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:36:41 +0200
Subject: [PATCH 076/195] tidy tidal package - move tidal repl to examples -
 make hs2js synchronous

---
 .../tidal => examples/tidal-repl}/.gitignore  |   0
 .../tidal => examples/tidal-repl}/README.md   |   0
 .../tidal => examples/tidal-repl}/index.html  |   3 +-
 examples/tidal-repl/main.js                   |  80 ++++++++++++++
 examples/tidal-repl/package.json              |  36 ++++++
 .../tidal-repl}/public/README.md              |   0
 packages/hs2js/package.json                   |   8 +-
 packages/hs2js/src/hs2js.mjs                  |   4 +-
 packages/hs2js/src/parser.mjs                 |  11 +-
 packages/tidal/package.json                   |  26 ++---
 packages/tidal/tidal.mjs                      |  53 ++-------
 pnpm-lock.yaml                                | 104 ++++--------------
 12 files changed, 171 insertions(+), 154 deletions(-)
 rename {packages/tidal => examples/tidal-repl}/.gitignore (100%)
 rename {packages/tidal => examples/tidal-repl}/README.md (100%)
 rename {packages/tidal => examples/tidal-repl}/index.html (91%)
 create mode 100644 examples/tidal-repl/main.js
 create mode 100644 examples/tidal-repl/package.json
 rename {packages/tidal => examples/tidal-repl}/public/README.md (100%)

diff --git a/packages/tidal/.gitignore b/examples/tidal-repl/.gitignore
similarity index 100%
rename from packages/tidal/.gitignore
rename to examples/tidal-repl/.gitignore
diff --git a/packages/tidal/README.md b/examples/tidal-repl/README.md
similarity index 100%
rename from packages/tidal/README.md
rename to examples/tidal-repl/README.md
diff --git a/packages/tidal/index.html b/examples/tidal-repl/index.html
similarity index 91%
rename from packages/tidal/index.html
rename to examples/tidal-repl/index.html
index 7f88bf0a..0d17855e 100644
--- a/packages/tidal/index.html
+++ b/examples/tidal-repl/index.html
@@ -23,6 +23,7 @@
   
     
     

-    
+    
   
 
diff --git a/examples/tidal-repl/main.js b/examples/tidal-repl/main.js
new file mode 100644
index 00000000..9e572ea8
--- /dev/null
+++ b/examples/tidal-repl/main.js
@@ -0,0 +1,80 @@
+import { run, parse } from 'hs2js';
+import { initStrudel, reify, late, samples, stack } from '@strudel/web';
+
+initStrudel({
+  prebake: () => samples('github:tidalcycles/dirt-samples'),
+});
+
+const textarea = document.getElementById('code');
+if (window.location.hash) {
+  textarea.value = atob(window.location.hash.slice(1));
+} else {
+  textarea.value = 'd1 $ s "jvbass(3,8)"';
+}
+textarea.addEventListener('input', (e) => {
+  window.location.hash = btoa(e.target.value);
+  update();
+});
+update();
+
+function getInfixOperators() {
+  let operators = {
+    '>': 'set',
+    '#': 'set',
+    '+': 'add',
+    '-': 'sub',
+    '*': 'mul',
+    '/': 'div',
+  };
+  let alignments = {
+    in: (s) => '|' + s,
+    out: (s) => s + '|',
+    mix: (s) => '|' + s + '|',
+  };
+  let ops = {};
+  Object.entries(operators).forEach(([o, name]) => {
+    // operator without alignment
+    ops[o] = (l, r) => reify(l)[name](reify(r));
+    Object.entries(alignments).forEach(([a, getSymbol]) => {
+      // get symbol with alignment
+      let symbol = getSymbol(o);
+      ops[symbol] = (l, r) => reify(l)[name][a](reify(r));
+    });
+  });
+  ops['~>'] = (l, r) => reify(l).late(reify(r));
+  ops['<~'] = (l, r) => reify(l).early(reify(r));
+  ops['<$>'] = (l, r) => reify(r).fmap(l).outerJoin(); // is this right?
+  return ops;
+}
+const ops = getInfixOperators();
+
+async function update() {
+  let result, tree;
+  try {
+    tree = await parse(textarea.value);
+  } catch (err) {
+    console.warn('parse error');
+    console.error(err);
+  }
+  console.log('parsed tree');
+  console.log(tree.rootNode.toString());
+  try {
+    let patterns = {};
+    window.p = (name, pattern) => {
+      patterns[name] = pattern;
+    };
+    window.d1 = (pat) => window.p(1, pat);
+    window.d2 = (pat) => window.p(2, pat);
+    window.d3 = (pat) => window.p(3, pat);
+    window.rot = late;
+    result = run(tree.rootNode, window, ops);
+    if (Object.values(patterns).length) {
+      stack(...Object.values(patterns)).play();
+    }
+  } catch (err) {
+    console.warn('eval error');
+    console.error(err);
+    result = 'ERROR: ' + err.message;
+  }
+  document.getElementById('result').innerHTML = 'Result: ' + result;
+}
diff --git a/examples/tidal-repl/package.json b/examples/tidal-repl/package.json
new file mode 100644
index 00000000..0e2d8aa5
--- /dev/null
+++ b/examples/tidal-repl/package.json
@@ -0,0 +1,36 @@
+{
+  "name": "@strudel/tidal",
+  "private": true,
+  "version": "0.0.1",
+  "type": "module",
+  "scripts": {
+    "dev": "vite",
+    "build": "pnpm copy-wasm && vite build",
+    "preview": "vite preview",
+    "copy-wasm": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public"
+  },
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/tidalcycles/strudel.git"
+  },
+  "keywords": [
+    "titdalcycles",
+    "strudel",
+    "pattern",
+    "livecoding",
+    "algorave"
+  ],
+  "author": "Felix Roos ",
+  "license": "AGPL-3.0-or-later",
+  "bugs": {
+    "url": "https://github.com/tidalcycles/strudel/issues"
+  },
+  "homepage": "https://github.com/tidalcycles/strudel#readme",
+  "dependencies": {
+    "@strudel/web": "workspace:*",
+    "hs2js": "workspace:*"
+  },
+  "devDependencies": {
+    "vite": "^5.0.8"
+  }
+}
diff --git a/packages/tidal/public/README.md b/examples/tidal-repl/public/README.md
similarity index 100%
rename from packages/tidal/public/README.md
rename to examples/tidal-repl/public/README.md
diff --git a/packages/hs2js/package.json b/packages/hs2js/package.json
index 1f980fcc..1d3907b1 100644
--- a/packages/hs2js/package.json
+++ b/packages/hs2js/package.json
@@ -2,8 +2,12 @@
   "name": "hs2js",
   "version": "0.0.7",
   "description": "Experimental Haskell in JavaScript interpreter",
-  "main": "dist/index.js",
-  "module": "dist/index.mjs",
+  "main": "src/index.mjs",
+  "type": "module",
+  "publishConfig": {
+    "main": "dist/index.js",
+    "module": "dist/index.mjs"
+  },
   "scripts": {
     "build-wasm": "tree-sitter build-wasm node_modules/tree-sitter-haskell && mv tree-sitter-haskell.wasm ./dist/ && cp node_modules/web-tree-sitter/tree-sitter.wasm ./dist/",
     "build": "vite build && npm run build-wasm",
diff --git a/packages/hs2js/src/hs2js.mjs b/packages/hs2js/src/hs2js.mjs
index e7b7cf46..4161b0e6 100644
--- a/packages/hs2js/src/hs2js.mjs
+++ b/packages/hs2js/src/hs2js.mjs
@@ -127,7 +127,7 @@ export function run(node, scope, ops = {}) {
   }
 }
 
-export async function evaluate(haskellCode, scope = globalThis, ops) {
-  const ast = await parse(haskellCode);
+export function evaluate(haskellCode, scope = globalThis, ops) {
+  const ast = parse(haskellCode);
   return run(ast.rootNode, scope, ops);
 }
diff --git a/packages/hs2js/src/parser.mjs b/packages/hs2js/src/parser.mjs
index 6fbd9ae2..25644c7e 100644
--- a/packages/hs2js/src/parser.mjs
+++ b/packages/hs2js/src/parser.mjs
@@ -5,15 +5,18 @@ export function setBase(path) {
   base = path;
 }
 
+let isReady = false,
+  parser;
 async function _loadParser() {
   await Parser.init({
     locateFile(scriptName, scriptDirectory) {
       return `${base}${scriptName}`;
     },
   });
-  const parser = new Parser();
+  parser = new Parser();
   const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`);
   parser.setLanguage(Lang);
+  isReady = true;
   return parser;
 }
 
@@ -25,8 +28,10 @@ export function loadParser() {
   return parserLoaded;
 }
 
-export async function parse(code) {
-  const parser = await loadParser();
+export function parse(code) {
+  if (!isReady) {
+    throw new Error('hs2js not ready. await loadParser before calling evaluate or parse functions');
+  }
   // for some reason, the parser doesn't like new lines..
   return parser.parse(code.replaceAll('\n\n', '~~~~').replaceAll('\n', '').replaceAll('~~~~', '\n'));
 }
diff --git a/packages/tidal/package.json b/packages/tidal/package.json
index 0e2d8aa5..772f5f4d 100644
--- a/packages/tidal/package.json
+++ b/packages/tidal/package.json
@@ -1,36 +1,26 @@
 {
   "name": "@strudel/tidal",
-  "private": true,
-  "version": "0.0.1",
-  "type": "module",
-  "scripts": {
-    "dev": "vite",
-    "build": "pnpm copy-wasm && vite build",
-    "preview": "vite preview",
-    "copy-wasm": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public"
-  },
+  "version": "0.0.7",
+  "description": "Experimental Tidal Code interpreter",
+  "module": "tidal.mjs",
   "repository": {
     "type": "git",
-    "url": "git+https://github.com/tidalcycles/strudel.git"
+    "url": "git+https://github.com/felixroos/hs2js.git"
   },
   "keywords": [
-    "titdalcycles",
-    "strudel",
-    "pattern",
-    "livecoding",
-    "algorave"
+    "haskell",
+    "javascript"
   ],
   "author": "Felix Roos ",
   "license": "AGPL-3.0-or-later",
   "bugs": {
     "url": "https://github.com/tidalcycles/strudel/issues"
   },
-  "homepage": "https://github.com/tidalcycles/strudel#readme",
+  "homepage": "https://github.com/tidalcycles/strudel/tree/main/packages/hs2js",
   "dependencies": {
-    "@strudel/web": "workspace:*",
     "hs2js": "workspace:*"
   },
   "devDependencies": {
-    "vite": "^5.0.8"
+    "vite": "^5.0.10"
   }
 }
diff --git a/packages/tidal/tidal.mjs b/packages/tidal/tidal.mjs
index 0d948504..60a76946 100644
--- a/packages/tidal/tidal.mjs
+++ b/packages/tidal/tidal.mjs
@@ -1,20 +1,4 @@
-import { run, parse } from 'hs2js';
-import { initStrudel, reify, late, samples, stack } from '@strudel/web';
-initStrudel({
-  prebake: () => samples('github:tidalcycles/dirt-samples'),
-});
-
-const textarea = document.getElementById('code');
-if (window.location.hash) {
-  textarea.value = atob(window.location.hash.slice(1));
-} else {
-  textarea.value = 'd1 $ s "jvbass(3,8)"';
-}
-textarea.addEventListener('input', (e) => {
-  window.location.hash = btoa(e.target.value);
-  update();
-});
-update();
+import { evaluate, loadParser } from 'hs2js';
 
 function getInfixOperators() {
   let operators = {
@@ -47,33 +31,10 @@ function getInfixOperators() {
 }
 const ops = getInfixOperators();
 
-async function update() {
-  let result, tree;
-  try {
-    tree = await parse(textarea.value);
-  } catch (err) {
-    console.warn('parse error');
-    console.error(err);
-  }
-  console.log('parsed tree');
-  console.log(tree.rootNode.toString());
-  try {
-    let patterns = {};
-    window.p = (name, pattern) => {
-      patterns[name] = pattern;
-    };
-    window.d1 = (pat) => window.p(1, pat);
-    window.d2 = (pat) => window.p(2, pat);
-    window.d3 = (pat) => window.p(3, pat);
-    window.rot = late;
-    result = run(tree.rootNode, window, ops);
-    if (Object.values(patterns).length) {
-      stack(...Object.values(patterns)).play();
-    }
-  } catch (err) {
-    console.warn('eval error');
-    console.error(err);
-    result = 'ERROR: ' + err.message;
-  }
-  document.getElementById('result').innerHTML = 'Result: ' + result;
+export async function initTidal() {
+  return loadParser();
+}
+
+export function tidal(code) {
+  return evaluate(code, window, ops);
 }
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8ac9adb0..7beea16b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -140,6 +140,19 @@ importers:
         specifier: ^5.0.10
         version: 5.0.10
 
+  examples/tidal-repl:
+    dependencies:
+      '@strudel/web':
+        specifier: workspace:*
+        version: link:../../packages/web
+      hs2js:
+        specifier: workspace:*
+        version: link:../../packages/hs2js
+    devDependencies:
+      vite:
+        specifier: ^5.0.8
+        version: 5.2.2(@types/node@20.10.6)
+
   packages/codemirror:
     dependencies:
       '@codemirror/autocomplete':
@@ -424,21 +437,12 @@ importers:
 
   packages/tidal:
     dependencies:
-      '@hpcc-js/wasm':
-        specifier: ^2.15.3
-        version: 2.16.2
-      '@strudel/web':
-        specifier: workspace:*
-        version: link:../web
       hs2js:
         specifier: workspace:*
         version: link:../hs2js
-      jgf-dot:
-        specifier: ^1.1.1
-        version: 1.1.1
     devDependencies:
       vite:
-        specifier: ^5.0.8
+        specifier: ^5.0.10
         version: 5.2.2(@types/node@20.10.6)
 
   packages/tonal:
@@ -619,6 +623,9 @@ importers:
       '@strudel/soundfonts':
         specifier: workspace:*
         version: link:../packages/soundfonts
+      '@strudel/tidal':
+        specifier: workspace:*
+        version: link:../packages/tidal
       '@strudel/tonal':
         specifier: workspace:*
         version: link:../packages/tonal
@@ -3069,13 +3076,6 @@ packages:
       react: 18.2.0
     dev: false
 
-  /@hpcc-js/wasm@2.16.2:
-    resolution: {integrity: sha512-THiidUMYR8/cIfFT3MVcWuRE7bQKh295nrFBxGvUNc4Nq8e2uU1LtiplHs7AUkJ0GxgvZoR+8TQ1/E3Qb/uE2g==}
-    hasBin: true
-    dependencies:
-      yargs: 17.7.2
-    dev: false
-
   /@humanwhocodes/config-array@0.11.13:
     resolution: {integrity: sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==}
     engines: {node: '>=10.10.0'}
@@ -6269,6 +6269,7 @@ packages:
       string-width: 4.2.3
       strip-ansi: 6.0.1
       wrap-ansi: 7.0.0
+    dev: true
 
   /clone-buffer@1.0.0:
     resolution: {integrity: sha512-KLLTJWrvwIP+OPfMn0x2PheDEP20RPUcGXj/ERegTgdmPEZylALQldygiqrPPu8P45uNuPs7ckmReLY6v/iA5g==}
@@ -6986,10 +6987,6 @@ packages:
     engines: {node: '>=12'}
     dev: true
 
-  /dotty@0.0.1:
-    resolution: {integrity: sha512-eDT0hfJEnQbGaZcTuCfj2igPkQ7qa/n9K2pGGDxhEqKhARLq+xE1TonvpOPHq+7KeG+D6A/V8BwCcsdPom2TQg==}
-    dev: false
-
   /dset@3.1.3:
     resolution: {integrity: sha512-20TuZZHCEZ2O71q9/+8BwKwZ0QtD9D8ObhrihJPr+vLLYlSuAU3/zL4cSlgbfeoGHTjCSJBa7NGcrF9/Bx/WJQ==}
     engines: {node: '>=4'}
@@ -7911,10 +7908,6 @@ packages:
     resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==}
     dev: true
 
-  /gather-stream@1.0.0:
-    resolution: {integrity: sha512-NspYMi3rN3EKmMdejUXbtluDYrcRlTEBBFhWzVRZVsOx94OPxlXp0AzyPKyLiT7iaurcoTE/KcHsHP/PowNEaA==}
-    dev: false
-
   /gauge@4.0.4:
     resolution: {integrity: sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==}
     engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
@@ -8252,33 +8245,6 @@ packages:
   /graphemer@1.4.0:
     resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
 
-  /graphlib-dot@0.6.4:
-    resolution: {integrity: sha512-rdhDTu0mBlloTpFMfkQq+e3y4yL22OqP5MhQbkw6QUURqa+4YLgv3XZy2fA64wdEcJNZ+waI76URemVgdFtzng==}
-    dependencies:
-      graphlib: 2.1.8
-      lodash: 4.17.21
-    dev: false
-
-  /graphlib-json-graph@1.0.0:
-    resolution: {integrity: sha512-sJsFuthZnSL5knaDDZhDx8fg1Zy5t/7ZqVHiytoeSzezGhMoSFD3T3K5YQakKFEyXtYjOzbnvsyr2qo+6/qq/Q==}
-    dependencies:
-      graphlib: 1.0.7
-      par: 0.3.0
-      prop: 0.1.1
-    dev: false
-
-  /graphlib@1.0.7:
-    resolution: {integrity: sha512-jNb7RbqTIRyZRmcVCxGefOlGWjNdbjcT2tFj36zhnRa8yhAlOvydh9nBixfLQIqSU+DwCx47tg3ysw8NIYhpsA==}
-    dependencies:
-      lodash: 3.10.1
-    dev: false
-
-  /graphlib@2.1.8:
-    resolution: {integrity: sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==}
-    dependencies:
-      lodash: 4.17.21
-    dev: false
-
   /gray-matter@4.0.3:
     resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==}
     engines: {node: '>=6.0'}
@@ -9184,15 +9150,6 @@ packages:
       supports-color: 7.2.0
     dev: true
 
-  /jgf-dot@1.1.1:
-    resolution: {integrity: sha512-/aw9bwVfn67A+lvjxtbocBuhB2rNdL5UY5rlHhKVh9ValvVJETU5lQ0jitDxiIjIPAEeuR4B1aFNA7E3wKNV1A==}
-    hasBin: true
-    dependencies:
-      graphlib-dot: 0.6.4
-      graphlib-json-graph: 1.0.0
-      read-file-stdin: 0.2.1
-    dev: false
-
   /jiti@1.21.0:
     resolution: {integrity: sha512-gFqAIbuKyyso/3G2qhiO2OM6shY6EPP/R0+mkDbyspxKazh8BXDC5FiFsUjlczgdNz/vfra0da2y+aHrusLG/Q==}
     hasBin: true
@@ -9649,12 +9606,9 @@ packages:
     resolution: {integrity: sha512-HDWXG8isMntAyRF5vZ7xKuEvOhT4AhlRt/3czTSjvGUxjYCBVRQY48ViDHyfYz9VIoBkW4TMGQNapx+l3RUwdA==}
     dev: true
 
-  /lodash@3.10.1:
-    resolution: {integrity: sha512-9mDDwqVIma6OZX79ZlDACZl8sBm0TEnkf99zV3iMA4GzkIT/9hiqP5mY0HoT1iNLCrKc/R1HByV+yJfRWVJryQ==}
-    dev: false
-
   /lodash@4.17.21:
     resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
+    dev: true
 
   /log-symbols@4.1.0:
     resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==}
@@ -11370,11 +11324,6 @@ packages:
       - supports-color
     dev: true
 
-  /par@0.3.0:
-    resolution: {integrity: sha512-6V910zFAoHnxjX6ILkwbQcpIkD3KI2gBAPfCtZQNaJTvTxgIoKXSwDQIE3ty0zbOGdBXHRnl6rd66a5jj12pfw==}
-    engines: {node: '>=0.6'}
-    dev: false
-
   /parent-module@1.0.1:
     resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}
     engines: {node: '>=6'}
@@ -11845,12 +11794,6 @@ packages:
       read: 2.1.0
     dev: true
 
-  /prop@0.1.1:
-    resolution: {integrity: sha512-hf5DdgiPkcoVxBfuSknP918U0lDC+7lArIjIB2U4Gh79p1Xtc0JP6W5DW3c0wC0x9/A6CsAISh3202I1GlMgkw==}
-    dependencies:
-      dotty: 0.0.1
-    dev: false
-
   /property-information@6.2.0:
     resolution: {integrity: sha512-kma4U7AFCTwpqq5twzC1YVIDXSqg6qQK6JN0smOw8fgRy1OkMi0CYSzFmsy6dnqSenamAtj0CyXMUJ1Mf6oROg==}
 
@@ -11982,12 +11925,6 @@ packages:
     engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
     dev: true
 
-  /read-file-stdin@0.2.1:
-    resolution: {integrity: sha512-dAqysQ4kfj9m5aejZOPr+aRGXZJXdLkMOLZ3BXMwMBQHiO+aylGBFJPh88AYPQrOf+D43F4Uc2oUIW9kBlItLA==}
-    dependencies:
-      gather-stream: 1.0.0
-    dev: false
-
   /read-package-json-fast@3.0.2:
     resolution: {integrity: sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw==}
     engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -14642,6 +14579,7 @@ packages:
       ansi-styles: 4.3.0
       string-width: 4.2.3
       strip-ansi: 6.0.1
+    dev: true
 
   /wrap-ansi@8.1.0:
     resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==}
@@ -14733,6 +14671,7 @@ packages:
   /y18n@5.0.8:
     resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
     engines: {node: '>=10'}
+    dev: true
 
   /yallist@3.1.1:
     resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
@@ -14803,6 +14742,7 @@ packages:
       string-width: 4.2.3
       y18n: 5.0.8
       yargs-parser: 21.1.1
+    dev: true
 
   /yocto-queue@0.1.0:
     resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}

From a35e9aef0ea75ea7ba8a4dfc23ec6d637b9a9c4a Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:37:04 +0200
Subject: [PATCH 077/195] add tidal package to website

---
 website/.gitignore        | 3 +++
 website/package.json      | 4 +++-
 website/src/repl/util.mjs | 1 +
 3 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/website/.gitignore b/website/.gitignore
index 02f6e50b..60c587b1 100644
--- a/website/.gitignore
+++ b/website/.gitignore
@@ -17,3 +17,6 @@ pnpm-debug.log*
 
 # macOS-specific files
 .DS_Store
+
+public/tree-sitter.wasm
+public/tree-sitter-haskell.wasm
\ No newline at end of file
diff --git a/website/package.json b/website/package.json
index 5065c106..16d86d93 100644
--- a/website/package.json
+++ b/website/package.json
@@ -9,7 +9,8 @@
     "check": "astro check && tsc",
     "build": "astro build",
     "preview": "astro preview --port 3009 --host 0.0.0.0",
-    "astro": "astro"
+    "astro": "astro",
+    "postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public"
   },
   "dependencies": {
     "@algolia/client-search": "^4.22.0",
@@ -39,6 +40,7 @@
     "@strudel/transpiler": "workspace:*",
     "@strudel/webaudio": "workspace:*",
     "@strudel/xen": "workspace:*",
+    "@strudel/tidal": "workspace:*",
     "@supabase/supabase-js": "^2.39.1",
     "@tailwindcss/forms": "^0.5.7",
     "@tailwindcss/typography": "^0.5.10",
diff --git a/website/src/repl/util.mjs b/website/src/repl/util.mjs
index 3147ae38..703d3447 100644
--- a/website/src/repl/util.mjs
+++ b/website/src/repl/util.mjs
@@ -82,6 +82,7 @@ export function loadModules() {
     import('@strudel/serial'),
     import('@strudel/soundfonts'),
     import('@strudel/csound'),
+    import('@strudel/tidal'),
   ];
   if (isTauri()) {
     modules = modules.concat([

From 5b89500acd36187ef6e2b2d852bfa4df0df3396c Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:38:30 +0200
Subject: [PATCH 078/195] fix: lint + format

---
 examples/tidal-repl/index.html | 7 +++++--
 packages/tidal/package.json    | 3 ++-
 packages/tidal/tidal.mjs       | 1 +
 pnpm-lock.yaml                 | 3 +++
 4 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/examples/tidal-repl/index.html b/examples/tidal-repl/index.html
index 0d17855e..25dc693e 100644
--- a/examples/tidal-repl/index.html
+++ b/examples/tidal-repl/index.html
@@ -23,7 +23,10 @@
   
     
     

-    
+    
   
 
diff --git a/packages/tidal/package.json b/packages/tidal/package.json
index 772f5f4d..7db0a82d 100644
--- a/packages/tidal/package.json
+++ b/packages/tidal/package.json
@@ -18,7 +18,8 @@
   },
   "homepage": "https://github.com/tidalcycles/strudel/tree/main/packages/hs2js",
   "dependencies": {
-    "hs2js": "workspace:*"
+    "hs2js": "workspace:*",
+    "@strudel/core": "workspace:*"
   },
   "devDependencies": {
     "vite": "^5.0.10"
diff --git a/packages/tidal/tidal.mjs b/packages/tidal/tidal.mjs
index 60a76946..785635f7 100644
--- a/packages/tidal/tidal.mjs
+++ b/packages/tidal/tidal.mjs
@@ -1,3 +1,4 @@
+import { reify } from '@strudel/core';
 import { evaluate, loadParser } from 'hs2js';
 
 function getInfixOperators() {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7beea16b..967c1e0d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -437,6 +437,9 @@ importers:
 
   packages/tidal:
     dependencies:
+      '@strudel/core':
+        specifier: workspace:*
+        version: link:../core
       hs2js:
         specifier: workspace:*
         version: link:../hs2js

From b4f1cedc20514ffe4d3473b4dba9ae70988d1e5c Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:44:44 +0200
Subject: [PATCH 079/195] update readme after making it sync

---
 packages/hs2js/README.md | 31 +++++++++++++++----------------
 1 file changed, 15 insertions(+), 16 deletions(-)

diff --git a/packages/hs2js/README.md b/packages/hs2js/README.md
index f4059ff0..24d9c774 100644
--- a/packages/hs2js/README.md
+++ b/packages/hs2js/README.md
@@ -15,10 +15,11 @@ You can load the library directly from a script tag via unpkg:
 
 
 ```
 
@@ -66,11 +67,11 @@ Example:
 
 ```js
 // simple
-hs2js.evaluate(`2 + 2`).then(console.log) // log 4
+hs2js.evaluate(`2 + 2`) // = 4
 // passing variables via scope:
-hs2js.evaluate(`a + b`, { a: 1, b: 2 }).then(console.log); // logs 3
+hs2js.evaluate(`a + b`, { a: 1, b: 2 }) // = 3
 // custom operator
-hs2js.evaluate(`2 |* 3`, {}, { '|*': (l, r) => l * r }).then(console.log); // logs 6
+hs2js.evaluate(`2 |* 3`, {}, { '|*': (l, r) => l * r }) // = 6
 ```
 
 ### parse
@@ -80,7 +81,8 @@ hs2js.evaluate(`2 |* 3`, {}, { '|*': (l, r) => l * r }).then(console.log); // lo
 Example:
 
 ```js
-hs2js.parse(`2 + 2`).then(ast=>console.log(ast.toString()))
+const ast = hs2js.parse(`2 + 2`)
+console.log(ast.toString())
 // (haskell declarations: (declarations (top_splice (apply function: (variable) argument: (literal (integer))))))
 ```
 
@@ -95,21 +97,18 @@ Evaluates `rootNode` of haskell AST (used by evaluate internally).
 Example:
 
 ```js
-async function main() {
-  const ast = await hs2js.parse(`2 + 3`);
-  const res = hs2js.run(ast.rootNode);
-  console.log(res);
-}
-main(); // logs 5
+const ast = hs2js.parse(`2 + 3`);
+const res = hs2js.run(ast.rootNode);
+console.log(res); // = 5
 ```
 
 ### loadParser
 
 Loads and caches the parser by fetching `tree-sitter.wasm` and `tree-sitter-haskell.wasm`.
-This function is called internally by `parse` but calling it yourself might make the parser be ready faster, depending on your application.
+Make sure to call and await this function before calling `parse` or `evaluate`.
 
 ```js
-hs2js.loadParser().then(() => console.log('parser loaded'))
+hs2js.loadParser().then(() => hs2js.evaluate('alert "ready"'))
 ```
 
 ### setBase

From d132344d1110d1e0248574f7272147a5b21732c3 Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:48:11 +0200
Subject: [PATCH 080/195] bump

---
 packages/hs2js/package.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/packages/hs2js/package.json b/packages/hs2js/package.json
index 1d3907b1..56ad995f 100644
--- a/packages/hs2js/package.json
+++ b/packages/hs2js/package.json
@@ -1,6 +1,6 @@
 {
   "name": "hs2js",
-  "version": "0.0.7",
+  "version": "0.0.8",
   "description": "Experimental Haskell in JavaScript interpreter",
   "main": "src/index.mjs",
   "type": "module",

From 71f8c0745c9c6a0870c52ae37fdd97c92a35d085 Mon Sep 17 00:00:00 2001
From: Felix Roos 
Date: Fri, 17 May 2024 20:51:43 +0200
Subject: [PATCH 081/195] update examples after making hs2js sync

---
 examples/buildless/tidal.html | 10 ++++++----
 examples/tidal-repl/main.js   |  7 +++++--
 2 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/examples/buildless/tidal.html b/examples/buildless/tidal.html
index 459ad0ed..16416b56 100644
--- a/examples/buildless/tidal.html
+++ b/examples/buildless/tidal.html
@@ -8,12 +8,13 @@
   
     
     

-    
-    
+    
+