Repository: AskingQuestions/Shadeup
Branch: main
Commit: 8b25bf92c1aa
Files: 402
Total size: 16.3 MB
Directory structure:
gitextract_91pjwq56/
├── .gitattributes
├── .gitignore
├── .vscode/
│ └── launch.json
├── README.md
├── cli/
│ ├── README.md
│ ├── cli.js
│ ├── compiler-dist/
│ │ ├── compiler.d.ts
│ │ ├── compiler.js
│ │ ├── readme.md
│ │ ├── shadeup-compiler.js
│ │ └── tree-sitter-shadeup.wasm
│ ├── electron/
│ │ ├── index.html
│ │ └── main.js
│ ├── index.js
│ ├── package.json
│ ├── test/
│ │ ├── main.d.ts
│ │ ├── main.js
│ │ ├── other.js
│ │ ├── other.shadeup
│ │ └── vite-project/
│ │ ├── .gitignore
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── index.ts
│ │ │ ├── logoPath.shadeup
│ │ │ ├── main.d.ts
│ │ │ ├── main.js
│ │ │ ├── main.shadeup
│ │ │ ├── style.css
│ │ │ └── vite-env.d.ts
│ │ └── tsconfig.json
│ └── vite/
│ ├── .gitignore
│ ├── index.html
│ ├── main.js
│ ├── package.json
│ ├── runner.d.ts
│ ├── runner.js
│ ├── style.css
│ └── vite.config.js
├── extension/
│ └── vscode/
│ └── shadeup/
│ ├── .vscodeignore
│ ├── CHANGELOG.md
│ ├── README.md
│ ├── Shadeup-tmLanguage.json
│ ├── client/
│ │ ├── package.json
│ │ ├── src/
│ │ │ └── extension.ts
│ │ ├── testFixture/
│ │ │ ├── completion.txt
│ │ │ └── diagnostics.txt
│ │ └── tsconfig.json
│ ├── lang.ts
│ ├── language-configuration.json
│ ├── package.json
│ ├── server/
│ │ ├── compiler-dist/
│ │ │ ├── compiler.d.ts
│ │ │ ├── compiler.js
│ │ │ ├── readme.md
│ │ │ ├── shadeup-compiler.umd.cjs
│ │ │ └── tree-sitter-shadeup.wasm
│ │ ├── package.json
│ │ ├── src/
│ │ │ └── server.ts
│ │ └── tsconfig.json
│ ├── shadeup.tmlanguage.json
│ ├── syntaxes/
│ │ └── shadeup.tmLanguage.json
│ └── tsconfig.json
├── lang/
│ ├── README.md
│ ├── shadeup/
│ │ ├── alert.ts
│ │ ├── compiler/
│ │ │ ├── assets.json
│ │ │ ├── assets.ts
│ │ │ ├── common.ts
│ │ │ ├── generateDocs.ts
│ │ │ ├── generateTsCache.ts
│ │ │ ├── interface.ts
│ │ │ ├── simple.ts
│ │ │ └── worker.ts
│ │ ├── engine/
│ │ │ ├── adapters/
│ │ │ │ ├── adapter.ts
│ │ │ │ ├── webgl.ts
│ │ │ │ └── webgpu.ts
│ │ │ ├── amd.ts
│ │ │ ├── engine-headless.ts
│ │ │ ├── engine.ts
│ │ │ ├── frame-embed.html
│ │ │ ├── frame-headless.html
│ │ │ ├── frame-preview.html
│ │ │ ├── frame.html
│ │ │ ├── gltf.js
│ │ │ ├── input/
│ │ │ │ ├── input.ts
│ │ │ │ └── keyboardKeys.ts
│ │ │ ├── requirejs.js
│ │ │ ├── setZero.ts
│ │ │ ├── shader.ts
│ │ │ ├── ui/
│ │ │ │ ├── components/
│ │ │ │ │ ├── Button.svelte
│ │ │ │ │ ├── Checkbox.svelte
│ │ │ │ │ ├── Combo.svelte
│ │ │ │ │ ├── FloatingPanel.svelte
│ │ │ │ │ ├── Group.svelte
│ │ │ │ │ ├── Host.svelte
│ │ │ │ │ ├── Label.svelte
│ │ │ │ │ ├── Slider.svelte
│ │ │ │ │ ├── Text.svelte
│ │ │ │ │ └── host.scss
│ │ │ │ ├── puck.ts
│ │ │ │ └── ui.ts
│ │ │ ├── util.ts
│ │ │ └── virtual-webgl2.js
│ │ ├── environment.ts
│ │ ├── environmentWorker.ts
│ │ ├── frame.html
│ │ ├── library/
│ │ │ ├── buffer.ts
│ │ │ ├── color.ts
│ │ │ ├── common.shadeup
│ │ │ ├── drawAttributes.ts
│ │ │ ├── drawCount.ts
│ │ │ ├── drawIndexed.ts
│ │ │ ├── examples/
│ │ │ │ ├── deferred.shadeup
│ │ │ │ ├── shadow-map.shadeup
│ │ │ │ └── transparency.shadeup
│ │ │ ├── files.ts
│ │ │ ├── geo.shadeup
│ │ │ ├── mesh.shadeup
│ │ │ ├── mesh.ts
│ │ │ ├── native.ts
│ │ │ ├── paint.ts
│ │ │ ├── physics.ts
│ │ │ ├── sdf.shadeup
│ │ │ ├── std.ts
│ │ │ ├── test.shadeup
│ │ │ ├── texture.ts
│ │ │ ├── textures.shadeup
│ │ │ ├── types.ts
│ │ │ └── ui.ts
│ │ ├── monaco/
│ │ │ └── connector.ts
│ │ ├── runner.ts
│ │ ├── symbol.ts
│ │ ├── vite.config.js
│ │ └── worker.ts
│ ├── shadeup-frontend/
│ │ ├── .gitignore
│ │ ├── f.js
│ │ ├── f.ts
│ │ ├── index.html
│ │ ├── lib/
│ │ │ ├── ariadne-ts/
│ │ │ │ └── src/
│ │ │ │ ├── _extensions.ts
│ │ │ │ ├── browser.ts
│ │ │ │ ├── data/
│ │ │ │ │ ├── Display.ts
│ │ │ │ │ ├── Formatter.ts
│ │ │ │ │ ├── Iter.ts
│ │ │ │ │ ├── Option.ts
│ │ │ │ │ ├── Range.ts
│ │ │ │ │ ├── Result.ts
│ │ │ │ │ ├── Show.ts
│ │ │ │ │ ├── Span.ts
│ │ │ │ │ └── Write.ts
│ │ │ │ ├── index.ts
│ │ │ │ ├── lib/
│ │ │ │ │ ├── Characters.ts
│ │ │ │ │ ├── Color.ts
│ │ │ │ │ ├── ColorGenerator.ts
│ │ │ │ │ ├── Config.ts
│ │ │ │ │ ├── Label.ts
│ │ │ │ │ ├── LabelInfo.ts
│ │ │ │ │ ├── Report.ts
│ │ │ │ │ ├── ReportBuilder.ts
│ │ │ │ │ ├── ReportKind.ts
│ │ │ │ │ ├── Source.ts
│ │ │ │ │ ├── SourceGroup.ts
│ │ │ │ │ └── chalk/
│ │ │ │ │ └── chalk/
│ │ │ │ │ ├── license
│ │ │ │ │ ├── readme.md
│ │ │ │ │ └── source/
│ │ │ │ │ ├── index.d.ts
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── utilities.js
│ │ │ │ │ └── vendor/
│ │ │ │ │ ├── ansi-styles/
│ │ │ │ │ │ ├── index.d.ts
│ │ │ │ │ │ └── index.js
│ │ │ │ │ └── supports-color/
│ │ │ │ │ ├── browser.d.ts
│ │ │ │ │ ├── browser.js
│ │ │ │ │ ├── index.d.ts
│ │ │ │ │ └── index.js
│ │ │ │ ├── stringFormat.ts
│ │ │ │ ├── utils/
│ │ │ │ │ ├── binary_search_by_key.ts
│ │ │ │ │ ├── include_str.ts
│ │ │ │ │ └── index.ts
│ │ │ │ └── write.ts
│ │ │ ├── environment/
│ │ │ │ ├── Errors.ts
│ │ │ │ ├── ShadeupEnvironment.ts
│ │ │ │ ├── TypescriptEnvironment.ts
│ │ │ │ ├── quickCache.json
│ │ │ │ ├── tagGraph.ts
│ │ │ │ └── validate.ts
│ │ │ ├── fast-diff/
│ │ │ │ └── diff.js
│ │ │ ├── generator/
│ │ │ │ ├── eval.js
│ │ │ │ ├── glsl.ts
│ │ │ │ ├── header.glsl
│ │ │ │ ├── header.wgsl
│ │ │ │ ├── root.ts
│ │ │ │ ├── toposort.ts
│ │ │ │ ├── transform.ts
│ │ │ │ ├── tsWalk.ts
│ │ │ │ ├── util.ts
│ │ │ │ └── wgsl.ts
│ │ │ ├── main.ts
│ │ │ ├── parser/
│ │ │ │ ├── AstContext.ts
│ │ │ │ ├── index.ts
│ │ │ │ ├── node.cjs
│ │ │ │ ├── tree-sitter-javascript.wasm
│ │ │ │ ├── tree-sitter-shadeup.wasm
│ │ │ │ ├── tree-sitter.wasm
│ │ │ │ ├── wasm.ts
│ │ │ │ └── web-tree-sitter/
│ │ │ │ └── tree-sitter.js
│ │ │ └── std/
│ │ │ ├── all.ts
│ │ │ ├── generate-static-math.ts
│ │ │ ├── global.d.ts
│ │ │ ├── math.ts
│ │ │ ├── static-math-db.ts
│ │ │ └── static-math.ts
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── index.ts
│ │ │ ├── main.ts
│ │ │ └── vite-env.d.ts
│ │ ├── test.js
│ │ ├── test.ts
│ │ ├── tsconfig.json
│ │ ├── vfs.js
│ │ └── vite.config.ts
│ └── tree-sitter/
│ ├── .gitignore
│ ├── .prettierrc
│ ├── Cargo.toml
│ ├── binding.gyp
│ ├── bindings/
│ │ ├── node/
│ │ │ ├── binding.cc
│ │ │ └── index.js
│ │ └── rust/
│ │ ├── build.rs
│ │ └── lib.rs
│ ├── build/
│ │ ├── Release/
│ │ │ ├── obj/
│ │ │ │ └── tree_sitter_shadeup_binding/
│ │ │ │ ├── bindings/
│ │ │ │ │ └── node/
│ │ │ │ │ └── binding.obj
│ │ │ │ ├── src/
│ │ │ │ │ ├── parser.obj
│ │ │ │ │ └── scanner.obj
│ │ │ │ ├── tree_sit.A95203FA.tlog/
│ │ │ │ │ ├── CL.command.1.tlog
│ │ │ │ │ ├── CL.read.1.tlog
│ │ │ │ │ ├── CL.write.1.tlog
│ │ │ │ │ ├── link.command.1.tlog
│ │ │ │ │ ├── link.read.1.tlog
│ │ │ │ │ ├── link.write.1.tlog
│ │ │ │ │ ├── tree_sitter_shadeup_binding.lastbuildstate
│ │ │ │ │ └── tree_sitter_shadeup_binding.write.1u.tlog
│ │ │ │ ├── tree_sitter_shadeup_binding.node.recipe
│ │ │ │ └── win_delay_load_hook.obj
│ │ │ ├── tree_sitter_shadeup_binding.exp
│ │ │ ├── tree_sitter_shadeup_binding.iobj
│ │ │ ├── tree_sitter_shadeup_binding.ipdb
│ │ │ ├── tree_sitter_shadeup_binding.lib
│ │ │ ├── tree_sitter_shadeup_binding.node
│ │ │ └── tree_sitter_shadeup_binding.pdb
│ │ ├── binding.sln
│ │ ├── config.gypi
│ │ ├── tree_sitter_shadeup_binding.vcxproj
│ │ └── tree_sitter_shadeup_binding.vcxproj.filters
│ ├── grammar.js
│ ├── grammer-fixed.js
│ ├── javascript.js
│ ├── package.json
│ ├── parser.exp
│ ├── parser.lib
│ ├── parser.obj
│ ├── readme.md
│ ├── scanner.obj
│ ├── shadeup-javascript.js
│ ├── src/
│ │ ├── grammar.json
│ │ ├── node-types.json
│ │ ├── parser.c
│ │ ├── scanner.c
│ │ └── tree_sitter/
│ │ └── parser.h
│ ├── test.shadeup
│ ├── tree-sitter-javascript.wasm
│ └── typescript.js
├── package/
│ ├── __lib.d.ts
│ ├── __lib.js
│ ├── __lib.shadeup
│ ├── engine-dist/
│ │ ├── DRACOLoader-4fcd2f44.js
│ │ ├── GLTFLoader-94b38cf6.js
│ │ ├── host-937690bb.js
│ │ ├── host-f3c963cd.js
│ │ ├── host-fa5c0296.js
│ │ ├── shadeup-engine.js
│ │ ├── style.css
│ │ ├── three.module-c8091b37.js
│ │ ├── ui-37189365.js
│ │ └── ui-f4b4a003.js
│ ├── engine.js
│ ├── index.js
│ ├── library.js
│ ├── main.d.ts
│ ├── math.d.ts
│ ├── package.json
│ └── util/
│ └── concat.js
├── package.json
└── unreal-engine/
├── .editorconfig
├── .gitattributes
├── .gitignore
├── .prettierignore
├── README.md
├── archive.js
├── archives/
│ └── CustomProxy_Plugin/
│ ├── ShadeupExamplePlugin.uplugin
│ ├── ShadeupExamplePlugin.uplugin.back
│ └── Source/
│ ├── CustomProxy/
│ │ ├── CustomProxy.Build.cs
│ │ ├── Private/
│ │ │ └── CustomProxy.cpp
│ │ └── Public/
│ │ └── CustomProxy.h
│ └── ShadeupTestPlugin/
│ ├── Private/
│ │ └── ShadeupExamplePlugin.cpp
│ ├── Public/
│ │ └── ShadeupExamplePlugin.h
│ └── ShadeupExamplePlugin.Build.cs
├── build/
│ └── grammar.js
├── cli.js
├── examples/
│ ├── pixel.shadeup
│ └── version2.shadeup
├── extension/
│ └── shadeup/
│ ├── .vscode/
│ │ └── launch.json
│ ├── .vscodeignore
│ ├── CHANGELOG.md
│ ├── README.md
│ ├── language-configuration.json
│ ├── package.json
│ ├── syntaxes/
│ │ └── shadeup.tmLanguage.json
│ └── vsc-extension-quickstart.md
├── index.js
├── p.shadeup
├── package.json
├── src/
│ ├── file.js
│ ├── grammar.ne
│ ├── parse.js
│ ├── plugin_template/
│ │ ├── ShadeupExamplePlugin.uplugin
│ │ └── Source/
│ │ └── ShadeupTestPlugin/
│ │ ├── Private/
│ │ │ └── ShadeupExamplePlugin.cpp
│ │ ├── Public/
│ │ │ └── ShadeupExamplePlugin.h
│ │ └── ShadeupExamplePlugin.Build.cs
│ ├── string.ne
│ ├── template/
│ │ ├── ModulePrivate.cpp
│ │ ├── ModulePublic.h
│ │ ├── Plugin/
│ │ │ ├── MyPlugin.uplugin
│ │ │ ├── Shaders/
│ │ │ │ ├── Compute/
│ │ │ │ │ └── Private/
│ │ │ │ │ └── Template.usf
│ │ │ │ └── Factory/
│ │ │ │ └── Private/
│ │ │ │ └── Template.ush
│ │ │ └── Source/
│ │ │ └── Module/
│ │ │ ├── Private/
│ │ │ │ ├── ActorTemplate.cpp
│ │ │ │ ├── ComputeTemplate.cpp
│ │ │ │ ├── ComputeTemplate.h
│ │ │ │ ├── FactoryTemplate.cpp
│ │ │ │ ├── FactoryTemplate.h
│ │ │ │ ├── ModuleTemplate.cpp
│ │ │ │ ├── ProxyTemplate.cpp
│ │ │ │ └── ProxyTemplate.h
│ │ │ ├── Public/
│ │ │ │ ├── ActorTemplate.h
│ │ │ │ └── ModuleTemplate.h
│ │ │ └── Template.Build.cs
│ │ ├── Template.Build.cs
│ │ ├── compute.cpp
│ │ └── lib/
│ │ ├── ShadeupLib.cpp
│ │ ├── ShadeupLib.h
│ │ └── readme.md
│ ├── templates/
│ │ ├── compute/
│ │ │ └── simple-compute-shader/
│ │ │ └── Plugin/
│ │ │ ├── Shaders/
│ │ │ │ └── [MODULE]/
│ │ │ │ └── Private/
│ │ │ │ └── [NAME]/
│ │ │ │ ├── $base[NAME].usf
│ │ │ │ ├── $basemat[NAME].usf
│ │ │ │ ├── $mat[NAME].usf
│ │ │ │ ├── $pi[NAME].usf
│ │ │ │ └── $rt[NAME].usf
│ │ │ └── Source/
│ │ │ └── [MODULE]/
│ │ │ ├── Private/
│ │ │ │ └── [NAME]/
│ │ │ │ ├── [NAME].cpp
│ │ │ │ └── [NAME].h
│ │ │ └── Public/
│ │ │ └── [NAME]/
│ │ │ ├── $base[NAME]_readme.md
│ │ │ ├── $basemat[NAME]_readme.md
│ │ │ ├── $mat[NAME]_readme.md
│ │ │ ├── $pi[NAME]_readme.md
│ │ │ ├── $rt[NAME]_readme.md
│ │ │ └── [NAME].h
│ │ ├── instancing/
│ │ │ ├── compute-indirect-drawing/
│ │ │ │ └── Plugin/
│ │ │ │ ├── Shaders/
│ │ │ │ │ └── [MODULE]/
│ │ │ │ │ └── Private/
│ │ │ │ │ └── [NAME]/
│ │ │ │ │ ├── [NAME].ush
│ │ │ │ │ ├── [NAME]Compute.usf
│ │ │ │ │ └── [NAME]VertexFactory.ush
│ │ │ │ └── Source/
│ │ │ │ └── [MODULE]/
│ │ │ │ ├── Private/
│ │ │ │ │ └── [NAME]/
│ │ │ │ │ ├── [NAME]Actor.cpp
│ │ │ │ │ ├── [NAME]Component.cpp
│ │ │ │ │ ├── [NAME]SceneProxy.cpp
│ │ │ │ │ ├── [NAME]SceneProxy.h
│ │ │ │ │ ├── [NAME]VertexFactory.cpp
│ │ │ │ │ └── [NAME]VertexFactory.h
│ │ │ │ └── Public/
│ │ │ │ └── [NAME]/
│ │ │ │ ├── $base[NAME]_readme.md
│ │ │ │ ├── [NAME]Actor.h
│ │ │ │ └── [NAME]Component.h
│ │ │ └── compute-instanced-static-mesh-component/
│ │ │ └── Plugin/
│ │ │ ├── Shaders/
│ │ │ │ └── [MODULE]/
│ │ │ │ └── Private/
│ │ │ │ └── [NAME]/
│ │ │ │ ├── [NAME].ush
│ │ │ │ ├── [NAME]Compute.usf
│ │ │ │ └── [NAME]VertexFactory.ush
│ │ │ └── Source/
│ │ │ └── [MODULE]/
│ │ │ ├── Private/
│ │ │ │ └── [NAME]/
│ │ │ │ ├── [NAME]Actor.cpp
│ │ │ │ ├── [NAME]Component.cpp
│ │ │ │ ├── [NAME]SceneProxy.cpp
│ │ │ │ ├── [NAME]SceneProxy.h
│ │ │ │ ├── [NAME]VertexFactory.cpp
│ │ │ │ └── [NAME]VertexFactory.h
│ │ │ └── Public/
│ │ │ └── [NAME]/
│ │ │ ├── $inst[NAME]_readme.md
│ │ │ ├── [NAME]Actor.h
│ │ │ └── [NAME]Component.h
│ │ └── nodes/
│ │ ├── dynamic/
│ │ │ └── Plugin/
│ │ │ └── Source/
│ │ │ └── [MODULE]/
│ │ │ ├── Private/
│ │ │ │ └── [NAME]MaterialExpression.cpp
│ │ │ └── Public/
│ │ │ ├── [NAME]MaterialExpression.h
│ │ │ └── [NAME]_readme.md
│ │ ├── fn/
│ │ │ └── Plugin/
│ │ │ └── Source/
│ │ │ └── [MODULE]/
│ │ │ ├── Private/
│ │ │ │ └── [NAME]MaterialExpression.cpp
│ │ │ └── Public/
│ │ │ └── [NAME]MaterialExpression.h
│ │ ├── input/
│ │ │ └── Plugin/
│ │ │ └── Source/
│ │ │ └── [MODULE]/
│ │ │ ├── Private/
│ │ │ │ └── [NAME]MaterialExpression.cpp
│ │ │ └── Public/
│ │ │ └── [NAME]MaterialExpression.h
│ │ └── output/
│ │ └── Plugin/
│ │ └── Source/
│ │ └── [MODULE]/
│ │ ├── Private/
│ │ │ └── [NAME]MaterialExpression.cpp
│ │ └── Public/
│ │ └── [NAME]MaterialExpression.h
│ ├── types/
│ │ ├── actor.js
│ │ ├── base.js
│ │ ├── compute.js
│ │ ├── factory.js
│ │ ├── shader.js
│ │ ├── template.js
│ │ └── value.js
│ ├── util.js
│ └── whitespace.ne
├── test.hlsl
├── test.js
└── test.shadeup
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto
================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
node_modules
================================================
FILE: .vscode/launch.json
================================================
// A launch configuration that launches the extension inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}/extension/vscode/shadeup",
"${workspaceFolder}/cli/test/vite-project/src/"
]
}
]
}
================================================
FILE: README.md
================================================

## Write **WebGPU** shaders without the boilerplate
Repository for the Shadeup ecosystem and tooling [Shadeup.dev](https://shadeup.dev/)
This currently includes:
- [Shadeup Language](./lang) - partial codebase
- [Shadeup Compiler Tools](./cli) `npm i -g @shadeup/cli`
- [Shadeup Engine Package](./package) `npm i shadeup`
- [Shadeup - Unreal Engine](./unreal-engine) `npm i -g @shadeup/unreal`
- [Shadeup VS Code extension](./extension/vscode) - [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Shadeup.shadeup-vscode)
---
================================================
FILE: cli/README.md
================================================

# Shadeup compiler tools
## Installation
```sh
npm install -g @shadeup/cli
```
## Usage
```sh
shadeup --help
```
```sh
CLI tool for compiling shadeup files
Options:
-V, --version output the version number
-v
-h, --help display help for command
Commands:
build [options] Build file
watch Watch a shadeup file and recompile on change
preview Live preview of a shadeup file in electron
```
## Example
```ts
// main.shadeup
fn main() {
draw(shader {
out.color = (in.uv, 0.5, 1.0);
});
}
```
```sh
$ shadeup build main.shadeup
```
After running the above command, you should find the following files in the same directory as `main.shadeup`:
- `main.js`
- `main.d.ts`
You can use the above files inside of a vite or webpack project to use the shader in your web application.
```sh
$ npm i shadeup
```
```js
// example.ts
import { makeShadeupInstance } from "./main";
const canvas = document.querySelector("#canvas")!;
(async () => {
const engine = await makeShadeupInstance(canvas);
// Optionally enable the UI
await engine.enableUI();
// The frame loop will start automatically
// You can call pub functions on the engine instance
// engine.files.main.exampleFunction();
})();
```
## Preview mode
```sh
$ shadeup preview main.shadeup
```
This will open an electron window with the shader preview. You can use this to quickly test your shader without having to set up a web project.

================================================
FILE: cli/cli.js
================================================
#!/usr/bin/env node
import colors from "colors";
import path from "path";
import fs from "fs";
import os from "os";
import inquirer from "inquirer";
import { program } from "commander";
import * as url from "url";
import {
makeCompiler,
makeIncrementalCompiler,
} from "./compiler-dist/compiler.js";
if (typeof __dirname == "undefined") {
global["__filename"] = url.fileURLToPath(import.meta.url);
global["__dirname"] = url.fileURLToPath(new URL(".", import.meta.url));
}
function findCommonPath(paths) {
// Find the common path without the filename or extension
if (paths.length == 0) return "";
if (paths.length == 1) return path.dirname(paths[0]) + "/";
paths = paths.map((p) => p).sort((a, b) => b.length - a.length);
let longest = paths[0];
for (let i = 0; i < longest.length; i++) {
let char = longest[i];
for (let path of paths) {
if (path[i] != char) {
return longest.slice(0, i);
}
}
}
}
function scanImports(baseFile) {
let imports = new Set();
imports.add(baseFile);
let data = fs.readFileSync(baseFile, "utf8");
let lines = data.split("\n");
for (let line of lines) {
let match = line.match(/import[^"]+"([^"]*)"/);
if (match) {
let importPath = match[1];
if (!importPath.endsWith(".shadeup")) {
importPath += ".shadeup";
}
if (importPath.startsWith("/")) {
continue;
}
let importFile = path.resolve(path.dirname(baseFile), importPath);
if (!imports.has(importFile)) {
imports.add(importFile);
scanImports(importFile).forEach((i) => imports.add(i));
}
}
}
return imports;
}
program
.name("shadeup")
.description("CLI tool for compiling shadeup files")
.version("1.3.0")
.option("-v")
.action(async (opts) => {
console.log("Shadeup v1.3.0".magenta);
if (opts.v) {
return;
}
try {
} catch (e) {
console.error(e);
}
});
function normalizePath(p) {
return p.replace(/\\/g, "/");
}
function printErrors(errors, common) {
for (let error of errors) {
let path = (common + error.file)
.replace(".ts", ".shadeup")
.replace(/^\/([A-Z]:)/g, "$1")
.replace(/\/\//g, "/");
console.error(
path + "\n\x1b[31m" + error.message.replace(error.file, path) + "\x1b[0m"
);
}
}
const buildFiles = async (files, options) => {
let compile = await makeCompiler();
let outputs = [];
let common = normalizePath(findCommonPath(files));
outputs.push(
compile({
files: files.map((f) => {
f = normalizePath(f).replace(common, "");
let data = fs.readFileSync(f, "utf8");
let filename = f.replace(".shadeup", "");
return { name: filename, body: data };
}),
})
);
let orig = console.log;
console.log = () => {};
let outs = await Promise.all(outputs);
console.log = orig;
for (let i = 0; i < outs.length; i++) {
let out = outs[i];
if (out.errors) {
printErrors(out.errors, common);
continue;
}
let file = files[i];
let outPath = options.output || file.replace(".shadeup", ".js");
console.log(`Writing ${outPath}`);
fs.writeFileSync(outPath, out.output);
if (out.dts) {
let dtsPath = file.replace(".shadeup", ".d.ts");
if (options.output) {
dtsPath = options.output.replace(".js", ".d.ts");
}
console.log(`Writing ${dtsPath}`);
fs.writeFileSync(dtsPath, out.dts);
}
}
};
program
.command("build")
.description("Build file")
.option("-o, --output ", "Output path", "")
.argument("file", "File to build")
.action(async (file, options) => {
file = path.resolve(file);
if (!fs.existsSync(file)) {
console.error(`File ${file} does not exist`);
return;
}
let fileSet = scanImports(file);
let files = [...fileSet.values()];
if (!options.output) {
delete options.output;
}
await buildFiles(files, {
output: file.replace(".shadeup", ".js"),
...options,
});
});
const debounce = (fn, time) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn(...args);
}, time);
};
};
const setupWatcher = async (file, options, outdir = "") => {
file = path.resolve(file);
let comp = await makeIncrementalCompiler();
let rebuild = debounce(async () => {
let fileSet = scanImports(file);
let files = [...fileSet.values()];
let common = normalizePath(findCommonPath(files));
let start = performance.now();
let orig = console.log;
// console.log = () => {};
let outs = await comp({
files: files.map((f) => {
f = normalizePath(f).replace(common, "");
let data = fs.readFileSync(f, "utf8");
let filename = f.replace(".shadeup", "");
return { name: filename, body: data };
}),
});
console.log = orig;
(async () => {
// let errs = await outs.errors;
// printErrors(errs, common);
})();
let outPath = options.output || file.replace(".shadeup", ".js");
if (outdir) {
outPath = path.join(outdir, path.basename(outPath));
}
console.log(
`\x1b[32mCompiled in ${Math.round(
performance.now() - start
)}ms\x1b[0m: writing out to ${outPath}`
);
fs.writeFileSync(outPath, outs.output);
fs.writeFileSync(outPath.replace(/\.js$/, ".d.ts"), outs.dts);
}, 100);
rebuild();
let handlers = new Map();
const buildHandlers = () => {
let fileSet = scanImports(file);
let files = Array.from(fileSet);
let unwatch = new Set(handlers.keys());
for (let file of files) {
unwatch.delete(file);
if (!fs.existsSync(file)) {
console.error(`File ${file} does not exist`);
continue;
}
if (handlers.has(file)) {
continue;
}
let handler = () => {
rebuild();
buildHandlers();
};
let watcher = fs.watch(file, handler);
watcher.on("change", handler);
watcher.on("error", (e) => {
console.error(e);
});
handlers.set(file, watcher);
}
for (let file of unwatch) {
handlers.get(file).close();
handlers.delete(file);
}
};
buildHandlers();
};
program
.command("watch")
.description("Watch a shadeup file and recompile on change")
.argument("file", "Main file to watch")
.action(async (file, options) => {
setupWatcher(file, options);
});
program
.command("preview")
.description("Live preview of a shadeup file in electron")
.argument("file", "Main file to preview")
.action(async (file, options) => {
const electron = await import("electron");
const proc = await import("node:child_process");
// shadeup home dir for vite
const shadeupHome = path.join(os.homedir(), ".shadeup_vite");
// Copy entire vite directory to shadeup home dir
if (!fs.existsSync(shadeupHome)) {
fs.mkdirSync(shadeupHome);
}
const viteDir = path.join(__dirname, "vite");
fs.cpSync(viteDir, shadeupHome, { recursive: true });
// run npm install on the vite directory if node_modules doesn't exist
if (!fs.existsSync(path.join(shadeupHome, "/node_modules"))) {
console.log(shadeupHome);
console.log("Installing dependencies...");
proc.execSync("npm install", {
cwd: shadeupHome,
stdio: "inherit",
});
}
fs.writeFileSync(
path.join(__dirname, "vite/runner.js"),
`export const makeShadeupInstance = async (canvas) => {
return {
enableUI: async () => {},
};
};
`
);
const child = proc.spawn(electron.default, [
path.join(__dirname, "electron/main.js"),
]);
child.stdout.on("data", (data) => {
console.log(data.toString());
});
child.stderr.on("data", (data) => {
console.error(data.toString());
});
setupWatcher(
file,
{
output: path.join(shadeupHome, "runner.js"),
},
shadeupHome
);
const vite = await import("vite");
const server = await vite.createServer({
root: shadeupHome,
server: {
port: 5128,
},
});
child.on("close", (code) => {
console.log(`child process exited with code ${code}`);
server.close();
process.exit();
});
await server.listen();
});
program.parse();
================================================
FILE: cli/compiler-dist/compiler.d.ts
================================================
export function makeLSPCompiler(): Promise;
================================================
FILE: cli/compiler-dist/compiler.js
================================================
import { makeSimpleShadeupEnvironment } from "./shadeup-compiler.js";
import Parser from "web-tree-sitter";
import minify from "uglify-js";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(new URL(import.meta.url));
function filterDTS(files) {
return `import * as __ from "shadeup/math";
declare namespace ShadeupFiles {
${[...files.entries()]
.map(
([name, dts]) =>
` declare namespace ${name} {\n${dts
.split("\n")
.map((s) => ` ${s}`)
.join("\n")
.trimEnd()}\n }`
)
.join("\n")}
}
export declare function makeShadeupInstance(
canvas: HTMLCanvasElement,
options?: {
preferredAdapter?: "webgl" | "webgpu";
limits?: GPUSupportedLimits;
ui?: boolean;
}
): Promise<{
/**
* Set to false to pause
*/
playing: boolean;
canvas: HTMLCanvasElement;
adapter: any;
hooks: {
beforeFrame?: () => void;
afterFrame?: () => void;
reset?: () => void;
}[];
start: () => void;
env: {
camera: {
position: __.float3;
rotation: __.float4;
width: __.float;
height: __.float;
fov: __.float;
near: __.float;
far: __.float;
};
camera2d: {
position: __.float2;
zoom: __.float;
};
deltaTime: __.float;
frame: __.int;
keyboard: any;
mouse: any;
screenSize: __.float2;
time: __.float;
};
/**
* Used to pass values into the shadeup env (accessed as env.input("name") inside)
*/
inputValues: Map;
enableUI: () => Promise;
loadTextureFromImageLike: (
img: HTMLImageElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | HTMLVideoElement
) => Promise<__.texture2d<__.float4>>;
loadTexture2dFromURL: (url: string) => Promise<__.texture2d<__.float4>>;
loadModelFromURL: (urlGltf: string) => Promise<__.texture2d<__.float4>>;
files: typeof ShadeupFiles;
}>;
`;
}
const prefixConst = (files) => {
let str = `import { bindShadeupEngine } from "shadeup";
export const makeShadeupInstance = bindShadeupEngine((define, localEngineContext) => {
const __shadeup_gen_shader =
localEngineContext.__shadeup_gen_shader.bind(localEngineContext);
const __shadeup_make_shader_inst =
localEngineContext.__shadeup_make_shader_inst.bind(localEngineContext);
const __shadeup_register_struct =
localEngineContext.__shadeup_register_struct.bind(localEngineContext);
const env = localEngineContext.env;\n`;
str += `((defineFunc) => {
let define = (deps, func) => defineFunc("/__meta.js", deps, func);
define(["require", "exports"], function (require, exports, __, std___std_all_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.files = [${files.map((f) => JSON.stringify(f)).join(",")}];
});
})(define);`;
return str;
};
export async function makeCompiler() {
await Parser.init();
const parser = new Parser();
const Lang = await Parser.Language.load(
path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm")
);
parser.setLanguage(Lang);
global.shadeupParser = () => {
return parser;
};
let envPool = [];
for (let i = 0; i < 1; i++) {
envPool.push(await makeSimpleShadeupEnvironment(true, true));
}
let queue = [];
async function consumeQueue() {
if (queue.length == 0) return;
if (envPool.length == 0) return;
let env = envPool.shift();
let item = queue.shift();
if (!item) return;
try {
let start = performance.now();
env.reset();
for (let i = 0; i < item.files.length; i++) {
const file = item.files[i];
if (i == item.files.length - 1) {
await env.writeFile("/" + file.name + ".ts", file.body);
} else {
env.writeFile("/" + file.name + ".ts", file.body);
}
}
// for (let file of item.files) {
// if (file.name == "main")
// await env.writeFile("/" + file.name + ".ts", file.body);
// }
let output = await env.regenerate();
let finalOutput = "";
let dts = "";
let fileDts = new Map();
let errors = await env.errors();
if (errors.length > 0) {
item.callback({
errors: errors,
});
envPool.push(env);
consumeQueue();
return;
}
for (let o of output) {
if (
!item.files.find(
(f) =>
f.name ==
o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", "")
) &&
!(item.files.length >= 1 && item.files[0].name == "__lib")
)
continue;
if (o.path.endsWith(".d.ts")) {
fileDts.set(
o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", ""),
o.contents
.split("\n")
.filter((l) => !l.startsWith("import"))
.join("\n")
);
} else {
if (item.files.length >= 1 && item.files[0].name == "__lib") {
finalOutput += `
((defineFunc) => {
let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func);
${o.contents}
})(define);
`;
} else {
finalOutput += `
((defineFunc) => {
let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func);
${o.contents}
})(define);
`;
}
}
}
let final =
prefixConst(item.files.map((f) => f.name)) + finalOutput + `\n});`;
if (item.files.length >= 1 && item.files[0].name == "__lib") {
final = finalOutput;
}
let doMinify = false;
if (doMinify) {
final = minify.minify(final);
// console.log(final);
}
console.log("Generated in " + (performance.now() - start) + "ms");
item.callback({
output: final,
dts: filterDTS(fileDts),
});
envPool.push(env);
consumeQueue();
} catch (e) {
console.error(e);
envPool.push(await makeSimpleShadeupEnvironment(true, true));
item.callback({
error: "Fatal error while compiling.",
});
consumeQueue();
}
}
return async function compile(data) {
return new Promise((resolve, reject) => {
queue.push({ ...data, files: data.files, callback: resolve });
consumeQueue();
});
};
}
export async function makeIncrementalCompiler() {
await Parser.init();
const parser = new Parser();
const Lang = await Parser.Language.load(
path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm")
);
parser.setLanguage(Lang);
global.shadeupParser = () => {
return parser;
};
const env = await makeSimpleShadeupEnvironment(true, true);
const fileCache = new Map();
const fileEmitCache = new Map();
return async function compile(item) {
try {
let start = performance.now();
let itemsToRegen = [];
let dirtyFiles = new Set();
for (let i = 0; i < item.files.length; i++) {
const file = item.files[i];
let fileKey = "/" + file.name + ".ts";
let didChange = false;
if (fileCache.has(fileKey)) {
if (fileCache.get(fileKey) != file.body) {
didChange = true;
}
} else {
didChange = true;
}
if (didChange) {
itemsToRegen.push(fileKey);
fileCache.set(fileKey, file.body);
dirtyFiles.add(fileKey);
}
}
let dirtyFilesArray = Array.from(dirtyFiles);
for (let i = 0; i < dirtyFilesArray.length; i++) {
const fileKey = dirtyFilesArray[i];
const file = item.files.find((f) => "/" + f.name + ".ts" == fileKey);
if (i == dirtyFilesArray.length - 1) {
await env.writeFile(fileKey, file.body, true);
} else {
env.writeFile(fileKey, file.body, true);
}
}
let output = await env.regenerate(itemsToRegen);
console.log("Regen took " + (performance.now() - start) + "ms");
let finalOutput = "";
let dts = "";
const fileDts = new Map();
for (let o of output) {
if (
!item.files.find(
(f) =>
f.name ==
o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", "")
) &&
!(item.files.length >= 1 && item.files[0].name == "__lib")
)
continue;
if (o.path.endsWith(".d.ts")) {
// dts += o.contents;
fileDts.set(
o.path.replace(/^\//g, "").replace(".js", "").replace(".d.ts", ""),
o.contents
.split("\n")
.filter((l) => !l.startsWith("import"))
.join("\n")
);
} else {
if (item.files.length >= 1 && item.files[0].name == "__lib") {
finalOutput += `
((defineFunc) => {
let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func);
${o.contents}
})(define);
`;
return finalOutput;
} else {
fileEmitCache.set(
o.path,
`
((defineFunc) => {
let define = (deps, func) => defineFunc(${JSON.stringify(o.path)}, deps, func);
${o.contents}
})(define);
`
);
}
}
}
for (let file of item.files) {
let fileKey = "/" + file.name + ".js";
if (fileEmitCache.has(fileKey)) {
finalOutput += fileEmitCache.get(fileKey);
}
}
let final =
prefixConst(item.files.map((f) => f.name)) + finalOutput + `\n});`;
console.log("Generated in " + (performance.now() - start) + "ms");
return {
output: final,
dts: filterDTS(fileDts),
// errors: env.errors(),
};
} catch (e) {
console.error(e);
}
};
}
export async function makeLSPCompiler() {
await Parser.init();
const parser = new Parser();
const Lang = await Parser.Language.load(
path.resolve(path.dirname(__filename), "tree-sitter-shadeup.wasm")
);
parser.setLanguage(Lang);
global.shadeupParser = () => {
return parser;
};
const env = await makeSimpleShadeupEnvironment(true, true);
return env;
}
================================================
FILE: cli/compiler-dist/readme.md
================================================
modify the output of shadeup-compiler.js to:
1. remove the tree sitter wasm strings
2. Replace getShadeupParse with:
async function getShadeupParser() {
return global.shadeupParser();
}
3. import fs and replace e4.readFileSync e4 trace up to \_\_viteexternal with fs
================================================
FILE: cli/compiler-dist/shadeup-compiler.js
================================================
import ts from "typescript";
import require$$0$1 from "path";
import require$$1 from "fs";
import { createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment } from "@typescript/vfs";
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function getAugmentedNamespace(n) {
if (n.__esModule)
return n;
var f = n.default;
if (typeof f == "function") {
var a = function a2() {
if (this instanceof a2) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else
a = {};
Object.defineProperty(a, "__esModule", { value: true });
Object.keys(n).forEach(function(k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function() {
return n[k];
}
});
});
return a;
}
var sha256$1 = { exports: {} };
(function(module) {
(function(root, factory2) {
var exports = {};
factory2(exports);
var sha2562 = exports["default"];
for (var k in exports) {
sha2562[k] = exports[k];
}
{
module.exports = sha2562;
}
})(commonjsGlobal, function(exports) {
exports.__esModule = true;
exports.digestLength = 32;
exports.blockSize = 64;
var K = new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
function hashBlocks(w, v, p, pos, len) {
var a, b, c2, d, e, f, g2, h, u, i, j, t1, t2;
while (len >= 64) {
a = v[0];
b = v[1];
c2 = v[2];
d = v[3];
e = v[4];
f = v[5];
g2 = v[6];
h = v[7];
for (i = 0; i < 16; i++) {
j = pos + i * 4;
w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255;
}
for (i = 16; i < 64; i++) {
u = w[i - 2];
t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
u = w[i - 15];
t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
}
for (i = 0; i < 64; i++) {
t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g2) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c2 ^ b & c2) | 0;
h = g2;
g2 = f;
f = e;
e = d + t1 | 0;
d = c2;
c2 = b;
b = a;
a = t1 + t2 | 0;
}
v[0] += a;
v[1] += b;
v[2] += c2;
v[3] += d;
v[4] += e;
v[5] += f;
v[6] += g2;
v[7] += h;
pos += 64;
len -= 64;
}
return pos;
}
var Hash = (
/** @class */
function() {
function Hash2() {
this.digestLength = exports.digestLength;
this.blockSize = exports.blockSize;
this.state = new Int32Array(8);
this.temp = new Int32Array(64);
this.buffer = new Uint8Array(128);
this.bufferLength = 0;
this.bytesHashed = 0;
this.finished = false;
this.reset();
}
Hash2.prototype.reset = function() {
this.state[0] = 1779033703;
this.state[1] = 3144134277;
this.state[2] = 1013904242;
this.state[3] = 2773480762;
this.state[4] = 1359893119;
this.state[5] = 2600822924;
this.state[6] = 528734635;
this.state[7] = 1541459225;
this.bufferLength = 0;
this.bytesHashed = 0;
this.finished = false;
return this;
};
Hash2.prototype.clean = function() {
for (var i = 0; i < this.buffer.length; i++) {
this.buffer[i] = 0;
}
for (var i = 0; i < this.temp.length; i++) {
this.temp[i] = 0;
}
this.reset();
};
Hash2.prototype.update = function(data, dataLength) {
if (dataLength === void 0) {
dataLength = data.length;
}
if (this.finished) {
throw new Error("SHA256: can't update because hash was finished.");
}
var dataPos = 0;
this.bytesHashed += dataLength;
if (this.bufferLength > 0) {
while (this.bufferLength < 64 && dataLength > 0) {
this.buffer[this.bufferLength++] = data[dataPos++];
dataLength--;
}
if (this.bufferLength === 64) {
hashBlocks(this.temp, this.state, this.buffer, 0, 64);
this.bufferLength = 0;
}
}
if (dataLength >= 64) {
dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
dataLength %= 64;
}
while (dataLength > 0) {
this.buffer[this.bufferLength++] = data[dataPos++];
dataLength--;
}
return this;
};
Hash2.prototype.finish = function(out) {
if (!this.finished) {
var bytesHashed = this.bytesHashed;
var left = this.bufferLength;
var bitLenHi = bytesHashed / 536870912 | 0;
var bitLenLo = bytesHashed << 3;
var padLength = bytesHashed % 64 < 56 ? 64 : 128;
this.buffer[left] = 128;
for (var i = left + 1; i < padLength - 8; i++) {
this.buffer[i] = 0;
}
this.buffer[padLength - 8] = bitLenHi >>> 24 & 255;
this.buffer[padLength - 7] = bitLenHi >>> 16 & 255;
this.buffer[padLength - 6] = bitLenHi >>> 8 & 255;
this.buffer[padLength - 5] = bitLenHi >>> 0 & 255;
this.buffer[padLength - 4] = bitLenLo >>> 24 & 255;
this.buffer[padLength - 3] = bitLenLo >>> 16 & 255;
this.buffer[padLength - 2] = bitLenLo >>> 8 & 255;
this.buffer[padLength - 1] = bitLenLo >>> 0 & 255;
hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
this.finished = true;
}
for (var i = 0; i < 8; i++) {
out[i * 4 + 0] = this.state[i] >>> 24 & 255;
out[i * 4 + 1] = this.state[i] >>> 16 & 255;
out[i * 4 + 2] = this.state[i] >>> 8 & 255;
out[i * 4 + 3] = this.state[i] >>> 0 & 255;
}
return this;
};
Hash2.prototype.digest = function() {
var out = new Uint8Array(this.digestLength);
this.finish(out);
return out;
};
Hash2.prototype._saveState = function(out) {
for (var i = 0; i < this.state.length; i++) {
out[i] = this.state[i];
}
};
Hash2.prototype._restoreState = function(from, bytesHashed) {
for (var i = 0; i < this.state.length; i++) {
this.state[i] = from[i];
}
this.bytesHashed = bytesHashed;
this.finished = false;
this.bufferLength = 0;
};
return Hash2;
}()
);
exports.Hash = Hash;
var HMAC = (
/** @class */
function() {
function HMAC2(key) {
this.inner = new Hash();
this.outer = new Hash();
this.blockSize = this.inner.blockSize;
this.digestLength = this.inner.digestLength;
var pad = new Uint8Array(this.blockSize);
if (key.length > this.blockSize) {
new Hash().update(key).finish(pad).clean();
} else {
for (var i = 0; i < key.length; i++) {
pad[i] = key[i];
}
}
for (var i = 0; i < pad.length; i++) {
pad[i] ^= 54;
}
this.inner.update(pad);
for (var i = 0; i < pad.length; i++) {
pad[i] ^= 54 ^ 92;
}
this.outer.update(pad);
this.istate = new Uint32Array(8);
this.ostate = new Uint32Array(8);
this.inner._saveState(this.istate);
this.outer._saveState(this.ostate);
for (var i = 0; i < pad.length; i++) {
pad[i] = 0;
}
}
HMAC2.prototype.reset = function() {
this.inner._restoreState(this.istate, this.inner.blockSize);
this.outer._restoreState(this.ostate, this.outer.blockSize);
return this;
};
HMAC2.prototype.clean = function() {
for (var i = 0; i < this.istate.length; i++) {
this.ostate[i] = this.istate[i] = 0;
}
this.inner.clean();
this.outer.clean();
};
HMAC2.prototype.update = function(data) {
this.inner.update(data);
return this;
};
HMAC2.prototype.finish = function(out) {
if (this.outer.finished) {
this.outer.finish(out);
} else {
this.inner.finish(out);
this.outer.update(out, this.digestLength).finish(out);
}
return this;
};
HMAC2.prototype.digest = function() {
var out = new Uint8Array(this.digestLength);
this.finish(out);
return out;
};
return HMAC2;
}()
);
exports.HMAC = HMAC;
function hash(data) {
var h = new Hash().update(data);
var digest = h.digest();
h.clean();
return digest;
}
exports.hash = hash;
exports["default"] = hash;
function hmac(key, data) {
var h = new HMAC(key).update(data);
var digest = h.digest();
h.clean();
return digest;
}
exports.hmac = hmac;
function fillBuffer(buffer2, hmac2, info, counter) {
var num = counter[0];
if (num === 0) {
throw new Error("hkdf: cannot expand more");
}
hmac2.reset();
if (num > 1) {
hmac2.update(buffer2);
}
if (info) {
hmac2.update(info);
}
hmac2.update(counter);
hmac2.finish(buffer2);
counter[0]++;
}
var hkdfSalt = new Uint8Array(exports.digestLength);
function hkdf(key, salt, info, length) {
if (salt === void 0) {
salt = hkdfSalt;
}
if (length === void 0) {
length = 32;
}
var counter = new Uint8Array([1]);
var okm = hmac(salt, key);
var hmac_ = new HMAC(okm);
var buffer2 = new Uint8Array(hmac_.digestLength);
var bufpos = buffer2.length;
var out = new Uint8Array(length);
for (var i = 0; i < length; i++) {
if (bufpos === buffer2.length) {
fillBuffer(buffer2, hmac_, info, counter);
bufpos = 0;
}
out[i] = buffer2[bufpos++];
}
hmac_.clean();
buffer2.fill(0);
counter.fill(0);
return out;
}
exports.hkdf = hkdf;
function pbkdf2(password, salt, iterations, dkLen) {
var prf = new HMAC(password);
var len = prf.digestLength;
var ctr = new Uint8Array(4);
var t = new Uint8Array(len);
var u = new Uint8Array(len);
var dk = new Uint8Array(dkLen);
for (var i = 0; i * len < dkLen; i++) {
var c2 = i + 1;
ctr[0] = c2 >>> 24 & 255;
ctr[1] = c2 >>> 16 & 255;
ctr[2] = c2 >>> 8 & 255;
ctr[3] = c2 >>> 0 & 255;
prf.reset();
prf.update(salt);
prf.update(ctr);
prf.finish(u);
for (var j = 0; j < len; j++) {
t[j] = u[j];
}
for (var j = 2; j <= iterations; j++) {
prf.reset();
prf.update(u).finish(u);
for (var k = 0; k < len; k++) {
t[k] ^= u[k];
}
}
for (var j = 0; j < len && i * len + j < dkLen; j++) {
dk[i * len + j] = t[j];
}
}
for (var i = 0; i < len; i++) {
t[i] = u[i] = 0;
}
for (var i = 0; i < 4; i++) {
ctr[i] = 0;
}
prf.clean();
return dk;
}
exports.pbkdf2 = pbkdf2;
});
})(sha256$1);
var sha256Exports = sha256$1.exports;
const sha256 = /* @__PURE__ */ getDefaultExportFromCjs(sha256Exports);
function cleanName(name) {
return name.replaceAll("file:///", "").replaceAll(".", "_dot_").replaceAll("/", "_slash_").replaceAll("-", "_dash_");
}
function closest(node2, cb) {
while (node2) {
if (cb(node2))
return node2;
node2 = node2.parent;
}
return null;
}
function findShadeupTags(declar) {
let matcher = /=tag\((.+)\)$/g;
let doc = ts.getJSDocTags(declar);
for (let d of doc) {
if (d.tagName.text !== "shadeup")
continue;
if (typeof d.comment === "string") {
let matches = matcher.exec(d.comment);
if (matches) {
return matches[1].split(",").map((s) => s.trim());
}
}
}
return [];
}
function getFunctionDeclarationFromCallExpression(checker, node2) {
if (ts.isCallExpression(node2)) {
let exprSmybol = checker.getSymbolAtLocation(node2.expression);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
let funcDeclar = exprSmybol.getDeclarations()?.[0];
if (funcDeclar && ts.isFunctionDeclaration(funcDeclar)) {
return funcDeclar;
}
}
}
}
function toposort(edges) {
return toposortinternal(uniqueNodes(edges), edges);
}
function toposortinternal(nodes, edges) {
var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes);
edges.forEach(function(edge) {
if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
throw new Error("Unknown node. There is an unknown node in the supplied edges.");
}
});
while (i--) {
if (!visited[i])
visit(nodes[i], i, /* @__PURE__ */ new Set());
}
return sorted;
function visit(node2, i2, predecessors) {
if (predecessors.has(node2)) {
var nodeRep;
try {
nodeRep = ", node was:" + JSON.stringify(node2);
} catch (e) {
nodeRep = "";
}
throw new Error("Cyclic dependency" + nodeRep);
}
if (!nodesHash.has(node2)) {
throw new Error(
"Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node2)
);
}
if (visited[i2])
return;
visited[i2] = true;
var outgoing = outgoingEdges.get(node2) || /* @__PURE__ */ new Set();
outgoing = Array.from(outgoing);
if (i2 = outgoing.length) {
predecessors.add(node2);
do {
var child = outgoing[--i2];
visit(child, nodesHash.get(child), predecessors);
} while (i2);
predecessors.delete(node2);
}
sorted[--cursor] = node2;
}
}
function uniqueNodes(arr) {
var res = /* @__PURE__ */ new Set();
for (var i = 0, len = arr.length; i < len; i++) {
var edge = arr[i];
res.add(edge[0]);
res.add(edge[1]);
}
return Array.from(res);
}
function makeOutgoingEdges(arr) {
var edges = /* @__PURE__ */ new Map();
for (var i = 0, len = arr.length; i < len; i++) {
var edge = arr[i];
if (!edges.has(edge[0]))
edges.set(edge[0], /* @__PURE__ */ new Set());
if (!edges.has(edge[1]))
edges.set(edge[1], /* @__PURE__ */ new Set());
edges.get(edge[0]).add(edge[1]);
}
return edges;
}
function makeNodesHash(arr) {
var res = /* @__PURE__ */ new Map();
for (var i = 0, len = arr.length; i < len; i++) {
res.set(arr[i], i);
}
return res;
}
const wgslHeader = "fn shadeup_up_swizzle_x_u32(n: u32) -> u32{\r\n return n;\r\n}\r\nfn shadeup_up_swizzle_xx_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\nfn shadeup_up_swizzle_xxx_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\nfn shadeup_up_swizzle_xxxx_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_u32(n: u32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_u32(n: u32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_u32(n: u32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_i32(n: i32) -> i32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_i32(n: i32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_i32(n: i32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_i32(n: i32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_x_f32(n: f32) -> f32{\r\n return n;\r\n}\r\n\r\nfn shadeup_up_swizzle_xx_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxx_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xxxx_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xy_f32(n: f32) -> vec2{\r\n return vec2(n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyz_f32(n: f32) -> vec3{\r\n return vec3(n, n, n);\r\n}\r\n\r\nfn shadeup_up_swizzle_xyzw_f32(n: f32) -> vec4{\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nfn squash_bool_vec2(n: vec2) -> bool {\r\n return n.x && n.y;\r\n}\r\n\r\nfn squash_bool_vec3(n: vec3) -> bool {\r\n return n.x && n.y && n.z;\r\n}\r\n\r\nfn squash_bool_vec4(n: vec4) -> bool {\r\n return n.x && n.y && n.z && n.w;\r\n}\r\n\r\nfn matrix_inversefloat4x4(m: mat4x4) -> mat4x4{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n14 = m[3][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n24 = m[3][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n let n34 = m[3][2];\r\n let n41 = m[0][3];\r\n let n42 = m[1][3];\r\n let n43 = m[2][3];\r\n let n44 = m[3][3];\r\n\r\n let t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;\r\n let t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;\r\n let t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;\r\n let t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat4x4 = mat4x4();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * idet;\r\n ret[0][2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * idet;\r\n ret[0][3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * idet;\r\n ret[1][2] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * idet;\r\n ret[1][3] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * idet;\r\n ret[2][2] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * idet;\r\n ret[2][3] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * idet;\r\n\r\n ret[3][0] = t14 * idet;\r\n ret[3][1] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * idet;\r\n ret[3][2] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * idet;\r\n ret[3][3] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat3x3(m: mat3x3) -> mat3x3{\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n13 = m[2][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n let n23 = m[2][1];\r\n let n31 = m[0][2];\r\n let n32 = m[1][2];\r\n let n33 = m[2][2];\r\n\r\n let t11 = n22 * n33 - n23 * n32;\r\n let t12 = n13 * n32 - n12 * n33;\r\n let t13 = n12 * n23 - n13 * n22;\r\n\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat3x3 = mat3x3();\r\n\r\n ret[0][0] = t11 * idet;\r\n ret[0][1] = (n23 * n31 - n21 * n33) * idet;\r\n ret[0][2] = (n21 * n32 - n22 * n31) * idet;\r\n\r\n ret[1][0] = t12 * idet;\r\n ret[1][1] = (n11 * n33 - n13 * n31) * idet;\r\n ret[1][2] = (n12 * n31 - n11 * n32) * idet;\r\n\r\n ret[2][0] = t13 * idet;\r\n ret[2][1] = (n13 * n21 - n11 * n23) * idet;\r\n ret[2][2] = (n11 * n22 - n12 * n21) * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_inversefloat2x2(m: mat2x2) -> mat2x2 {\r\n let n11 = m[0][0];\r\n let n12 = m[1][0];\r\n let n21 = m[0][1];\r\n let n22 = m[1][1];\r\n\r\n let det = n11 * n22 - n12 * n21;\r\n let idet = 1.0 / det;\r\n\r\n var ret: mat2x2 = mat2x2();\r\n\r\n ret[0][0] = n22 * idet;\r\n ret[0][1] = -n12 * idet;\r\n ret[1][0] = -n21 * idet;\r\n ret[1][1] = n11 * idet;\r\n\r\n return ret;\r\n}\r\n\r\nfn matrix_transposefloat2x2(m: mat2x2) -> mat2x2 {\r\n return mat2x2(m[0][0], m[1][0], m[0][1], m[1][1]);\r\n}\r\n\r\nfn matrix_transposefloat3x3(m: mat3x3) -> mat3x3 {\r\n return mat3x3\r\n (\r\n m[0][0], m[1][0], m[2][0],\r\n m[0][1], m[1][1], m[2][1],\r\n m[0][2], m[1][2], m[2][2]\r\n );\r\n}\r\n\r\nfn matrix_transposefloat4x4(m: mat4x4) -> mat4x4 {\r\n return mat4x4\r\n (\r\n m[0][0], m[1][0], m[2][0], m[3][0],\r\n m[0][1], m[1][1], m[2][1], m[3][1],\r\n m[0][2], m[1][2], m[2][2], m[3][2],\r\n m[0][3], m[1][3], m[2][3], m[3][3]\r\n );\r\n}\r\n\r\nfn bilerp_float(a: f32, b: f32, c: f32, d: f32, x: f32, y: f32) -> f32 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2(a: vec2, b: vec2, c: vec2, d: vec2, x: f32, y: f32) -> vec2 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float3(a: vec3, b: vec3, c: vec3, d: vec3, x: f32, y: f32) -> vec3 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float4(a: vec4, b: vec4, c: vec4, d: vec4, x: f32, y: f32) -> vec4 {\r\n return mix(mix(a, b, x), mix(c, d, x), y);\r\n}\r\n\r\nfn bilerp_float2x2(a: mat2x2, b: mat2x2, c: mat2x2, d: mat2x2, x: f32, y: f32) -> mat2x2 {\r\n return mat2x2\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float3x3(a: mat3x3, b: mat3x3, c: mat3x3, d: mat3x3, x: f32, y: f32) -> mat3x3 {\r\n return mat3x3\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y)\r\n );\r\n}\r\n\r\nfn bilerp_float4x4(a: mat4x4, b: mat4x4, c: mat4x4, d: mat4x4, x: f32, y: f32) -> mat4x4 {\r\n return mat4x4\r\n (\r\n bilerp_float(a[0][0], b[0][0], c[0][0], d[0][0], x, y),\r\n bilerp_float(a[0][1], b[0][1], c[0][1], d[0][1], x, y),\r\n bilerp_float(a[0][2], b[0][2], c[0][2], d[0][2], x, y),\r\n bilerp_float(a[0][3], b[0][3], c[0][3], d[0][3], x, y),\r\n bilerp_float(a[1][0], b[1][0], c[1][0], d[1][0], x, y),\r\n bilerp_float(a[1][1], b[1][1], c[1][1], d[1][1], x, y),\r\n bilerp_float(a[1][2], b[1][2], c[1][2], d[1][2], x, y),\r\n bilerp_float(a[1][3], b[1][3], c[1][3], d[1][3], x, y),\r\n bilerp_float(a[2][0], b[2][0], c[2][0], d[2][0], x, y),\r\n bilerp_float(a[2][1], b[2][1], c[2][1], d[2][1], x, y),\r\n bilerp_float(a[2][2], b[2][2], c[2][2], d[2][2], x, y),\r\n bilerp_float(a[2][3], b[2][3], c[2][3], d[2][3], x, y),\r\n bilerp_float(a[3][0], b[3][0], c[3][0], d[3][0], x, y),\r\n bilerp_float(a[3][1], b[3][1], c[3][1], d[3][1], x, y),\r\n bilerp_float(a[3][2], b[3][2], c[3][2], d[3][2], x, y),\r\n bilerp_float(a[3][3], b[3][3], c[3][3], d[3][3], x, y)\r\n );\r\n}";
function validate(file, ast, checker) {
performance.now();
const errors2 = [];
function add(e) {
if (e) {
if (Array.isArray(e)) {
errors2.push(...e);
} else {
errors2.push(e);
}
}
}
function visit(ctx) {
ctx.node.forEachChild(
(node2) => visit({
...ctx,
node: node2
})
);
if (ctx.node.kind == ts.SyntaxKind.PropertyAccessExpression) {
if (ts.isPropertyAccessExpression(ctx.node)) {
add(validatePropertyAccessExpression(ctx, ctx.node));
}
} else if (ctx.node.kind == ts.SyntaxKind.ConditionalExpression) {
if (ts.isConditionalExpression(ctx.node)) {
add(validateConditionalExpression(ctx, ctx.node));
}
} else if (ctx.node.kind == ts.SyntaxKind.CallExpression) {
if (ts.isCallExpression(ctx.node)) {
add(validateCallExpression(ctx, ctx.node));
}
}
}
visit({
file,
ast,
checker,
node: ast
});
return errors2;
}
function validateGraph(env2, file, ast, checker) {
performance.now();
const errors2 = [];
function add(e) {
if (e) {
if (Array.isArray(e)) {
errors2.push(...e);
} else {
errors2.push(e);
}
}
}
function visit(ctx) {
ctx.node.forEachChild(
(node2) => visit({
...ctx,
node: node2
})
);
if (ts.isCallExpression(ctx.node)) {
let lhsType = checker?.getTypeAtLocation(ctx.node.getChildAt(0));
let sig = lhsType?.getCallSignatures();
if (sig && sig[0] && sig[0].getDeclaration()) {
let declaration = sig[0].getDeclaration();
if (ts.isIdentifier(ctx.node.expression) && ctx.node.expression.text == "makeShader") {
checker?.getTypeAtLocation(declaration);
if (ctx.node.arguments.length >= 2) {
if (ts.isArrowFunction(ctx.node.arguments[1])) {
add(validateShaderCalls(env2, ctx, ctx.node.arguments[1]));
}
}
}
}
}
if (ts.isExpressionStatement(ctx.node)) {
add(validateStatement(ctx, ctx.node));
}
if (ts.isArrayLiteralExpression(ctx.node)) {
add(validateArrayLiteral(ctx, ctx.node));
}
}
visit({
file,
ast,
checker,
node: ast
});
return errors2;
}
function isStaticPropertyAccessExpression(checker, node2) {
let resultType = checker.getSymbolAtLocation(node2);
if (!resultType)
return false;
let tos = checker.getTypeOfSymbolAtLocation(resultType, node2);
let isStaticMember = false;
if (resultType.parent) {
let p = resultType.parent;
if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) {
isStaticMember = true;
}
}
tos.getCallSignatures().forEach((s) => {
if (s.declaration) {
s.declaration.modifiers?.forEach((m) => {
if (m.kind == ts.SyntaxKind.StaticKeyword) {
isStaticMember = true;
}
});
}
});
return isStaticMember;
}
function validateStatement({ checker, file }, node2) {
if (ts.isLiteralExpression(node2.expression) || ts.isPropertyAccessChain(node2.expression) || ts.isPropertyAccessExpression(node2.expression) || ts.isIdentifier(node2.expression)) {
return {
file: node2.getSourceFile(),
code: 0,
messageText: `This expression has no effect`,
category: ts.DiagnosticCategory.Error,
start: node2.getStart(),
length: node2.getEnd() - node2.getStart()
};
}
}
function validateConditionalExpression({ checker, file }, node2) {
let thenType = checker.getTypeAtLocation(node2.whenTrue);
let elseType = checker.getTypeAtLocation(node2.whenFalse);
if (!isTypeCompatible(checker, thenType, elseType)) {
return void 0;
}
return void 0;
}
function validateCallExpression({ checker, file }, node2) {
if (ts.isPropertyAccessExpression(node2.expression)) {
let left = node2.expression.expression;
if (!ts.isIdentifier(left))
return void 0;
if (left.text != "__")
return void 0;
let right = node2.expression.name.text;
if (right.startsWith("int") && (right[right.length - 1] == "2" || right[right.length - 1] == "3" || right[right.length - 1] == "4")) {
for (let i = 0; i < node2.arguments.length; i++) {
let arg = node2.arguments[i];
let type2 = checker.getTypeAtLocation(arg);
let typeName = checker.typeToString(type2);
if (typeName.startsWith("uint")) {
if (node2.arguments.length != 1) {
return {
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot convert from uint to int during vector construction, use int() before`,
category: ts.DiagnosticCategory.Error,
start: arg.getStart(),
length: arg.getEnd() - arg.getStart()
};
}
}
}
}
}
return void 0;
}
function validatePropertyAccessExpression({ checker, file }, node2) {
let midNode = node2.getChildren()[1];
if (file.mapping && midNode) {
let range2 = lookupIndexMappingRange(file.mapping, midNode.getStart(), midNode.getEnd());
let s = file.content.substring(range2.start, range2.end);
let isStaticAccess = s == "::";
let resultType = checker.getSymbolAtLocation(node2);
if (resultType) {
let tos = checker.getTypeOfSymbolAtLocation(resultType, node2);
let isStaticMember = false;
if (resultType.parent) {
let p = resultType.parent;
if (p.valueDeclaration && p.name != "__" && !ts.isSourceFile(p.valueDeclaration) && p.flags & ts.SymbolFlags.Namespace) {
isStaticMember = true;
}
}
tos.getCallSignatures().forEach((s2) => {
if (s2.declaration) {
s2.declaration.modifiers?.forEach((m) => {
if (m.kind == ts.SyntaxKind.StaticKeyword) {
isStaticMember = true;
}
});
}
});
resultType.getDeclarations()?.forEach((d) => {
if (ts.canHaveModifiers(d) && d.modifiers) {
d.modifiers.forEach((m) => {
if (m.kind == ts.SyntaxKind.StaticKeyword) {
isStaticMember = true;
}
});
}
});
if (isStaticMember && !isStaticAccess) {
return {
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot access static member with '${s}' use '::' instead`,
category: ts.DiagnosticCategory.Error,
start: midNode.getStart(),
length: midNode.getEnd() - midNode.getStart()
};
} else if (!isStaticMember && isStaticAccess) {
return {
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot access non-static member with '${s}' use '.' instead`,
category: ts.DiagnosticCategory.Error,
start: midNode.getStart(),
length: midNode.getEnd() - midNode.getStart()
};
}
}
}
return void 0;
}
function isTypeCompatible(checker, type2, typeOther) {
return checker.isTypeAssignableTo(type2, typeOther);
}
function validateArrayLiteral({ checker, file }, node2) {
if (node2.elements.length == 3) {
let name1 = checker.typeToString(checker.getTypeAtLocation(node2.elements[0]));
let name2 = checker.typeToString(checker.getTypeAtLocation(node2.elements[1]));
let name3 = checker.typeToString(checker.getTypeAtLocation(node2.elements[2]));
if (name1 == "0" && name2 == "shader" && name3 == "0") {
return void 0;
}
}
return void 0;
}
const SHADER_TYPE_BLACKLIST = ["string", "null", "map"];
function validateShaderTypeUse(env2, { checker, file }, diags, node2, typeNode) {
let type2 = checker.typeToString(typeNode);
if (SHADER_TYPE_BLACKLIST.includes(type2) || type2.startsWith("map<")) {
diags.push({
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot use type '${type2}' in shader`,
category: ts.DiagnosticCategory.Error,
start: node2.getStart(),
length: node2.getEnd() - node2.getStart()
});
}
if (typeNode.isUnion() && type2 != "boolean") {
diags.push({
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot use union types in shaders ('${type2}')`,
category: ts.DiagnosticCategory.Error,
start: node2.getStart(),
length: node2.getEnd() - node2.getStart()
});
}
if (typeNode.isLiteral()) {
diags.push({
file: node2.getSourceFile(),
code: 0,
messageText: `Cannot use literal types in shaders ('${type2}')`,
category: ts.DiagnosticCategory.Error,
start: node2.getStart(),
length: node2.getEnd() - node2.getStart()
});
}
}
function validateShaderCalls(env2, vs, node2) {
let diags = [];
const { checker, file } = vs;
let visit = (node22) => {
if (ts.isCallExpression(node22)) {
let declar = getFunctionDeclarationFromCallExpression(checker, node22);
if (declar) {
let graphNodeName = getFunctionNodeName(declar);
let graphNode = env2.tagGraph.getNode(graphNodeName);
if (graphNode) {
if (graphNode.tags.includes("async")) {
let rawChain = env2.tagGraph.resolveTagSourceChain(graphNodeName, "async");
let chain = rawChain.map((m) => m.split(":")[1]).join(" <- ");
if (rawChain[rawChain.length - 1].split(":")[1] == "texture2d_internal_empty")
;
else {
diags.push({
file: node22.getSourceFile(),
code: 0,
messageText: `Cannot call cpu-only function from a shader. ${chain}`,
category: ts.DiagnosticCategory.Error,
start: node22.getStart(),
length: node22.getEnd() - node22.getStart()
});
}
}
}
}
validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22));
}
if (ts.isPropertyAccessExpression(node22)) {
validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22));
}
if (ts.isIdentifier(node22)) {
validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22));
}
if (ts.isElementAccessExpression(node22)) {
validateShaderTypeUse(env2, vs, diags, node22, checker.getTypeAtLocation(node22));
}
if (ts.isVariableDeclaration(node22)) {
let arrType = checker.getTypeAtLocation(node22);
let typeInfo = getArrayTypeInfo(checker, arrType);
if (typeInfo.isArray) {
if (typeInfo.staticSize <= 0) {
diags.push({
file: node22.getSourceFile(),
code: 0,
messageText: `Please explicitly specify the size of the array (let a: T[10] = ...)`,
category: ts.DiagnosticCategory.Error,
start: node22.getStart(),
length: node22.getEnd() - node22.getStart()
});
}
}
}
ts.forEachChild(node22, visit);
};
ts.forEachChild(node2, visit);
return diags;
}
var tsutils = {};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2)
if (b2.hasOwnProperty(p))
d2[p] = b2[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign2(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c2 < 3 ? d(r) : c2 > 3 ? d(target, key, r) : d(target, key)) || r;
return c2 > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function(target, key) {
decorator(target, key, paramIndex);
};
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1)
throw t[1];
return t[1];
}, trys: [], ops: [] }, f, y, t, g2;
return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
return this;
}), g2;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding(o, m, k, k2) {
if (k2 === void 0)
k2 = k;
o[k2] = m[k];
}
function __exportStar(m, exports) {
for (var p in m)
if (p !== "default" && !exports.hasOwnProperty(p))
exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function() {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
} finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g2 = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i;
function verb(n) {
if (g2[n])
i[n] = function(v) {
return new Promise(function(a, b) {
q.push([n, v, a, b]) > 1 || resume(n, v);
});
};
}
function resume(n, v) {
try {
step(g2[n](v));
} catch (e) {
settle(q[0][3], e);
}
}
function step(r) {
r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
}
function fulfill(value) {
resume("next", value);
}
function reject(value) {
resume("throw", value);
}
function settle(f, v) {
if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]);
}
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function(e) {
throw e;
}), verb("return"), i[Symbol.iterator] = function() {
return this;
}, i;
function verb(n, f) {
i[n] = o[n] ? function(v) {
return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
} : f;
}
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i);
function verb(n) {
i[n] = o[n] && function(v) {
return new Promise(function(resolve, reject) {
v = o[n](v), settle(resolve, reject, v.done, v.value);
});
};
}
function settle(resolve, reject, d, v) {
Promise.resolve(v).then(function(v2) {
resolve({ value: v2, done: d });
}, reject);
}
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
} else {
cooked.raw = raw;
}
return cooked;
}
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null) {
for (var k in mod)
if (Object.hasOwnProperty.call(mod, k))
result[k] = mod[k];
}
result.default = mod;
return result;
}
function __importDefault(mod) {
return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
const tslib_es6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
get __assign() {
return __assign;
},
__asyncDelegator,
__asyncGenerator,
__asyncValues,
__await,
__awaiter,
__classPrivateFieldGet,
__classPrivateFieldSet,
__createBinding,
__decorate,
__exportStar,
__extends,
__generator,
__importDefault,
__importStar,
__makeTemplateObject,
__metadata,
__param,
__read,
__rest,
__spread,
__spreadArrays,
__values
}, Symbol.toStringTag, { value: "Module" }));
const require$$0 = /* @__PURE__ */ getAugmentedNamespace(tslib_es6);
var typeguard = {};
var node$4 = {};
var node$3 = {};
var node$2 = {};
var node$1 = {};
var node = {};
var hasRequiredNode$4;
function requireNode$4() {
if (hasRequiredNode$4)
return node;
hasRequiredNode$4 = 1;
Object.defineProperty(node, "__esModule", { value: true });
node.isExpressionStatement = node.isExpression = node.isExportSpecifier = node.isExportDeclaration = node.isExportAssignment = node.isEnumMember = node.isEnumDeclaration = node.isEntityNameExpression = node.isEntityName = node.isEmptyStatement = node.isElementAccessExpression = node.isDoStatement = node.isDeleteExpression = node.isDefaultClause = node.isDecorator = node.isDebuggerStatement = node.isComputedPropertyName = node.isContinueStatement = node.isConstructSignatureDeclaration = node.isConstructorTypeNode = node.isConstructorDeclaration = node.isConditionalTypeNode = node.isConditionalExpression = node.isCommaListExpression = node.isClassLikeDeclaration = node.isClassExpression = node.isClassDeclaration = node.isCatchClause = node.isCaseOrDefaultClause = node.isCaseClause = node.isCaseBlock = node.isCallSignatureDeclaration = node.isCallLikeExpression = node.isCallExpression = node.isBreakStatement = node.isBreakOrContinueStatement = node.isBooleanLiteral = node.isBlockLike = node.isBlock = node.isBindingPattern = node.isBindingElement = node.isBinaryExpression = node.isAwaitExpression = node.isAssertionExpression = node.isAsExpression = node.isArrowFunction = node.isArrayTypeNode = node.isArrayLiteralExpression = node.isArrayBindingPattern = node.isAccessorDeclaration = void 0;
node.isNamespaceImport = node.isNamespaceDeclaration = node.isNamedImports = node.isNamedExports = node.isModuleDeclaration = node.isModuleBlock = node.isMethodSignature = node.isMethodDeclaration = node.isMetaProperty = node.isMappedTypeNode = node.isLiteralTypeNode = node.isLiteralExpression = node.isLabeledStatement = node.isJsxText = node.isJsxSpreadAttribute = node.isJsxSelfClosingElement = node.isJsxOpeningLikeElement = node.isJsxOpeningFragment = node.isJsxOpeningElement = node.isJsxFragment = node.isJsxExpression = node.isJsxElement = node.isJsxClosingFragment = node.isJsxClosingElement = node.isJsxAttributes = node.isJsxAttributeLike = node.isJsxAttribute = node.isJsDoc = node.isIterationStatement = node.isIntersectionTypeNode = node.isInterfaceDeclaration = node.isInferTypeNode = node.isIndexSignatureDeclaration = node.isIndexedAccessTypeNode = node.isImportSpecifier = node.isImportEqualsDeclaration = node.isImportDeclaration = node.isImportClause = node.isIfStatement = node.isIdentifier = node.isGetAccessorDeclaration = node.isFunctionTypeNode = node.isFunctionExpression = node.isFunctionDeclaration = node.isForStatement = node.isForOfStatement = node.isForInOrOfStatement = node.isForInStatement = node.isExternalModuleReference = node.isExpressionWithTypeArguments = void 0;
node.isVariableStatement = node.isVariableDeclaration = node.isUnionTypeNode = node.isTypeQueryNode = node.isTypeReferenceNode = node.isTypePredicateNode = node.isTypeParameterDeclaration = node.isTypeOperatorNode = node.isTypeOfExpression = node.isTypeLiteralNode = node.isTypeAssertion = node.isTypeAliasDeclaration = node.isTupleTypeNode = node.isTryStatement = node.isThrowStatement = node.isTextualLiteral = node.isTemplateLiteral = node.isTemplateExpression = node.isTaggedTemplateExpression = node.isSyntaxList = node.isSwitchStatement = node.isStringLiteral = node.isSpreadElement = node.isSpreadAssignment = node.isSourceFile = node.isSignatureDeclaration = node.isShorthandPropertyAssignment = node.isSetAccessorDeclaration = node.isReturnStatement = node.isRegularExpressionLiteral = node.isQualifiedName = node.isPropertySignature = node.isPropertyDeclaration = node.isPropertyAssignment = node.isPropertyAccessExpression = node.isPrefixUnaryExpression = node.isPostfixUnaryExpression = node.isParenthesizedTypeNode = node.isParenthesizedExpression = node.isParameterDeclaration = node.isOmittedExpression = node.isObjectLiteralExpression = node.isObjectBindingPattern = node.isNumericOrStringLikeLiteral = node.isNumericLiteral = node.isNullLiteral = node.isNoSubstitutionTemplateLiteral = node.isNonNullExpression = node.isNewExpression = node.isNamespaceExportDeclaration = void 0;
node.isWithStatement = node.isWhileStatement = node.isVoidExpression = node.isVariableDeclarationList = void 0;
const ts$1 = ts;
function isAccessorDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.GetAccessor || node2.kind === ts$1.SyntaxKind.SetAccessor;
}
node.isAccessorDeclaration = isAccessorDeclaration;
function isArrayBindingPattern(node2) {
return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern;
}
node.isArrayBindingPattern = isArrayBindingPattern;
function isArrayLiteralExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ArrayLiteralExpression;
}
node.isArrayLiteralExpression = isArrayLiteralExpression;
function isArrayTypeNode2(node2) {
return node2.kind === ts$1.SyntaxKind.ArrayType;
}
node.isArrayTypeNode = isArrayTypeNode2;
function isArrowFunction(node2) {
return node2.kind === ts$1.SyntaxKind.ArrowFunction;
}
node.isArrowFunction = isArrowFunction;
function isAsExpression(node2) {
return node2.kind === ts$1.SyntaxKind.AsExpression;
}
node.isAsExpression = isAsExpression;
function isAssertionExpression(node2) {
return node2.kind === ts$1.SyntaxKind.AsExpression || node2.kind === ts$1.SyntaxKind.TypeAssertionExpression;
}
node.isAssertionExpression = isAssertionExpression;
function isAwaitExpression(node2) {
return node2.kind === ts$1.SyntaxKind.AwaitExpression;
}
node.isAwaitExpression = isAwaitExpression;
function isBinaryExpression(node2) {
return node2.kind === ts$1.SyntaxKind.BinaryExpression;
}
node.isBinaryExpression = isBinaryExpression;
function isBindingElement(node2) {
return node2.kind === ts$1.SyntaxKind.BindingElement;
}
node.isBindingElement = isBindingElement;
function isBindingPattern(node2) {
return node2.kind === ts$1.SyntaxKind.ArrayBindingPattern || node2.kind === ts$1.SyntaxKind.ObjectBindingPattern;
}
node.isBindingPattern = isBindingPattern;
function isBlock(node2) {
return node2.kind === ts$1.SyntaxKind.Block;
}
node.isBlock = isBlock;
function isBlockLike(node2) {
return node2.statements !== void 0;
}
node.isBlockLike = isBlockLike;
function isBooleanLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.TrueKeyword || node2.kind === ts$1.SyntaxKind.FalseKeyword;
}
node.isBooleanLiteral = isBooleanLiteral;
function isBreakOrContinueStatement(node2) {
return node2.kind === ts$1.SyntaxKind.BreakStatement || node2.kind === ts$1.SyntaxKind.ContinueStatement;
}
node.isBreakOrContinueStatement = isBreakOrContinueStatement;
function isBreakStatement(node2) {
return node2.kind === ts$1.SyntaxKind.BreakStatement;
}
node.isBreakStatement = isBreakStatement;
function isCallExpression2(node2) {
return node2.kind === ts$1.SyntaxKind.CallExpression;
}
node.isCallExpression = isCallExpression2;
function isCallLikeExpression(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.CallExpression:
case ts$1.SyntaxKind.Decorator:
case ts$1.SyntaxKind.JsxOpeningElement:
case ts$1.SyntaxKind.JsxSelfClosingElement:
case ts$1.SyntaxKind.NewExpression:
case ts$1.SyntaxKind.TaggedTemplateExpression:
return true;
default:
return false;
}
}
node.isCallLikeExpression = isCallLikeExpression;
function isCallSignatureDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.CallSignature;
}
node.isCallSignatureDeclaration = isCallSignatureDeclaration;
function isCaseBlock(node2) {
return node2.kind === ts$1.SyntaxKind.CaseBlock;
}
node.isCaseBlock = isCaseBlock;
function isCaseClause(node2) {
return node2.kind === ts$1.SyntaxKind.CaseClause;
}
node.isCaseClause = isCaseClause;
function isCaseOrDefaultClause(node2) {
return node2.kind === ts$1.SyntaxKind.CaseClause || node2.kind === ts$1.SyntaxKind.DefaultClause;
}
node.isCaseOrDefaultClause = isCaseOrDefaultClause;
function isCatchClause(node2) {
return node2.kind === ts$1.SyntaxKind.CatchClause;
}
node.isCatchClause = isCatchClause;
function isClassDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ClassDeclaration;
}
node.isClassDeclaration = isClassDeclaration;
function isClassExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ClassExpression;
}
node.isClassExpression = isClassExpression;
function isClassLikeDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ClassDeclaration || node2.kind === ts$1.SyntaxKind.ClassExpression;
}
node.isClassLikeDeclaration = isClassLikeDeclaration;
function isCommaListExpression(node2) {
return node2.kind === ts$1.SyntaxKind.CommaListExpression;
}
node.isCommaListExpression = isCommaListExpression;
function isConditionalExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ConditionalExpression;
}
node.isConditionalExpression = isConditionalExpression;
function isConditionalTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.ConditionalType;
}
node.isConditionalTypeNode = isConditionalTypeNode;
function isConstructorDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.Constructor;
}
node.isConstructorDeclaration = isConstructorDeclaration;
function isConstructorTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.ConstructorType;
}
node.isConstructorTypeNode = isConstructorTypeNode;
function isConstructSignatureDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ConstructSignature;
}
node.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
function isContinueStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ContinueStatement;
}
node.isContinueStatement = isContinueStatement;
function isComputedPropertyName(node2) {
return node2.kind === ts$1.SyntaxKind.ComputedPropertyName;
}
node.isComputedPropertyName = isComputedPropertyName;
function isDebuggerStatement(node2) {
return node2.kind === ts$1.SyntaxKind.DebuggerStatement;
}
node.isDebuggerStatement = isDebuggerStatement;
function isDecorator(node2) {
return node2.kind === ts$1.SyntaxKind.Decorator;
}
node.isDecorator = isDecorator;
function isDefaultClause(node2) {
return node2.kind === ts$1.SyntaxKind.DefaultClause;
}
node.isDefaultClause = isDefaultClause;
function isDeleteExpression(node2) {
return node2.kind === ts$1.SyntaxKind.DeleteExpression;
}
node.isDeleteExpression = isDeleteExpression;
function isDoStatement(node2) {
return node2.kind === ts$1.SyntaxKind.DoStatement;
}
node.isDoStatement = isDoStatement;
function isElementAccessExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ElementAccessExpression;
}
node.isElementAccessExpression = isElementAccessExpression;
function isEmptyStatement(node2) {
return node2.kind === ts$1.SyntaxKind.EmptyStatement;
}
node.isEmptyStatement = isEmptyStatement;
function isEntityName(node2) {
return node2.kind === ts$1.SyntaxKind.Identifier || isQualifiedName(node2);
}
node.isEntityName = isEntityName;
function isEntityNameExpression(node2) {
return node2.kind === ts$1.SyntaxKind.Identifier || isPropertyAccessExpression2(node2) && isEntityNameExpression(node2.expression);
}
node.isEntityNameExpression = isEntityNameExpression;
function isEnumDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.EnumDeclaration;
}
node.isEnumDeclaration = isEnumDeclaration;
function isEnumMember(node2) {
return node2.kind === ts$1.SyntaxKind.EnumMember;
}
node.isEnumMember = isEnumMember;
function isExportAssignment(node2) {
return node2.kind === ts$1.SyntaxKind.ExportAssignment;
}
node.isExportAssignment = isExportAssignment;
function isExportDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ExportDeclaration;
}
node.isExportDeclaration = isExportDeclaration;
function isExportSpecifier(node2) {
return node2.kind === ts$1.SyntaxKind.ExportSpecifier;
}
node.isExportSpecifier = isExportSpecifier;
function isExpression(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.ArrayLiteralExpression:
case ts$1.SyntaxKind.ArrowFunction:
case ts$1.SyntaxKind.AsExpression:
case ts$1.SyntaxKind.AwaitExpression:
case ts$1.SyntaxKind.BinaryExpression:
case ts$1.SyntaxKind.CallExpression:
case ts$1.SyntaxKind.ClassExpression:
case ts$1.SyntaxKind.CommaListExpression:
case ts$1.SyntaxKind.ConditionalExpression:
case ts$1.SyntaxKind.DeleteExpression:
case ts$1.SyntaxKind.ElementAccessExpression:
case ts$1.SyntaxKind.FalseKeyword:
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.Identifier:
case ts$1.SyntaxKind.JsxElement:
case ts$1.SyntaxKind.JsxFragment:
case ts$1.SyntaxKind.JsxExpression:
case ts$1.SyntaxKind.JsxOpeningElement:
case ts$1.SyntaxKind.JsxOpeningFragment:
case ts$1.SyntaxKind.JsxSelfClosingElement:
case ts$1.SyntaxKind.MetaProperty:
case ts$1.SyntaxKind.NewExpression:
case ts$1.SyntaxKind.NonNullExpression:
case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral:
case ts$1.SyntaxKind.NullKeyword:
case ts$1.SyntaxKind.NumericLiteral:
case ts$1.SyntaxKind.ObjectLiteralExpression:
case ts$1.SyntaxKind.OmittedExpression:
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.PostfixUnaryExpression:
case ts$1.SyntaxKind.PrefixUnaryExpression:
case ts$1.SyntaxKind.PropertyAccessExpression:
case ts$1.SyntaxKind.RegularExpressionLiteral:
case ts$1.SyntaxKind.SpreadElement:
case ts$1.SyntaxKind.StringLiteral:
case ts$1.SyntaxKind.SuperKeyword:
case ts$1.SyntaxKind.TaggedTemplateExpression:
case ts$1.SyntaxKind.TemplateExpression:
case ts$1.SyntaxKind.ThisKeyword:
case ts$1.SyntaxKind.TrueKeyword:
case ts$1.SyntaxKind.TypeAssertionExpression:
case ts$1.SyntaxKind.TypeOfExpression:
case ts$1.SyntaxKind.VoidExpression:
case ts$1.SyntaxKind.YieldExpression:
return true;
default:
return false;
}
}
node.isExpression = isExpression;
function isExpressionStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ExpressionStatement;
}
node.isExpressionStatement = isExpressionStatement;
function isExpressionWithTypeArguments(node2) {
return node2.kind === ts$1.SyntaxKind.ExpressionWithTypeArguments;
}
node.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
function isExternalModuleReference(node2) {
return node2.kind === ts$1.SyntaxKind.ExternalModuleReference;
}
node.isExternalModuleReference = isExternalModuleReference;
function isForInStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ForInStatement;
}
node.isForInStatement = isForInStatement;
function isForInOrOfStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ForOfStatement || node2.kind === ts$1.SyntaxKind.ForInStatement;
}
node.isForInOrOfStatement = isForInOrOfStatement;
function isForOfStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ForOfStatement;
}
node.isForOfStatement = isForOfStatement;
function isForStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ForStatement;
}
node.isForStatement = isForStatement;
function isFunctionDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.FunctionDeclaration;
}
node.isFunctionDeclaration = isFunctionDeclaration;
function isFunctionExpression(node2) {
return node2.kind === ts$1.SyntaxKind.FunctionExpression;
}
node.isFunctionExpression = isFunctionExpression;
function isFunctionTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.FunctionType;
}
node.isFunctionTypeNode = isFunctionTypeNode;
function isGetAccessorDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.GetAccessor;
}
node.isGetAccessorDeclaration = isGetAccessorDeclaration;
function isIdentifier2(node2) {
return node2.kind === ts$1.SyntaxKind.Identifier;
}
node.isIdentifier = isIdentifier2;
function isIfStatement(node2) {
return node2.kind === ts$1.SyntaxKind.IfStatement;
}
node.isIfStatement = isIfStatement;
function isImportClause(node2) {
return node2.kind === ts$1.SyntaxKind.ImportClause;
}
node.isImportClause = isImportClause;
function isImportDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ImportDeclaration;
}
node.isImportDeclaration = isImportDeclaration;
function isImportEqualsDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ImportEqualsDeclaration;
}
node.isImportEqualsDeclaration = isImportEqualsDeclaration;
function isImportSpecifier(node2) {
return node2.kind === ts$1.SyntaxKind.ImportSpecifier;
}
node.isImportSpecifier = isImportSpecifier;
function isIndexedAccessTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.IndexedAccessType;
}
node.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
function isIndexSignatureDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.IndexSignature;
}
node.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
function isInferTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.InferType;
}
node.isInferTypeNode = isInferTypeNode;
function isInterfaceDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.InterfaceDeclaration;
}
node.isInterfaceDeclaration = isInterfaceDeclaration;
function isIntersectionTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.IntersectionType;
}
node.isIntersectionTypeNode = isIntersectionTypeNode;
function isIterationStatement(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.ForStatement:
case ts$1.SyntaxKind.ForOfStatement:
case ts$1.SyntaxKind.ForInStatement:
case ts$1.SyntaxKind.WhileStatement:
case ts$1.SyntaxKind.DoStatement:
return true;
default:
return false;
}
}
node.isIterationStatement = isIterationStatement;
function isJsDoc(node2) {
return node2.kind === ts$1.SyntaxKind.JSDocComment;
}
node.isJsDoc = isJsDoc;
function isJsxAttribute(node2) {
return node2.kind === ts$1.SyntaxKind.JsxAttribute;
}
node.isJsxAttribute = isJsxAttribute;
function isJsxAttributeLike(node2) {
return node2.kind === ts$1.SyntaxKind.JsxAttribute || node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute;
}
node.isJsxAttributeLike = isJsxAttributeLike;
function isJsxAttributes(node2) {
return node2.kind === ts$1.SyntaxKind.JsxAttributes;
}
node.isJsxAttributes = isJsxAttributes;
function isJsxClosingElement(node2) {
return node2.kind === ts$1.SyntaxKind.JsxClosingElement;
}
node.isJsxClosingElement = isJsxClosingElement;
function isJsxClosingFragment(node2) {
return node2.kind === ts$1.SyntaxKind.JsxClosingFragment;
}
node.isJsxClosingFragment = isJsxClosingFragment;
function isJsxElement(node2) {
return node2.kind === ts$1.SyntaxKind.JsxElement;
}
node.isJsxElement = isJsxElement;
function isJsxExpression(node2) {
return node2.kind === ts$1.SyntaxKind.JsxExpression;
}
node.isJsxExpression = isJsxExpression;
function isJsxFragment(node2) {
return node2.kind === ts$1.SyntaxKind.JsxFragment;
}
node.isJsxFragment = isJsxFragment;
function isJsxOpeningElement(node2) {
return node2.kind === ts$1.SyntaxKind.JsxOpeningElement;
}
node.isJsxOpeningElement = isJsxOpeningElement;
function isJsxOpeningFragment(node2) {
return node2.kind === ts$1.SyntaxKind.JsxOpeningFragment;
}
node.isJsxOpeningFragment = isJsxOpeningFragment;
function isJsxOpeningLikeElement(node2) {
return node2.kind === ts$1.SyntaxKind.JsxOpeningElement || node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement;
}
node.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
function isJsxSelfClosingElement(node2) {
return node2.kind === ts$1.SyntaxKind.JsxSelfClosingElement;
}
node.isJsxSelfClosingElement = isJsxSelfClosingElement;
function isJsxSpreadAttribute(node2) {
return node2.kind === ts$1.SyntaxKind.JsxSpreadAttribute;
}
node.isJsxSpreadAttribute = isJsxSpreadAttribute;
function isJsxText(node2) {
return node2.kind === ts$1.SyntaxKind.JsxText;
}
node.isJsxText = isJsxText;
function isLabeledStatement(node2) {
return node2.kind === ts$1.SyntaxKind.LabeledStatement;
}
node.isLabeledStatement = isLabeledStatement;
function isLiteralExpression(node2) {
return node2.kind >= ts$1.SyntaxKind.FirstLiteralToken && node2.kind <= ts$1.SyntaxKind.LastLiteralToken;
}
node.isLiteralExpression = isLiteralExpression;
function isLiteralTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.LiteralType;
}
node.isLiteralTypeNode = isLiteralTypeNode;
function isMappedTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.MappedType;
}
node.isMappedTypeNode = isMappedTypeNode;
function isMetaProperty(node2) {
return node2.kind === ts$1.SyntaxKind.MetaProperty;
}
node.isMetaProperty = isMetaProperty;
function isMethodDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.MethodDeclaration;
}
node.isMethodDeclaration = isMethodDeclaration;
function isMethodSignature(node2) {
return node2.kind === ts$1.SyntaxKind.MethodSignature;
}
node.isMethodSignature = isMethodSignature;
function isModuleBlock(node2) {
return node2.kind === ts$1.SyntaxKind.ModuleBlock;
}
node.isModuleBlock = isModuleBlock;
function isModuleDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.ModuleDeclaration;
}
node.isModuleDeclaration = isModuleDeclaration;
function isNamedExports(node2) {
return node2.kind === ts$1.SyntaxKind.NamedExports;
}
node.isNamedExports = isNamedExports;
function isNamedImports(node2) {
return node2.kind === ts$1.SyntaxKind.NamedImports;
}
node.isNamedImports = isNamedImports;
function isNamespaceDeclaration(node2) {
return isModuleDeclaration(node2) && node2.name.kind === ts$1.SyntaxKind.Identifier && node2.body !== void 0 && (node2.body.kind === ts$1.SyntaxKind.ModuleBlock || isNamespaceDeclaration(node2.body));
}
node.isNamespaceDeclaration = isNamespaceDeclaration;
function isNamespaceImport(node2) {
return node2.kind === ts$1.SyntaxKind.NamespaceImport;
}
node.isNamespaceImport = isNamespaceImport;
function isNamespaceExportDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.NamespaceExportDeclaration;
}
node.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
function isNewExpression(node2) {
return node2.kind === ts$1.SyntaxKind.NewExpression;
}
node.isNewExpression = isNewExpression;
function isNonNullExpression(node2) {
return node2.kind === ts$1.SyntaxKind.NonNullExpression;
}
node.isNonNullExpression = isNonNullExpression;
function isNoSubstitutionTemplateLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral;
}
node.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
function isNullLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.NullKeyword;
}
node.isNullLiteral = isNullLiteral;
function isNumericLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.NumericLiteral;
}
node.isNumericLiteral = isNumericLiteral;
function isNumericOrStringLikeLiteral(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.StringLiteral:
case ts$1.SyntaxKind.NumericLiteral:
case ts$1.SyntaxKind.NoSubstitutionTemplateLiteral:
return true;
default:
return false;
}
}
node.isNumericOrStringLikeLiteral = isNumericOrStringLikeLiteral;
function isObjectBindingPattern(node2) {
return node2.kind === ts$1.SyntaxKind.ObjectBindingPattern;
}
node.isObjectBindingPattern = isObjectBindingPattern;
function isObjectLiteralExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ObjectLiteralExpression;
}
node.isObjectLiteralExpression = isObjectLiteralExpression;
function isOmittedExpression(node2) {
return node2.kind === ts$1.SyntaxKind.OmittedExpression;
}
node.isOmittedExpression = isOmittedExpression;
function isParameterDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.Parameter;
}
node.isParameterDeclaration = isParameterDeclaration;
function isParenthesizedExpression(node2) {
return node2.kind === ts$1.SyntaxKind.ParenthesizedExpression;
}
node.isParenthesizedExpression = isParenthesizedExpression;
function isParenthesizedTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.ParenthesizedType;
}
node.isParenthesizedTypeNode = isParenthesizedTypeNode;
function isPostfixUnaryExpression(node2) {
return node2.kind === ts$1.SyntaxKind.PostfixUnaryExpression;
}
node.isPostfixUnaryExpression = isPostfixUnaryExpression;
function isPrefixUnaryExpression(node2) {
return node2.kind === ts$1.SyntaxKind.PrefixUnaryExpression;
}
node.isPrefixUnaryExpression = isPrefixUnaryExpression;
function isPropertyAccessExpression2(node2) {
return node2.kind === ts$1.SyntaxKind.PropertyAccessExpression;
}
node.isPropertyAccessExpression = isPropertyAccessExpression2;
function isPropertyAssignment(node2) {
return node2.kind === ts$1.SyntaxKind.PropertyAssignment;
}
node.isPropertyAssignment = isPropertyAssignment;
function isPropertyDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.PropertyDeclaration;
}
node.isPropertyDeclaration = isPropertyDeclaration;
function isPropertySignature(node2) {
return node2.kind === ts$1.SyntaxKind.PropertySignature;
}
node.isPropertySignature = isPropertySignature;
function isQualifiedName(node2) {
return node2.kind === ts$1.SyntaxKind.QualifiedName;
}
node.isQualifiedName = isQualifiedName;
function isRegularExpressionLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.RegularExpressionLiteral;
}
node.isRegularExpressionLiteral = isRegularExpressionLiteral;
function isReturnStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ReturnStatement;
}
node.isReturnStatement = isReturnStatement;
function isSetAccessorDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.SetAccessor;
}
node.isSetAccessorDeclaration = isSetAccessorDeclaration;
function isShorthandPropertyAssignment(node2) {
return node2.kind === ts$1.SyntaxKind.ShorthandPropertyAssignment;
}
node.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
function isSignatureDeclaration(node2) {
return node2.parameters !== void 0;
}
node.isSignatureDeclaration = isSignatureDeclaration;
function isSourceFile(node2) {
return node2.kind === ts$1.SyntaxKind.SourceFile;
}
node.isSourceFile = isSourceFile;
function isSpreadAssignment(node2) {
return node2.kind === ts$1.SyntaxKind.SpreadAssignment;
}
node.isSpreadAssignment = isSpreadAssignment;
function isSpreadElement(node2) {
return node2.kind === ts$1.SyntaxKind.SpreadElement;
}
node.isSpreadElement = isSpreadElement;
function isStringLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.StringLiteral;
}
node.isStringLiteral = isStringLiteral;
function isSwitchStatement(node2) {
return node2.kind === ts$1.SyntaxKind.SwitchStatement;
}
node.isSwitchStatement = isSwitchStatement;
function isSyntaxList(node2) {
return node2.kind === ts$1.SyntaxKind.SyntaxList;
}
node.isSyntaxList = isSyntaxList;
function isTaggedTemplateExpression(node2) {
return node2.kind === ts$1.SyntaxKind.TaggedTemplateExpression;
}
node.isTaggedTemplateExpression = isTaggedTemplateExpression;
function isTemplateExpression(node2) {
return node2.kind === ts$1.SyntaxKind.TemplateExpression;
}
node.isTemplateExpression = isTemplateExpression;
function isTemplateLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.TemplateExpression || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral;
}
node.isTemplateLiteral = isTemplateLiteral;
function isTextualLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.StringLiteral || node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral;
}
node.isTextualLiteral = isTextualLiteral;
function isThrowStatement(node2) {
return node2.kind === ts$1.SyntaxKind.ThrowStatement;
}
node.isThrowStatement = isThrowStatement;
function isTryStatement(node2) {
return node2.kind === ts$1.SyntaxKind.TryStatement;
}
node.isTryStatement = isTryStatement;
function isTupleTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.TupleType;
}
node.isTupleTypeNode = isTupleTypeNode;
function isTypeAliasDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.TypeAliasDeclaration;
}
node.isTypeAliasDeclaration = isTypeAliasDeclaration;
function isTypeAssertion(node2) {
return node2.kind === ts$1.SyntaxKind.TypeAssertionExpression;
}
node.isTypeAssertion = isTypeAssertion;
function isTypeLiteralNode(node2) {
return node2.kind === ts$1.SyntaxKind.TypeLiteral;
}
node.isTypeLiteralNode = isTypeLiteralNode;
function isTypeOfExpression(node2) {
return node2.kind === ts$1.SyntaxKind.TypeOfExpression;
}
node.isTypeOfExpression = isTypeOfExpression;
function isTypeOperatorNode(node2) {
return node2.kind === ts$1.SyntaxKind.TypeOperator;
}
node.isTypeOperatorNode = isTypeOperatorNode;
function isTypeParameterDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.TypeParameter;
}
node.isTypeParameterDeclaration = isTypeParameterDeclaration;
function isTypePredicateNode(node2) {
return node2.kind === ts$1.SyntaxKind.TypePredicate;
}
node.isTypePredicateNode = isTypePredicateNode;
function isTypeReferenceNode(node2) {
return node2.kind === ts$1.SyntaxKind.TypeReference;
}
node.isTypeReferenceNode = isTypeReferenceNode;
function isTypeQueryNode(node2) {
return node2.kind === ts$1.SyntaxKind.TypeQuery;
}
node.isTypeQueryNode = isTypeQueryNode;
function isUnionTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.UnionType;
}
node.isUnionTypeNode = isUnionTypeNode;
function isVariableDeclaration(node2) {
return node2.kind === ts$1.SyntaxKind.VariableDeclaration;
}
node.isVariableDeclaration = isVariableDeclaration;
function isVariableStatement(node2) {
return node2.kind === ts$1.SyntaxKind.VariableStatement;
}
node.isVariableStatement = isVariableStatement;
function isVariableDeclarationList(node2) {
return node2.kind === ts$1.SyntaxKind.VariableDeclarationList;
}
node.isVariableDeclarationList = isVariableDeclarationList;
function isVoidExpression(node2) {
return node2.kind === ts$1.SyntaxKind.VoidExpression;
}
node.isVoidExpression = isVoidExpression;
function isWhileStatement(node2) {
return node2.kind === ts$1.SyntaxKind.WhileStatement;
}
node.isWhileStatement = isWhileStatement;
function isWithStatement(node2) {
return node2.kind === ts$1.SyntaxKind.WithStatement;
}
node.isWithStatement = isWithStatement;
return node;
}
var hasRequiredNode$3;
function requireNode$3() {
if (hasRequiredNode$3)
return node$1;
hasRequiredNode$3 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isImportTypeNode = void 0;
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode$4(), exports);
const ts$1 = ts;
function isImportTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.ImportType;
}
exports.isImportTypeNode = isImportTypeNode;
})(node$1);
return node$1;
}
var hasRequiredNode$2;
function requireNode$2() {
if (hasRequiredNode$2)
return node$2;
hasRequiredNode$2 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSyntheticExpression = exports.isRestTypeNode = exports.isOptionalTypeNode = void 0;
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode$3(), exports);
const ts$1 = ts;
function isOptionalTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.OptionalType;
}
exports.isOptionalTypeNode = isOptionalTypeNode;
function isRestTypeNode(node2) {
return node2.kind === ts$1.SyntaxKind.RestType;
}
exports.isRestTypeNode = isRestTypeNode;
function isSyntheticExpression(node2) {
return node2.kind === ts$1.SyntaxKind.SyntheticExpression;
}
exports.isSyntheticExpression = isSyntheticExpression;
})(node$2);
return node$2;
}
var hasRequiredNode$1;
function requireNode$1() {
if (hasRequiredNode$1)
return node$3;
hasRequiredNode$1 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBigIntLiteral = void 0;
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode$2(), exports);
const ts$1 = ts;
function isBigIntLiteral(node2) {
return node2.kind === ts$1.SyntaxKind.BigIntLiteral;
}
exports.isBigIntLiteral = isBigIntLiteral;
})(node$3);
return node$3;
}
var hasRequiredNode;
function requireNode() {
if (hasRequiredNode)
return node$4;
hasRequiredNode = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode$1(), exports);
})(node$4);
return node$4;
}
var type$5 = {};
var type$4 = {};
var type$3 = {};
var type$2 = {};
var type$1 = {};
var hasRequiredType$5;
function requireType$5() {
if (hasRequiredType$5)
return type$1;
hasRequiredType$5 = 1;
Object.defineProperty(type$1, "__esModule", { value: true });
type$1.isUniqueESSymbolType = type$1.isUnionType = type$1.isUnionOrIntersectionType = type$1.isTypeVariable = type$1.isTypeReference = type$1.isTypeParameter = type$1.isSubstitutionType = type$1.isObjectType = type$1.isLiteralType = type$1.isIntersectionType = type$1.isInterfaceType = type$1.isInstantiableType = type$1.isIndexedAccessype = type$1.isIndexedAccessType = type$1.isGenericType = type$1.isEnumType = type$1.isConditionalType = void 0;
const ts$1 = ts;
function isConditionalType(type2) {
return (type2.flags & ts$1.TypeFlags.Conditional) !== 0;
}
type$1.isConditionalType = isConditionalType;
function isEnumType(type2) {
return (type2.flags & ts$1.TypeFlags.Enum) !== 0;
}
type$1.isEnumType = isEnumType;
function isGenericType(type2) {
return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0;
}
type$1.isGenericType = isGenericType;
function isIndexedAccessType(type2) {
return (type2.flags & ts$1.TypeFlags.IndexedAccess) !== 0;
}
type$1.isIndexedAccessType = isIndexedAccessType;
function isIndexedAccessype(type2) {
return (type2.flags & ts$1.TypeFlags.Index) !== 0;
}
type$1.isIndexedAccessype = isIndexedAccessype;
function isInstantiableType(type2) {
return (type2.flags & ts$1.TypeFlags.Instantiable) !== 0;
}
type$1.isInstantiableType = isInstantiableType;
function isInterfaceType(type2) {
return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.ClassOrInterface) !== 0;
}
type$1.isInterfaceType = isInterfaceType;
function isIntersectionType(type2) {
return (type2.flags & ts$1.TypeFlags.Intersection) !== 0;
}
type$1.isIntersectionType = isIntersectionType;
function isLiteralType(type2) {
return (type2.flags & (ts$1.TypeFlags.StringOrNumberLiteral | ts$1.TypeFlags.BigIntLiteral)) !== 0;
}
type$1.isLiteralType = isLiteralType;
function isObjectType(type2) {
return (type2.flags & ts$1.TypeFlags.Object) !== 0;
}
type$1.isObjectType = isObjectType;
function isSubstitutionType(type2) {
return (type2.flags & ts$1.TypeFlags.Substitution) !== 0;
}
type$1.isSubstitutionType = isSubstitutionType;
function isTypeParameter(type2) {
return (type2.flags & ts$1.TypeFlags.TypeParameter) !== 0;
}
type$1.isTypeParameter = isTypeParameter;
function isTypeReference(type2) {
return (type2.flags & ts$1.TypeFlags.Object) !== 0 && (type2.objectFlags & ts$1.ObjectFlags.Reference) !== 0;
}
type$1.isTypeReference = isTypeReference;
function isTypeVariable(type2) {
return (type2.flags & ts$1.TypeFlags.TypeVariable) !== 0;
}
type$1.isTypeVariable = isTypeVariable;
function isUnionOrIntersectionType(type2) {
return (type2.flags & ts$1.TypeFlags.UnionOrIntersection) !== 0;
}
type$1.isUnionOrIntersectionType = isUnionOrIntersectionType;
function isUnionType(type2) {
return (type2.flags & ts$1.TypeFlags.Union) !== 0;
}
type$1.isUnionType = isUnionType;
function isUniqueESSymbolType(type2) {
return (type2.flags & ts$1.TypeFlags.UniqueESSymbol) !== 0;
}
type$1.isUniqueESSymbolType = isUniqueESSymbolType;
return type$1;
}
var hasRequiredType$4;
function requireType$4() {
if (hasRequiredType$4)
return type$2;
hasRequiredType$4 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireType$5(), exports);
})(type$2);
return type$2;
}
var hasRequiredType$3;
function requireType$3() {
if (hasRequiredType$3)
return type$3;
hasRequiredType$3 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTupleTypeReference = exports.isTupleType = void 0;
const tslib_1 = require$$0;
tslib_1.__exportStar(requireType$4(), exports);
const ts$1 = ts;
const type_1 = requireType$4();
function isTupleType(type2) {
return (type2.flags & ts$1.TypeFlags.Object && type2.objectFlags & ts$1.ObjectFlags.Tuple) !== 0;
}
exports.isTupleType = isTupleType;
function isTupleTypeReference(type2) {
return type_1.isTypeReference(type2) && isTupleType(type2.target);
}
exports.isTupleTypeReference = isTupleTypeReference;
})(type$3);
return type$3;
}
var hasRequiredType$2;
function requireType$2() {
if (hasRequiredType$2)
return type$4;
hasRequiredType$2 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireType$3(), exports);
})(type$4);
return type$4;
}
var hasRequiredType$1;
function requireType$1() {
if (hasRequiredType$1)
return type$5;
hasRequiredType$1 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireType$2(), exports);
})(type$5);
return type$5;
}
var hasRequiredTypeguard;
function requireTypeguard() {
if (hasRequiredTypeguard)
return typeguard;
hasRequiredTypeguard = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode(), exports);
tslib_1.__exportStar(requireType$1(), exports);
})(typeguard);
return typeguard;
}
var util$2 = {};
var util$1 = {};
var _3_2 = {};
var hasRequired_3_2;
function require_3_2() {
if (hasRequired_3_2)
return _3_2;
hasRequired_3_2 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireNode$1(), exports);
tslib_1.__exportStar(requireType$2(), exports);
})(_3_2);
return _3_2;
}
var type = {};
var hasRequiredType;
function requireType() {
if (hasRequiredType)
return type;
hasRequiredType = 1;
Object.defineProperty(type, "__esModule", { value: true });
type.getBaseClassMemberOfClassElement = type.getIteratorYieldResultFromIteratorResult = type.getInstanceTypeOfClassLikeDeclaration = type.getConstructorTypeOfClassLikeDeclaration = type.getSymbolOfClassLikeDeclaration = type.getPropertyNameFromType = type.symbolHasReadonlyDeclaration = type.isPropertyReadonlyInType = type.getWellKnownSymbolPropertyOfType = type.getPropertyOfType = type.isBooleanLiteralType = type.isFalsyType = type.isThenableType = type.someTypePart = type.intersectionTypeParts = type.unionTypeParts = type.getCallSignaturesOfType = type.isTypeAssignableToString = type.isTypeAssignableToNumber = type.isOptionalChainingUndefinedMarkerType = type.removeOptionalChainingUndefinedMarkerType = type.removeOptionalityFromType = type.isEmptyObjectType = void 0;
const ts$1 = ts;
const type_1 = requireType$1();
const util_1 = requireUtil$1();
const node_1 = requireNode();
function isEmptyObjectType(type2) {
if (type_1.isObjectType(type2) && type2.objectFlags & ts$1.ObjectFlags.Anonymous && type2.getProperties().length === 0 && type2.getCallSignatures().length === 0 && type2.getConstructSignatures().length === 0 && type2.getStringIndexType() === void 0 && type2.getNumberIndexType() === void 0) {
const baseTypes = type2.getBaseTypes();
return baseTypes === void 0 || baseTypes.every(isEmptyObjectType);
}
return false;
}
type.isEmptyObjectType = isEmptyObjectType;
function removeOptionalityFromType(checker, type2) {
if (!containsTypeWithFlag(type2, ts$1.TypeFlags.Undefined))
return type2;
const allowsNull = containsTypeWithFlag(type2, ts$1.TypeFlags.Null);
type2 = checker.getNonNullableType(type2);
return allowsNull ? checker.getNullableType(type2, ts$1.TypeFlags.Null) : type2;
}
type.removeOptionalityFromType = removeOptionalityFromType;
function containsTypeWithFlag(type2, flag) {
for (const t of unionTypeParts(type2))
if (util_1.isTypeFlagSet(t, flag))
return true;
return false;
}
function removeOptionalChainingUndefinedMarkerType(checker, type2) {
if (!type_1.isUnionType(type2))
return isOptionalChainingUndefinedMarkerType(checker, type2) ? type2.getNonNullableType() : type2;
let flags = 0;
let containsUndefinedMarker = false;
for (const t of type2.types) {
if (isOptionalChainingUndefinedMarkerType(checker, t)) {
containsUndefinedMarker = true;
} else {
flags |= t.flags;
}
}
return containsUndefinedMarker ? checker.getNullableType(type2.getNonNullableType(), flags) : type2;
}
type.removeOptionalChainingUndefinedMarkerType = removeOptionalChainingUndefinedMarkerType;
function isOptionalChainingUndefinedMarkerType(checker, t) {
return util_1.isTypeFlagSet(t, ts$1.TypeFlags.Undefined) && checker.getNullableType(t.getNonNullableType(), ts$1.TypeFlags.Undefined) !== t;
}
type.isOptionalChainingUndefinedMarkerType = isOptionalChainingUndefinedMarkerType;
function isTypeAssignableToNumber(checker, type2) {
return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.NumberLike);
}
type.isTypeAssignableToNumber = isTypeAssignableToNumber;
function isTypeAssignableToString(checker, type2) {
return isTypeAssignableTo(checker, type2, ts$1.TypeFlags.StringLike);
}
type.isTypeAssignableToString = isTypeAssignableToString;
function isTypeAssignableTo(checker, type2, flags) {
flags |= ts$1.TypeFlags.Any;
let typeParametersSeen;
return function check(t) {
if (type_1.isTypeParameter(t) && t.symbol !== void 0 && t.symbol.declarations !== void 0) {
if (typeParametersSeen === void 0) {
typeParametersSeen = /* @__PURE__ */ new Set([t]);
} else if (!typeParametersSeen.has(t)) {
typeParametersSeen.add(t);
} else {
return false;
}
const declaration = t.symbol.declarations[0];
if (declaration.constraint === void 0)
return true;
return check(checker.getTypeFromTypeNode(declaration.constraint));
}
if (type_1.isUnionType(t))
return t.types.every(check);
if (type_1.isIntersectionType(t))
return t.types.some(check);
return util_1.isTypeFlagSet(t, flags);
}(type2);
}
function getCallSignaturesOfType(type2) {
if (type_1.isUnionType(type2)) {
const signatures = [];
for (const t of type2.types)
signatures.push(...getCallSignaturesOfType(t));
return signatures;
}
if (type_1.isIntersectionType(type2)) {
let signatures;
for (const t of type2.types) {
const sig = getCallSignaturesOfType(t);
if (sig.length !== 0) {
if (signatures !== void 0)
return [];
signatures = sig;
}
}
return signatures === void 0 ? [] : signatures;
}
return type2.getCallSignatures();
}
type.getCallSignaturesOfType = getCallSignaturesOfType;
function unionTypeParts(type2) {
return type_1.isUnionType(type2) ? type2.types : [type2];
}
type.unionTypeParts = unionTypeParts;
function intersectionTypeParts(type2) {
return type_1.isIntersectionType(type2) ? type2.types : [type2];
}
type.intersectionTypeParts = intersectionTypeParts;
function someTypePart(type2, predicate, cb) {
return predicate(type2) ? type2.types.some(cb) : cb(type2);
}
type.someTypePart = someTypePart;
function isThenableType(checker, node2, type2 = checker.getTypeAtLocation(node2)) {
for (const ty of unionTypeParts(checker.getApparentType(type2))) {
const then = ty.getProperty("then");
if (then === void 0)
continue;
const thenType = checker.getTypeOfSymbolAtLocation(then, node2);
for (const t of unionTypeParts(thenType))
for (const signature of t.getCallSignatures())
if (signature.parameters.length !== 0 && isCallback2(checker, signature.parameters[0], node2))
return true;
}
return false;
}
type.isThenableType = isThenableType;
function isCallback2(checker, param, node2) {
let type2 = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node2));
if (param.valueDeclaration.dotDotDotToken) {
type2 = type2.getNumberIndexType();
if (type2 === void 0)
return false;
}
for (const t of unionTypeParts(type2))
if (t.getCallSignatures().length !== 0)
return true;
return false;
}
function isFalsyType(type2) {
if (type2.flags & (ts$1.TypeFlags.Undefined | ts$1.TypeFlags.Null | ts$1.TypeFlags.Void))
return true;
if (type_1.isLiteralType(type2))
return !type2.value;
return isBooleanLiteralType(type2, false);
}
type.isFalsyType = isFalsyType;
function isBooleanLiteralType(type2, literal) {
return util_1.isTypeFlagSet(type2, ts$1.TypeFlags.BooleanLiteral) && type2.intrinsicName === (literal ? "true" : "false");
}
type.isBooleanLiteralType = isBooleanLiteralType;
function getPropertyOfType(type2, name) {
if (!name.startsWith("__"))
return type2.getProperty(name);
return type2.getProperties().find((s) => s.escapedName === name);
}
type.getPropertyOfType = getPropertyOfType;
function getWellKnownSymbolPropertyOfType(type2, wellKnownSymbolName, checker) {
const prefix = "__@" + wellKnownSymbolName;
for (const prop of type2.getProperties()) {
if (!prop.name.startsWith(prefix))
continue;
const globalSymbol = checker.getApparentType(checker.getTypeAtLocation(prop.valueDeclaration.name.expression)).symbol;
if (prop.escapedName === getPropertyNameOfWellKnownSymbol(checker, globalSymbol, wellKnownSymbolName))
return prop;
}
return;
}
type.getWellKnownSymbolPropertyOfType = getWellKnownSymbolPropertyOfType;
function getPropertyNameOfWellKnownSymbol(checker, symbolConstructor, symbolName) {
const knownSymbol = symbolConstructor && checker.getTypeOfSymbolAtLocation(symbolConstructor, symbolConstructor.valueDeclaration).getProperty(symbolName);
const knownSymbolType = knownSymbol && checker.getTypeOfSymbolAtLocation(knownSymbol, knownSymbol.valueDeclaration);
if (knownSymbolType && type_1.isUniqueESSymbolType(knownSymbolType))
return knownSymbolType.escapedName;
return "__@" + symbolName;
}
function isPropertyReadonlyInType(type2, name, checker) {
let seenProperty = false;
let seenReadonlySignature = false;
for (const t of unionTypeParts(type2)) {
if (getPropertyOfType(t, name) === void 0) {
const index = (util_1.isNumericPropertyName(name) ? checker.getIndexInfoOfType(t, ts$1.IndexKind.Number) : void 0) || checker.getIndexInfoOfType(t, ts$1.IndexKind.String);
if (index !== void 0 && index.isReadonly) {
if (seenProperty)
return true;
seenReadonlySignature = true;
}
} else if (seenReadonlySignature || isReadonlyPropertyIntersection(t, name, checker)) {
return true;
} else {
seenProperty = true;
}
}
return false;
}
type.isPropertyReadonlyInType = isPropertyReadonlyInType;
function isReadonlyPropertyIntersection(type2, name, checker) {
return someTypePart(type2, type_1.isIntersectionType, (t) => {
const prop = getPropertyOfType(t, name);
if (prop === void 0)
return false;
if (prop.flags & ts$1.SymbolFlags.Transient) {
if (/^(?:[1-9]\d*|0)$/.test(name) && type_1.isTupleTypeReference(t))
return t.target.readonly;
switch (isReadonlyPropertyFromMappedType(t, name, checker)) {
case true:
return true;
case false:
return false;
}
}
return (
// members of namespace import
util_1.isSymbolFlagSet(prop, ts$1.SymbolFlags.ValueModule) || // we unwrapped every mapped type, now we can check the actual declarations
symbolHasReadonlyDeclaration(prop, checker)
);
});
}
function isReadonlyPropertyFromMappedType(type2, name, checker) {
if (!type_1.isObjectType(type2) || !util_1.isObjectFlagSet(type2, ts$1.ObjectFlags.Mapped))
return;
const declaration = type2.symbol.declarations[0];
if (declaration.readonlyToken !== void 0 && !/^__@[^@]+$/.test(name))
return declaration.readonlyToken.kind !== ts$1.SyntaxKind.MinusToken;
return isPropertyReadonlyInType(type2.modifiersType, name, checker);
}
function symbolHasReadonlyDeclaration(symbol, checker) {
return (symbol.flags & ts$1.SymbolFlags.Accessor) === ts$1.SymbolFlags.GetAccessor || symbol.declarations !== void 0 && symbol.declarations.some((node2) => util_1.isModifierFlagSet(node2, ts$1.ModifierFlags.Readonly) || node_1.isVariableDeclaration(node2) && util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.Const) || node_1.isCallExpression(node2) && util_1.isReadonlyAssignmentDeclaration(node2, checker) || node_1.isEnumMember(node2) || (node_1.isPropertyAssignment(node2) || node_1.isShorthandPropertyAssignment(node2)) && util_1.isInConstContext(node2.parent));
}
type.symbolHasReadonlyDeclaration = symbolHasReadonlyDeclaration;
function getPropertyNameFromType(type2) {
if (type2.flags & (ts$1.TypeFlags.StringLiteral | ts$1.TypeFlags.NumberLiteral)) {
const value = String(type2.value);
return { displayName: value, symbolName: ts$1.escapeLeadingUnderscores(value) };
}
if (type_1.isUniqueESSymbolType(type2))
return {
displayName: `[${type2.symbol ? `${isKnownSymbol(type2.symbol) ? "Symbol." : ""}${type2.symbol.name}` : type2.escapedName.replace(/^__@|@\d+$/g, "")}]`,
symbolName: type2.escapedName
};
}
type.getPropertyNameFromType = getPropertyNameFromType;
function isKnownSymbol(symbol) {
return util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Property) && symbol.valueDeclaration !== void 0 && node_1.isInterfaceDeclaration(symbol.valueDeclaration.parent) && symbol.valueDeclaration.parent.name.text === "SymbolConstructor" && isGlobalDeclaration(symbol.valueDeclaration.parent);
}
function isGlobalDeclaration(node2) {
return util_1.isNodeFlagSet(node2.parent, ts$1.NodeFlags.GlobalAugmentation) || node_1.isSourceFile(node2.parent) && !ts$1.isExternalModule(node2.parent);
}
function getSymbolOfClassLikeDeclaration(node2, checker) {
var _a;
return checker.getSymbolAtLocation((_a = node2.name) !== null && _a !== void 0 ? _a : util_1.getChildOfKind(node2, ts$1.SyntaxKind.ClassKeyword));
}
type.getSymbolOfClassLikeDeclaration = getSymbolOfClassLikeDeclaration;
function getConstructorTypeOfClassLikeDeclaration(node2, checker) {
return node2.kind === ts$1.SyntaxKind.ClassExpression ? checker.getTypeAtLocation(node2) : checker.getTypeOfSymbolAtLocation(getSymbolOfClassLikeDeclaration(node2, checker), node2);
}
type.getConstructorTypeOfClassLikeDeclaration = getConstructorTypeOfClassLikeDeclaration;
function getInstanceTypeOfClassLikeDeclaration(node2, checker) {
return node2.kind === ts$1.SyntaxKind.ClassDeclaration ? checker.getTypeAtLocation(node2) : checker.getDeclaredTypeOfSymbol(getSymbolOfClassLikeDeclaration(node2, checker));
}
type.getInstanceTypeOfClassLikeDeclaration = getInstanceTypeOfClassLikeDeclaration;
function getIteratorYieldResultFromIteratorResult(type2, node2, checker) {
return type_1.isUnionType(type2) && type2.types.find((t) => {
const done = t.getProperty("done");
return done !== void 0 && isBooleanLiteralType(removeOptionalityFromType(checker, checker.getTypeOfSymbolAtLocation(done, node2)), false);
}) || type2;
}
type.getIteratorYieldResultFromIteratorResult = getIteratorYieldResultFromIteratorResult;
function getBaseClassMemberOfClassElement(node2, checker) {
if (!node_1.isClassLikeDeclaration(node2.parent))
return;
const base = util_1.getBaseOfClassLikeExpression(node2.parent);
if (base === void 0)
return;
const name = util_1.getSingleLateBoundPropertyNameOfPropertyName(node2.name, checker);
if (name === void 0)
return;
const baseType = checker.getTypeAtLocation(util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.StaticKeyword) ? base.expression : base);
return getPropertyOfType(baseType, name.symbolName);
}
type.getBaseClassMemberOfClassElement = getBaseClassMemberOfClassElement;
return type;
}
var hasRequiredUtil$1;
function requireUtil$1() {
if (hasRequiredUtil$1)
return util$1;
hasRequiredUtil$1 = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidIdentifier = exports.getLineBreakStyle = exports.getLineRanges = exports.forEachComment = exports.forEachTokenWithTrivia = exports.forEachToken = exports.isFunctionWithBody = exports.hasOwnThisReference = exports.isBlockScopeBoundary = exports.isFunctionScopeBoundary = exports.isTypeScopeBoundary = exports.isScopeBoundary = exports.ScopeBoundarySelector = exports.ScopeBoundary = exports.isInSingleStatementContext = exports.isBlockScopedDeclarationStatement = exports.isBlockScopedVariableDeclaration = exports.isBlockScopedVariableDeclarationList = exports.getVariableDeclarationKind = exports.VariableDeclarationKind = exports.forEachDeclaredVariable = exports.forEachDestructuringIdentifier = exports.getPropertyName = exports.getWrappedNodeAtPosition = exports.getAstNodeAtPosition = exports.commentText = exports.isPositionInComment = exports.getCommentAtPosition = exports.getTokenAtPosition = exports.getNextToken = exports.getPreviousToken = exports.getNextStatement = exports.getPreviousStatement = exports.isModifierFlagSet = exports.isObjectFlagSet = exports.isSymbolFlagSet = exports.isTypeFlagSet = exports.isNodeFlagSet = exports.hasAccessModifier = exports.isParameterProperty = exports.hasModifier = exports.getModifier = exports.isThisParameter = exports.isKeywordKind = exports.isJsDocKind = exports.isTypeNodeKind = exports.isAssignmentKind = exports.isNodeKind = exports.isTokenKind = exports.getChildOfKind = void 0;
exports.getBaseOfClassLikeExpression = exports.hasExhaustiveCaseClauses = exports.formatPseudoBigInt = exports.unwrapParentheses = exports.getSingleLateBoundPropertyNameOfPropertyName = exports.getLateBoundPropertyNamesOfPropertyName = exports.getLateBoundPropertyNames = exports.getPropertyNameOfWellKnownSymbol = exports.isWellKnownSymbolLiterally = exports.isBindableObjectDefinePropertyCall = exports.isReadonlyAssignmentDeclaration = exports.isInConstContext = exports.isConstAssertion = exports.getTsCheckDirective = exports.getCheckJsDirective = exports.isAmbientModule = exports.isCompilerOptionEnabled = exports.isStrictCompilerOptionEnabled = exports.getIIFE = exports.isAmbientModuleBlock = exports.isStatementInAmbientContext = exports.findImportLikeNodes = exports.findImports = exports.ImportKind = exports.parseJsDocOfNode = exports.getJsDoc = exports.canHaveJsDoc = exports.isReassignmentTarget = exports.getAccessKind = exports.AccessKind = exports.isExpressionValueUsed = exports.getDeclarationOfBindingElement = exports.hasSideEffects = exports.SideEffectOptions = exports.isSameLine = exports.isNumericPropertyName = exports.isValidJsxIdentifier = exports.isValidNumericLiteral = exports.isValidPropertyName = exports.isValidPropertyAccess = void 0;
const ts$1 = ts;
const node_1 = requireNode();
const _3_2_1 = require_3_2();
const type_1 = requireType();
function getChildOfKind(node2, kind, sourceFile) {
for (const child of node2.getChildren(sourceFile))
if (child.kind === kind)
return child;
}
exports.getChildOfKind = getChildOfKind;
function isTokenKind(kind) {
return kind >= ts$1.SyntaxKind.FirstToken && kind <= ts$1.SyntaxKind.LastToken;
}
exports.isTokenKind = isTokenKind;
function isNodeKind(kind) {
return kind >= ts$1.SyntaxKind.FirstNode;
}
exports.isNodeKind = isNodeKind;
function isAssignmentKind(kind) {
return kind >= ts$1.SyntaxKind.FirstAssignment && kind <= ts$1.SyntaxKind.LastAssignment;
}
exports.isAssignmentKind = isAssignmentKind;
function isTypeNodeKind(kind) {
return kind >= ts$1.SyntaxKind.FirstTypeNode && kind <= ts$1.SyntaxKind.LastTypeNode;
}
exports.isTypeNodeKind = isTypeNodeKind;
function isJsDocKind(kind) {
return kind >= ts$1.SyntaxKind.FirstJSDocNode && kind <= ts$1.SyntaxKind.LastJSDocNode;
}
exports.isJsDocKind = isJsDocKind;
function isKeywordKind(kind) {
return kind >= ts$1.SyntaxKind.FirstKeyword && kind <= ts$1.SyntaxKind.LastKeyword;
}
exports.isKeywordKind = isKeywordKind;
function isThisParameter(parameter) {
return parameter.name.kind === ts$1.SyntaxKind.Identifier && parameter.name.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword;
}
exports.isThisParameter = isThisParameter;
function getModifier(node2, kind) {
if (node2.modifiers !== void 0) {
for (const modifier of node2.modifiers)
if (modifier.kind === kind)
return modifier;
}
}
exports.getModifier = getModifier;
function hasModifier(modifiers, ...kinds) {
if (modifiers === void 0)
return false;
for (const modifier of modifiers)
if (kinds.includes(modifier.kind))
return true;
return false;
}
exports.hasModifier = hasModifier;
function isParameterProperty(node2) {
return hasModifier(node2.modifiers, ts$1.SyntaxKind.PublicKeyword, ts$1.SyntaxKind.ProtectedKeyword, ts$1.SyntaxKind.PrivateKeyword, ts$1.SyntaxKind.ReadonlyKeyword);
}
exports.isParameterProperty = isParameterProperty;
function hasAccessModifier(node2) {
return isModifierFlagSet(node2, ts$1.ModifierFlags.AccessibilityModifier);
}
exports.hasAccessModifier = hasAccessModifier;
function isFlagSet(obj, flag) {
return (obj.flags & flag) !== 0;
}
exports.isNodeFlagSet = isFlagSet;
exports.isTypeFlagSet = isFlagSet;
exports.isSymbolFlagSet = isFlagSet;
function isObjectFlagSet(objectType, flag) {
return (objectType.objectFlags & flag) !== 0;
}
exports.isObjectFlagSet = isObjectFlagSet;
function isModifierFlagSet(node2, flag) {
return (ts$1.getCombinedModifierFlags(node2) & flag) !== 0;
}
exports.isModifierFlagSet = isModifierFlagSet;
function getPreviousStatement(statement) {
const parent = statement.parent;
if (node_1.isBlockLike(parent)) {
const index = parent.statements.indexOf(statement);
if (index > 0)
return parent.statements[index - 1];
}
}
exports.getPreviousStatement = getPreviousStatement;
function getNextStatement(statement) {
const parent = statement.parent;
if (node_1.isBlockLike(parent)) {
const index = parent.statements.indexOf(statement);
if (index < parent.statements.length)
return parent.statements[index + 1];
}
}
exports.getNextStatement = getNextStatement;
function getPreviousToken(node2, sourceFile) {
const { pos } = node2;
if (pos === 0)
return;
do
node2 = node2.parent;
while (node2.pos === pos);
return getTokenAtPositionWorker(node2, pos - 1, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false);
}
exports.getPreviousToken = getPreviousToken;
function getNextToken(node2, sourceFile) {
if (node2.kind === ts$1.SyntaxKind.SourceFile || node2.kind === ts$1.SyntaxKind.EndOfFileToken)
return;
const end = node2.end;
node2 = node2.parent;
while (node2.end === end) {
if (node2.parent === void 0)
return node2.endOfFileToken;
node2 = node2.parent;
}
return getTokenAtPositionWorker(node2, end, sourceFile !== null && sourceFile !== void 0 ? sourceFile : node2.getSourceFile(), false);
}
exports.getNextToken = getNextToken;
function getTokenAtPosition(parent, pos, sourceFile, allowJsDoc) {
if (pos < parent.pos || pos >= parent.end)
return;
if (isTokenKind(parent.kind))
return parent;
return getTokenAtPositionWorker(parent, pos, sourceFile !== null && sourceFile !== void 0 ? sourceFile : parent.getSourceFile(), allowJsDoc === true);
}
exports.getTokenAtPosition = getTokenAtPosition;
function getTokenAtPositionWorker(node2, pos, sourceFile, allowJsDoc) {
if (!allowJsDoc) {
node2 = getAstNodeAtPosition(node2, pos);
if (isTokenKind(node2.kind))
return node2;
}
outer:
while (true) {
for (const child of node2.getChildren(sourceFile)) {
if (child.end > pos && (allowJsDoc || child.kind !== ts$1.SyntaxKind.JSDocComment)) {
if (isTokenKind(child.kind))
return child;
node2 = child;
continue outer;
}
}
return;
}
}
function getCommentAtPosition(sourceFile, pos, parent = sourceFile) {
const token = getTokenAtPosition(parent, pos, sourceFile);
if (token === void 0 || token.kind === ts$1.SyntaxKind.JsxText || pos >= token.end - (ts$1.tokenToString(token.kind) || "").length)
return;
const startPos = token.pos === 0 ? (ts$1.getShebang(sourceFile.text) || "").length : token.pos;
return startPos !== 0 && ts$1.forEachTrailingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos) || ts$1.forEachLeadingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos);
}
exports.getCommentAtPosition = getCommentAtPosition;
function commentAtPositionCallback(pos, end, kind, _nl, at) {
return at >= pos && at < end ? { pos, end, kind } : void 0;
}
function isPositionInComment(sourceFile, pos, parent) {
return getCommentAtPosition(sourceFile, pos, parent) !== void 0;
}
exports.isPositionInComment = isPositionInComment;
function commentText(sourceText, comment) {
return sourceText.substring(comment.pos + 2, comment.kind === ts$1.SyntaxKind.SingleLineCommentTrivia ? comment.end : comment.end - 2);
}
exports.commentText = commentText;
function getAstNodeAtPosition(node2, pos) {
if (node2.pos > pos || node2.end <= pos)
return;
while (isNodeKind(node2.kind)) {
const nested = ts$1.forEachChild(node2, (child) => child.pos <= pos && child.end > pos ? child : void 0);
if (nested === void 0)
break;
node2 = nested;
}
return node2;
}
exports.getAstNodeAtPosition = getAstNodeAtPosition;
function getWrappedNodeAtPosition(wrap, pos) {
if (wrap.node.pos > pos || wrap.node.end <= pos)
return;
outer:
while (true) {
for (const child of wrap.children) {
if (child.node.pos > pos)
return wrap;
if (child.node.end > pos) {
wrap = child;
continue outer;
}
}
return wrap;
}
}
exports.getWrappedNodeAtPosition = getWrappedNodeAtPosition;
function getPropertyName(propertyName) {
if (propertyName.kind === ts$1.SyntaxKind.ComputedPropertyName) {
const expression = unwrapParentheses(propertyName.expression);
if (node_1.isPrefixUnaryExpression(expression)) {
let negate = false;
switch (expression.operator) {
case ts$1.SyntaxKind.MinusToken:
negate = true;
case ts$1.SyntaxKind.PlusToken:
return node_1.isNumericLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text}` : _3_2_1.isBigIntLiteral(expression.operand) ? `${negate ? "-" : ""}${expression.operand.text.slice(0, -1)}` : void 0;
default:
return;
}
}
if (_3_2_1.isBigIntLiteral(expression))
return expression.text.slice(0, -1);
if (node_1.isNumericOrStringLikeLiteral(expression))
return expression.text;
return;
}
return propertyName.kind === ts$1.SyntaxKind.PrivateIdentifier ? void 0 : propertyName.text;
}
exports.getPropertyName = getPropertyName;
function forEachDestructuringIdentifier(pattern, fn) {
for (const element of pattern.elements) {
if (element.kind !== ts$1.SyntaxKind.BindingElement)
continue;
let result;
if (element.name.kind === ts$1.SyntaxKind.Identifier) {
result = fn(element);
} else {
result = forEachDestructuringIdentifier(element.name, fn);
}
if (result)
return result;
}
}
exports.forEachDestructuringIdentifier = forEachDestructuringIdentifier;
function forEachDeclaredVariable(declarationList, cb) {
for (const declaration of declarationList.declarations) {
let result;
if (declaration.name.kind === ts$1.SyntaxKind.Identifier) {
result = cb(declaration);
} else {
result = forEachDestructuringIdentifier(declaration.name, cb);
}
if (result)
return result;
}
}
exports.forEachDeclaredVariable = forEachDeclaredVariable;
(function(VariableDeclarationKind) {
VariableDeclarationKind[VariableDeclarationKind["Var"] = 0] = "Var";
VariableDeclarationKind[VariableDeclarationKind["Let"] = 1] = "Let";
VariableDeclarationKind[VariableDeclarationKind["Const"] = 2] = "Const";
})(exports.VariableDeclarationKind || (exports.VariableDeclarationKind = {}));
function getVariableDeclarationKind(declarationList) {
if (declarationList.flags & ts$1.NodeFlags.Let)
return 1;
if (declarationList.flags & ts$1.NodeFlags.Const)
return 2;
return 0;
}
exports.getVariableDeclarationKind = getVariableDeclarationKind;
function isBlockScopedVariableDeclarationList(declarationList) {
return (declarationList.flags & ts$1.NodeFlags.BlockScoped) !== 0;
}
exports.isBlockScopedVariableDeclarationList = isBlockScopedVariableDeclarationList;
function isBlockScopedVariableDeclaration(declaration) {
const parent = declaration.parent;
return parent.kind === ts$1.SyntaxKind.CatchClause || isBlockScopedVariableDeclarationList(parent);
}
exports.isBlockScopedVariableDeclaration = isBlockScopedVariableDeclaration;
function isBlockScopedDeclarationStatement(statement) {
switch (statement.kind) {
case ts$1.SyntaxKind.VariableStatement:
return isBlockScopedVariableDeclarationList(statement.declarationList);
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.EnumDeclaration:
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
return true;
default:
return false;
}
}
exports.isBlockScopedDeclarationStatement = isBlockScopedDeclarationStatement;
function isInSingleStatementContext(statement) {
switch (statement.parent.kind) {
case ts$1.SyntaxKind.ForStatement:
case ts$1.SyntaxKind.ForInStatement:
case ts$1.SyntaxKind.ForOfStatement:
case ts$1.SyntaxKind.WhileStatement:
case ts$1.SyntaxKind.DoStatement:
case ts$1.SyntaxKind.IfStatement:
case ts$1.SyntaxKind.WithStatement:
case ts$1.SyntaxKind.LabeledStatement:
return true;
default:
return false;
}
}
exports.isInSingleStatementContext = isInSingleStatementContext;
(function(ScopeBoundary) {
ScopeBoundary[ScopeBoundary["None"] = 0] = "None";
ScopeBoundary[ScopeBoundary["Function"] = 1] = "Function";
ScopeBoundary[ScopeBoundary["Block"] = 2] = "Block";
ScopeBoundary[ScopeBoundary["Type"] = 4] = "Type";
ScopeBoundary[ScopeBoundary["ConditionalType"] = 8] = "ConditionalType";
})(exports.ScopeBoundary || (exports.ScopeBoundary = {}));
(function(ScopeBoundarySelector) {
ScopeBoundarySelector[ScopeBoundarySelector["Function"] = 1] = "Function";
ScopeBoundarySelector[ScopeBoundarySelector["Block"] = 3] = "Block";
ScopeBoundarySelector[ScopeBoundarySelector["Type"] = 7] = "Type";
ScopeBoundarySelector[ScopeBoundarySelector["InferType"] = 8] = "InferType";
})(exports.ScopeBoundarySelector || (exports.ScopeBoundarySelector = {}));
function isScopeBoundary(node2) {
return isFunctionScopeBoundary(node2) || isBlockScopeBoundary(node2) || isTypeScopeBoundary(node2);
}
exports.isScopeBoundary = isScopeBoundary;
function isTypeScopeBoundary(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
case ts$1.SyntaxKind.MappedType:
return 4;
case ts$1.SyntaxKind.ConditionalType:
return 8;
default:
return 0;
}
}
exports.isTypeScopeBoundary = isTypeScopeBoundary;
function isFunctionScopeBoundary(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.ArrowFunction:
case ts$1.SyntaxKind.Constructor:
case ts$1.SyntaxKind.ModuleDeclaration:
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.ClassExpression:
case ts$1.SyntaxKind.EnumDeclaration:
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
case ts$1.SyntaxKind.MethodSignature:
case ts$1.SyntaxKind.CallSignature:
case ts$1.SyntaxKind.ConstructSignature:
case ts$1.SyntaxKind.ConstructorType:
case ts$1.SyntaxKind.FunctionType:
return 1;
case ts$1.SyntaxKind.SourceFile:
return ts$1.isExternalModule(node2) ? 1 : 0;
default:
return 0;
}
}
exports.isFunctionScopeBoundary = isFunctionScopeBoundary;
function isBlockScopeBoundary(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.Block:
const parent = node2.parent;
return parent.kind !== ts$1.SyntaxKind.CatchClause && // blocks inside SourceFile are block scope boundaries
(parent.kind === ts$1.SyntaxKind.SourceFile || // blocks that are direct children of a function scope boundary are no scope boundary
// for example the FunctionBlock is part of the function scope of the containing function
!isFunctionScopeBoundary(parent)) ? 2 : 0;
case ts$1.SyntaxKind.ForStatement:
case ts$1.SyntaxKind.ForInStatement:
case ts$1.SyntaxKind.ForOfStatement:
case ts$1.SyntaxKind.CaseBlock:
case ts$1.SyntaxKind.CatchClause:
case ts$1.SyntaxKind.WithStatement:
return 2;
default:
return 0;
}
}
exports.isBlockScopeBoundary = isBlockScopeBoundary;
function hasOwnThisReference(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.ClassExpression:
case ts$1.SyntaxKind.FunctionExpression:
return true;
case ts$1.SyntaxKind.FunctionDeclaration:
return node2.body !== void 0;
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
return node2.parent.kind === ts$1.SyntaxKind.ObjectLiteralExpression;
default:
return false;
}
}
exports.hasOwnThisReference = hasOwnThisReference;
function isFunctionWithBody(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.Constructor:
return node2.body !== void 0;
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.ArrowFunction:
return true;
default:
return false;
}
}
exports.isFunctionWithBody = isFunctionWithBody;
function forEachToken(node2, cb, sourceFile = node2.getSourceFile()) {
const queue = [];
while (true) {
if (isTokenKind(node2.kind)) {
cb(node2);
} else if (node2.kind !== ts$1.SyntaxKind.JSDocComment) {
const children = node2.getChildren(sourceFile);
if (children.length === 1) {
node2 = children[0];
continue;
}
for (let i = children.length - 1; i >= 0; --i)
queue.push(children[i]);
}
if (queue.length === 0)
break;
node2 = queue.pop();
}
}
exports.forEachToken = forEachToken;
function forEachTokenWithTrivia(node2, cb, sourceFile = node2.getSourceFile()) {
const fullText = sourceFile.text;
const scanner = ts$1.createScanner(sourceFile.languageVersion, false, sourceFile.languageVariant, fullText);
return forEachToken(node2, (token) => {
const tokenStart = token.kind === ts$1.SyntaxKind.JsxText || token.pos === token.end ? token.pos : token.getStart(sourceFile);
if (tokenStart !== token.pos) {
scanner.setTextPos(token.pos);
let kind = scanner.scan();
let pos = scanner.getTokenPos();
while (pos < tokenStart) {
const textPos = scanner.getTextPos();
cb(fullText, kind, { pos, end: textPos }, token.parent);
if (textPos === tokenStart)
break;
kind = scanner.scan();
pos = scanner.getTokenPos();
}
}
return cb(fullText, token.kind, { end: token.end, pos: tokenStart }, token.parent);
}, sourceFile);
}
exports.forEachTokenWithTrivia = forEachTokenWithTrivia;
function forEachComment(node2, cb, sourceFile = node2.getSourceFile()) {
const fullText = sourceFile.text;
const notJsx = sourceFile.languageVariant !== ts$1.LanguageVariant.JSX;
return forEachToken(node2, (token) => {
if (token.pos === token.end)
return;
if (token.kind !== ts$1.SyntaxKind.JsxText)
ts$1.forEachLeadingCommentRange(
fullText,
// skip shebang at position 0
token.pos === 0 ? (ts$1.getShebang(fullText) || "").length : token.pos,
commentCallback
);
if (notJsx || canHaveTrailingTrivia(token))
return ts$1.forEachTrailingCommentRange(fullText, token.end, commentCallback);
}, sourceFile);
function commentCallback(pos, end, kind) {
cb(fullText, { pos, end, kind });
}
}
exports.forEachComment = forEachComment;
function canHaveTrailingTrivia(token) {
switch (token.kind) {
case ts$1.SyntaxKind.CloseBraceToken:
return token.parent.kind !== ts$1.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent.parent);
case ts$1.SyntaxKind.GreaterThanToken:
switch (token.parent.kind) {
case ts$1.SyntaxKind.JsxOpeningElement:
return token.end !== token.parent.end;
case ts$1.SyntaxKind.JsxOpeningFragment:
return false;
case ts$1.SyntaxKind.JsxSelfClosingElement:
return token.end !== token.parent.end || // if end is not equal, this is part of the type arguments list
!isJsxElementOrFragment(token.parent.parent);
case ts$1.SyntaxKind.JsxClosingElement:
case ts$1.SyntaxKind.JsxClosingFragment:
return !isJsxElementOrFragment(token.parent.parent.parent);
}
}
return true;
}
function isJsxElementOrFragment(node2) {
return node2.kind === ts$1.SyntaxKind.JsxElement || node2.kind === ts$1.SyntaxKind.JsxFragment;
}
function getLineRanges(sourceFile) {
const lineStarts = sourceFile.getLineStarts();
const result = [];
const length = lineStarts.length;
const sourceText = sourceFile.text;
let pos = 0;
for (let i = 1; i < length; ++i) {
const end = lineStarts[i];
let lineEnd = end;
for (; lineEnd > pos; --lineEnd)
if (!ts$1.isLineBreak(sourceText.charCodeAt(lineEnd - 1)))
break;
result.push({
pos,
end,
contentLength: lineEnd - pos
});
pos = end;
}
result.push({
pos,
end: sourceFile.end,
contentLength: sourceFile.end - pos
});
return result;
}
exports.getLineRanges = getLineRanges;
function getLineBreakStyle(sourceFile) {
const lineStarts = sourceFile.getLineStarts();
return lineStarts.length === 1 || lineStarts[1] < 2 || sourceFile.text[lineStarts[1] - 2] !== "\r" ? "\n" : "\r\n";
}
exports.getLineBreakStyle = getLineBreakStyle;
let cachedScanner;
function scanToken(text, languageVersion) {
if (cachedScanner === void 0) {
cachedScanner = ts$1.createScanner(languageVersion, false, void 0, text);
} else {
cachedScanner.setScriptTarget(languageVersion);
cachedScanner.setText(text);
}
cachedScanner.scan();
return cachedScanner;
}
function isValidIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) {
const scan = scanToken(text, languageVersion);
return scan.isIdentifier() && scan.getTextPos() === text.length && scan.getTokenPos() === 0;
}
exports.isValidIdentifier = isValidIdentifier;
function charSize(ch) {
return ch >= 65536 ? 2 : 1;
}
function isValidPropertyAccess(text, languageVersion = ts$1.ScriptTarget.Latest) {
if (text.length === 0)
return false;
let ch = text.codePointAt(0);
if (!ts$1.isIdentifierStart(ch, languageVersion))
return false;
for (let i = charSize(ch); i < text.length; i += charSize(ch)) {
ch = text.codePointAt(i);
if (!ts$1.isIdentifierPart(ch, languageVersion))
return false;
}
return true;
}
exports.isValidPropertyAccess = isValidPropertyAccess;
function isValidPropertyName(text, languageVersion = ts$1.ScriptTarget.Latest) {
if (isValidPropertyAccess(text, languageVersion))
return true;
const scan = scanToken(text, languageVersion);
return scan.getTextPos() === text.length && scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTokenValue() === text;
}
exports.isValidPropertyName = isValidPropertyName;
function isValidNumericLiteral(text, languageVersion = ts$1.ScriptTarget.Latest) {
const scan = scanToken(text, languageVersion);
return scan.getToken() === ts$1.SyntaxKind.NumericLiteral && scan.getTextPos() === text.length && scan.getTokenPos() === 0;
}
exports.isValidNumericLiteral = isValidNumericLiteral;
function isValidJsxIdentifier(text, languageVersion = ts$1.ScriptTarget.Latest) {
if (text.length === 0)
return false;
let seenNamespaceSeparator = false;
let ch = text.codePointAt(0);
if (!ts$1.isIdentifierStart(ch, languageVersion))
return false;
for (let i = charSize(ch); i < text.length; i += charSize(ch)) {
ch = text.codePointAt(i);
if (!ts$1.isIdentifierPart(ch, languageVersion) && ch !== 45) {
if (!seenNamespaceSeparator && ch === 58 && i + charSize(ch) !== text.length) {
seenNamespaceSeparator = true;
} else {
return false;
}
}
}
return true;
}
exports.isValidJsxIdentifier = isValidJsxIdentifier;
function isNumericPropertyName(name) {
return String(+name) === name;
}
exports.isNumericPropertyName = isNumericPropertyName;
function isSameLine(sourceFile, pos1, pos2) {
return ts$1.getLineAndCharacterOfPosition(sourceFile, pos1).line === ts$1.getLineAndCharacterOfPosition(sourceFile, pos2).line;
}
exports.isSameLine = isSameLine;
(function(SideEffectOptions) {
SideEffectOptions[SideEffectOptions["None"] = 0] = "None";
SideEffectOptions[SideEffectOptions["TaggedTemplate"] = 1] = "TaggedTemplate";
SideEffectOptions[SideEffectOptions["Constructor"] = 2] = "Constructor";
SideEffectOptions[SideEffectOptions["JsxElement"] = 4] = "JsxElement";
})(exports.SideEffectOptions || (exports.SideEffectOptions = {}));
function hasSideEffects(node2, options) {
var _a, _b;
const queue = [];
while (true) {
switch (node2.kind) {
case ts$1.SyntaxKind.CallExpression:
case ts$1.SyntaxKind.PostfixUnaryExpression:
case ts$1.SyntaxKind.AwaitExpression:
case ts$1.SyntaxKind.YieldExpression:
case ts$1.SyntaxKind.DeleteExpression:
return true;
case ts$1.SyntaxKind.TypeAssertionExpression:
case ts$1.SyntaxKind.AsExpression:
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.NonNullExpression:
case ts$1.SyntaxKind.VoidExpression:
case ts$1.SyntaxKind.TypeOfExpression:
case ts$1.SyntaxKind.PropertyAccessExpression:
case ts$1.SyntaxKind.SpreadElement:
case ts$1.SyntaxKind.PartiallyEmittedExpression:
node2 = node2.expression;
continue;
case ts$1.SyntaxKind.BinaryExpression:
if (isAssignmentKind(node2.operatorToken.kind))
return true;
queue.push(node2.right);
node2 = node2.left;
continue;
case ts$1.SyntaxKind.PrefixUnaryExpression:
switch (node2.operator) {
case ts$1.SyntaxKind.PlusPlusToken:
case ts$1.SyntaxKind.MinusMinusToken:
return true;
default:
node2 = node2.operand;
continue;
}
case ts$1.SyntaxKind.ElementAccessExpression:
if (node2.argumentExpression !== void 0)
queue.push(node2.argumentExpression);
node2 = node2.expression;
continue;
case ts$1.SyntaxKind.ConditionalExpression:
queue.push(node2.whenTrue, node2.whenFalse);
node2 = node2.condition;
continue;
case ts$1.SyntaxKind.NewExpression:
if (options & 2)
return true;
if (node2.arguments !== void 0)
queue.push(...node2.arguments);
node2 = node2.expression;
continue;
case ts$1.SyntaxKind.TaggedTemplateExpression:
if (options & 1)
return true;
queue.push(node2.tag);
node2 = node2.template;
if (node2.kind === ts$1.SyntaxKind.NoSubstitutionTemplateLiteral)
break;
case ts$1.SyntaxKind.TemplateExpression:
for (const child of node2.templateSpans)
queue.push(child.expression);
break;
case ts$1.SyntaxKind.ClassExpression: {
if (node2.decorators !== void 0)
return true;
for (const child of node2.members) {
if (child.decorators !== void 0)
return true;
if (!hasModifier(child.modifiers, ts$1.SyntaxKind.DeclareKeyword)) {
if (((_a = child.name) === null || _a === void 0 ? void 0 : _a.kind) === ts$1.SyntaxKind.ComputedPropertyName)
queue.push(child.name.expression);
if (node_1.isMethodDeclaration(child)) {
for (const p of child.parameters)
if (p.decorators !== void 0)
return true;
} else if (node_1.isPropertyDeclaration(child) && child.initializer !== void 0 && hasModifier(child.modifiers, ts$1.SyntaxKind.StaticKeyword)) {
queue.push(child.initializer);
}
}
}
const base = getBaseOfClassLikeExpression(node2);
if (base === void 0)
break;
node2 = base.expression;
continue;
}
case ts$1.SyntaxKind.ArrayLiteralExpression:
queue.push(...node2.elements);
break;
case ts$1.SyntaxKind.ObjectLiteralExpression:
for (const child of node2.properties) {
if (((_b = child.name) === null || _b === void 0 ? void 0 : _b.kind) === ts$1.SyntaxKind.ComputedPropertyName)
queue.push(child.name.expression);
switch (child.kind) {
case ts$1.SyntaxKind.PropertyAssignment:
queue.push(child.initializer);
break;
case ts$1.SyntaxKind.SpreadAssignment:
queue.push(child.expression);
}
}
break;
case ts$1.SyntaxKind.JsxExpression:
if (node2.expression === void 0)
break;
node2 = node2.expression;
continue;
case ts$1.SyntaxKind.JsxElement:
case ts$1.SyntaxKind.JsxFragment:
for (const child of node2.children)
if (child.kind !== ts$1.SyntaxKind.JsxText)
queue.push(child);
if (node2.kind === ts$1.SyntaxKind.JsxFragment)
break;
node2 = node2.openingElement;
case ts$1.SyntaxKind.JsxSelfClosingElement:
case ts$1.SyntaxKind.JsxOpeningElement:
if (options & 4)
return true;
for (const child of node2.attributes.properties) {
if (child.kind === ts$1.SyntaxKind.JsxSpreadAttribute) {
queue.push(child.expression);
} else if (child.initializer !== void 0) {
queue.push(child.initializer);
}
}
break;
case ts$1.SyntaxKind.CommaListExpression:
queue.push(...node2.elements);
}
if (queue.length === 0)
return false;
node2 = queue.pop();
}
}
exports.hasSideEffects = hasSideEffects;
function getDeclarationOfBindingElement(node2) {
let parent = node2.parent.parent;
while (parent.kind === ts$1.SyntaxKind.BindingElement)
parent = parent.parent.parent;
return parent;
}
exports.getDeclarationOfBindingElement = getDeclarationOfBindingElement;
function isExpressionValueUsed(node2) {
while (true) {
const parent = node2.parent;
switch (parent.kind) {
case ts$1.SyntaxKind.CallExpression:
case ts$1.SyntaxKind.NewExpression:
case ts$1.SyntaxKind.ElementAccessExpression:
case ts$1.SyntaxKind.WhileStatement:
case ts$1.SyntaxKind.DoStatement:
case ts$1.SyntaxKind.WithStatement:
case ts$1.SyntaxKind.ThrowStatement:
case ts$1.SyntaxKind.ReturnStatement:
case ts$1.SyntaxKind.JsxExpression:
case ts$1.SyntaxKind.JsxSpreadAttribute:
case ts$1.SyntaxKind.JsxElement:
case ts$1.SyntaxKind.JsxFragment:
case ts$1.SyntaxKind.JsxSelfClosingElement:
case ts$1.SyntaxKind.ComputedPropertyName:
case ts$1.SyntaxKind.ArrowFunction:
case ts$1.SyntaxKind.ExportSpecifier:
case ts$1.SyntaxKind.ExportAssignment:
case ts$1.SyntaxKind.ImportDeclaration:
case ts$1.SyntaxKind.ExternalModuleReference:
case ts$1.SyntaxKind.Decorator:
case ts$1.SyntaxKind.TaggedTemplateExpression:
case ts$1.SyntaxKind.TemplateSpan:
case ts$1.SyntaxKind.ExpressionWithTypeArguments:
case ts$1.SyntaxKind.TypeOfExpression:
case ts$1.SyntaxKind.AwaitExpression:
case ts$1.SyntaxKind.YieldExpression:
case ts$1.SyntaxKind.LiteralType:
case ts$1.SyntaxKind.JsxAttributes:
case ts$1.SyntaxKind.JsxOpeningElement:
case ts$1.SyntaxKind.JsxClosingElement:
case ts$1.SyntaxKind.IfStatement:
case ts$1.SyntaxKind.CaseClause:
case ts$1.SyntaxKind.SwitchStatement:
return true;
case ts$1.SyntaxKind.PropertyAccessExpression:
return parent.expression === node2;
case ts$1.SyntaxKind.QualifiedName:
return parent.left === node2;
case ts$1.SyntaxKind.ShorthandPropertyAssignment:
return parent.objectAssignmentInitializer === node2 || !isInDestructuringAssignment(parent);
case ts$1.SyntaxKind.PropertyAssignment:
return parent.initializer === node2 && !isInDestructuringAssignment(parent);
case ts$1.SyntaxKind.SpreadAssignment:
case ts$1.SyntaxKind.SpreadElement:
case ts$1.SyntaxKind.ArrayLiteralExpression:
return !isInDestructuringAssignment(parent);
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.AsExpression:
case ts$1.SyntaxKind.TypeAssertionExpression:
case ts$1.SyntaxKind.PostfixUnaryExpression:
case ts$1.SyntaxKind.PrefixUnaryExpression:
case ts$1.SyntaxKind.NonNullExpression:
node2 = parent;
continue;
case ts$1.SyntaxKind.ForStatement:
return parent.condition === node2;
case ts$1.SyntaxKind.ForInStatement:
case ts$1.SyntaxKind.ForOfStatement:
return parent.expression === node2;
case ts$1.SyntaxKind.ConditionalExpression:
if (parent.condition === node2)
return true;
node2 = parent;
break;
case ts$1.SyntaxKind.PropertyDeclaration:
case ts$1.SyntaxKind.BindingElement:
case ts$1.SyntaxKind.VariableDeclaration:
case ts$1.SyntaxKind.Parameter:
case ts$1.SyntaxKind.EnumMember:
return parent.initializer === node2;
case ts$1.SyntaxKind.ImportEqualsDeclaration:
return parent.moduleReference === node2;
case ts$1.SyntaxKind.CommaListExpression:
if (parent.elements[parent.elements.length - 1] !== node2)
return false;
node2 = parent;
break;
case ts$1.SyntaxKind.BinaryExpression:
if (parent.right === node2) {
if (parent.operatorToken.kind === ts$1.SyntaxKind.CommaToken) {
node2 = parent;
break;
}
return true;
}
switch (parent.operatorToken.kind) {
case ts$1.SyntaxKind.CommaToken:
case ts$1.SyntaxKind.EqualsToken:
return false;
case ts$1.SyntaxKind.EqualsEqualsEqualsToken:
case ts$1.SyntaxKind.EqualsEqualsToken:
case ts$1.SyntaxKind.ExclamationEqualsEqualsToken:
case ts$1.SyntaxKind.ExclamationEqualsToken:
case ts$1.SyntaxKind.InstanceOfKeyword:
case ts$1.SyntaxKind.PlusToken:
case ts$1.SyntaxKind.MinusToken:
case ts$1.SyntaxKind.AsteriskToken:
case ts$1.SyntaxKind.SlashToken:
case ts$1.SyntaxKind.PercentToken:
case ts$1.SyntaxKind.AsteriskAsteriskToken:
case ts$1.SyntaxKind.GreaterThanToken:
case ts$1.SyntaxKind.GreaterThanGreaterThanToken:
case ts$1.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
case ts$1.SyntaxKind.GreaterThanEqualsToken:
case ts$1.SyntaxKind.LessThanToken:
case ts$1.SyntaxKind.LessThanLessThanToken:
case ts$1.SyntaxKind.LessThanEqualsToken:
case ts$1.SyntaxKind.AmpersandToken:
case ts$1.SyntaxKind.BarToken:
case ts$1.SyntaxKind.CaretToken:
case ts$1.SyntaxKind.BarBarToken:
case ts$1.SyntaxKind.AmpersandAmpersandToken:
case ts$1.SyntaxKind.QuestionQuestionToken:
case ts$1.SyntaxKind.InKeyword:
case ts$1.SyntaxKind.QuestionQuestionEqualsToken:
case ts$1.SyntaxKind.AmpersandAmpersandEqualsToken:
case ts$1.SyntaxKind.BarBarEqualsToken:
return true;
default:
node2 = parent;
}
break;
default:
return false;
}
}
}
exports.isExpressionValueUsed = isExpressionValueUsed;
function isInDestructuringAssignment(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.ShorthandPropertyAssignment:
if (node2.objectAssignmentInitializer !== void 0)
return true;
case ts$1.SyntaxKind.PropertyAssignment:
case ts$1.SyntaxKind.SpreadAssignment:
node2 = node2.parent;
break;
case ts$1.SyntaxKind.SpreadElement:
if (node2.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression)
return false;
node2 = node2.parent;
}
while (true) {
switch (node2.parent.kind) {
case ts$1.SyntaxKind.BinaryExpression:
return node2.parent.left === node2 && node2.parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken;
case ts$1.SyntaxKind.ForOfStatement:
return node2.parent.initializer === node2;
case ts$1.SyntaxKind.ArrayLiteralExpression:
case ts$1.SyntaxKind.ObjectLiteralExpression:
node2 = node2.parent;
break;
case ts$1.SyntaxKind.SpreadAssignment:
case ts$1.SyntaxKind.PropertyAssignment:
node2 = node2.parent.parent;
break;
case ts$1.SyntaxKind.SpreadElement:
if (node2.parent.parent.kind !== ts$1.SyntaxKind.ArrayLiteralExpression)
return false;
node2 = node2.parent.parent;
break;
default:
return false;
}
}
}
(function(AccessKind) {
AccessKind[AccessKind["None"] = 0] = "None";
AccessKind[AccessKind["Read"] = 1] = "Read";
AccessKind[AccessKind["Write"] = 2] = "Write";
AccessKind[AccessKind["Delete"] = 4] = "Delete";
AccessKind[AccessKind["ReadWrite"] = 3] = "ReadWrite";
AccessKind[AccessKind["Modification"] = 6] = "Modification";
})(exports.AccessKind || (exports.AccessKind = {}));
function getAccessKind(node2) {
const parent = node2.parent;
switch (parent.kind) {
case ts$1.SyntaxKind.DeleteExpression:
return 4;
case ts$1.SyntaxKind.PostfixUnaryExpression:
return 3;
case ts$1.SyntaxKind.PrefixUnaryExpression:
return parent.operator === ts$1.SyntaxKind.PlusPlusToken || parent.operator === ts$1.SyntaxKind.MinusMinusToken ? 3 : 1;
case ts$1.SyntaxKind.BinaryExpression:
return parent.right === node2 ? 1 : !isAssignmentKind(parent.operatorToken.kind) ? 1 : parent.operatorToken.kind === ts$1.SyntaxKind.EqualsToken ? 2 : 3;
case ts$1.SyntaxKind.ShorthandPropertyAssignment:
return parent.objectAssignmentInitializer === node2 ? 1 : isInDestructuringAssignment(parent) ? 2 : 1;
case ts$1.SyntaxKind.PropertyAssignment:
return parent.name === node2 ? 0 : isInDestructuringAssignment(parent) ? 2 : 1;
case ts$1.SyntaxKind.ArrayLiteralExpression:
case ts$1.SyntaxKind.SpreadElement:
case ts$1.SyntaxKind.SpreadAssignment:
return isInDestructuringAssignment(parent) ? 2 : 1;
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.NonNullExpression:
case ts$1.SyntaxKind.TypeAssertionExpression:
case ts$1.SyntaxKind.AsExpression:
return getAccessKind(parent);
case ts$1.SyntaxKind.ForOfStatement:
case ts$1.SyntaxKind.ForInStatement:
return parent.initializer === node2 ? 2 : 1;
case ts$1.SyntaxKind.ExpressionWithTypeArguments:
return parent.parent.token === ts$1.SyntaxKind.ExtendsKeyword && parent.parent.parent.kind !== ts$1.SyntaxKind.InterfaceDeclaration ? 1 : 0;
case ts$1.SyntaxKind.ComputedPropertyName:
case ts$1.SyntaxKind.ExpressionStatement:
case ts$1.SyntaxKind.TypeOfExpression:
case ts$1.SyntaxKind.ElementAccessExpression:
case ts$1.SyntaxKind.ForStatement:
case ts$1.SyntaxKind.IfStatement:
case ts$1.SyntaxKind.DoStatement:
case ts$1.SyntaxKind.WhileStatement:
case ts$1.SyntaxKind.SwitchStatement:
case ts$1.SyntaxKind.WithStatement:
case ts$1.SyntaxKind.ThrowStatement:
case ts$1.SyntaxKind.CallExpression:
case ts$1.SyntaxKind.NewExpression:
case ts$1.SyntaxKind.TaggedTemplateExpression:
case ts$1.SyntaxKind.JsxExpression:
case ts$1.SyntaxKind.Decorator:
case ts$1.SyntaxKind.TemplateSpan:
case ts$1.SyntaxKind.JsxOpeningElement:
case ts$1.SyntaxKind.JsxSelfClosingElement:
case ts$1.SyntaxKind.JsxSpreadAttribute:
case ts$1.SyntaxKind.VoidExpression:
case ts$1.SyntaxKind.ReturnStatement:
case ts$1.SyntaxKind.AwaitExpression:
case ts$1.SyntaxKind.YieldExpression:
case ts$1.SyntaxKind.ConditionalExpression:
case ts$1.SyntaxKind.CaseClause:
case ts$1.SyntaxKind.JsxElement:
return 1;
case ts$1.SyntaxKind.ArrowFunction:
return parent.body === node2 ? 1 : 2;
case ts$1.SyntaxKind.PropertyDeclaration:
case ts$1.SyntaxKind.VariableDeclaration:
case ts$1.SyntaxKind.Parameter:
case ts$1.SyntaxKind.EnumMember:
case ts$1.SyntaxKind.BindingElement:
case ts$1.SyntaxKind.JsxAttribute:
return parent.initializer === node2 ? 1 : 0;
case ts$1.SyntaxKind.PropertyAccessExpression:
return parent.expression === node2 ? 1 : 0;
case ts$1.SyntaxKind.ExportAssignment:
return parent.isExportEquals ? 1 : 0;
}
return 0;
}
exports.getAccessKind = getAccessKind;
function isReassignmentTarget(node2) {
return (getAccessKind(node2) & 2) !== 0;
}
exports.isReassignmentTarget = isReassignmentTarget;
function canHaveJsDoc(node2) {
const kind = node2.kind;
switch (kind) {
case ts$1.SyntaxKind.Parameter:
case ts$1.SyntaxKind.CallSignature:
case ts$1.SyntaxKind.ConstructSignature:
case ts$1.SyntaxKind.MethodSignature:
case ts$1.SyntaxKind.PropertySignature:
case ts$1.SyntaxKind.ArrowFunction:
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.SpreadAssignment:
case ts$1.SyntaxKind.ShorthandPropertyAssignment:
case ts$1.SyntaxKind.PropertyAssignment:
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.LabeledStatement:
case ts$1.SyntaxKind.ExpressionStatement:
case ts$1.SyntaxKind.VariableStatement:
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.Constructor:
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.PropertyDeclaration:
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.ClassExpression:
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
case ts$1.SyntaxKind.EnumMember:
case ts$1.SyntaxKind.EnumDeclaration:
case ts$1.SyntaxKind.ModuleDeclaration:
case ts$1.SyntaxKind.ImportEqualsDeclaration:
case ts$1.SyntaxKind.ImportDeclaration:
case ts$1.SyntaxKind.NamespaceExportDeclaration:
case ts$1.SyntaxKind.ExportAssignment:
case ts$1.SyntaxKind.IndexSignature:
case ts$1.SyntaxKind.FunctionType:
case ts$1.SyntaxKind.ConstructorType:
case ts$1.SyntaxKind.JSDocFunctionType:
case ts$1.SyntaxKind.ExportDeclaration:
case ts$1.SyntaxKind.NamedTupleMember:
case ts$1.SyntaxKind.EndOfFileToken:
return true;
default:
return false;
}
}
exports.canHaveJsDoc = canHaveJsDoc;
function getJsDoc(node2, sourceFile) {
const result = [];
for (const child of node2.getChildren(sourceFile)) {
if (!node_1.isJsDoc(child))
break;
result.push(child);
}
return result;
}
exports.getJsDoc = getJsDoc;
function parseJsDocOfNode(node2, considerTrailingComments, sourceFile = node2.getSourceFile()) {
if (canHaveJsDoc(node2) && node2.kind !== ts$1.SyntaxKind.EndOfFileToken) {
const result = getJsDoc(node2, sourceFile);
if (result.length !== 0 || !considerTrailingComments)
return result;
}
return parseJsDocWorker(node2, node2.getStart(sourceFile), sourceFile, considerTrailingComments);
}
exports.parseJsDocOfNode = parseJsDocOfNode;
function parseJsDocWorker(node2, nodeStart, sourceFile, considerTrailingComments) {
const start = ts$1[considerTrailingComments && isSameLine(sourceFile, node2.pos, nodeStart) ? "forEachTrailingCommentRange" : "forEachLeadingCommentRange"](
sourceFile.text,
node2.pos,
// return object to make `0` a truthy value
(pos, _end, kind) => kind === ts$1.SyntaxKind.MultiLineCommentTrivia && sourceFile.text[pos + 2] === "*" ? { pos } : void 0
);
if (start === void 0)
return [];
const startPos = start.pos;
const text = sourceFile.text.slice(startPos, nodeStart);
const newSourceFile = ts$1.createSourceFile("jsdoc.ts", `${text}var a;`, sourceFile.languageVersion);
const result = getJsDoc(newSourceFile.statements[0], newSourceFile);
for (const doc of result)
updateNode(doc, node2);
return result;
function updateNode(n, parent) {
n.pos += startPos;
n.end += startPos;
n.parent = parent;
return ts$1.forEachChild(n, (child) => updateNode(child, n), (children) => {
children.pos += startPos;
children.end += startPos;
for (const child of children)
updateNode(child, n);
});
}
}
(function(ImportKind) {
ImportKind[ImportKind["ImportDeclaration"] = 1] = "ImportDeclaration";
ImportKind[ImportKind["ImportEquals"] = 2] = "ImportEquals";
ImportKind[ImportKind["ExportFrom"] = 4] = "ExportFrom";
ImportKind[ImportKind["DynamicImport"] = 8] = "DynamicImport";
ImportKind[ImportKind["Require"] = 16] = "Require";
ImportKind[ImportKind["ImportType"] = 32] = "ImportType";
ImportKind[ImportKind["All"] = 63] = "All";
ImportKind[ImportKind["AllImports"] = 59] = "AllImports";
ImportKind[ImportKind["AllStaticImports"] = 3] = "AllStaticImports";
ImportKind[ImportKind["AllImportExpressions"] = 24] = "AllImportExpressions";
ImportKind[ImportKind["AllRequireLike"] = 18] = "AllRequireLike";
ImportKind[ImportKind["AllNestedImports"] = 56] = "AllNestedImports";
ImportKind[ImportKind["AllTopLevelImports"] = 7] = "AllTopLevelImports";
})(exports.ImportKind || (exports.ImportKind = {}));
function findImports(sourceFile, kinds, ignoreFileName = true) {
const result = [];
for (const node2 of findImportLikeNodes(sourceFile, kinds, ignoreFileName)) {
switch (node2.kind) {
case ts$1.SyntaxKind.ImportDeclaration:
addIfTextualLiteral(node2.moduleSpecifier);
break;
case ts$1.SyntaxKind.ImportEqualsDeclaration:
addIfTextualLiteral(node2.moduleReference.expression);
break;
case ts$1.SyntaxKind.ExportDeclaration:
addIfTextualLiteral(node2.moduleSpecifier);
break;
case ts$1.SyntaxKind.CallExpression:
addIfTextualLiteral(node2.arguments[0]);
break;
case ts$1.SyntaxKind.ImportType:
if (node_1.isLiteralTypeNode(node2.argument))
addIfTextualLiteral(node2.argument.literal);
break;
default:
throw new Error("unexpected node");
}
}
return result;
function addIfTextualLiteral(node2) {
if (node_1.isTextualLiteral(node2))
result.push(node2);
}
}
exports.findImports = findImports;
function findImportLikeNodes(sourceFile, kinds, ignoreFileName = true) {
return new ImportFinder(sourceFile, kinds, ignoreFileName).find();
}
exports.findImportLikeNodes = findImportLikeNodes;
class ImportFinder {
constructor(_sourceFile, _options, _ignoreFileName) {
this._sourceFile = _sourceFile;
this._options = _options;
this._ignoreFileName = _ignoreFileName;
this._result = [];
}
find() {
if (this._sourceFile.isDeclarationFile)
this._options &= ~24;
if (this._options & 7)
this._findImports(this._sourceFile.statements);
if (this._options & 56)
this._findNestedImports();
return this._result;
}
_findImports(statements) {
for (const statement of statements) {
if (node_1.isImportDeclaration(statement)) {
if (this._options & 1)
this._result.push(statement);
} else if (node_1.isImportEqualsDeclaration(statement)) {
if (this._options & 2 && statement.moduleReference.kind === ts$1.SyntaxKind.ExternalModuleReference)
this._result.push(statement);
} else if (node_1.isExportDeclaration(statement)) {
if (statement.moduleSpecifier !== void 0 && this._options & 4)
this._result.push(statement);
} else if (node_1.isModuleDeclaration(statement)) {
this._findImportsInModule(statement);
}
}
}
_findImportsInModule(declaration) {
if (declaration.body === void 0)
return;
if (declaration.body.kind === ts$1.SyntaxKind.ModuleDeclaration)
return this._findImportsInModule(declaration.body);
this._findImports(declaration.body.statements);
}
_findNestedImports() {
const isJavaScriptFile = this._ignoreFileName || (this._sourceFile.flags & ts$1.NodeFlags.JavaScriptFile) !== 0;
let re;
let includeJsDoc;
if ((this._options & 56) === 16) {
if (!isJavaScriptFile)
return;
re = /\brequire\s*[(]/g;
includeJsDoc = false;
} else if (this._options & 16 && isJavaScriptFile) {
re = /\b(?:import|require)\s*[(]/g;
includeJsDoc = (this._options & 32) !== 0;
} else {
re = /\bimport\s*[(]/g;
includeJsDoc = isJavaScriptFile && (this._options & 32) !== 0;
}
for (let match2 = re.exec(this._sourceFile.text); match2 !== null; match2 = re.exec(this._sourceFile.text)) {
const token = getTokenAtPositionWorker(
this._sourceFile,
match2.index,
this._sourceFile,
// only look for ImportTypeNode within JSDoc in JS files
match2[0][0] === "i" && includeJsDoc
);
if (token.kind === ts$1.SyntaxKind.ImportKeyword) {
if (token.end - "import".length !== match2.index)
continue;
switch (token.parent.kind) {
case ts$1.SyntaxKind.ImportType:
this._result.push(token.parent);
break;
case ts$1.SyntaxKind.CallExpression:
if (token.parent.arguments.length > 1)
this._result.push(token.parent);
}
} else if (token.kind === ts$1.SyntaxKind.Identifier && token.end - "require".length === match2.index && token.parent.kind === ts$1.SyntaxKind.CallExpression && token.parent.expression === token && token.parent.arguments.length === 1) {
this._result.push(token.parent);
}
}
}
}
function isStatementInAmbientContext(node2) {
while (node2.flags & ts$1.NodeFlags.NestedNamespace)
node2 = node2.parent;
return hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword) || isAmbientModuleBlock(node2.parent);
}
exports.isStatementInAmbientContext = isStatementInAmbientContext;
function isAmbientModuleBlock(node2) {
while (node2.kind === ts$1.SyntaxKind.ModuleBlock) {
do
node2 = node2.parent;
while (node2.flags & ts$1.NodeFlags.NestedNamespace);
if (hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword))
return true;
node2 = node2.parent;
}
return false;
}
exports.isAmbientModuleBlock = isAmbientModuleBlock;
function getIIFE(func) {
let node2 = func.parent;
while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression)
node2 = node2.parent;
return node_1.isCallExpression(node2) && func.end <= node2.expression.end ? node2 : void 0;
}
exports.getIIFE = getIIFE;
function isStrictCompilerOptionEnabled(options, option) {
return (options.strict ? options[option] !== false : options[option] === true) && (option !== "strictPropertyInitialization" || isStrictCompilerOptionEnabled(options, "strictNullChecks"));
}
exports.isStrictCompilerOptionEnabled = isStrictCompilerOptionEnabled;
function isCompilerOptionEnabled(options, option) {
switch (option) {
case "stripInternal":
case "declarationMap":
case "emitDeclarationOnly":
return options[option] === true && isCompilerOptionEnabled(options, "declaration");
case "declaration":
return options.declaration || isCompilerOptionEnabled(options, "composite");
case "incremental":
return options.incremental === void 0 ? isCompilerOptionEnabled(options, "composite") : options.incremental;
case "skipDefaultLibCheck":
return options.skipDefaultLibCheck || isCompilerOptionEnabled(options, "skipLibCheck");
case "suppressImplicitAnyIndexErrors":
return options.suppressImplicitAnyIndexErrors === true && isCompilerOptionEnabled(options, "noImplicitAny");
case "allowSyntheticDefaultImports":
return options.allowSyntheticDefaultImports !== void 0 ? options.allowSyntheticDefaultImports : isCompilerOptionEnabled(options, "esModuleInterop") || options.module === ts$1.ModuleKind.System;
case "noUncheckedIndexedAccess":
return options.noUncheckedIndexedAccess === true && isCompilerOptionEnabled(options, "strictNullChecks");
case "allowJs":
return options.allowJs === void 0 ? isCompilerOptionEnabled(options, "checkJs") : options.allowJs;
case "noImplicitAny":
case "noImplicitThis":
case "strictNullChecks":
case "strictFunctionTypes":
case "strictPropertyInitialization":
case "alwaysStrict":
case "strictBindCallApply":
return isStrictCompilerOptionEnabled(options, option);
}
return options[option] === true;
}
exports.isCompilerOptionEnabled = isCompilerOptionEnabled;
function isAmbientModule(node2) {
return node2.name.kind === ts$1.SyntaxKind.StringLiteral || (node2.flags & ts$1.NodeFlags.GlobalAugmentation) !== 0;
}
exports.isAmbientModule = isAmbientModule;
function getCheckJsDirective(source) {
return getTsCheckDirective(source);
}
exports.getCheckJsDirective = getCheckJsDirective;
function getTsCheckDirective(source) {
let directive;
ts$1.forEachLeadingCommentRange(source, (ts$1.getShebang(source) || "").length, (pos, end, kind) => {
if (kind === ts$1.SyntaxKind.SingleLineCommentTrivia) {
const text = source.slice(pos, end);
const match2 = /^\/{2,3}\s*@ts-(no)?check(?:\s|$)/i.exec(text);
if (match2 !== null)
directive = { pos, end, enabled: match2[1] === void 0 };
}
});
return directive;
}
exports.getTsCheckDirective = getTsCheckDirective;
function isConstAssertion(node2) {
return node_1.isTypeReferenceNode(node2.type) && node2.type.typeName.kind === ts$1.SyntaxKind.Identifier && node2.type.typeName.escapedText === "const";
}
exports.isConstAssertion = isConstAssertion;
function isInConstContext(node2) {
let current = node2;
while (true) {
const parent = current.parent;
outer:
switch (parent.kind) {
case ts$1.SyntaxKind.TypeAssertionExpression:
case ts$1.SyntaxKind.AsExpression:
return isConstAssertion(parent);
case ts$1.SyntaxKind.PrefixUnaryExpression:
if (current.kind !== ts$1.SyntaxKind.NumericLiteral)
return false;
switch (parent.operator) {
case ts$1.SyntaxKind.PlusToken:
case ts$1.SyntaxKind.MinusToken:
current = parent;
break outer;
default:
return false;
}
case ts$1.SyntaxKind.PropertyAssignment:
if (parent.initializer !== current)
return false;
current = parent.parent;
break;
case ts$1.SyntaxKind.ShorthandPropertyAssignment:
current = parent.parent;
break;
case ts$1.SyntaxKind.ParenthesizedExpression:
case ts$1.SyntaxKind.ArrayLiteralExpression:
case ts$1.SyntaxKind.ObjectLiteralExpression:
case ts$1.SyntaxKind.TemplateExpression:
current = parent;
break;
default:
return false;
}
}
}
exports.isInConstContext = isInConstContext;
function isReadonlyAssignmentDeclaration(node2, checker) {
if (!isBindableObjectDefinePropertyCall(node2))
return false;
const descriptorType = checker.getTypeAtLocation(node2.arguments[2]);
if (descriptorType.getProperty("value") === void 0)
return descriptorType.getProperty("set") === void 0;
const writableProp = descriptorType.getProperty("writable");
if (writableProp === void 0)
return false;
const writableType = writableProp.valueDeclaration !== void 0 && node_1.isPropertyAssignment(writableProp.valueDeclaration) ? checker.getTypeAtLocation(writableProp.valueDeclaration.initializer) : checker.getTypeOfSymbolAtLocation(writableProp, node2.arguments[2]);
return type_1.isBooleanLiteralType(writableType, false);
}
exports.isReadonlyAssignmentDeclaration = isReadonlyAssignmentDeclaration;
function isBindableObjectDefinePropertyCall(node2) {
return node2.arguments.length === 3 && node_1.isEntityNameExpression(node2.arguments[0]) && node_1.isNumericOrStringLikeLiteral(node2.arguments[1]) && node_1.isPropertyAccessExpression(node2.expression) && node2.expression.name.escapedText === "defineProperty" && node_1.isIdentifier(node2.expression.expression) && node2.expression.expression.escapedText === "Object";
}
exports.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
function isWellKnownSymbolLiterally(node2) {
return ts$1.isPropertyAccessExpression(node2) && ts$1.isIdentifier(node2.expression) && node2.expression.escapedText === "Symbol";
}
exports.isWellKnownSymbolLiterally = isWellKnownSymbolLiterally;
function getPropertyNameOfWellKnownSymbol(node2) {
return {
displayName: `[Symbol.${node2.name.text}]`,
symbolName: "__@" + node2.name.text
};
}
exports.getPropertyNameOfWellKnownSymbol = getPropertyNameOfWellKnownSymbol;
const isTsBefore43 = (([major, minor]) => major < "4" || major === "4" && minor < "3")(ts$1.versionMajorMinor.split("."));
function getLateBoundPropertyNames(node2, checker) {
const result = {
known: true,
names: []
};
node2 = unwrapParentheses(node2);
if (isTsBefore43 && isWellKnownSymbolLiterally(node2)) {
result.names.push(getPropertyNameOfWellKnownSymbol(node2));
} else {
const type2 = checker.getTypeAtLocation(node2);
for (const key of type_1.unionTypeParts(checker.getBaseConstraintOfType(type2) || type2)) {
const propertyName = type_1.getPropertyNameFromType(key);
if (propertyName) {
result.names.push(propertyName);
} else {
result.known = false;
}
}
}
return result;
}
exports.getLateBoundPropertyNames = getLateBoundPropertyNames;
function getLateBoundPropertyNamesOfPropertyName(node2, checker) {
const staticName = getPropertyName(node2);
return staticName !== void 0 ? { known: true, names: [{ displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) }] } : node2.kind === ts$1.SyntaxKind.PrivateIdentifier ? { known: true, names: [{ displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName }] } : getLateBoundPropertyNames(node2.expression, checker);
}
exports.getLateBoundPropertyNamesOfPropertyName = getLateBoundPropertyNamesOfPropertyName;
function getSingleLateBoundPropertyNameOfPropertyName(node2, checker) {
const staticName = getPropertyName(node2);
if (staticName !== void 0)
return { displayName: staticName, symbolName: ts$1.escapeLeadingUnderscores(staticName) };
if (node2.kind === ts$1.SyntaxKind.PrivateIdentifier)
return { displayName: node2.text, symbolName: checker.getSymbolAtLocation(node2).escapedName };
const { expression } = node2;
return isTsBefore43 && isWellKnownSymbolLiterally(expression) ? getPropertyNameOfWellKnownSymbol(expression) : type_1.getPropertyNameFromType(checker.getTypeAtLocation(expression));
}
exports.getSingleLateBoundPropertyNameOfPropertyName = getSingleLateBoundPropertyNameOfPropertyName;
function unwrapParentheses(node2) {
while (node2.kind === ts$1.SyntaxKind.ParenthesizedExpression)
node2 = node2.expression;
return node2;
}
exports.unwrapParentheses = unwrapParentheses;
function formatPseudoBigInt(v) {
return `${v.negative ? "-" : ""}${v.base10Value}n`;
}
exports.formatPseudoBigInt = formatPseudoBigInt;
function hasExhaustiveCaseClauses(node2, checker) {
const caseClauses = node2.caseBlock.clauses.filter(node_1.isCaseClause);
if (caseClauses.length === 0)
return false;
const typeParts = type_1.unionTypeParts(checker.getTypeAtLocation(node2.expression));
if (typeParts.length > caseClauses.length)
return false;
const types2 = new Set(typeParts.map(getPrimitiveLiteralFromType));
if (types2.has(void 0))
return false;
const seen = /* @__PURE__ */ new Set();
for (const clause of caseClauses) {
const expressionType = checker.getTypeAtLocation(clause.expression);
if (exports.isTypeFlagSet(expressionType, ts$1.TypeFlags.Never))
continue;
const type2 = getPrimitiveLiteralFromType(expressionType);
if (types2.has(type2)) {
seen.add(type2);
} else if (type2 !== "null" && type2 !== "undefined") {
return false;
}
}
return types2.size === seen.size;
}
exports.hasExhaustiveCaseClauses = hasExhaustiveCaseClauses;
function getPrimitiveLiteralFromType(t) {
if (exports.isTypeFlagSet(t, ts$1.TypeFlags.Null))
return "null";
if (exports.isTypeFlagSet(t, ts$1.TypeFlags.Undefined))
return "undefined";
if (exports.isTypeFlagSet(t, ts$1.TypeFlags.NumberLiteral))
return `${exports.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}${t.value}`;
if (exports.isTypeFlagSet(t, ts$1.TypeFlags.StringLiteral))
return `${exports.isTypeFlagSet(t, ts$1.TypeFlags.EnumLiteral) ? "enum:" : ""}string:${t.value}`;
if (exports.isTypeFlagSet(t, ts$1.TypeFlags.BigIntLiteral))
return formatPseudoBigInt(t.value);
if (_3_2_1.isUniqueESSymbolType(t))
return t.escapedName;
if (type_1.isBooleanLiteralType(t, true))
return "true";
if (type_1.isBooleanLiteralType(t, false))
return "false";
}
function getBaseOfClassLikeExpression(node2) {
var _a;
if (((_a = node2.heritageClauses) === null || _a === void 0 ? void 0 : _a[0].token) === ts$1.SyntaxKind.ExtendsKeyword)
return node2.heritageClauses[0].types[0];
}
exports.getBaseOfClassLikeExpression = getBaseOfClassLikeExpression;
})(util$1);
return util$1;
}
var usage = {};
var hasRequiredUsage;
function requireUsage() {
if (hasRequiredUsage)
return usage;
hasRequiredUsage = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectVariableUsage = exports.getDeclarationDomain = exports.getUsageDomain = exports.UsageDomain = exports.DeclarationDomain = void 0;
const util_1 = requireUtil$1();
const ts$1 = ts;
(function(DeclarationDomain) {
DeclarationDomain[DeclarationDomain["Namespace"] = 1] = "Namespace";
DeclarationDomain[DeclarationDomain["Type"] = 2] = "Type";
DeclarationDomain[DeclarationDomain["Value"] = 4] = "Value";
DeclarationDomain[DeclarationDomain["Import"] = 8] = "Import";
DeclarationDomain[DeclarationDomain["Any"] = 7] = "Any";
})(exports.DeclarationDomain || (exports.DeclarationDomain = {}));
(function(UsageDomain) {
UsageDomain[UsageDomain["Namespace"] = 1] = "Namespace";
UsageDomain[UsageDomain["Type"] = 2] = "Type";
UsageDomain[UsageDomain["Value"] = 4] = "Value";
UsageDomain[UsageDomain["ValueOrNamespace"] = 5] = "ValueOrNamespace";
UsageDomain[UsageDomain["Any"] = 7] = "Any";
UsageDomain[UsageDomain["TypeQuery"] = 8] = "TypeQuery";
})(exports.UsageDomain || (exports.UsageDomain = {}));
function getUsageDomain(node2) {
const parent = node2.parent;
switch (parent.kind) {
case ts$1.SyntaxKind.TypeReference:
return node2.originalKeywordKind !== ts$1.SyntaxKind.ConstKeyword ? 2 : void 0;
case ts$1.SyntaxKind.ExpressionWithTypeArguments:
return parent.parent.token === ts$1.SyntaxKind.ImplementsKeyword || parent.parent.parent.kind === ts$1.SyntaxKind.InterfaceDeclaration ? 2 : 4;
case ts$1.SyntaxKind.TypeQuery:
return 5 | 8;
case ts$1.SyntaxKind.QualifiedName:
if (parent.left === node2) {
if (getEntityNameParent(parent).kind === ts$1.SyntaxKind.TypeQuery)
return 1 | 8;
return 1;
}
break;
case ts$1.SyntaxKind.ExportSpecifier:
if (parent.propertyName === void 0 || parent.propertyName === node2)
return 7;
break;
case ts$1.SyntaxKind.ExportAssignment:
return 7;
case ts$1.SyntaxKind.BindingElement:
if (parent.initializer === node2)
return 5;
break;
case ts$1.SyntaxKind.Parameter:
case ts$1.SyntaxKind.EnumMember:
case ts$1.SyntaxKind.PropertyDeclaration:
case ts$1.SyntaxKind.VariableDeclaration:
case ts$1.SyntaxKind.PropertyAssignment:
case ts$1.SyntaxKind.PropertyAccessExpression:
case ts$1.SyntaxKind.ImportEqualsDeclaration:
if (parent.name !== node2)
return 5;
break;
case ts$1.SyntaxKind.JsxAttribute:
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.NamespaceImport:
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.ClassExpression:
case ts$1.SyntaxKind.ModuleDeclaration:
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.EnumDeclaration:
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
case ts$1.SyntaxKind.LabeledStatement:
case ts$1.SyntaxKind.BreakStatement:
case ts$1.SyntaxKind.ContinueStatement:
case ts$1.SyntaxKind.ImportClause:
case ts$1.SyntaxKind.ImportSpecifier:
case ts$1.SyntaxKind.TypePredicate:
case ts$1.SyntaxKind.MethodSignature:
case ts$1.SyntaxKind.PropertySignature:
case ts$1.SyntaxKind.NamespaceExportDeclaration:
case ts$1.SyntaxKind.NamespaceExport:
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
case ts$1.SyntaxKind.TypeParameter:
case ts$1.SyntaxKind.NamedTupleMember:
break;
default:
return 5;
}
}
exports.getUsageDomain = getUsageDomain;
function getDeclarationDomain(node2) {
switch (node2.parent.kind) {
case ts$1.SyntaxKind.TypeParameter:
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
return 2;
case ts$1.SyntaxKind.ClassDeclaration:
case ts$1.SyntaxKind.ClassExpression:
return 2 | 4;
case ts$1.SyntaxKind.EnumDeclaration:
return 7;
case ts$1.SyntaxKind.NamespaceImport:
case ts$1.SyntaxKind.ImportClause:
return 7 | 8;
case ts$1.SyntaxKind.ImportEqualsDeclaration:
case ts$1.SyntaxKind.ImportSpecifier:
return node2.parent.name === node2 ? 7 | 8 : void 0;
case ts$1.SyntaxKind.ModuleDeclaration:
return 1;
case ts$1.SyntaxKind.Parameter:
if (node2.parent.parent.kind === ts$1.SyntaxKind.IndexSignature || node2.originalKeywordKind === ts$1.SyntaxKind.ThisKeyword)
return;
case ts$1.SyntaxKind.BindingElement:
case ts$1.SyntaxKind.VariableDeclaration:
return node2.parent.name === node2 ? 4 : void 0;
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.FunctionExpression:
return 4;
}
}
exports.getDeclarationDomain = getDeclarationDomain;
function collectVariableUsage(sourceFile) {
return new UsageWalker().getUsage(sourceFile);
}
exports.collectVariableUsage = collectVariableUsage;
class AbstractScope {
constructor(_global) {
this._global = _global;
this._variables = /* @__PURE__ */ new Map();
this._uses = [];
this._namespaceScopes = void 0;
this._enumScopes = void 0;
}
addVariable(identifier, name, selector, exported, domain) {
const variables = this.getDestinationScope(selector).getVariables();
const declaration = {
domain,
exported,
declaration: name
};
const variable = variables.get(identifier);
if (variable === void 0) {
variables.set(identifier, {
domain,
declarations: [declaration],
uses: []
});
} else {
variable.domain |= domain;
variable.declarations.push(declaration);
}
}
addUse(use) {
this._uses.push(use);
}
getVariables() {
return this._variables;
}
getFunctionScope() {
return this;
}
end(cb) {
if (this._namespaceScopes !== void 0)
this._namespaceScopes.forEach((value) => value.finish(cb));
this._namespaceScopes = this._enumScopes = void 0;
this._applyUses();
this._variables.forEach((variable) => {
for (const declaration of variable.declarations) {
const result = {
declarations: [],
domain: declaration.domain,
exported: declaration.exported,
inGlobalScope: this._global,
uses: []
};
for (const other of variable.declarations)
if (other.domain & declaration.domain)
result.declarations.push(other.declaration);
for (const use of variable.uses)
if (use.domain & declaration.domain)
result.uses.push(use);
cb(result, declaration.declaration, this);
}
});
}
// tslint:disable-next-line:prefer-function-over-method
markExported(_name) {
}
// only relevant for the root scope
createOrReuseNamespaceScope(name, _exported, ambient, hasExportStatement) {
let scope;
if (this._namespaceScopes === void 0) {
this._namespaceScopes = /* @__PURE__ */ new Map();
} else {
scope = this._namespaceScopes.get(name);
}
if (scope === void 0) {
scope = new NamespaceScope(ambient, hasExportStatement, this);
this._namespaceScopes.set(name, scope);
} else {
scope.refresh(ambient, hasExportStatement);
}
return scope;
}
createOrReuseEnumScope(name, _exported) {
let scope;
if (this._enumScopes === void 0) {
this._enumScopes = /* @__PURE__ */ new Map();
} else {
scope = this._enumScopes.get(name);
}
if (scope === void 0) {
scope = new EnumScope(this);
this._enumScopes.set(name, scope);
}
return scope;
}
_applyUses() {
for (const use of this._uses)
if (!this._applyUse(use))
this._addUseToParent(use);
this._uses = [];
}
_applyUse(use, variables = this._variables) {
const variable = variables.get(use.location.text);
if (variable === void 0 || (variable.domain & use.domain) === 0)
return false;
variable.uses.push(use);
return true;
}
_addUseToParent(_use) {
}
// tslint:disable-line:prefer-function-over-method
}
class RootScope extends AbstractScope {
constructor(_exportAll, global2) {
super(global2);
this._exportAll = _exportAll;
this._exports = void 0;
this._innerScope = new NonRootScope(
this,
1
/* Function */
);
}
addVariable(identifier, name, selector, exported, domain) {
if (domain & 8)
return super.addVariable(identifier, name, selector, exported, domain);
return this._innerScope.addVariable(identifier, name, selector, exported, domain);
}
addUse(use, origin) {
if (origin === this._innerScope)
return super.addUse(use);
return this._innerScope.addUse(use);
}
markExported(id) {
if (this._exports === void 0) {
this._exports = [id.text];
} else {
this._exports.push(id.text);
}
}
end(cb) {
this._innerScope.end((value, key) => {
value.exported = value.exported || this._exportAll || this._exports !== void 0 && this._exports.includes(key.text);
value.inGlobalScope = this._global;
return cb(value, key, this);
});
return super.end((value, key, scope) => {
value.exported = value.exported || scope === this && this._exports !== void 0 && this._exports.includes(key.text);
return cb(value, key, scope);
});
}
getDestinationScope() {
return this;
}
}
class NonRootScope extends AbstractScope {
constructor(_parent, _boundary) {
super(false);
this._parent = _parent;
this._boundary = _boundary;
}
_addUseToParent(use) {
return this._parent.addUse(use, this);
}
getDestinationScope(selector) {
return this._boundary & selector ? this : this._parent.getDestinationScope(selector);
}
}
class EnumScope extends NonRootScope {
constructor(parent) {
super(
parent,
1
/* Function */
);
}
end() {
this._applyUses();
}
}
class ConditionalTypeScope extends NonRootScope {
constructor(parent) {
super(
parent,
8
/* ConditionalType */
);
this._state = 0;
}
updateState(newState) {
this._state = newState;
}
addUse(use) {
if (this._state === 2)
return void this._uses.push(use);
return this._parent.addUse(use, this);
}
}
class FunctionScope extends NonRootScope {
constructor(parent) {
super(
parent,
1
/* Function */
);
}
beginBody() {
this._applyUses();
}
}
class AbstractNamedExpressionScope extends NonRootScope {
constructor(_name, _domain, parent) {
super(
parent,
1
/* Function */
);
this._name = _name;
this._domain = _domain;
}
end(cb) {
this._innerScope.end(cb);
return cb({
declarations: [this._name],
domain: this._domain,
exported: false,
uses: this._uses,
inGlobalScope: false
}, this._name, this);
}
addUse(use, source) {
if (source !== this._innerScope)
return this._innerScope.addUse(use);
if (use.domain & this._domain && use.location.text === this._name.text) {
this._uses.push(use);
} else {
return this._parent.addUse(use, this);
}
}
getFunctionScope() {
return this._innerScope;
}
getDestinationScope() {
return this._innerScope;
}
}
class FunctionExpressionScope extends AbstractNamedExpressionScope {
constructor(name, parent) {
super(name, 4, parent);
this._innerScope = new FunctionScope(this);
}
beginBody() {
return this._innerScope.beginBody();
}
}
class ClassExpressionScope extends AbstractNamedExpressionScope {
constructor(name, parent) {
super(name, 4 | 2, parent);
this._innerScope = new NonRootScope(
this,
1
/* Function */
);
}
}
class BlockScope extends NonRootScope {
constructor(_functionScope, parent) {
super(
parent,
2
/* Block */
);
this._functionScope = _functionScope;
}
getFunctionScope() {
return this._functionScope;
}
}
function mapDeclaration(declaration) {
return {
declaration,
exported: true,
domain: getDeclarationDomain(declaration)
};
}
class NamespaceScope extends NonRootScope {
constructor(_ambient, _hasExport, parent) {
super(
parent,
1
/* Function */
);
this._ambient = _ambient;
this._hasExport = _hasExport;
this._innerScope = new NonRootScope(
this,
1
/* Function */
);
this._exports = void 0;
}
finish(cb) {
return super.end(cb);
}
end(cb) {
this._innerScope.end((variable, key, scope) => {
if (scope !== this._innerScope || !variable.exported && (!this._ambient || this._exports !== void 0 && !this._exports.has(key.text)))
return cb(variable, key, scope);
const namespaceVar = this._variables.get(key.text);
if (namespaceVar === void 0) {
this._variables.set(key.text, {
declarations: variable.declarations.map(mapDeclaration),
domain: variable.domain,
uses: [...variable.uses]
});
} else {
outer:
for (const declaration of variable.declarations) {
for (const existing of namespaceVar.declarations)
if (existing.declaration === declaration)
continue outer;
namespaceVar.declarations.push(mapDeclaration(declaration));
}
namespaceVar.domain |= variable.domain;
for (const use of variable.uses) {
if (namespaceVar.uses.includes(use))
continue;
namespaceVar.uses.push(use);
}
}
});
this._applyUses();
this._innerScope = new NonRootScope(
this,
1
/* Function */
);
}
createOrReuseNamespaceScope(name, exported, ambient, hasExportStatement) {
if (!exported && (!this._ambient || this._hasExport))
return this._innerScope.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement);
return super.createOrReuseNamespaceScope(name, exported, ambient || this._ambient, hasExportStatement);
}
createOrReuseEnumScope(name, exported) {
if (!exported && (!this._ambient || this._hasExport))
return this._innerScope.createOrReuseEnumScope(name, exported);
return super.createOrReuseEnumScope(name, exported);
}
addUse(use, source) {
if (source !== this._innerScope)
return this._innerScope.addUse(use);
this._uses.push(use);
}
refresh(ambient, hasExport) {
this._ambient = ambient;
this._hasExport = hasExport;
}
markExported(name, _as) {
if (this._exports === void 0)
this._exports = /* @__PURE__ */ new Set();
this._exports.add(name.text);
}
getDestinationScope() {
return this._innerScope;
}
}
function getEntityNameParent(name) {
let parent = name.parent;
while (parent.kind === ts$1.SyntaxKind.QualifiedName)
parent = parent.parent;
return parent;
}
class UsageWalker {
constructor() {
this._result = /* @__PURE__ */ new Map();
}
getUsage(sourceFile) {
const variableCallback = (variable, key) => {
this._result.set(key, variable);
};
const isModule = ts$1.isExternalModule(sourceFile);
this._scope = new RootScope(sourceFile.isDeclarationFile && isModule && !containsExportStatement(sourceFile), !isModule);
const cb = (node2) => {
if (util_1.isBlockScopeBoundary(node2))
return continueWithScope(node2, new BlockScope(this._scope.getFunctionScope(), this._scope), handleBlockScope);
switch (node2.kind) {
case ts$1.SyntaxKind.ClassExpression:
return continueWithScope(node2, node2.name !== void 0 ? new ClassExpressionScope(node2.name, this._scope) : new NonRootScope(
this._scope,
1
/* Function */
));
case ts$1.SyntaxKind.ClassDeclaration:
this._handleDeclaration(
node2,
true,
4 | 2
/* Type */
);
return continueWithScope(node2, new NonRootScope(
this._scope,
1
/* Function */
));
case ts$1.SyntaxKind.InterfaceDeclaration:
case ts$1.SyntaxKind.TypeAliasDeclaration:
this._handleDeclaration(
node2,
true,
2
/* Type */
);
return continueWithScope(node2, new NonRootScope(
this._scope,
4
/* Type */
));
case ts$1.SyntaxKind.EnumDeclaration:
this._handleDeclaration(
node2,
true,
7
/* Any */
);
return continueWithScope(node2, this._scope.createOrReuseEnumScope(node2.name.text, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword)));
case ts$1.SyntaxKind.ModuleDeclaration:
return this._handleModule(node2, continueWithScope);
case ts$1.SyntaxKind.MappedType:
return continueWithScope(node2, new NonRootScope(
this._scope,
4
/* Type */
));
case ts$1.SyntaxKind.FunctionExpression:
case ts$1.SyntaxKind.ArrowFunction:
case ts$1.SyntaxKind.Constructor:
case ts$1.SyntaxKind.MethodDeclaration:
case ts$1.SyntaxKind.FunctionDeclaration:
case ts$1.SyntaxKind.GetAccessor:
case ts$1.SyntaxKind.SetAccessor:
case ts$1.SyntaxKind.MethodSignature:
case ts$1.SyntaxKind.CallSignature:
case ts$1.SyntaxKind.ConstructSignature:
case ts$1.SyntaxKind.ConstructorType:
case ts$1.SyntaxKind.FunctionType:
return this._handleFunctionLikeDeclaration(node2, cb, variableCallback);
case ts$1.SyntaxKind.ConditionalType:
return this._handleConditionalType(node2, cb, variableCallback);
case ts$1.SyntaxKind.VariableDeclarationList:
this._handleVariableDeclaration(node2);
break;
case ts$1.SyntaxKind.Parameter:
if (node2.parent.kind !== ts$1.SyntaxKind.IndexSignature && (node2.name.kind !== ts$1.SyntaxKind.Identifier || node2.name.originalKeywordKind !== ts$1.SyntaxKind.ThisKeyword))
this._handleBindingName(node2.name, false, false);
break;
case ts$1.SyntaxKind.EnumMember:
this._scope.addVariable(
util_1.getPropertyName(node2.name),
node2.name,
1,
true,
4
/* Value */
);
break;
case ts$1.SyntaxKind.ImportClause:
case ts$1.SyntaxKind.ImportSpecifier:
case ts$1.SyntaxKind.NamespaceImport:
case ts$1.SyntaxKind.ImportEqualsDeclaration:
this._handleDeclaration(
node2,
false,
7 | 8
/* Import */
);
break;
case ts$1.SyntaxKind.TypeParameter:
this._scope.addVariable(
node2.name.text,
node2.name,
node2.parent.kind === ts$1.SyntaxKind.InferType ? 8 : 7,
false,
2
/* Type */
);
break;
case ts$1.SyntaxKind.ExportSpecifier:
if (node2.propertyName !== void 0)
return this._scope.markExported(node2.propertyName, node2.name);
return this._scope.markExported(node2.name);
case ts$1.SyntaxKind.ExportAssignment:
if (node2.expression.kind === ts$1.SyntaxKind.Identifier)
return this._scope.markExported(node2.expression);
break;
case ts$1.SyntaxKind.Identifier:
const domain = getUsageDomain(node2);
if (domain !== void 0)
this._scope.addUse({ domain, location: node2 });
return;
}
return ts$1.forEachChild(node2, cb);
};
const continueWithScope = (node2, scope, next = forEachChild) => {
const savedScope = this._scope;
this._scope = scope;
next(node2);
this._scope.end(variableCallback);
this._scope = savedScope;
};
const handleBlockScope = (node2) => {
if (node2.kind === ts$1.SyntaxKind.CatchClause && node2.variableDeclaration !== void 0)
this._handleBindingName(node2.variableDeclaration.name, true, false);
return ts$1.forEachChild(node2, cb);
};
ts$1.forEachChild(sourceFile, cb);
this._scope.end(variableCallback);
return this._result;
function forEachChild(node2) {
return ts$1.forEachChild(node2, cb);
}
}
_handleConditionalType(node2, cb, varCb) {
const savedScope = this._scope;
const scope = this._scope = new ConditionalTypeScope(savedScope);
cb(node2.checkType);
scope.updateState(
1
/* Extends */
);
cb(node2.extendsType);
scope.updateState(
2
/* TrueType */
);
cb(node2.trueType);
scope.updateState(
3
/* FalseType */
);
cb(node2.falseType);
scope.end(varCb);
this._scope = savedScope;
}
_handleFunctionLikeDeclaration(node2, cb, varCb) {
if (node2.decorators !== void 0)
node2.decorators.forEach(cb);
const savedScope = this._scope;
if (node2.kind === ts$1.SyntaxKind.FunctionDeclaration)
this._handleDeclaration(
node2,
false,
4
/* Value */
);
const scope = this._scope = node2.kind === ts$1.SyntaxKind.FunctionExpression && node2.name !== void 0 ? new FunctionExpressionScope(node2.name, savedScope) : new FunctionScope(savedScope);
if (node2.name !== void 0)
cb(node2.name);
if (node2.typeParameters !== void 0)
node2.typeParameters.forEach(cb);
node2.parameters.forEach(cb);
if (node2.type !== void 0)
cb(node2.type);
if (node2.body !== void 0) {
scope.beginBody();
cb(node2.body);
}
scope.end(varCb);
this._scope = savedScope;
}
_handleModule(node2, next) {
if (node2.flags & ts$1.NodeFlags.GlobalAugmentation)
return next(node2, this._scope.createOrReuseNamespaceScope("-global", false, true, false));
if (node2.name.kind === ts$1.SyntaxKind.Identifier) {
const exported = isNamespaceExported(node2);
this._scope.addVariable(
node2.name.text,
node2.name,
1,
exported,
1 | 4
/* Value */
);
const ambient = util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.DeclareKeyword);
return next(node2, this._scope.createOrReuseNamespaceScope(node2.name.text, exported, ambient, ambient && namespaceHasExportStatement(node2)));
}
return next(node2, this._scope.createOrReuseNamespaceScope(`"${node2.name.text}"`, false, true, namespaceHasExportStatement(node2)));
}
_handleDeclaration(node2, blockScoped, domain) {
if (node2.name !== void 0)
this._scope.addVariable(node2.name.text, node2.name, blockScoped ? 3 : 1, util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword), domain);
}
_handleBindingName(name, blockScoped, exported) {
if (name.kind === ts$1.SyntaxKind.Identifier)
return this._scope.addVariable(
name.text,
name,
blockScoped ? 3 : 1,
exported,
4
/* Value */
);
util_1.forEachDestructuringIdentifier(name, (declaration) => {
this._scope.addVariable(
declaration.name.text,
declaration.name,
blockScoped ? 3 : 1,
exported,
4
/* Value */
);
});
}
_handleVariableDeclaration(declarationList) {
const blockScoped = util_1.isBlockScopedVariableDeclarationList(declarationList);
const exported = declarationList.parent.kind === ts$1.SyntaxKind.VariableStatement && util_1.hasModifier(declarationList.parent.modifiers, ts$1.SyntaxKind.ExportKeyword);
for (const declaration of declarationList.declarations)
this._handleBindingName(declaration.name, blockScoped, exported);
}
}
function isNamespaceExported(node2) {
return node2.parent.kind === ts$1.SyntaxKind.ModuleDeclaration || util_1.hasModifier(node2.modifiers, ts$1.SyntaxKind.ExportKeyword);
}
function namespaceHasExportStatement(ns) {
if (ns.body === void 0 || ns.body.kind !== ts$1.SyntaxKind.ModuleBlock)
return false;
return containsExportStatement(ns.body);
}
function containsExportStatement(block) {
for (const statement of block.statements)
if (statement.kind === ts$1.SyntaxKind.ExportDeclaration || statement.kind === ts$1.SyntaxKind.ExportAssignment)
return true;
return false;
}
})(usage);
return usage;
}
var controlFlow = {};
var hasRequiredControlFlow;
function requireControlFlow() {
if (hasRequiredControlFlow)
return controlFlow;
hasRequiredControlFlow = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.callExpressionAffectsControlFlow = exports.SignatureEffect = exports.getControlFlowEnd = exports.endsControlFlow = void 0;
const ts$1 = ts;
const node_1 = requireNode();
const util_1 = requireUtil$1();
function endsControlFlow(statement, checker) {
return getControlFlowEnd(statement, checker).end;
}
exports.endsControlFlow = endsControlFlow;
const defaultControlFlowEnd = { statements: [], end: false };
function getControlFlowEnd(statement, checker) {
return node_1.isBlockLike(statement) ? handleBlock(statement, checker) : getControlFlowEndWorker(statement, checker);
}
exports.getControlFlowEnd = getControlFlowEnd;
function getControlFlowEndWorker(statement, checker) {
switch (statement.kind) {
case ts$1.SyntaxKind.ReturnStatement:
case ts$1.SyntaxKind.ThrowStatement:
case ts$1.SyntaxKind.ContinueStatement:
case ts$1.SyntaxKind.BreakStatement:
return { statements: [statement], end: true };
case ts$1.SyntaxKind.Block:
return handleBlock(statement, checker);
case ts$1.SyntaxKind.ForStatement:
case ts$1.SyntaxKind.WhileStatement:
return handleForAndWhileStatement(statement, checker);
case ts$1.SyntaxKind.ForOfStatement:
case ts$1.SyntaxKind.ForInStatement:
return handleForInOrOfStatement(statement, checker);
case ts$1.SyntaxKind.DoStatement:
return matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
case ts$1.SyntaxKind.IfStatement:
return handleIfStatement(statement, checker);
case ts$1.SyntaxKind.SwitchStatement:
return matchBreakOrContinue(handleSwitchStatement(statement, checker), node_1.isBreakStatement);
case ts$1.SyntaxKind.TryStatement:
return handleTryStatement(statement, checker);
case ts$1.SyntaxKind.LabeledStatement:
return matchLabel(getControlFlowEndWorker(statement.statement, checker), statement.label);
case ts$1.SyntaxKind.WithStatement:
return getControlFlowEndWorker(statement.statement, checker);
case ts$1.SyntaxKind.ExpressionStatement:
if (checker === void 0)
return defaultControlFlowEnd;
return handleExpressionStatement(statement, checker);
default:
return defaultControlFlowEnd;
}
}
function handleBlock(statement, checker) {
const result = { statements: [], end: false };
for (const s of statement.statements) {
const current = getControlFlowEndWorker(s, checker);
result.statements.push(...current.statements);
if (current.end) {
result.end = true;
break;
}
}
return result;
}
function handleForInOrOfStatement(statement, checker) {
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
end.end = false;
return end;
}
function handleForAndWhileStatement(statement, checker) {
const constantCondition = statement.kind === ts$1.SyntaxKind.WhileStatement ? getConstantCondition(statement.expression) : statement.condition === void 0 || getConstantCondition(statement.condition);
if (constantCondition === false)
return defaultControlFlowEnd;
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), node_1.isBreakOrContinueStatement);
if (constantCondition === void 0)
end.end = false;
return end;
}
function getConstantCondition(node2) {
switch (node2.kind) {
case ts$1.SyntaxKind.TrueKeyword:
return true;
case ts$1.SyntaxKind.FalseKeyword:
return false;
default:
return;
}
}
function handleIfStatement(node2, checker) {
switch (getConstantCondition(node2.expression)) {
case true:
return getControlFlowEndWorker(node2.thenStatement, checker);
case false:
return node2.elseStatement === void 0 ? defaultControlFlowEnd : getControlFlowEndWorker(node2.elseStatement, checker);
}
const then = getControlFlowEndWorker(node2.thenStatement, checker);
if (node2.elseStatement === void 0)
return {
statements: then.statements,
end: false
};
const elze = getControlFlowEndWorker(node2.elseStatement, checker);
return {
statements: [...then.statements, ...elze.statements],
end: then.end && elze.end
};
}
function handleSwitchStatement(node2, checker) {
let hasDefault = false;
const result = {
statements: [],
end: false
};
for (const clause of node2.caseBlock.clauses) {
if (clause.kind === ts$1.SyntaxKind.DefaultClause)
hasDefault = true;
const current = handleBlock(clause, checker);
result.end = current.end;
result.statements.push(...current.statements);
}
result.end && (result.end = hasDefault || checker !== void 0 && util_1.hasExhaustiveCaseClauses(node2, checker));
return result;
}
function handleTryStatement(node2, checker) {
let finallyResult;
if (node2.finallyBlock !== void 0) {
finallyResult = handleBlock(node2.finallyBlock, checker);
if (finallyResult.end)
return finallyResult;
}
const tryResult = handleBlock(node2.tryBlock, checker);
if (node2.catchClause === void 0)
return { statements: finallyResult.statements.concat(tryResult.statements), end: tryResult.end };
const catchResult = handleBlock(node2.catchClause.block, checker);
return {
statements: tryResult.statements.filter((s) => s.kind !== ts$1.SyntaxKind.ThrowStatement && s.kind !== ts$1.SyntaxKind.ExpressionStatement).concat(catchResult.statements, finallyResult === void 0 ? [] : finallyResult.statements),
end: tryResult.end && catchResult.end
// only ends control flow if try AND catch definitely end control flow
};
}
function isDottedNameWithExplicitTypeAnnotation(node2, checker) {
while (true) {
switch (node2.kind) {
case ts$1.SyntaxKind.Identifier: {
const symbol = checker.getExportSymbolOfSymbol(checker.getSymbolAtLocation(node2));
return isExplicitlyTypedSymbol(util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : symbol, checker);
}
case ts$1.SyntaxKind.ThisKeyword:
return isExplicitlyTypedThis(node2);
case ts$1.SyntaxKind.SuperKeyword:
return true;
case ts$1.SyntaxKind.PropertyAccessExpression:
if (!isExplicitlyTypedSymbol(checker.getSymbolAtLocation(node2), checker))
return false;
case ts$1.SyntaxKind.ParenthesizedExpression:
node2 = node2.expression;
continue;
default:
return false;
}
}
}
function isExplicitlyTypedSymbol(symbol, checker) {
if (symbol === void 0)
return false;
if (util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Function | ts$1.SymbolFlags.Method | ts$1.SymbolFlags.Class | ts$1.SymbolFlags.ValueModule))
return true;
if (!util_1.isSymbolFlagSet(symbol, ts$1.SymbolFlags.Variable | ts$1.SymbolFlags.Property))
return false;
if (symbol.valueDeclaration === void 0)
return false;
if (declarationHasExplicitTypeAnnotation(symbol.valueDeclaration))
return true;
return node_1.isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.parent.parent.kind === ts$1.SyntaxKind.ForOfStatement && isDottedNameWithExplicitTypeAnnotation(symbol.valueDeclaration.parent.parent.expression, checker);
}
function declarationHasExplicitTypeAnnotation(node2) {
if (ts$1.isJSDocPropertyLikeTag(node2))
return node2.typeExpression !== void 0;
return (node_1.isVariableDeclaration(node2) || node_1.isParameterDeclaration(node2) || node_1.isPropertyDeclaration(node2) || node_1.isPropertySignature(node2)) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocType(node2) : node2.type) !== void 0;
}
function isExplicitlyTypedThis(node2) {
var _a;
do {
node2 = node2.parent;
if (node_1.isDecorator(node2)) {
if (node2.parent.kind === ts$1.SyntaxKind.Parameter && node_1.isClassLikeDeclaration(node2.parent.parent.parent)) {
node2 = node2.parent.parent.parent.parent;
} else if (node_1.isClassLikeDeclaration(node2.parent.parent)) {
node2 = node2.parent.parent.parent;
} else if (node_1.isClassLikeDeclaration(node2.parent)) {
node2 = node2.parent.parent;
}
}
} while (util_1.isFunctionScopeBoundary(node2) !== 1 || node2.kind === ts$1.SyntaxKind.ArrowFunction);
return util_1.isFunctionWithBody(node2) && (util_1.isNodeFlagSet(node2, ts$1.NodeFlags.JavaScriptFile) ? ((_a = ts$1.getJSDocThisTag(node2)) === null || _a === void 0 ? void 0 : _a.typeExpression) !== void 0 : node2.parameters.length !== 0 && util_1.isThisParameter(node2.parameters[0]) && node2.parameters[0].type !== void 0) || node_1.isClassLikeDeclaration(node2.parent);
}
(function(SignatureEffect) {
SignatureEffect[SignatureEffect["Never"] = 1] = "Never";
SignatureEffect[SignatureEffect["Asserts"] = 2] = "Asserts";
})(exports.SignatureEffect || (exports.SignatureEffect = {}));
function callExpressionAffectsControlFlow(node2, checker) {
var _a, _b, _c;
if (!node_1.isExpressionStatement(node2.parent) || ts$1.isOptionalChain(node2) || !isDottedNameWithExplicitTypeAnnotation(node2.expression, checker))
return;
const signature = checker.getResolvedSignature(node2);
if ((signature === null || signature === void 0 ? void 0 : signature.declaration) === void 0)
return;
const typeNode = ts$1.isJSDocSignature(signature.declaration) ? (_b = (_a = signature.declaration.type) === null || _a === void 0 ? void 0 : _a.typeExpression) === null || _b === void 0 ? void 0 : _b.type : (_c = signature.declaration.type) !== null && _c !== void 0 ? _c : util_1.isNodeFlagSet(signature.declaration, ts$1.NodeFlags.JavaScriptFile) ? ts$1.getJSDocReturnType(signature.declaration) : void 0;
if (typeNode === void 0)
return;
if (node_1.isTypePredicateNode(typeNode) && typeNode.assertsModifier !== void 0)
return 2;
return util_1.isTypeFlagSet(checker.getTypeFromTypeNode(typeNode), ts$1.TypeFlags.Never) ? 1 : void 0;
}
exports.callExpressionAffectsControlFlow = callExpressionAffectsControlFlow;
function handleExpressionStatement(node2, checker) {
if (!node_1.isCallExpression(node2.expression))
return defaultControlFlowEnd;
switch (callExpressionAffectsControlFlow(node2.expression, checker)) {
case 2:
return { statements: [node2], end: false };
case 1:
return { statements: [node2], end: true };
case void 0:
return defaultControlFlowEnd;
}
}
function matchBreakOrContinue(current, pred) {
const result = {
statements: [],
end: current.end
};
for (const statement of current.statements) {
if (pred(statement) && statement.label === void 0) {
result.end = false;
continue;
}
result.statements.push(statement);
}
return result;
}
function matchLabel(current, label) {
const result = {
statements: [],
end: current.end
};
const labelText = label.text;
for (const statement of current.statements) {
switch (statement.kind) {
case ts$1.SyntaxKind.BreakStatement:
case ts$1.SyntaxKind.ContinueStatement:
if (statement.label !== void 0 && statement.label.text === labelText) {
result.end = false;
continue;
}
}
result.statements.push(statement);
}
return result;
}
})(controlFlow);
return controlFlow;
}
var convertAst = {};
var hasRequiredConvertAst;
function requireConvertAst() {
if (hasRequiredConvertAst)
return convertAst;
hasRequiredConvertAst = 1;
Object.defineProperty(convertAst, "__esModule", { value: true });
convertAst.convertAst = void 0;
const ts$1 = ts;
const util_1 = requireUtil$1();
function convertAst$1(sourceFile) {
const wrapped = {
node: sourceFile,
parent: void 0,
kind: ts$1.SyntaxKind.SourceFile,
children: [],
next: void 0,
skip: void 0
};
const flat = [];
let current = wrapped;
function collectChildren(node2) {
current.children.push({
node: node2,
parent: current,
kind: node2.kind,
children: [],
next: void 0,
skip: void 0
});
}
const stack = [];
while (true) {
if (current.children.length === 0) {
ts$1.forEachChild(current.node, collectChildren);
if (current.children.length === 0) {
current = current.parent;
} else {
const firstChild = current.children[0];
current.next = firstChild;
flat.push(firstChild.node);
if (util_1.isNodeKind(firstChild.kind))
current = firstChild;
stack.push(1);
}
} else {
const index = stack[stack.length - 1];
if (index < current.children.length) {
const currentChild = current.children[index];
flat.push(currentChild.node);
let previous = current.children[index - 1];
while (previous.children.length !== 0) {
previous.skip = currentChild;
previous = previous.children[previous.children.length - 1];
}
previous.skip = previous.next = currentChild;
++stack[stack.length - 1];
if (util_1.isNodeKind(currentChild.kind))
current = currentChild;
} else {
if (stack.length === 1)
break;
stack.pop();
current = current.parent;
}
}
}
return {
wrapped,
flat
};
}
convertAst.convertAst = convertAst$1;
return convertAst;
}
var hasRequiredUtil;
function requireUtil() {
if (hasRequiredUtil)
return util$2;
hasRequiredUtil = 1;
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireUtil$1(), exports);
tslib_1.__exportStar(requireUsage(), exports);
tslib_1.__exportStar(requireControlFlow(), exports);
tslib_1.__exportStar(requireType(), exports);
tslib_1.__exportStar(requireConvertAst(), exports);
})(util$2);
return util$2;
}
(function(exports) {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require$$0;
tslib_1.__exportStar(requireTypeguard(), exports);
tslib_1.__exportStar(requireUtil(), exports);
})(tsutils);
const glslHeader = "uint shadeup_up_swizzle_x_uint(uint n) {\r\n return n;\r\n}\r\n\r\nuvec2 shadeup_up_swizzle_xx_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xxx_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xxxx_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_uint(uint n) {\r\n return uvec2(n, n);\r\n}\r\n\r\nuvec3 shadeup_up_swizzle_xyz_uint(uint n) {\r\n return uvec3(n, n, n);\r\n}\r\n\r\nuvec4 shadeup_up_swizzle_xyzw_uint(uint n) {\r\n return uvec4(n, n, n, n);\r\n}\r\n\r\nint shadeup_up_swizzle_x_int(int n) {\r\n return n;\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xx_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xxx_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec2 shadeup_up_swizzle_xy_int(int n) {\r\n return ivec2(n, n);\r\n}\r\n\r\nivec3 shadeup_up_swizzle_xyz_int(int n) {\r\n return ivec3(n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xyzw_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nivec4 shadeup_up_swizzle_xxxx_int(int n) {\r\n return ivec4(n, n, n, n);\r\n}\r\n\r\nfloat shadeup_up_swizzle_x_float(float n) {\r\n return n;\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xx_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xxx_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xxxx_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nvec2 shadeup_up_swizzle_xy_float(float n) {\r\n return vec2(n, n);\r\n}\r\n\r\nvec3 shadeup_up_swizzle_xyz_float(float n) {\r\n return vec3(n, n, n);\r\n}\r\n\r\nvec4 shadeup_up_swizzle_xyzw_float(float n) {\r\n return vec4(n, n, n, n);\r\n}\r\n\r\nmat4 matrix_inversefloat4x4(mat4 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat3 matrix_inversefloat3x3(mat3 m) {\r\n return inverse(m);\r\n}\r\n\r\nmat2 matrix_inversefloat2x2(mat2 m) {\r\n return inverse(m);\r\n}\r\n\r\nfloat bilerp_float(float a, float b, float c, float d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec2 bilerp_float2(vec2 a, vec2 b, vec2 c, vec2 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec3 bilerp_float3(vec3 a, vec3 b, vec3 c, vec3 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nvec4 bilerp_float4(vec4 a, vec4 b, vec4 c, vec4 d, float u, float v) {\r\n return mix(mix(a, b, u), mix(c, d, u), v);\r\n}\r\n\r\nmat2 bilerp_float2x2(mat2 a, mat2 b, mat2 c, mat2 d, float u, float v) {\r\n return mat2(bilerp_float2(a[0], b[0], c[0], d[0], u, v), bilerp_float2(a[1], b[1], c[1], d[1], u, v));\r\n}\r\n\r\nmat3 bilerp_float3x3(mat3 a, mat3 b, mat3 c, mat3 d, float u, float v) {\r\n return mat3(bilerp_float3(a[0], b[0], c[0], d[0], u, v), bilerp_float3(a[1], b[1], c[1], d[1], u, v), bilerp_float3(a[2], b[2], c[2], d[2], u, v));\r\n}\r\n\r\nmat4 bilerp_float4x4(mat4 a, mat4 b, mat4 c, mat4 d, float u, float v) {\r\n return mat4(bilerp_float4(a[0], b[0], c[0], d[0], u, v), bilerp_float4(a[1], b[1], c[1], d[1], u, v), bilerp_float4(a[2], b[2], c[2], d[2], u, v), bilerp_float4(a[3], b[3], c[3], d[3], u, v));\r\n}";
let { factory: factory$1, isIdentifier: isIdentifier$1 } = ts;
const TYPE_BLACKLIST$1 = [
"never",
"object",
"symbol",
"bigint",
"undefined",
"null",
"map",
"string"
];
const RESERVED_WORDS$1 = ["attribute", "sample", "varying", "uniform", "layout"];
class GLSLCompilationError extends Error {
constructor(message, node2) {
super(message);
this.message = message;
this.node = node2;
this.context = node2;
}
}
function generateDefaultForType$2(checker, _type_node) {
let _type = checker.getTypeFromTypeNode(_type_node);
let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString();
switch (name) {
case "int":
return "int(0)";
case "uint":
return "uint(0)";
case "uint8":
return "uint(0)";
case "float":
return "float(0.0)";
case "float2":
return "vec2(0.0, 0.0)";
case "float3":
return "vec3(0.0, 0.0, 0.0)";
case "float4":
return "vec4(0.0, 0.0, 0.0, 0.0)";
case "int2":
return "ivec2(0, 0)";
case "int3":
return "ivec3(0, 0, 0)";
case "int4":
return "ivec4(0, 0, 0, 0)";
case "uint2":
return "uvec2(0u, 0u)";
case "uint3":
return "uvec3(0u, 0u, 0u)";
case "uint4":
return "uvec4(0u, 0u, 0u, 0u)";
case "float2x2":
return "mat2(0.0, 0.0, 0.0, 0.0)";
case "float3x3":
return "mat3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "float4x4":
return "mat4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "bool":
return "false";
default:
let decl = _type.getSymbol()?.getDeclarations();
if (ts.isTupleTypeNode(_type_node)) {
let len = _type_node.elements.length;
let args = [];
let rootNode = _type_node.elements[0];
if (rootNode) {
for (let i = 0; i < len; i++) {
args.push(generateDefaultForType$2(checker, _type_node.elements[i]));
}
let rootType = checker.getTypeFromTypeNode(rootNode);
return translateType$1(checker, rootType) + `[${len}] {` + args.join(", ") + "}";
} else {
return "0";
}
}
if (decl && decl.length > 0) {
let d = decl[0];
let structProps = [];
if (ts.isClassDeclaration(d)) {
let symd = _type.getSymbol();
symd?.members?.forEach((v, k) => {
let decl2 = v.valueDeclaration;
if (decl2 && ts.isPropertyDeclaration(decl2)) {
structProps.push([k?.toString() ?? "", decl2.type]);
}
});
let sortedPropsByKey = structProps.sort((a, b) => {
return a[0].localeCompare(b[0]);
});
let args = sortedPropsByKey.map((p) => {
return "/* " + p[0] + ": */ " + generateDefaultForType$2(checker, p[1]) + "\n";
});
return "_make_struct_" + resolveStructName$1(d) + "(\n" + args.join(", ") + "\n)";
} else {
return "0";
}
} else {
return "0";
}
}
}
function getTypeFallback$2(checker, t) {
let n = (t.aliasSymbol || t.getSymbol())?.escapedName;
if (!n && t.intrinsicName)
n = t.intrinsicName;
if (typeof n !== "string") {
let props = t.getApparentProperties();
if (props.length > 0) {
for (let p of props) {
if (p.escapedName.toString() === "_opaque_int")
return "int";
if (p.escapedName.toString() === "_opaque_float")
return "float";
if (p.escapedName.toString() === "_opaque_uint")
return "uint";
}
}
let btype = t.getBaseTypes();
if (btype && btype.length > 0) {
for (let b of btype) {
let tn = getTypeFallback$2(checker, b);
if (tn)
return tn;
}
return null;
}
} else {
return n;
}
}
function followTypeReferences$1(t) {
if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) {
if (t.target === t) {
return t;
}
return followTypeReferences$1(t.target);
} else {
return t;
}
}
function translateType$1(checker, t, templateFormat = false) {
let n = getTypeFallback$2(checker, t);
let originalType = t;
if (n === void 0) {
t = followTypeReferences$1(t);
}
if (templateFormat) {
let name = n?.toString() ?? "unknown";
if (name === "Array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = originalType;
let args = typeRef.typeArguments || checker.getTypeArguments(typeRef);
return {
type: "array",
element: translateType$1(checker, args[0], true)
};
}
if (name == "boolean" || name == "false" || name == "true")
name = "bool";
if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "atomic")
return { type: "primitive", name };
let symbol = t.aliasSymbol || t.getSymbol();
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
if (ts.isClassDeclaration(symbol.declarations[0])) {
let fields = {};
let decl = symbol.declarations[0];
for (let member of decl.members) {
if (ts.isPropertyDeclaration(member)) {
let name2 = member.name.getText();
let type2 = checker.getTypeFromTypeNode(member.type);
fields[name2] = translateType$1(checker, type2, true);
}
}
return {
type: "struct",
name: resolveStructName$1(decl),
fields
};
} else {
return {
type: "unknown"
};
}
}
} else {
if (n === "Array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = originalType;
let toStringed = checker.typeToString(typeRef);
let args = typeRef.typeArguments || checker.getTypeArguments(typeRef);
let translated = translateType$1(checker, args[0]);
if (toStringed.endsWith("[]")) {
return translated + "[]";
} else {
let staticSize = 0;
if (tsutils.isTupleType(t)) {
staticSize = t.fixedLength;
}
return translated + "[" + staticSize + "]";
}
}
if (n === "texture2d")
return `sampler2D`;
if (n == "atomic") {
let args = t.typeArguments || checker.getTypeArguments(t);
let translated = translateType$1(checker, args[0]);
return `atomic_${translated}`;
}
if (n === "bool")
return "bool";
if (n === "boolean")
return "bool";
if (n === "float")
return "float";
if (n === "float2")
return "vec2";
if (n === "float3")
return "vec3";
if (n === "float4")
return "vec4";
if (n === "int")
return "int";
if (n === "int2")
return "ivec2";
if (n === "int3")
return "ivec3";
if (n === "int4")
return "ivec4";
if (n === "uint")
return "uint";
if (n === "uint8")
return "uint";
if (n === "uint2")
return "uvec2";
if (n === "uint3")
return "uvec3";
if (n === "uint4")
return "uvec4";
if (n === "float2x2")
return "mat2";
if (n === "float3x3")
return "mat3";
if (n === "float4x4")
return "mat4";
if (n === "void")
return "void";
if (n === "error")
return "void";
if (t.isUnion()) {
let types2 = t.types.map((t2) => translateType$1(checker, t2));
for (let sub of types2) {
if (sub && sub !== "void" && sub !== "undefined")
return sub;
}
}
let symbol = t.aliasSymbol || t.getSymbol();
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
if (ts.isClassDeclaration(symbol.declarations[0])) {
return resolveStructName$1(symbol.declarations[0]);
} else {
return n?.toString() ?? "void";
}
} else {
return n?.toString() ?? "void";
}
}
}
function isTypeNameVector$1(name) {
if (name.startsWith("float") || name.startsWith("int")) {
if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) {
return true;
}
}
return false;
}
function getTypeNameVectorElementType$1(name) {
if (name == "float") {
return ["float", 1];
}
if (name == "int") {
return ["int", 1];
}
if (name == "uint") {
return ["uint", 1];
}
if (name.startsWith("float")) {
return ["float", parseInt(name.substring(5))];
}
if (name.startsWith("int")) {
return ["int", parseInt(name.substring(3))];
}
if (name.startsWith("uint")) {
return ["uint", parseInt(name.substring(4))];
}
if (name.startsWith("vec")) {
return ["float", parseInt(name.substring(3))];
}
if (name.startsWith("ivec")) {
return ["int", parseInt(name.substring(4))];
}
if (name.startsWith("uvec")) {
return ["uint", parseInt(name.substring(4))];
}
return ["", 0];
}
function isTranslatedTypeNameVectorOrScalar$1(name) {
if (name == "float" || name == "int" || name == "uint")
return true;
if (name.startsWith("vec") || name.startsWith("ivec") || name.startsWith("uvec")) {
if (name.endsWith("2") || name.endsWith("3") || name.endsWith("4")) {
return true;
}
return true;
}
return false;
}
function isVector$1(checker, t) {
let name = getTypeFallback$2(checker, t);
if (name) {
return isTypeNameVector$1(name);
}
return false;
}
function getVectorElementType$1(checker, t) {
let name = getTypeFallback$2(checker, t);
if (name) {
return getTypeNameVectorElementType$1(name);
}
return ["", 0];
}
function isNumeric$1(checker, t) {
let name = getTypeFallback$2(checker, t);
if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) {
return true;
}
return false;
}
function escapeIdentifier$1(id) {
if (RESERVED_WORDS$1.includes(id)) {
return "_" + id;
}
return id.replaceAll("___", "_ii_").replaceAll("__", "_i_");
}
function getVectorMask$1(num) {
let outMask = "";
let comps = ["x", "y", "z", "w"];
for (let i = 0; i < num; i++) {
outMask += comps[i];
}
return outMask;
}
function isGLSLType$1(name) {
return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name.startsWith("isampler") || name.startsWith("usampler") || name.startsWith("uvec") || name.startsWith("ivec") || name == "bool" || name == "float" || name == "int" || name == "uint" || name == "uint8" || name == "void";
}
function autoCastNumeric$1(value, input, expected) {
let inputType = getTypeNameVectorElementType$1(input);
let expectedType = getTypeNameVectorElementType$1(expected);
if (inputType[0] != expectedType[0]) {
if (expectedType[1] == 1) {
return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]);
} else {
return new SourceNode(value.startIndex, value.endIndex, [`${expectedType[0]}(`, value, `)`]);
}
}
return value;
}
function convertConciseBodyToBlock$1(body) {
if (ts.isBlock(body)) {
return body;
} else {
return ts.factory.createBlock([ts.factory.createReturnStatement(body)]);
}
}
function compile$2(ctx, ast, originalMapping) {
function c2(ast2) {
if (!ast2) {
return s([]);
}
return compile$2(ctx, ast2);
}
function cplain(ast2) {
if (!ast2) {
return s([]);
}
return compile$2(
{
checker: ctx.checker,
parentFunction: ctx.parentFunction
},
ast2
);
}
function s(c22) {
if (originalMapping) {
let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd());
return new SourceNode(reverseMapped.start, reverseMapped.end, c22);
} else {
return new SourceNode(0, 0, c22);
}
}
function join(c22, sep) {
return c22.reduce((acc, cur) => {
if (acc.length === 0) {
return [cur];
}
return [...acc, sep, cur];
}, []);
}
function children() {
return ast.getChildren().map((child) => c2(child));
}
function autoCastParameter(callExpr, argIndex) {
let signature = ctx.checker.getResolvedSignature(callExpr);
let params = signature.getParameters();
let param = params[argIndex];
let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr);
let paramTypeString = translateType$1(ctx.checker, paramType);
let arg = callExpr.arguments[argIndex];
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeString = translateType$1(ctx.checker, argType);
if (paramTypeString !== argTypeString) {
return autoCastNumeric$1(c2(arg), argTypeString, paramTypeString);
}
return s([c2(arg)]);
}
let prefixFunctions = [];
if (ctx.composed) {
if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) {
for (let [i, arg] of ctx.composed.arguments.entries()) {
if (ts.isArrowFunction(arg)) {
let paramFromIndex = ast.parameters[i];
let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i;
let signature = ctx.checker.getSignatureFromDeclaration(arg);
let returnType = signature.getReturnType();
let vars = getClosureVars$1(ctx.checker, arg);
let vvv = vars.map(
(p) => s([
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0])),
" ",
p.escapedName
])
);
let joins = join([...arg.parameters.map((p) => cplain(p)), ...vvv], ", ");
prefixFunctions.push(
s([
translateType$1(ctx.checker, returnType),
" ",
name,
"(",
...joins,
")",
" {\n",
...convertConciseBodyToBlock$1(arg.body).statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
])
);
}
}
}
}
switch (ast.kind) {
case ts.SyntaxKind.FirstPunctuation:
return s([ast.getText()]);
case ts.SyntaxKind.SyntaxList:
return s(children());
case ts.SyntaxKind.SourceFile:
return s(children());
case ts.SyntaxKind.BreakStatement:
return s(["break;"]);
case ts.SyntaxKind.ContinueStatement:
return s(["continue;"]);
case ts.SyntaxKind.MethodDeclaration:
let fnDeclar = ast;
let fnName = resolveFunctionName$1(fnDeclar);
if (ctx.composed) {
fnName = fnName + "_composed_" + ctx.composed.pos;
}
let isStatic = false;
let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar);
if (ts.canHaveModifiers(fnDeclar)) {
let mods = ts.getModifiers(fnDeclar);
if (mods) {
if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) {
isStatic = true;
}
}
}
let returnType = signature.getReturnType();
return s([
...prefixFunctions,
translateType$1(ctx.checker, returnType),
" ",
fnName,
"(",
,
...join(
[
...isStatic ? [] : [
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent)) + " _this"
],
...fnDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
return true;
}).map((p) => c2(p))
],
", "
),
")",
" {\n",
...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
]);
case ts.SyntaxKind.FunctionDeclaration:
let mthdDeclar = ast;
let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar);
let mthdreturnType = mthdsignature.getReturnType();
let mthdName = resolveFunctionName$1(mthdDeclar);
if (ctx.composed) {
mthdName = mthdName + "_composed_" + ctx.composed.pos;
}
return s([
...prefixFunctions,
translateType$1(ctx.checker, mthdreturnType),
" ",
mthdName,
"(",
...join(
mthdDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
return true;
}).map((p) => c2(p)),
", "
),
")",
" {\n",
...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
]);
case ts.SyntaxKind.ReturnStatement:
let ret = ast;
if (!ctx.parentFunction) {
if (ret.expression) {
return s(["return ", c2(ret.expression), ";\n"]);
} else {
return s(["return;\n"]);
}
} else {
let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType();
let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression);
if (ret.expression) {
let sss = s([
"return ",
autoCastNumeric$1(
c2(ret.expression),
translateType$1(ctx.checker, actualReturnType),
translateType$1(ctx.checker, expectedReturnType)
),
";\n"
]);
return sss;
} else {
return s(["return;\n"]);
}
}
case ts.SyntaxKind.AsExpression:
let asExpr = ast;
return c2(asExpr.expression);
case ts.SyntaxKind.Parameter:
let param = ast;
if (ctx.composed) {
let indexOf2 = param.parent.parameters.indexOf(param);
let expr2 = ctx.composed.arguments[indexOf2];
if (expr2) {
if (ts.isArrowFunction(expr2)) {
let vars = getClosureVars$1(ctx.checker, expr2.body);
let closureVars = vars.map((v) => {
return s([
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration)),
" ",
v.name
]);
});
return s(join(closureVars, ", "));
}
}
}
return s([
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(param)),
" ",
escapeIdentifier$1(param.name.getText())
]);
case ts.SyntaxKind.ArrowFunction:
let arrow = ast;
let body = convertConciseBodyToBlock$1(arrow.body);
return s([
"\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/\nvoid main() {\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n",
...body.statements.map((s2) => c2(s2)),
"\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n"
]);
case ts.SyntaxKind.VariableStatement:
let varStatement = ast;
return s([
...join(
varStatement.declarationList.declarations.map((d) => c2(d)),
", "
),
";\n"
]);
case ts.SyntaxKind.VariableDeclaration:
let varDecl = ast;
let type2 = ctx.checker.getTypeAtLocation(varDecl);
return s([
translateType$1(ctx.checker, type2),
" ",
varDecl.name.getText(),
" = ",
c2(varDecl.initializer)
]);
case ts.SyntaxKind.CallExpression:
let call = ast;
let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression);
if (call.expression.getText() == "Math.random") {
return s(["0.0"]);
}
if (!exprSmybol) {
return s(["/* TODO: Unknown symbol */"]);
}
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol);
}
let symName = exprSmybol?.getName() ?? call.expression.getText();
if (symName == "__index") {
if (ts.isPropertyAccessExpression(call.expression)) {
let innerType = translateType$1(
ctx.checker,
ctx.checker.getTypeAtLocation(call.expression.expression)
);
let returnType2 = ctx.checker.getTypeAtLocation(call);
let vecOut = getVectorElementType$1(ctx.checker, returnType2);
let outMask = getVectorMask$1(vecOut[1]);
if (innerType == "sampler2D") {
return s([
"texelFetch(",
c2(call.expression.expression),
", ivec2(",
c2(call.arguments[0]),
"), 0)." + outMask
]);
}
}
return s([c2(call.expression), "[", c2(call.arguments[0]), "]"]);
} else if (symName == "len") {
let expr2 = call.expression;
if (ts.isPropertyAccessExpression(expr2)) {
let left = expr2.expression;
return s([c2(left), "_size"]);
}
} else if (symName == "min" || symName == "max") {
if (call.arguments.length > 2) {
let args2 = call.arguments.map((a) => c2(a));
while (args2.length > 2) {
let left = args2.shift();
let right = args2.shift();
args2.unshift(s([symName, "(", left, ",", right, ")"]));
}
return s([symName, "(", ...join(args2, ","), ")"]);
}
} else if (symName == "sample") {
if (ts.isPropertyAccessExpression(call.expression)) {
let innerType = translateType$1(
ctx.checker,
ctx.checker.getTypeAtLocation(call.expression.expression)
);
if (innerType == "sampler2D") {
return s([
"texture(",
c2(call.expression.expression),
", vec2(",
c2(call.arguments[0]),
"))"
]);
}
}
} else if (symName == "__index_assign") {
return s([
c2(call.expression.expression),
"[",
c2(call.arguments[0]),
"] = ",
autoCastParameter(call, 1)
]);
} else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") {
throw new GLSLCompilationError(
"rand() in shaders needs to be seeded, use rand(seed) instead",
call
);
}
if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) {
if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) {
let exprSig2 = ctx.checker.getResolvedSignature(call);
if (exprSig2) {
return s([
translateType$1(ctx.checker, ctx.checker.getReturnTypeOfSignature(exprSig2)),
"(",
...join(
call.arguments.map((a) => c2(a)),
", "
),
")"
]);
}
}
}
if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) {
if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) {
ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration);
let arg = call.arguments[0];
let arg2 = call.arguments[1];
let propAccess = "";
if (ts.isStringLiteral(arg2)) {
propAccess = arg2.text;
}
let argType = ctx.checker.getTypeAtLocation(arg);
if (isVector$1(ctx.checker, argType)) {
return s([c2(arg), ".", propAccess]);
} else if (isNumeric$1(ctx.checker, argType)) {
let numericType = translateType$1(ctx.checker, argType);
return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]);
} else {
return s([c2(arg), ".", propAccess]);
}
}
}
if (isTypeNameVector$1(exprSmybol?.getName() ?? "")) {
return s([
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(call.expression)),
"(",
...join(call.arguments.length == 0 ? [s(["0"])] : call.arguments.map((a) => c2(a)), ", "),
")"
]);
}
let funcName = c2(call.expression);
let callArgs = [];
let preArgs = [];
let exprSig = ctx.checker.getResolvedSignature(call);
let exprDeclar = exprSig.getDeclaration();
if (exprDeclar) {
if (ts.isMethodDeclaration(exprDeclar)) {
let isStatic2 = false;
if (ts.canHaveModifiers(exprDeclar)) {
let mods = ts.getModifiers(exprDeclar);
if (mods) {
if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) {
isStatic2 = true;
}
}
}
if (!isStatic2) {
if (ts.isPropertyAccessExpression(call.expression)) {
preArgs.push(c2(call.expression.expression));
}
}
}
}
exprSmybol.getName() + "(";
for (let [i, arg] of call.arguments.entries()) {
let argStr = c2(arg);
if (exprSig) {
let p = exprSig.getTypeParameterAtPosition(i);
if (p) {
let translatedBase = translateType$1(ctx.checker, p);
let translatedPass = translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg));
if (isTranslatedTypeNameVectorOrScalar$1(translatedPass)) {
if (translatedBase != translatedPass && isGLSLType$1(translatedBase)) {
argStr = s([`${translatedBase}(`, argStr, `)`]);
}
}
} else {
translateType$1(ctx.checker, ctx.checker.getTypeAtLocation(arg));
}
}
if (ts.isArrowFunction(arg)) {
let arrow2 = arg;
let vars = getClosureVars$1(ctx.checker, arrow2.body);
if (vars.length > 0)
callArgs.push(vars.map((v) => v.escapedName).join(", "));
} else {
callArgs.push(argStr);
}
}
if (exprSmybol) {
let signature2 = ctx.checker.getResolvedSignature(call);
let mapping = findRealSignatureMappingToGLSL(ctx.checker, signature2) ?? findSignatureMappingToGLSL(ctx.checker, exprSmybol);
if (mapping !== null) {
if (mapping.startsWith("!")) {
let minType = "";
let noOp = false;
for (let arg of call.arguments) {
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeName = translateType$1(ctx.checker, argType);
if (!(argTypeName == "float" || argTypeName.startsWith("vec") || argTypeName == "int" || argTypeName.startsWith("ivec") || argTypeName == "uint" || argTypeName.startsWith("uvec"))) {
noOp = true;
}
if (minType == "") {
if (argTypeName == "float" || argTypeName.startsWith("vec")) {
minType = "float";
} else if (argTypeName == "int" || argTypeName.startsWith("ivec")) {
minType = "int";
} else if (argTypeName == "uint" || minType.startsWith("uvec")) {
minType = "uint";
}
} else if (argTypeName == "float" || minType.startsWith("vec")) {
minType = "float";
}
}
if (!noOp) {
for (let i = 0; i < callArgs.length; i++) {
let arg = call.arguments[i];
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeName = translateType$1(ctx.checker, argType);
let argTypeStripped = "";
if (argTypeName == "float" || argTypeName.startsWith("vec")) {
argTypeStripped = "float";
} else if (argTypeName == "int" || argTypeName.startsWith("ivec")) {
argTypeStripped = "int";
} else if (argTypeName == "uint" || argTypeName.startsWith("uvec")) {
argTypeStripped = "uint";
}
if (argTypeStripped != minType) {
if (argTypeName.startsWith("float") || argTypeName.startsWith("int")) {
callArgs[i] = s([`${minType}(`, callArgs[i], `)`]);
} else if (argTypeName.startsWith("vec") || argTypeName.startsWith("ivec")) {
let len = argTypeName.match(/\d+/)?.[0];
if (len === void 0) {
throw new Error("Invalid type");
}
callArgs[i] = s([
`${minType == "float" ? "vec" : "ivec"}${len}(`,
callArgs[i],
`)`
]);
} else
;
}
}
}
let template = mapping.slice(1);
let outs = [];
let argCounter = 0;
let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration());
for (let i = 0; i < callArgs.length; i++) {
let paramType = ctx.checker.getTypeAtLocation(
sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0]
);
template = template.replace(
"`" + argCounter + "`",
ctx.checker.typeToString(paramType)
);
argCounter++;
}
let result = template.split("$");
for (let r of result) {
if (/^\d+$/.test(r)) {
outs.push(callArgs[parseInt(r)]);
} else if (r == "self") {
if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
let propAccess = call.expression;
outs.push(c2(propAccess.getChildAt(0)));
} else {
outs.push(c2(call.expression));
}
} else {
outs.push(r);
}
}
if (outs.includes(" % ")) {
if (call.arguments.length == 2) {
let first = getVectorElementType$1(
ctx.checker,
ctx.checker.getTypeAtLocation(call.arguments[0])
);
let last = getVectorElementType$1(
ctx.checker,
ctx.checker.getTypeAtLocation(call.arguments[1])
);
if (first[1] != last[1] && last[1] == 1) {
getVectorMask$1(first[1]);
if (first[0] == "float" || last[0] == "float") {
outs = [`mod(`, outs[1], ", ", outs[3], ")"];
}
}
}
}
return s(outs);
} else if (mapping.startsWith("#")) {
let typeName = "";
if (call.arguments.length > 0) {
let firstArg = call.arguments[0];
let firstArgType = ctx.checker.getTypeAtLocation(firstArg);
typeName = ctx.checker.typeToString(firstArgType);
}
return s([
new SourceNode(call.expression.getStart(), call.expression.getEnd(), [
mapping.substring(1) + typeName
]),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
} else {
return s([
new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
}
if (exprSmybol.declarations[0].parent) {
let param2 = exprSmybol.declarations[0];
if (ts.isParameter(param2))
;
}
let funcDeclar = exprSmybol.valueDeclaration;
if (exprSmybol.declarations[0].parent) {
let param2 = exprSmybol.declarations[0];
if (ts.isParameter(param2)) {
let indexOf2 = param2.parent.parameters.indexOf(param2);
let additionalArgs = [];
if (ctx.composed) {
let realAnonymousFunc = ctx.composed.arguments[indexOf2];
if (ts.isArrowFunction(realAnonymousFunc)) {
let vars = getClosureVars$1(ctx.checker, realAnonymousFunc.body);
additionalArgs = vars.map((v) => v.escapedName);
callArgs.push(...additionalArgs);
return s([
funcName,
"_composed_",
realAnonymousFunc.pos.toString(),
"_arg_",
indexOf2.toString(),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
}
}
}
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
funcName = new SourceNode(
call.expression.getStart(),
call.expression.getEnd(),
resolveFunctionName$1(funcDeclar)
);
let parentDeclar = closest(ast, (n2) => ts.isFunctionDeclaration(n2));
if (parentDeclar && ts.isFunctionDeclaration(parentDeclar))
;
if (isComposedFunction$1(ctx.checker, funcDeclar)) {
return s([
funcName,
"_composed_",
call.pos.toString(),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
}
}
return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]);
case ts.SyntaxKind.NewExpression:
let newExpr = ast;
let newExprSymbol = ctx.checker.getSymbolAtLocation(newExpr.expression);
let args = [];
if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) {
let object = newExpr.arguments[0];
let props = object.properties;
let sortedPropsByKey = [];
let structProps = [];
newExprSymbol?.members?.forEach((v, k) => {
let decl2 = v.valueDeclaration;
if (decl2 && ts.isPropertyDeclaration(decl2)) {
structProps.push([k?.toString() ?? "", decl2.type]);
}
});
sortedPropsByKey = structProps.sort((a, b) => {
return a[0].localeCompare(b[0]);
});
args = [
...sortedPropsByKey.map((p) => {
let prop2 = props.find((p2) => {
if (ts.isPropertyAssignment(p2)) {
return p2.name.getText() == p[0];
} else if (ts.isShorthandPropertyAssignment(p2)) {
return p2.name.getText() == p[0];
} else {
return false;
}
});
if (prop2) {
if (ts.isPropertyAssignment(prop2)) {
return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]);
} else if (ts.isShorthandPropertyAssignment(prop2)) {
return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]);
} else {
return s(["/* ", c2(prop2), ": */ ", "\n"]);
}
} else {
return s(["/* ", p[0], ": */ ", generateDefaultForType$2(ctx.checker, p[1]), "\n"]);
}
})
];
}
let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations();
if (decl && ts.isClassDeclaration(decl[0])) {
return s(["_make_struct_", resolveStructName$1(decl[0]), "(\n", ...join(args, ", "), "\n)"]);
} else {
return s(["/*", ...join(args, ", "), "*/"]);
}
case ts.SyntaxKind.ExpressionStatement:
let expr = ast;
return s([c2(expr.expression), ";\n"]);
case ts.SyntaxKind.ObjectLiteralExpression:
let obj = ast;
return s([
"{",
...join(
obj.properties.map((p) => {
if (ts.isPropertyAssignment(p)) {
return s([c2(p.name), ": ", c2(p.initializer)]);
} else if (ts.isShorthandPropertyAssignment(p)) {
return s([c2(p.name)]);
} else {
return s(["/*", c2(p), "*/"]);
}
}),
", "
),
"}"
]);
case ts.SyntaxKind.ConditionalExpression:
let cond = ast;
return s([c2(cond.condition), " ? ", c2(cond.whenTrue), " : ", c2(cond.whenFalse)]);
case ts.SyntaxKind.Identifier:
let id = ast;
if (ts.isIdentifier(id)) {
let sym = ctx.checker.getSymbolAtLocation(id);
if (sym && sym.flags & ts.SymbolFlags.Alias) {
sym = ctx.checker.getAliasedSymbol(sym);
}
if (sym?.declarations?.length == 1) {
let decl2 = sym.declarations[0];
if (isUniformable$1(ctx.checker, decl2)) {
if (isVariableDeclarationValue$1(ctx.checker, decl2)) {
if (!isInSameScope$1(decl2, ast)) {
if (!isInShader$2(decl2)) {
if (ts.isBinaryExpression(ast.parent)) {
if (ast.parent.left == ast) {
throw new GLSLCompilationError(
`Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`,
ast
);
}
}
let isGlobalVar = isRootNode$1(decl2);
let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`;
return s([glslVarName]);
} else {
return s([escapeIdentifier$1(id.text.toString())]);
}
}
}
}
}
return s([escapeIdentifier$1(id.text.toString())]);
} else {
return c2(id.expression);
}
case ts.SyntaxKind.PropertyAccessExpression:
let prop = ast;
let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop);
if (isStaticMember) {
return s([c2(prop.expression), "_static_", c2(prop.name)]);
} else {
let propName = prop.name.getText();
if (propName == "__index") {
return s([c2(prop.expression)]);
} else if (propName == "size") {
let innerType = translateType$1(
ctx.checker,
ctx.checker.getTypeAtLocation(prop.expression)
);
if (innerType == "sampler2D") {
return s([c2(prop.expression), "_", propName]);
}
} else {
return s([c2(prop.expression), ".", c2(prop.name)]);
}
}
case ts.SyntaxKind.ThisKeyword:
return s(["_this"]);
case ts.SyntaxKind.FirstLiteralToken:
let lit = ast;
return s([lit.text]);
case ts.SyntaxKind.IfStatement:
let ifStmt = ast;
if (isIdentifier$1(ifStmt.expression)) {
if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") {
return s([c2(ifStmt.thenStatement)]);
}
if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") {
if (ifStmt.elseStatement) {
return s([c2(ifStmt.elseStatement)]);
} else {
return s([""]);
}
}
}
return s([
"if (",
c2(ifStmt.expression),
")",
c2(ifStmt.thenStatement),
ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""])
]);
case ts.SyntaxKind.TrueKeyword:
return s(["true"]);
case ts.SyntaxKind.FalseKeyword:
return s(["false"]);
case ts.SyntaxKind.PostfixUnaryExpression:
let post = ast;
return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]);
case ts.SyntaxKind.PlusPlusToken:
return s(["++"]);
case ts.SyntaxKind.MinusMinusToken:
return s(["--"]);
case ts.SyntaxKind.ParenthesizedExpression:
let paren = ast;
return s(["(", c2(paren.expression), ")"]);
case ts.SyntaxKind.VariableDeclarationList:
let varDeclList = ast;
if (varDeclList.declarations.length > 0) {
for (let decl2 of varDeclList.declarations) {
let varDecl2 = decl2;
let type22 = ctx.checker.getTypeAtLocation(varDecl2);
return s([
translateType$1(ctx.checker, type22),
" ",
varDecl2.name.getText(),
" = ",
c2(varDecl2.initializer)
]);
}
} else {
return s([""]);
}
case ts.SyntaxKind.ForStatement:
let forStmt = ast;
return s([
"for (",
c2(forStmt.initializer),
";",
c2(forStmt.condition),
";",
c2(forStmt.incrementor),
")",
c2(forStmt.statement)
]);
case ts.SyntaxKind.BinaryExpression:
let bin = ast;
if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) {
let leftType = ctx.checker.getTypeAtLocation(bin.left);
let rightType = ctx.checker.getTypeAtLocation(bin.right);
if (isVector$1(ctx.checker, leftType) && isVector$1(ctx.checker, rightType)) {
let [leftElementType, leftElementSize] = getVectorElementType$1(ctx.checker, leftType);
let [rightElementType, rightElementSize] = getVectorElementType$1(ctx.checker, rightType);
if (leftElementType != rightElementType) {
if (leftElementType == "float" && rightElementType == "int") {
return s([c2(bin.left), ` = vec${leftElementSize}(`, c2(bin.right), ")"]);
} else if (leftElementType == "int" && rightElementType == "float") {
return s([c2(bin.left), ` = ivec${leftElementSize}(`, c2(bin.right), ")"]);
}
}
}
return s([c2(bin.left), " = ", c2(bin.right)]);
}
let binExprText = bin.operatorToken.getText();
if (binExprText == "===") {
binExprText = "==";
}
return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]);
case ts.SyntaxKind.StringLiteral:
return s(["0"]);
case ts.SyntaxKind.ArrayLiteralExpression:
let arr = ast;
return s([
"[",
...join(
arr.elements.map((e) => c2(e)),
", "
),
"]"
]);
case ts.SyntaxKind.ElementAccessExpression:
let elem = ast;
return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]"]);
case ts.SyntaxKind.Block:
let block = ast;
return s([
"{\n",
...join(
block.statements.map((child) => c2(child)),
";"
),
"\n}"
]);
case ts.SyntaxKind.TypeOfExpression:
return s(["0"]);
case ts.SyntaxKind.WhileStatement:
let whileStmt = ast;
return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]);
default:
throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast);
}
}
function getClosureVars$1(checker, func) {
let result = [];
let recur = (node2) => {
if (node2.kind == ts.SyntaxKind.Identifier) {
let id = node2;
let symbol = checker.getSymbolAtLocation(id);
let declar = symbol.valueDeclaration;
if (isVariableDeclarationValue$1(checker, declar)) {
if (declar) {
if (!isInSameScope$1(declar, node2) && isInShader$2(declar)) {
result.push(symbol);
}
}
}
} else {
node2.forEachChild(recur);
}
};
recur(func);
return result;
}
function getDeclarationType$1(checker, node2) {
return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2);
}
class GLSLShader {
constructor(key, source) {
this.globals = {};
this.locals = {};
this.key = key;
this.source = source;
}
}
function resolveFunctionName$1(f) {
if (ts.isMethodDeclaration(f)) {
let parentName = "anon";
if (f.parent && ts.isClassDeclaration(f.parent)) {
parentName = f.parent.name?.text ?? "anon";
}
return removeDoubleUnderscores$1(
`fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}`
);
} else {
return removeDoubleUnderscores$1(
`fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}`
);
}
}
function resolveStructName$1(c2) {
if (c2.name?.text == "ShaderInput")
return "ShaderInput";
if (c2.name?.text == "ShaderOutput")
return "ShaderOutput";
return removeDoubleUnderscores$1(
`str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_")
);
}
function isInSameScope$1(node2, other) {
return closest(node2, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
}) == closest(other, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
});
}
function isInShader$2(node2) {
return closest(node2, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) {
if (hasShadeupDocTag(node22, "shader")) {
return true;
}
}
return false;
});
}
function isRootNode$1(node2) {
let parentRoot = closest(node2, (node22) => {
if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
});
return parentRoot && ts.isSourceFile(parentRoot);
}
function isComposedFunction$1(checker, func) {
let isComposed = false;
func.parameters.forEach((param) => {
let type2 = checker.getTypeAtLocation(param);
if (type2.getCallSignatures().length > 0) {
isComposed = true;
}
});
return isComposed;
}
function resolveDeps$1(checker, root, table = {
graph: /* @__PURE__ */ new Map(),
functions: /* @__PURE__ */ new Map(),
structs: /* @__PURE__ */ new Map(),
structsProps: /* @__PURE__ */ new Map(),
globals: /* @__PURE__ */ new Map(),
composed: /* @__PURE__ */ new Map()
}) {
function resolveFunction(f1, f2, call) {
let n1 = f1 ? resolveFunctionName$1(f1) : "main";
let n2 = resolveFunctionName$1(f2);
if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || hasShadeupDocTag(f2, "noemit_gpu"))
return;
if (isComposedFunction$1(checker, f2)) {
n2 = n2 + "_composed_" + call.pos;
table.composed.set(n2, call);
}
let deps = table.graph.get(n1) ?? [];
if (!deps.includes(n2))
deps.push(n2);
table.graph.set(n1, deps);
table.functions.set(n2, f2);
}
function resolveStruct(decl) {
let name = resolveStructName$1(decl);
if (table.structs.has(name))
return;
for (let member of decl.members) {
if (ts.isPropertyDeclaration(member)) {
let type2 = checker.getTypeAtLocation(member);
resolveTypeUse(type2, member);
}
}
table.structs.set(name, decl);
}
function isValidShaderType(type2, checker2) {
let symbol = type2.aliasSymbol || type2.getSymbol();
let name = checker2.typeToString(type2);
let bases = type2.getBaseTypes();
if (bases && bases.length > 0) {
for (let base of bases) {
if (!isValidShaderType(base, checker2))
return false;
}
}
if (TYPE_BLACKLIST$1.includes(symbol?.getName() ?? "")) {
return false;
}
return !TYPE_BLACKLIST$1.includes(name);
}
function resolveTypeUse(typeNode, context2, fullStruct = false) {
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
let name = checker.typeToString(typeNode);
if (!isValidShaderType(typeNode, checker)) {
throw new GLSLCompilationError(`Type '${name}' is not supported in shaders`, context2);
}
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
resolveStruct(decl);
}
let typestr = checker.typeToString(typeNode);
if (typeNode.aliasTypeArguments)
for (let args of typeNode.aliasTypeArguments) {
resolveTypeUse(args, context2, typestr.startsWith("buffer<"));
}
}
function resolvePropertyAccess(node2) {
let typeNode = checker.getTypeAtLocation(node2.expression);
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
checker.typeToString(typeNode);
if (!isValidShaderType(typeNode, checker)) {
throw new GLSLCompilationError(
`Type '${symbol?.getName()}' is not supported in shaders`,
node2
);
}
resolveTypeUse(typeNode, node2);
resolveTypeUse(checker.getTypeAtLocation(node2), node2);
let prop = node2.name.getText();
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
let name2 = resolveStructName$1(decl);
let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set();
props.add(prop);
table.structsProps.set(name2, props);
}
}
walkNodes$2(root, (node2) => {
if (ts.isCallExpression(node2)) {
let exprSmybol = checker.getSymbolAtLocation(node2.expression);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
let funcDeclar = exprSmybol.getDeclarations()?.[0];
exprSmybol.valueDeclaration;
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
let signature = checker.getResolvedSignature(node2);
let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol);
if (mapping === null) {
let parentDeclar = closest(
node2,
(n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n)
);
if (parentDeclar && ts.isArrowFunction(parentDeclar)) {
let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n));
if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) {
let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression);
if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) {
parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol);
}
if (parentParentSymbol) {
let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0];
if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) {
resolveFunction(parentParentFuncDeclar, funcDeclar, node2);
}
}
}
} else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) {
resolveFunction(parentDeclar, funcDeclar, node2);
} else {
resolveFunction(null, funcDeclar, node2);
}
if (!table.graph.has(resolveFunctionName$1(funcDeclar))) {
table.graph.set(resolveFunctionName$1(funcDeclar), []);
resolveDeps$1(checker, funcDeclar, table);
}
let sig = checker.getSignatureFromDeclaration(funcDeclar);
let returnType = checker.getReturnTypeOfSignature(sig);
resolveTypeUse(returnType, node2);
}
}
}
}
if (ts.isPropertyAccessExpression(node2)) {
resolvePropertyAccess(node2);
}
if (ts.isIdentifier(node2)) {
if (checker.getSymbolAtLocation(node2)) {
let decl = checker.getSymbolAtLocation(node2)?.declarations;
let type2 = checker.getTypeAtLocation(node2);
resolveTypeUse(type2, node2);
if (decl && ts.isVariableDeclaration(decl[0])) {
if (!isInSameScope$1(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) {
if (isVariableDeclarationValue$1(checker, decl[0])) {
table.globals.set(node2.text.toString(), decl[0]);
}
}
}
}
}
if (ts.isVariableDeclaration(node2)) {
let type2 = checker.getTypeAtLocation(node2);
resolveTypeUse(type2, node2);
}
});
return table;
}
function resolveUniforms$1(checker, root) {
let uniforms = [];
walkNodesWithCalls$1(checker, root, (node2) => {
if (ts.isIdentifier(node2)) {
let decl = checker.getSymbolAtLocation(node2);
if (decl && decl.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(decl);
}
if (decl && decl.declarations && decl.declarations.length == 1) {
let declNode = decl.declarations[0];
if (declNode) {
if (isVariableDeclarationValue$1(checker, declNode)) {
if (!isInSameScope$1(declNode, node2) && !isInShader$2(declNode)) {
if (uniforms.findIndex((d) => d === declNode) == -1)
uniforms.push(declNode);
}
}
}
}
}
});
return uniforms;
}
function isVariableDeclarationValue$1(checker, node2) {
try {
if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) {
let type2 = checker.getTypeAtLocation(node2);
let calls = type2.getCallSignatures();
return calls.length == 0;
} else {
return false;
}
} catch (e) {
return false;
}
}
function isUniformable$1(checker, decl) {
let exprSmybol = checker.getSymbolAtLocation(decl);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
exprSmybol.getDeclarations()?.[0];
}
return ts.isVariableDeclaration(decl) || ts.isParameter(decl);
}
function addGLSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) {
let deps = resolveDeps$1(checker, root);
let uniforms = resolveUniforms$1(checker, root);
let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat();
let sorted = [];
try {
sorted = toposort(mapping).reverse();
} catch (e) {
sorted = [];
}
let preFuncs = [];
for (let s of deps.structs.values()) {
let name = resolveStructName$1(s);
let hasAnyProperty = false;
let sp = deps.structsProps.get(name);
let members = s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return "";
let type2 = checker.getTypeAtLocation(m);
let translated = translateType$1(checker, type2);
let preComment = "";
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
preComment = `// `;
}
}
if (preComment == "") {
hasAnyProperty = true;
}
return new SourceNode(
m.getStart(),
m.getEnd(),
`${preComment} ${translated} ${m.name.getText()};
`
);
});
let memberNames = s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return "";
checker.getTypeAtLocation(m);
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
return "";
}
}
return m.name.getText();
}).filter((m) => m != "");
let memberParams = s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return "";
let type2 = checker.getTypeAtLocation(m);
let translated = translateType$1(checker, type2);
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
return "";
}
}
return translated + " " + m.name.getText();
}).filter((m) => m != "");
if (!hasAnyProperty)
continue;
preFuncs.push(
new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} {
`, ...members, "\n};\n"])
);
if (name != "ShaderInput" && name != "ShaderOutput") {
preFuncs.push(
new SourceNode(s.getStart(), s.getEnd(), [
name + " _make_struct_" + name + "(",
memberParams.join(", ") + ")",
" {\n",
name,
" _s;",
"",
...memberNames.map((m) => ` _s.${m} = ${m};
`),
" return _s;\n",
"}\n"
])
);
}
}
for (let u of uniforms) {
if (isUniformable$1(checker, u)) {
let _type = checker.getTypeAtLocation(u);
let translated = translateType$1(checker, _type);
let isGlobalVar = isRootNode$1(u);
let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`;
if (translated.includes("[]")) {
translated = translated.replace(/\[\]$/, ``);
preFuncs.push(
new SourceNode(u.getStart(), u.getEnd(), [
"uniform ",
"int",
" ",
glslVarName,
"_size;\n"
])
);
glslVarName += `[%${glslVarName}_size%]`;
}
preFuncs.push(
new SourceNode(u.getStart(), u.getEnd(), ["uniform ", translated, " ", glslVarName, ";\n"])
);
if (translated == "sampler2D") {
preFuncs.push(
new SourceNode(u.getStart(), u.getEnd(), ["uniform vec2 ", glslVarName, "_size;\n"])
);
}
}
}
for (let k of sorted) {
if (k == "main")
continue;
let v = deps.functions.get(k);
if (v) {
let sourceFile2 = v.getSourceFile();
let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName);
preFuncs.push(
compile$2(
{ parentFunction: v, checker, composed: deps.composed.get(k) ?? null },
v,
originalFile2?.mapping
)
);
}
}
let sourceFile = root.getSourceFile();
let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName);
let main = compile$2(
{
checker
},
root,
originalFile.mapping
);
preFuncs.push(main);
let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs);
let ss = { indexMapping: [], str: "" };
source.toString(ss);
let matches = glslHeader.match(/^([a-zA-Z_][a-zA-Z0-9_]+ [^\(]+)/gm);
let finalShaderOutput = ss.str;
let headerSplits = [];
for (let i = 0; i < matches.length; i++) {
let index = glslHeader.indexOf(matches[i]);
let toIndex = i == matches.length - 1 ? glslHeader.length : glslHeader.indexOf(matches[i + 1]);
headerSplits.push(glslHeader.substring(index, toIndex));
}
let realHeader = "";
for (let i = 0; i < headerSplits.length; i++) {
let headerText = headerSplits[i];
let fnName = headerText.match(/^[a-zA-Z_][a-zA-Z0-9_]+ ([^\(]+)/)?.[1];
if (fnName) {
if (finalShaderOutput.includes(fnName)) {
realHeader += headerText;
}
}
}
finalShaderOutput = realHeader + finalShaderOutput;
let output = new GLSLShader(`shd_${key}`, finalShaderOutput);
output.sourceMapping = ss.indexMapping;
for (let u of uniforms) {
if (isUniformable$1(checker, u)) {
let name = u.name.getText();
let isGlobalVar = isRootNode$1(u);
if (name) {
let filterProps = function(props) {
if (props && props.name) {
let sp = deps.structsProps.get(props.name);
let realStruct = deps.structs.get(props.name);
if (props.type == "struct" && realStruct) {
for (let f of Object.keys(props.fields)) {
if (!sp || !sp.has(f)) {
delete props.fields[f];
} else {
if (props.fields[f].type == "struct") {
props.fields[f] = filterProps(props.fields[f]);
}
}
}
}
}
return props;
};
let typeOut = getDeclarationType$1(checker, u);
let typeNode = checker.getTypeAtLocation(u);
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
resolveStructName$1(decl);
}
if (isGlobalVar) {
output.globals[name] = {
fileName: getNodeSourceFileName$1(u),
structure: filterProps(translateType$1(checker, typeOut, true))
};
} else {
output.locals[name] = filterProps(translateType$1(checker, typeOut, true));
}
}
}
}
return output;
}
function getNodeSourceFileName$1(node2) {
let found = closest(node2, (n) => ts.isSourceFile(n));
if (found && ts.isSourceFile(found)) {
return found.fileName;
} else {
return "";
}
}
function walkNodes$2(node2, cb) {
cb(node2);
node2.forEachChild((n) => walkNodes$2(n, cb));
}
function walkNodesWithCalls$1(checker, node2, cb) {
cb(node2);
node2.forEachChild((n) => {
if (ts.isCallExpression(node2)) {
let exprSmybol = checker.getSymbolAtLocation(node2.expression);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
let funcDeclar = exprSmybol.getDeclarations()?.[0];
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
let signature = checker.getResolvedSignature(node2);
let mapping = findRealSignatureMappingToGLSL(checker, signature) ?? findSignatureMappingToGLSL(checker, exprSmybol);
if (mapping === null) {
if (funcDeclar.body) {
walkNodesWithCalls$1(checker, funcDeclar.body, cb);
}
}
}
}
}
walkNodesWithCalls$1(checker, n, cb);
});
}
function findSignatureMappingToGLSL(checker, sym) {
let matcher = /=(?:glsl|univ)\((.+)\)$/g;
if (!sym.valueDeclaration)
return null;
let doc = ts.getJSDocTags(sym.valueDeclaration);
for (let d of doc) {
if (d.tagName.text !== "shadeup")
continue;
if (typeof d.comment === "string") {
let matches = matcher.exec(d.comment);
if (matches) {
return matches[1];
}
}
}
return null;
}
function findRealSignatureMappingToGLSL(checker, sig) {
let matcher = /=(?:glsl|univ)\((.+)\)$/g;
let doc = ts.getJSDocTags(sig.getDeclaration());
for (let d of doc) {
if (d.tagName.text !== "shadeup")
continue;
if (typeof d.comment === "string") {
let matches = matcher.exec(d.comment);
if (matches) {
return matches[1];
}
}
}
return null;
}
function removeDoubleUnderscores$1(str) {
return str.replace(/__/g, "_ii");
}
let {
factory,
isArrayTypeNode,
isCallExpression,
isIdentifier,
isPropertyAccessChain,
isPropertyAccessExpression
} = ts;
const TYPE_BLACKLIST = [
"never",
"object",
"symbol",
"bigint",
"undefined",
"null",
"map",
"string"
];
const RESERVED_WORDS = [
"this",
"target",
"attribute",
"sample",
"varying",
"uniform",
"layout",
"delete"
];
function generateDefaultForType$1(checker, _type_node) {
let _type = checker.getTypeFromTypeNode(_type_node);
let name = (_type.aliasSymbol || _type.getSymbol())?.escapedName.toString();
switch (name) {
case "int":
return "i32(0)";
case "float":
return "f32(0.0)";
case "float2":
return "vec2(0.0, 0.0)";
case "float3":
return "vec3(0.0, 0.0, 0.0)";
case "float4":
return "vec4(0.0, 0.0, 0.0, 0.0)";
case "int2":
return "vec2(0, 0)";
case "int3":
return "vec3(0, 0, 0)";
case "int4":
return "vec4(0, 0, 0, 0)";
case "uint":
return "u32(0)";
case "uint2":
return "vec2(0, 0)";
case "uint3":
return "vec3(0, 0, 0)";
case "uint4":
return "vec4(0, 0, 0, 0)";
case "float2x2":
return "mat2x2(0.0, 0.0, 0.0, 0.0)";
case "float3x3":
return "mat3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "float4x4":
return "mat4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "bool":
return "0";
default:
let decl = _type.getSymbol()?.getDeclarations();
if (ts.isTupleTypeNode(_type_node)) {
let len = _type_node.elements.length;
let args = [];
let rootNode = _type_node.elements[0];
if (rootNode) {
for (let i = 0; i < len; i++) {
args.push(generateDefaultForType$1(checker, _type_node.elements[i]));
}
let rootType = checker.getTypeFromTypeNode(rootNode);
return translateType(checker, rootType) + `[${len}] {` + args.join(", ") + "}";
} else {
return "0";
}
}
if (decl && decl.length > 0) {
let d = decl[0];
let structProps = [];
if (ts.isClassDeclaration(d)) {
let symd = _type.getSymbol();
symd?.members?.forEach((v, k) => {
let decl2 = v.valueDeclaration;
if (decl2 && ts.isPropertyDeclaration(decl2)) {
structProps.push([k?.toString() ?? "", decl2.type]);
}
});
let sortedPropsByKey = structProps.sort((a, b) => {
return a[0].localeCompare(b[0]);
});
let args = sortedPropsByKey.map((p) => {
return "/* " + p[0] + ": */ " + generateDefaultForType$1(checker, p[1]) + "\n";
});
return "_make_struct_" + resolveStructName(d) + "(\n" + args.join(", ") + "\n)";
} else {
return "0";
}
} else {
return "0";
}
}
}
function getTypeFallback$1(checker, t) {
let n = (t.aliasSymbol || t.getSymbol())?.escapedName;
if (!n && t.intrinsicName)
n = t.intrinsicName;
if (typeof n !== "string") {
let props = t.getApparentProperties();
if (props.length > 0) {
for (let p of props) {
if (p.escapedName.toString() === "_opaque_int")
return "int";
if (p.escapedName.toString() === "_opaque_float")
return "float";
if (p.escapedName.toString() === "_opaque_uint")
return "uint";
}
}
let btype = t.getBaseTypes();
if (btype && btype.length > 0) {
for (let b of btype) {
let tn = getTypeFallback$1(checker, b);
if (tn)
return tn;
}
return null;
}
} else {
return n;
}
}
function followTypeReferences(t) {
if (t.flags & ts.TypeFlags.Object && t.objectFlags & ts.ObjectFlags.Reference) {
if (t.target === t) {
return t;
}
return followTypeReferences(t.target);
} else {
return t;
}
}
function getArrayTypeInfo(checker, t) {
let n = getTypeFallback$1(checker, t);
let originalType = t;
if (n === void 0) {
t = followTypeReferences(t);
}
let isArray = false;
let staticSize = -1;
let elementType = "";
if (n === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = originalType;
let args = typeRef.typeArguments || checker.getTypeArguments(typeRef);
let translated = translateType(checker, args[0]);
if (tsutils.isTupleType(t)) {
staticSize = t.fixedLength;
}
checker.typeToString(typeRef);
isArray = true;
elementType = translated;
}
return {
isArray,
staticSize,
elementType
};
}
function translateType(checker, t, templateFormat = false, usedInsidePotentiallyExternalType = false) {
let n = getTypeFallback$1(checker, t);
let originalType = t;
if (n === void 0) {
t = followTypeReferences(t);
}
if (templateFormat) {
let name = n?.toString() ?? "unknown";
if (name === "Array" || name === "array" || name === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = originalType;
let args = typeRef.typeArguments || checker.getTypeArguments(typeRef);
return {
type: name == "buffer" ? "buffer" : "array",
element: translateType(checker, args[0], true),
staticSize: args.length
};
}
if (name == "boolean" || name == "false" || name == "true")
name = "bool";
if (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint") || name == "bool" || name == "texture2d" || name == "texture3d")
return { type: "primitive", name };
if (name == "atomic") {
let args = t.typeArguments || checker.getTypeArguments(t);
let translated = translateType(checker, args[0]);
return { type: "primitive", name, element: translated };
}
let symbol = t.aliasSymbol || t.getSymbol();
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
if (ts.isClassDeclaration(symbol.declarations[0])) {
let fields = [];
let decl = symbol.declarations[0];
for (let member of decl.members) {
if (ts.isPropertyDeclaration(member)) {
let name2 = member.name.getText();
let type2 = checker.getTypeFromTypeNode(member.type);
fields.push([name2, translateType(checker, type2, true)]);
}
}
return {
type: "struct",
name: resolveStructName(decl),
fields
};
} else {
return {
type: "unknown"
};
}
}
} else {
if (n === "Array" || n === "array" || n === "buffer" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = originalType;
let args = typeRef.typeArguments || checker.getTypeArguments(typeRef);
let translated = translateType(checker, args[0]);
let typeInfo = getWGSLTypeInfo(translated);
let toStringed = checker.typeToString(typeRef);
if (n == "buffer") {
return `array<${translated}>`;
}
if (typeInfo.needsAlignment) {
translated = `vec4<${typeInfo.elementType ?? "f32"}>`;
}
if (toStringed.endsWith("[]")) {
return "array<" + translated + ">";
} else {
let arraySize = 0;
if (tsutils.isTupleType(t)) {
arraySize = t.fixedLength;
}
return "array<" + translated + ", " + arraySize + ">";
}
}
if (n === "texture2d")
return `sampler`;
if (n == "atomic") {
let args = t.typeArguments || checker.getTypeArguments(t);
let translated = translateType(checker, args[0]);
return `atomic<${translated}>`;
}
if (n === "bool")
return "bool";
if (n === "boolean")
return "bool";
if (n === "uint8")
return "f32";
if (n === "float")
return "f32";
if (n === "float2")
return "vec2";
if (n === "float3")
return "vec3";
if (n === "float4")
return "vec4";
if (n === "int")
return "i32";
if (n === "int2")
return "vec2";
if (n === "int3")
return "vec3";
if (n === "int4")
return "vec4";
if (n === "uint")
return "u32";
if (n === "uint2")
return "vec2";
if (n === "uint3")
return "vec3";
if (n === "uint4")
return "vec4";
if (n === "float2x2")
return "mat2x2";
if (n === "float3x3")
return "mat3x3";
if (n === "float4x4")
return "mat4x4";
if (n === "void")
return "void";
if (n === "error")
return "void";
if (t.isUnion()) {
let types2 = t.types.map((t2) => translateType(checker, t2));
for (let sub of types2) {
if (sub && sub !== "void" && sub !== "undefined")
return sub;
}
}
let symbol = t.aliasSymbol || t.getSymbol();
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
if (ts.isClassDeclaration(symbol.declarations[0])) {
return resolveStructName(symbol.declarations[0]);
} else {
return n?.toString() ?? "void";
}
} else {
return n?.toString() ?? "void";
}
}
}
function isTypeNameVector(name) {
if (name == "float2" || name == "float3" || name == "float4" || name == "int2" || name == "int3" || name == "int4" || name == "uint2" || name == "uint3" || name == "uint4") {
return true;
}
return false;
}
function getTypeNameVectorElementType(name) {
if (name == "float") {
return ["float", 1];
}
if (name == "int") {
return ["int", 1];
}
if (name == "uint") {
return ["uint", 1];
}
if (name.startsWith("float")) {
return ["float", parseInt(name.substring(5))];
}
if (name.startsWith("int")) {
return ["int", parseInt(name.substring(3))];
}
if (name.startsWith("uint")) {
return ["uint", parseInt(name.substring(4))];
}
if (name.startsWith("f32")) {
return ["f32", 1];
}
if (name.startsWith("i32")) {
return ["i32", 1];
}
if (name.startsWith("u32")) {
return ["u32", 1];
}
if (name.endsWith("")) {
return ["float", parseInt(name.substring(3, 4))];
}
if (name.endsWith("")) {
return ["int", parseInt(name.substring(3, 4))];
}
if (name.endsWith("")) {
return ["uint", parseInt(name.substring(3, 4))];
}
return ["", 0];
}
function getTypeNameVectorElementTypeWGSL(name) {
if (name == "f32") {
return ["f32", 1];
}
if (name == "i32") {
return ["i32", 1];
}
if (name == "u32") {
return ["u32", 1];
}
if (name.endsWith("")) {
return ["f32", parseInt(name.substring(3, 4))];
}
if (name.endsWith("")) {
return ["i32", parseInt(name.substring(3, 4))];
}
if (name.endsWith("")) {
return ["u32", parseInt(name.substring(3, 4))];
}
return ["", 0];
}
function isTranslatedTypeNameVectorOrScalar(name) {
if (name == "float" || name == "int" || name == "uint")
return true;
if (name.endsWith("") || name.endsWith("") || name.endsWith("")) {
if (name.startsWith("vec2") || name.startsWith("vec3") || name.startsWith("vec4")) {
return true;
}
return true;
}
return false;
}
function getWGSLTypeInfo(name) {
switch (name) {
case "bool":
return { type: "bool", length: 1, size: 1, needsAlignment: true, elementType: "i32" };
case "u32":
return {
type: "integer",
length: 1,
signed: false,
size: 4,
needsAlignment: true,
elementType: "u32"
};
case "i32":
return {
type: "integer",
length: 1,
signed: true,
size: 4,
needsAlignment: true,
elementType: "i32"
};
case "f32":
return { type: "float", length: 1, size: 4, needsAlignment: true, elementType: "f32" };
case "vec2":
return {
type: "vector",
length: 2,
element: "float",
size: 8,
needsAlignment: true,
elementType: "f32"
};
case "vec3":
return {
type: "vector",
length: 3,
element: "float",
size: 12,
needsAlignment: true,
elementType: "f32"
};
case "vec4":
return {
type: "vector",
length: 4,
element: "float",
size: 16,
needsAlignment: false,
elementType: "f32"
};
case "vec2":
return {
type: "vector",
length: 2,
signed: true,
element: "integer",
size: 8,
needsAlignment: true,
elementType: "i32"
};
case "vec3":
return {
type: "vector",
length: 3,
signed: true,
element: "integer",
size: 12,
needsAlignment: true,
elementType: "i32"
};
case "vec4":
return {
type: "vector",
length: 4,
signed: true,
element: "integer",
size: 16,
needsAlignment: false,
elementType: "i32"
};
case "vec2":
return {
type: "vector",
length: 2,
signed: false,
element: "integer",
size: 8,
needsAlignment: true,
elementType: "u32"
};
case "vec3":
return {
type: "vector",
length: 3,
signed: false,
element: "integer",
size: 12,
needsAlignment: true,
elementType: "u32"
};
case "vec4":
return {
type: "vector",
length: 4,
signed: false,
element: "integer",
size: 16,
needsAlignment: false,
elementType: "u32"
};
case "mat2x2":
return { type: "matrix", element: "float", size: 16, needsAlignment: false };
case "mat3x3":
return { type: "matrix", element: "float", size: 36, needsAlignment: false };
case "mat4x4":
return { type: "matrix", element: "float", size: 64, needsAlignment: false };
default:
return { type: "unknown", size: 0, needsAlignment: false };
}
}
function isVector(checker, t) {
let name = getTypeFallback$1(checker, t);
if (name) {
return isTypeNameVector(name);
}
return false;
}
function getVectorElementType(checker, t) {
let name = getTypeFallback$1(checker, t);
if (name) {
return getTypeNameVectorElementType(name);
}
return ["", 0];
}
function isNumeric(checker, t) {
let name = getTypeFallback$1(checker, t);
if (name && (name.startsWith("float") || name.startsWith("int") || name.startsWith("uint"))) {
return true;
}
return false;
}
function escapeIdentifier(id) {
if (RESERVED_WORDS.includes(id)) {
return "_" + id;
}
return id.replaceAll("___", "_ii_").replaceAll("__", "_i_");
}
function isAssignableType(t) {
return !(t.startsWith("texture") || t.startsWith("sampler") || t.startsWith("buffer"));
}
function isGLSLType(name) {
return name.startsWith("vec") || name.startsWith("mat") || name.startsWith("sampler") || name.startsWith("texture") || name == "bool" || name == "f32" || name == "i32" || name == "void";
}
function autoCastNumeric(value, input, expected, node2) {
let inputType = getTypeNameVectorElementTypeWGSL(input);
let expectedType = getTypeNameVectorElementTypeWGSL(expected);
if (inputType[0] !== "" && expectedType[0] !== "") {
if (inputType[0] != expectedType[0]) {
if (expectedType[1] == 1) {
if (typeof expectedType[0] == "string" && expectedType[0].startsWith("vector")) {
return new SourceNode(value.startIndex, value.endIndex, [value]);
} else {
if (inputType[0] == "u32") {
throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2);
}
if (expectedType[0] == "i32")
;
return new SourceNode(value.startIndex, value.endIndex, [
`${expectedType[0]}(`,
value,
`)`
]);
}
} else {
if (inputType[0] == "u32") {
throw new GLSLCompilationError(`Cannot cast uint to ${expectedType[0]}`, node2);
}
return new SourceNode(value.startIndex, value.endIndex, [
`vec${expectedType[1]}<${expectedType[0]}>(`,
value,
`)`
]);
}
}
}
return value;
}
function isUniformAccess(ctx, expr) {
if (isCallExpression(expr)) {
expr = expr.expression;
}
let id = null;
if (ts.isIdentifier(expr)) {
id = expr;
}
if (isPropertyAccessExpression(expr)) {
let chain = expr;
while (chain.expression) {
if (ts.isPropertyAccessExpression(chain.expression)) {
chain = chain.expression;
} else {
break;
}
}
id = chain.expression;
}
if (id) {
if (ts.isIdentifier(id)) {
let sym = ctx.checker.getSymbolAtLocation(id);
if (sym && sym.flags & ts.SymbolFlags.Alias) {
sym = ctx.checker.getAliasedSymbol(sym);
}
if (sym?.declarations?.length == 1) {
let decl = sym.declarations[0];
if (isUniformable(ctx.checker, decl)) {
if (isVariableDeclarationValue(ctx.checker, decl)) {
if (!isInSameScope(decl, id)) {
if (!isInShader$1(decl)) {
return true;
}
}
}
}
}
}
}
return false;
}
function accessWrap(ctx, expr, inner) {
if (isPropertyAccessExpression(expr)) {
let chain = expr;
while (chain.expression) {
if (ts.isPropertyAccessExpression(chain.expression)) {
chain = chain.expression;
} else {
break;
}
}
let id = chain.expression;
if (ts.isIdentifier(id)) {
let sym = ctx.checker.getSymbolAtLocation(id);
if (sym && sym.flags & ts.SymbolFlags.Alias) {
sym = ctx.checker.getAliasedSymbol(sym);
}
if (sym?.declarations?.length == 1) {
let decl = sym.declarations[0];
if (isUniformable(ctx.checker, decl)) {
if (isVariableDeclarationValue(ctx.checker, decl)) {
if (!isInSameScope(decl, chain.expression)) {
if (!isInShader$1(decl)) {
let outputType = ctx.checker.getTypeAtLocation(expr);
let isBooleanAccess = false;
if (isArrayType$1(outputType, ctx.checker)) {
let typeRef = outputType;
let args = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef);
let t = args[0];
let n = getTypeFallback$1(ctx.checker, t);
if (n == "boolean" || n == "bool") {
isBooleanAccess = true;
}
} else {
let n = getTypeFallback$1(ctx.checker, outputType);
if (n == "boolean" || n == "bool") {
isBooleanAccess = true;
}
}
if (isBooleanAccess) {
return new SourceNode(inner.startIndex, inner.endIndex, [`((`, inner, `) == 1)`]);
}
}
}
}
}
}
}
}
return inner;
}
function getVectorMask(num) {
let outMask = "";
let comps = ["x", "y", "z", "w"];
for (let i = 0; i < num; i++) {
outMask += comps[i];
}
return outMask;
}
function convertConciseBodyToBlock(body) {
if (ts.isBlock(body)) {
return body;
} else {
return ts.factory.createBlock([ts.factory.createReturnStatement(body)]);
}
}
function getRealReturnType(checker, call) {
let fnCallSignature = checker.getResolvedSignature(call);
return fnCallSignature.getReturnType();
}
function augmentParameter(checker, p) {
const type2 = checker.getTypeAtLocation(p);
const tt = translateType(checker, type2);
if (tt == "sampler") {
const args = checker.getTypeArguments(type2);
let innerType = "f32";
if (args && args.length > 0) {
let [et, _] = getVectorElementType(checker, args[0]);
innerType = {
float: "f32",
int: "i32",
uint: "u32"
}[et];
}
return [
new SourceNode(p.getStart(), p.getEnd(), [
p.name.getText() + "_texture: texture_2d<" + innerType + ">"
])
];
}
return [];
}
function augmentArgument(ctx, arg) {
let type2 = ctx.checker.getTypeAtLocation(arg);
let tt = translateType(ctx.checker, type2);
if (tt == "sampler") {
let args = ctx.checker.getTypeArguments(type2);
if (args && args.length > 0) {
getVectorElementType(ctx.checker, args[0]);
}
return [new SourceNode(arg.getStart(), arg.getEnd(), [compile$1(ctx, arg), "_texture"])];
}
return [];
}
function compile$1(ctx, ast, originalMapping) {
function c2(ast2) {
if (!ast2) {
return s([]);
}
return compile$1(ctx, ast2);
}
function cplain(ast2) {
if (!ast2) {
return s([]);
}
return compile$1(
{
checker: ctx.checker,
parentFunction: ctx.parentFunction
},
ast2
);
}
function s(c22) {
if (originalMapping) {
let reverseMapped = lookupIndexMappingRange(originalMapping, ast.getStart(), ast.getEnd());
return new SourceNode(reverseMapped.start, reverseMapped.end, c22);
} else {
return new SourceNode(0, 0, c22);
}
}
function join(c22, sep) {
return c22.reduce((acc, cur) => {
if (acc.length === 0) {
return [cur];
}
return [...acc, sep, cur];
}, []);
}
function children() {
return ast.getChildren().map((child) => c2(child));
}
let prefixFunctions = [];
if (ctx.composed) {
if (ts.isMethodDeclaration(ast) || ts.isFunctionDeclaration(ast)) {
for (let [i, arg] of ctx.composed.arguments.entries()) {
if (ts.isArrowFunction(arg)) {
let paramFromIndex = ast.parameters[i];
let name = paramFromIndex.name.getText() + "_composed_" + arg.pos + "_arg_" + i;
let signature = ctx.checker.getSignatureFromDeclaration(arg);
let returnType = signature.getReturnType();
let vars = getClosureVars(ctx.checker, arg);
let vvv = vars.map((p) => {
let tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(p.declarations[0]));
return s([p.escapedName, isAssignableType(tt) ? "_const" : "", ": ", tt]);
});
let joins = join(
[
...arg.parameters.map((p) => {
let aug = augmentParameter(ctx.checker, p);
return [cplain(p), ...aug];
}).flat(),
...vvv
],
", "
);
let returnStr = " -> " + translateType(ctx.checker, returnType);
if (returnStr == " -> void")
returnStr = "";
prefixFunctions.push(
s([
"fn ",
name,
"(",
...joins,
")",
returnStr,
" {\n",
...vars.filter((p) => {
let type2 = ctx.checker.getTypeAtLocation(p.declarations[0]);
let tt = translateType(ctx.checker, type2);
return isAssignableType(tt);
}).map((p) => {
return s([
"var ",
p.escapedName.toString(),
" = ",
p.escapedName.toString(),
"_const;\n"
]);
}),
...arg.parameters.filter((p) => {
let type2 = ctx.checker.getTypeAtLocation(p.type);
let tt = translateType(ctx.checker, type2);
return isAssignableType(tt);
}).map((p) => {
return s(["var ", p.name.getText(), " = ", p.name.getText(), "_const;\n"]);
}),
...convertConciseBodyToBlock(arg.body).statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
])
);
}
}
}
}
function autoCastParameter(callExpr, argIndex) {
let signature = ctx.checker.getResolvedSignature(callExpr);
let params = signature.getParameters();
let param = params[argIndex];
let paramType = ctx.checker.getTypeOfSymbolAtLocation(param, callExpr);
let paramTypeString = translateType(ctx.checker, paramType);
let arg = callExpr.arguments[argIndex];
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeString = translateType(ctx.checker, argType);
if (paramTypeString !== argTypeString) {
return autoCastNumeric(c2(arg), argTypeString, paramTypeString, arg);
}
return s([c2(arg)]);
}
switch (ast.kind) {
case ts.SyntaxKind.FirstPunctuation:
return s([ast.getText()]);
case ts.SyntaxKind.SyntaxList:
return s(children());
case ts.SyntaxKind.SourceFile:
return s(children());
case ts.SyntaxKind.BreakStatement:
return s(["break;"]);
case ts.SyntaxKind.ContinueStatement:
return s(["continue;"]);
case ts.SyntaxKind.MethodDeclaration:
let fnDeclar = ast;
let fnName = resolveFunctionName(fnDeclar);
if (ctx.composed) {
fnName = fnName + "_composed_" + ctx.composed.pos;
}
let isStatic = false;
let signature = ctx.checker.getSignatureFromDeclaration(fnDeclar);
if (ts.canHaveModifiers(fnDeclar)) {
let mods = ts.getModifiers(fnDeclar);
if (mods) {
if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) {
isStatic = true;
}
}
}
let returnType = signature.getReturnType();
let returnStr = " -> " + translateType(ctx.checker, returnType);
if (returnStr == " -> void")
returnStr = "";
return s([
...prefixFunctions,
"fn ",
fnName,
"(",
...join(
[
...isStatic ? [] : [
"_this: " + translateType(ctx.checker, ctx.checker.getTypeAtLocation(fnDeclar.parent))
],
...fnDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
return true;
}).map((p) => {
const o = c2(p);
const aug = augmentParameter(ctx.checker, p);
return [o, ...aug];
}).flat()
],
", "
),
")",
returnStr,
" {\n",
...fnDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
return true;
}).map(
(p) => s([
"var ",
escapeIdentifier(p.name.getText()),
" = ",
escapeIdentifier(p.name.getText()),
"_const;\n"
])
),
...fnDeclar.body?.statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
]);
case ts.SyntaxKind.FunctionDeclaration:
let mthdDeclar = ast;
let mthdsignature = ctx.checker.getSignatureFromDeclaration(mthdDeclar);
let mthdreturnType = mthdsignature.getReturnType();
let mthdName = resolveFunctionName(mthdDeclar);
if (ctx.composed) {
mthdName = mthdName + "_composed_" + ctx.composed.pos;
}
let returnStrMethod = " -> " + translateType(ctx.checker, mthdreturnType);
if (returnStrMethod == " -> void")
returnStrMethod = "";
return s([
...prefixFunctions,
"fn ",
mthdName,
"(",
...join(
mthdDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
return true;
}).map((p) => {
const o = c2(p);
const aug = augmentParameter(ctx.checker, p);
return [o, ...aug];
}).flat(),
", "
),
")",
returnStrMethod,
" {\n",
...mthdDeclar.parameters.filter((p) => {
let type22 = ctx.checker.getTypeAtLocation(p);
if (type22.getCallSignatures().length > 0) {
return false;
}
let tt2 = translateType(ctx.checker, type22);
return isAssignableType(tt2);
}).map(
(p) => s([
"var ",
escapeIdentifier(p.name.getText()),
" = ",
escapeIdentifier(p.name.getText()),
"_const;\n"
])
),
...mthdDeclar.body?.statements.map((s2) => c2(s2)) ?? [],
"\n}\n\n"
]);
case ts.SyntaxKind.ReturnStatement:
let ret = ast;
if (!ctx.parentFunction) {
if (ret.expression) {
return s(["return ", c2(ret.expression), ";\n"]);
} else {
return s(["return;\n"]);
}
} else {
let expectedReturnType = ctx.checker.getSignatureFromDeclaration(ctx.parentFunction).getReturnType();
let actualReturnType = ctx.checker.getTypeAtLocation(ret.expression);
if (ret.expression) {
let sss = s([
"return ",
autoCastNumeric(
c2(ret.expression),
translateType(ctx.checker, actualReturnType),
translateType(ctx.checker, expectedReturnType),
ret.expression
),
";\n"
]);
return sss;
} else {
return s(["return;\n"]);
}
}
case ts.SyntaxKind.AsExpression:
let asExpr = ast;
return c2(asExpr.expression);
case ts.SyntaxKind.Parameter:
let param = ast;
if (ctx.composed) {
let indexOf2 = param.parent.parameters.indexOf(param);
let expr2 = ctx.composed.arguments[indexOf2];
if (expr2) {
if (ts.isArrowFunction(expr2)) {
let vars = getClosureVars(ctx.checker, expr2.body);
let closureVars = vars.map((v) => {
return s([
v.name,
": ",
translateType(ctx.checker, ctx.checker.getTypeAtLocation(v.valueDeclaration))
]);
});
return s(join(closureVars, ", "));
}
}
}
const tt = translateType(ctx.checker, ctx.checker.getTypeAtLocation(param));
return s([
escapeIdentifier(param.name.getText()),
isAssignableType(tt) ? "_const" : "",
": ",
tt
]);
case ts.SyntaxKind.ArrowFunction:
let arrow = ast;
let body = convertConciseBodyToBlock(arrow.body);
let preMain = "";
if (ctx.isComputeShader) {
preMain = `
@compute @workgroup_size(${ctx.computeSize[0]}, ${ctx.computeSize[1]}, ${ctx.computeSize[2]})`;
}
return s([
"\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_BEFORE__*/" + preMain + "\nfn main(/*__SHADEUP_TEMPLATE_INPUT*/)" + (ctx.isComputeShader ? "" : "-> /*__SHADEUP_TEMPLATE_OUTPUT*/") + "{\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_START__*/\n",
...body.statements.filter((s2) => !ts.isFunctionDeclaration(s2)).map((s2) => c2(s2)),
"\n/*__SHADEUP_TEMPLATE_INSERT_MAIN_END__*/\n}\n"
]);
case ts.SyntaxKind.VariableStatement:
let varStatement = ast;
return s([
...join(
varStatement.declarationList.declarations.map((d) => c2(d)),
", "
),
";\n"
]);
case ts.SyntaxKind.VariableDeclaration:
let varDecl = ast;
let type2 = ctx.checker.getTypeAtLocation(varDecl);
let fullText = varDecl.getSourceFile().getFullText();
let fullStart = varDecl.getFullStart();
let prefix = `// @workgroup
`;
let mySelf = fullText.slice(fullStart - prefix.length, fullStart);
if (mySelf.includes("@workgroup")) {
return s([]);
} else {
let translated = translateType(ctx.checker, type2);
if (translated.startsWith("array")) {
translated = "";
}
if (isInShader$1(varDecl)) {
let arrType = ctx.checker.getTypeAtLocation(varDecl);
let typeInfo = getArrayTypeInfo(ctx.checker, arrType);
if (typeInfo.isArray) {
if (typeInfo.staticSize <= 0) {
throw new GLSLCompilationError(
"Cannot declare an array without a static size in a shader",
varDecl
);
}
}
}
let initializerVal = c2(varDecl.initializer);
if (translated) {
let leftType2 = type2;
let rightType2 = ctx.checker.getTypeAtLocation(varDecl.initializer);
if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) {
let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2);
let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2);
if (leftElementType != rightElementType) {
if (leftElementType == "float" && rightElementType == "int") {
initializerVal = s([`vec${leftElementSize}f(`, initializerVal, ")"]);
} else if (leftElementType == "int" && rightElementType == "float") {
initializerVal = s([`vec${leftElementSize}i(`, initializerVal, ")"]);
}
}
}
if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) {
let leftTypeStr = translateType(ctx.checker, leftType2);
let rightTypeStr = translateType(ctx.checker, rightType2);
if (leftTypeStr != rightTypeStr) {
initializerVal = s([
autoCastNumeric(initializerVal, rightTypeStr, leftTypeStr, varDecl.initializer)
]);
}
}
}
if (translated == "___atomic_compare_exchange_result") {
translated = "";
}
return s([
"var ",
escapeIdentifier(varDecl.name.getText()),
translated ? ": " : "",
translated,
" = ",
initializerVal
]);
}
case ts.SyntaxKind.CallExpression:
let call = ast;
let exprSmybol = ctx.checker.getSymbolAtLocation(call.expression);
if (call.expression.getText() == "Math.random") {
return s(["0.0"]);
}
if (!exprSmybol) {
return s(["/* TODO: Unknown symbol */"]);
}
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = ctx.checker.getAliasedSymbol(exprSmybol);
}
let symName = exprSmybol?.getName() ?? call.expression.getText();
if (ts.isIdentifier(call.expression)) {
if (isUniformAccess(ctx, call.expression)) {
let typ = ctx.checker.getTypeAtLocation(call.expression);
if (typ.getSymbol().getName().startsWith("shader") || typ.aliasSymbol && typ.aliasSymbol.getName() == "shader") {
console.log("Uniform access to shader", typ.getSymbol().getName());
}
}
}
if (symName == "__index") {
let postfix2 = "";
let t2 = ctx.checker.getTypeAtLocation(
call.expression.expression
);
isUniformAccess(
ctx,
call.expression.expression
);
if (ts.isPropertyAccessExpression(call.expression)) {
let innerType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.expression.expression)
);
let returnType2 = getRealReturnType(ctx.checker, call);
let vecOut = getVectorElementType(ctx.checker, returnType2);
let outMask = getVectorMask(vecOut[1]);
if (innerType == "sampler") {
if (ts.isCallExpression(call.expression.expression)) {
let callIndex = call.expression.expression;
return s([
"textureLoad(",
c2(callIndex.expression),
"_texture, ",
...join([...callIndex.arguments.map((a) => c2(a))], ","),
", vec2(",
c2(call.arguments[0]),
"), 0)." + outMask
]);
} else {
return s([
"textureLoad(",
c2(call.expression.expression),
"_texture, vec2(",
c2(call.arguments[0]),
"), 0)." + outMask
]);
}
}
}
let translatedOut = translateType(ctx.checker, ctx.checker.getTypeAtLocation(call));
if (isArrayType$1(t2, ctx.checker) && isUniformAccess(ctx, call.expression.expression) && !translatedOut.startsWith("mat")) {
let typeRef = t2;
let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef);
let translated = translateType(ctx.checker, args2[0]);
let typeInfo = getWGSLTypeInfo(translated);
if (typeInfo.needsAlignment) {
translated = `vec4<${typeInfo.elementType ?? "f32"}>`;
}
let lengths = {
1: "x",
2: "xy",
3: "xyz",
4: "xyzw"
};
if (typeInfo.type != "unknown") {
postfix2 = `.${lengths[typeInfo.length ?? 1]}`;
}
}
return accessWrap(
ctx,
call.expression.expression,
s([c2(call.expression), "[", c2(call.arguments[0]), "]", postfix2])
);
} else if (symName == "attr") {
let expr2 = call.expression;
if (ts.isPropertyAccessExpression(expr2)) {
let left2 = expr2.expression;
let leftName = ctx.checker.getTypeAtLocation(left2).getSymbol()?.getName() ?? "";
if (leftName == "ShaderInput") {
if (call.arguments.length >= 1) {
let arg1 = call.arguments[0];
if (ts.isCallExpression(arg1)) {
arg1 = arg1.arguments[0];
}
if (!ts.isNumericLiteral(arg1)) {
throw new GLSLCompilationError("Attribute index must be a number literal", arg1);
}
let index = parseInt(arg1.getText());
let interpMode = "perspective";
if (call.arguments.length >= 2) {
let arg2 = call.arguments[1];
if (ts.isStringLiteral(arg2)) {
interpMode = arg2.text;
}
}
let valType = "";
if (call.typeArguments.length == 1) {
valType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.typeArguments[0])
);
}
ctx.addCustomAttribute("in", index, valType, interpMode);
return s(["_i_in.custom", index.toString()]);
}
} else if (leftName == "ShaderOutput") {
if (call.arguments.length >= 2) {
let arg1 = call.arguments[0];
if (ts.isCallExpression(arg1)) {
arg1 = arg1.arguments[0];
}
if (!ts.isNumericLiteral(arg1)) {
throw new GLSLCompilationError("Attribute index must be a number literal", arg1);
}
let index = parseInt(arg1.getText());
let interpMode = "perspective";
if (call.arguments.length >= 3) {
let arg2 = call.arguments[2];
if (ts.isStringLiteral(arg2)) {
interpMode = arg2.text;
}
}
let valType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.arguments[1])
);
ctx.addCustomAttribute("out", index, valType, interpMode);
return s(["_i_out.custom", index.toString(), " = ", c2(call.arguments[1])]);
}
}
}
} else if (symName == "len") {
let expr2 = call.expression;
if (ts.isPropertyAccessExpression(expr2)) {
let left2 = expr2.expression;
if (isUniformAccess(ctx, left2)) {
return s(["_in_uniforms.", c2(left2), "_size"]);
} else {
let arrType = ctx.checker.getTypeAtLocation(left2);
let typeInfo = getArrayTypeInfo(ctx.checker, arrType);
return s([typeInfo.staticSize.toString()]);
}
}
} else if (symName == "min" || symName == "max") {
if (call.arguments.length > 2) {
let args2 = call.arguments.map((a) => c2(a));
while (args2.length > 2) {
let left2 = args2.shift();
let right2 = args2.shift();
args2.unshift(s([symName, "(", left2, ",", right2, ")"]));
}
return s([symName, "(", ...join(args2, ","), ")"]);
}
} else if (symName == "clamp") {
if (call.arguments.length == 3) {
let inType = ctx.checker.getTypeAtLocation(call.arguments[0]);
let vType = translateType(ctx.checker, inType);
let vTypeInfo = getWGSLTypeInfo(vType);
if (vTypeInfo.type == "vector") {
let minV = call.arguments[1];
let maxV = call.arguments[2];
let minType = ctx.checker.getTypeAtLocation(minV);
let maxType = ctx.checker.getTypeAtLocation(maxV);
let minTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, minType));
let maxTypeInfo = getWGSLTypeInfo(translateType(ctx.checker, maxType));
if (minTypeInfo.type == "vector" && maxTypeInfo.type == "vector")
;
else {
let minStr = c2(minV);
let maxStr = c2(maxV);
if (minTypeInfo.type != "vector") {
minStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, minStr, ")"]);
}
if (maxTypeInfo.type != "vector") {
maxStr = s([`vec${vTypeInfo.length}<${vTypeInfo.elementType}>(`, maxStr, ")"]);
}
return s(["clamp(", c2(call.arguments[0]), ",", minStr, ",", maxStr, ")"]);
}
}
}
} else if (symName == "atomic") {
throw new GLSLCompilationError(
"Atomics cannot be constructed in shaders, create them outside or in a workgroup",
call.expression
);
} else if (symName == "sample") {
if (ts.isPropertyAccessExpression(call.expression)) {
let innerType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.expression.expression)
);
if (innerType == "sampler") {
if (ts.isCallExpression(call.expression.expression)) {
let callIndex = call.expression.expression;
return s([
"textureSample(",
c2(callIndex.expression),
"_texture, ",
c2(callIndex.expression),
",",
"vec2(",
c2(call.arguments[0]),
"),",
...join([...callIndex.arguments.map((a) => c2(a))], ","),
")"
]);
} else {
return s([
"textureSample(",
c2(call.expression.expression),
"_texture, ",
c2(call.expression.expression),
", vec2(",
c2(call.arguments[0]),
"))"
]);
}
}
}
} else if (symName == "__index_assign") {
let postfix2 = "";
if (ts.isPropertyAccessExpression(call.expression)) {
let innerType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.expression.expression)
);
if (innerType == "sampler") {
if (ts.isCallExpression(call.expression.expression)) {
let callIndex = call.expression.expression;
return s([
"textureStore(",
c2(callIndex.expression),
"_texture_write, ",
...join([...callIndex.arguments.map((a) => c2(a))], ","),
", vec2(",
c2(call.arguments[0]),
"), vec4(",
autoCastParameter(call, 1),
"))"
]);
} else {
return s([
"textureStore(",
c2(call.expression.expression),
"_texture_write, vec2(",
c2(call.arguments[0]),
"), vec4(",
autoCastParameter(call, 1),
"))"
]);
}
}
}
ctx.checker.getTypeAtLocation(
call.expression.expression
);
return accessWrap(
ctx,
call.expression.expression,
s([
c2(call.expression.expression),
"[",
c2(call.arguments[0]),
"]",
postfix2,
" = ",
autoCastParameter(call, 1)
])
);
} else if (symName == "eq" && call.expression.getText() == "__.eq") {
let leftArg = call.arguments[0];
let rightArg = call.arguments[1];
let leftType2 = ctx.checker.getTypeAtLocation(leftArg);
let rightType2 = ctx.checker.getTypeAtLocation(rightArg);
let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2);
if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) {
return s([
"squash_bool_vec",
leftElementSize.toString(),
"(",
c2(leftArg),
" == ",
c2(rightArg),
")"
]);
}
} else if (symName == "rand" && call.arguments.length == 0 && call.expression.getText() == "rand") {
throw new GLSLCompilationError(
"rand() in shaders needs to be seeded, use rand(seed) instead",
call
);
}
if (exprSmybol?.getName() == "makeVector" && exprSmybol.valueDeclaration) {
if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) {
let exprSig2 = ctx.checker.getResolvedSignature(call);
if (exprSig2) {
let returnType2 = ctx.checker.getReturnTypeOfSignature(exprSig2);
let returnTypeStr = translateType(ctx.checker, returnType2);
let returnTypeInfo = getWGSLTypeInfo(returnTypeStr);
let callType = translateType(ctx.checker, returnType2);
let argStrs = [];
for (let [i, arg] of call.arguments.entries()) {
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeStr = translateType(ctx.checker, argType);
let argTypeInfo = getWGSLTypeInfo(argTypeStr);
let paramType = ctx.checker.getTypeAtLocation(
exprSig2.parameters[i].getDeclarations()[0]
);
let paramTypeStr = translateType(ctx.checker, paramType);
if (argTypeInfo.elementType !== returnTypeInfo.elementType) {
paramTypeStr = `vec${argTypeInfo.length}<${returnTypeInfo.elementType}>`;
}
argStrs.push(autoCastNumeric(c2(arg), argTypeStr, paramTypeStr, arg));
}
return s([callType, "(", ...join(argStrs, ", "), ")"]);
}
}
}
if (exprSmybol?.getName() == "swizzle" && exprSmybol.valueDeclaration) {
if (ts.isFunctionDeclaration(exprSmybol.valueDeclaration)) {
ctx.checker.getSignatureFromDeclaration(exprSmybol.valueDeclaration);
let arg = call.arguments[0];
let arg2 = call.arguments[1];
let propAccess = "";
if (ts.isStringLiteral(arg2)) {
propAccess = arg2.text;
}
let argType = ctx.checker.getTypeAtLocation(arg);
if (isVector(ctx.checker, argType)) {
if (call.arguments.length == 2) {
return s([c2(arg), ".", propAccess]);
} else {
let t2 = s([
"var tempVal_",
call.getStart().toString(),
" = ",
c2(call.arguments[2]),
";\n"
]);
let assigns = [];
for (let i = 0; i < propAccess.length; i++) {
let char = propAccess[i];
assigns.push(
s([
c2(arg),
".",
char,
" = ",
"tempVal_",
call.getStart().toString(),
...propAccess.length > 1 ? [".", char] : [],
";\n"
])
);
}
return s([t2, ...assigns]);
}
} else if (isNumeric(ctx.checker, argType)) {
let numericType = translateType(ctx.checker, argType);
return s([`shadeup_up_swizzle_${propAccess}_${numericType}(`, c2(arg), ")"]);
} else {
return s([c2(arg), ".", propAccess]);
}
}
}
let mutations = {
arguments: new Array(call.arguments.length)
};
for (let [i, arg] of call.arguments.entries()) {
mutations.arguments[i] = null;
}
if (exprSmybol?.getName() == "max" || exprSmybol?.getName() == "min") {
let exprSig2 = ctx.checker.getResolvedSignature(call);
if (exprSig2 && exprSig2.parameters.length == 2) {
let skip = false;
let unbalanced = false;
let singleArg = -1;
let targetLength = 0;
let targetType = "";
for (let [i, arg] of call.arguments.entries()) {
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeStr = translateType(ctx.checker, argType);
let argTypeInfo = getWGSLTypeInfo(argTypeStr);
if (argTypeInfo.length === 1) {
if (unbalanced) {
skip = true;
}
unbalanced = true;
singleArg = i;
}
}
for (let [i, arg] of call.arguments.entries()) {
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeStr = translateType(ctx.checker, argType);
let argTypeInfo = getWGSLTypeInfo(argTypeStr);
if (argTypeInfo.length !== 1) {
targetLength = argTypeInfo.length;
targetType = argTypeInfo.elementType;
}
}
if (!skip && unbalanced && singleArg !== -1) {
mutations.arguments[singleArg] = s([
`vec${targetLength}<${targetType}>(`,
c2(call.arguments[singleArg]),
`)`
]);
}
}
}
let funcName = c2(call.expression);
let callArgs = [];
let preArgs = [];
let exprSig = ctx.checker.getResolvedSignature(call);
let exprDeclar = exprSig.getDeclaration();
if (exprDeclar) {
if (ts.isMethodDeclaration(exprDeclar)) {
let isStatic2 = false;
if (ts.canHaveModifiers(exprDeclar)) {
let mods = ts.getModifiers(exprDeclar);
if (mods) {
if (mods.some((m) => m.kind == ts.SyntaxKind.StaticKeyword)) {
isStatic2 = true;
}
}
}
if (!isStatic2) {
if (ts.isPropertyAccessExpression(call.expression)) {
preArgs.push(c2(call.expression.expression));
}
}
}
}
exprSmybol.getName() + "(";
for (let [i, arg] of call.arguments.entries()) {
let argStr = c2(arg);
if (exprSig) {
let p = exprSig.getTypeParameterAtPosition(i);
if (p) {
let translatedBase = translateType(ctx.checker, p);
let translatedPass = translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg));
if (isTranslatedTypeNameVectorOrScalar(translatedPass)) {
if (translatedBase != translatedPass && isGLSLType(translatedBase)) {
if (translatedBase == "vector2" || translatedBase == "vector3" || translatedBase == "vector4") {
argStr = argStr;
} else {
argStr = s([`${translatedBase}(`, argStr, `)`]);
}
}
}
} else {
translateType(ctx.checker, ctx.checker.getTypeAtLocation(arg));
}
}
if (ts.isArrowFunction(arg)) {
let arrow2 = arg;
let vars = getClosureVars(ctx.checker, arrow2.body);
if (vars.length > 0)
callArgs.push(vars.map((v) => v.escapedName).join(", "));
} else {
let augs = augmentArgument(ctx, arg);
if (augs.length > 0) {
argStr = s([argStr, ",", ...join(augs, ",")]);
}
callArgs.push(argStr);
}
}
const levelCalls = {
mix: true
};
const constructs = {
"vec2": true,
"vec3": true,
"vec4": true,
"vec2": true,
"vec3": true,
"vec4": true,
"vec2": true,
"vec3": true,
"vec4": true,
"mat2x2": true,
"mat3x3": true,
"mat4x4": true,
"mat2x2": true,
"mat3x3": true,
"mat4x4": true
};
if (exprSmybol) {
let mapping = findSignatureMappingToWGSL(ctx.checker, exprSmybol);
if (mapping !== null) {
let levelCastArguments = mapping.startsWith("!") || (levelCalls[mapping] ?? false) || (constructs[mapping] ?? false);
if (levelCastArguments) {
let minType = "";
let noOp = false;
for (let arg of call.arguments) {
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeName = translateType(ctx.checker, argType);
if (!(argTypeName == "f32" || argTypeName.endsWith("") || argTypeName == "i32" || argTypeName.endsWith(""))) {
noOp = true;
}
if (minType == "") {
if (argTypeName == "f32" || argTypeName.endsWith("")) {
minType = "f32";
} else if (argTypeName == "i32" || argTypeName.endsWith("")) {
minType = "i32";
}
} else if (argTypeName == "f32" || minType.endsWith("")) {
minType = "f32";
}
}
if (constructs[mapping]) {
noOp = false;
if (mapping.endsWith("")) {
minType = "f32";
} else if (mapping.endsWith("")) {
minType = "i32";
}
}
if (!noOp) {
for (let i = 0; i < callArgs.length; i++) {
let arg = call.arguments[i];
let argType = ctx.checker.getTypeAtLocation(arg);
let argTypeName = translateType(ctx.checker, argType);
let argTypeStripped = "";
if (argTypeName == "f32" || argTypeName.endsWith("")) {
argTypeStripped = "f32";
} else if (argTypeName == "i32" || argTypeName.endsWith("")) {
argTypeStripped = "i32";
}
if (argTypeStripped != minType) {
if (argTypeName.startsWith("f32") || argTypeName.startsWith("i32")) {
callArgs[i] = s([`${minType}(`, callArgs[i], `)`]);
} else if (argTypeName.endsWith("") || argTypeName.endsWith("")) {
let len = argTypeName.match(/\d+/)?.[0];
if (len === void 0) {
throw new Error("Invalid type");
}
callArgs[i] = s([`vec${len}<${minType}>(`, callArgs[i], `)`]);
} else
;
}
}
}
} else {
let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration());
sig = exprSig;
for (let i = 0; i < callArgs.length; i++) {
let arg = call.arguments[i];
let argType = ctx.checker.getTypeAtLocation(arg);
let paramType = ctx.checker.getTypeAtLocation(
sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0]
);
paramType = sig.getTypeParameterAtPosition(Math.min(i, sig.parameters.length - 1)) ?? paramType;
let carg = c2(arg);
let augs = augmentArgument(ctx, arg);
if (augs.length > 0) {
carg = s([carg, ",", ...join(augs, ",")]);
}
callArgs[i] = autoCastNumeric(
carg,
translateType(ctx.checker, argType),
translateType(ctx.checker, paramType),
arg
);
}
}
if (mapping.startsWith("!")) {
let template = mapping.slice(1);
let outs = [];
let argCounter = 0;
let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration());
for (let i = 0; i < callArgs.length; i++) {
let paramType = ctx.checker.getTypeAtLocation(
sig.parameters[Math.min(i, sig.parameters.length - 1)].getDeclarations()[0]
);
template = template.replace(
"`" + argCounter + "`",
ctx.checker.typeToString(paramType)
);
argCounter++;
}
let result = template.split("$");
for (let r of result) {
if (/^\d+$/.test(r)) {
outs.push(callArgs[parseInt(r)]);
} else if (/^\[\d+\]$/.test(r)) {
let templateType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(call.typeArguments[parseInt(r.slice(1, -1))])
);
outs.push(templateType);
} else if (r == "self") {
if (call.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
let propAccess = call.expression;
outs.push(c2(propAccess.getChildAt(0)));
} else {
outs.push(c2(call.expression));
}
} else {
outs.push(r);
}
}
return s(outs);
} else if (mapping.startsWith("#")) {
let typeName = "";
if (call.arguments.length > 0) {
let firstArg = call.arguments[0];
let firstArgType = ctx.checker.getTypeAtLocation(firstArg);
typeName = ctx.checker.typeToString(firstArgType);
}
return s([
new SourceNode(call.expression.getStart(), call.expression.getEnd(), [
mapping.substring(1) + typeName
]),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
} else {
for (let [i, mutation] of mutations.arguments.entries()) {
if (mutation) {
callArgs[i] = mutation;
}
}
return s([
new SourceNode(call.expression.getStart(), call.expression.getEnd(), [mapping]),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
} else {
let sig = ctx.checker.getSignatureFromDeclaration(exprSig.getDeclaration());
for (let i = 0; i < callArgs.length; i++) {
let arg = call.arguments[i];
let argType = ctx.checker.getTypeAtLocation(arg);
let paramType = ctx.checker.getTypeAtLocation(sig.parameters[i].getDeclarations()[0]);
let carg = c2(arg);
let augs = augmentArgument(ctx, arg);
if (augs.length > 0) {
carg = s([carg, ",", ...join(augs, ",")]);
}
callArgs[i] = autoCastNumeric(
carg,
translateType(ctx.checker, argType),
translateType(ctx.checker, paramType),
arg
);
}
}
if (exprSmybol.declarations[0].parent) {
let param2 = exprSmybol.declarations[0];
if (ts.isParameter(param2))
;
}
let funcDeclar = exprSmybol.valueDeclaration;
if (exprSmybol.declarations[0].parent) {
let param2 = exprSmybol.declarations[0];
if (ts.isParameter(param2)) {
let indexOf2 = param2.parent.parameters.indexOf(param2);
let additionalArgs = [];
if (ctx.composed) {
let realAnonymousFunc = ctx.composed.arguments[indexOf2];
if (ts.isArrowFunction(realAnonymousFunc)) {
let vars = getClosureVars(ctx.checker, realAnonymousFunc.body);
additionalArgs = vars.map((v) => v.escapedName);
callArgs.push(...additionalArgs);
return s([
funcName,
"_composed_",
realAnonymousFunc.pos.toString(),
"_arg_",
indexOf2.toString(),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
}
}
}
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
funcName = new SourceNode(
call.expression.getStart(),
call.expression.getEnd(),
resolveFunctionName(funcDeclar)
);
let parentDeclar = closest(ast, (n3) => ts.isFunctionDeclaration(n3));
if (parentDeclar && ts.isFunctionDeclaration(parentDeclar))
;
if (isComposedFunction(ctx.checker, funcDeclar)) {
return s([
funcName,
"_composed_",
call.pos.toString(),
"(",
...join([...preArgs, ...callArgs], ", "),
")"
]);
}
}
}
for (let [i, mutation] of mutations.arguments.entries()) {
if (mutation) {
callArgs[i] = mutation;
}
}
return s([funcName, "(", ...join([...preArgs, ...callArgs], ", "), ")"]);
case ts.SyntaxKind.NewExpression:
let newExpr = ast;
let newExprSymbol = getSymbolAtLocationAndFollowAliases(ctx.checker, newExpr.expression);
let args = [];
if (newExpr.arguments?.length == 1 && ts.isObjectLiteralExpression(newExpr.arguments[0])) {
let object = newExpr.arguments[0];
let props = object.properties;
let sortedPropsByKey = [];
let structProps = [];
newExprSymbol?.members?.forEach((v, k) => {
let decl2 = v.valueDeclaration;
if (decl2 && ts.isPropertyDeclaration(decl2)) {
const typeStr = translateType(ctx.checker, ctx.checker.getTypeAtLocation(decl2));
if (typeStr.startsWith("atomic<")) {
return;
}
structProps.push([k?.toString() ?? "", decl2.type]);
}
});
sortedPropsByKey = structProps.sort((a, b) => {
return a[0].localeCompare(b[0]);
});
args = [
...sortedPropsByKey.map((p) => {
let prop2 = props.find((p2) => {
if (ts.isPropertyAssignment(p2)) {
return p2.name.getText() == p[0];
} else if (ts.isShorthandPropertyAssignment(p2)) {
return p2.name.getText() == p[0];
} else {
return false;
}
});
if (prop2) {
if (ts.isPropertyAssignment(prop2)) {
let propType = ctx.checker.getTypeAtLocation(p[1]);
let propValType = ctx.checker.getTypeAtLocation(prop2.initializer);
let propTypeStr = translateType(ctx.checker, propType);
let propValTypeStr = translateType(ctx.checker, propValType);
if (propTypeStr != propValTypeStr) {
return s([
"/* ",
p[0],
": */ ",
autoCastNumeric(c2(prop2.initializer), propValTypeStr, propTypeStr, prop2),
"\n"
]);
} else {
return s(["/* ", p[0], ": */ ", c2(prop2.initializer), "\n"]);
}
} else if (ts.isShorthandPropertyAssignment(prop2)) {
return s(["/* ", p[0], ": */ ", c2(prop2.name), "\n"]);
} else {
return s(["/* ", c2(prop2), ": */ ", "\n"]);
}
} else {
return s(["/* ", p[0], ": */ ", generateDefaultForType$1(ctx.checker, p[1]), "\n"]);
}
})
];
}
let decl = ctx.checker.getTypeAtLocation(newExpr.expression).getSymbol()?.getDeclarations();
if (decl && ts.isClassDeclaration(decl[0])) {
return s(["_make_struct_", resolveStructName(decl[0]), "(\n", ...join(args, ", "), "\n)"]);
} else {
return s(["/*", ...join(args, ", "), "*/"]);
}
case ts.SyntaxKind.ExpressionStatement:
let expr = ast;
return s([c2(expr.expression), ";\n"]);
case ts.SyntaxKind.ObjectLiteralExpression:
let obj = ast;
return s([
"{",
...join(
obj.properties.map((p) => {
if (ts.isPropertyAssignment(p)) {
return s([c2(p.name), ": ", c2(p.initializer)]);
} else if (ts.isShorthandPropertyAssignment(p)) {
return s([c2(p.name)]);
} else {
return s(["/*", c2(p), "*/"]);
}
}),
", "
),
"}"
]);
case ts.SyntaxKind.ConditionalExpression:
let cond = ast;
let left = c2(cond.whenTrue);
let right = c2(cond.whenFalse);
let leftType = ctx.checker.getTypeAtLocation(cond.whenTrue);
let rightType = ctx.checker.getTypeAtLocation(cond.whenFalse);
if (isVector(ctx.checker, leftType) && isVector(ctx.checker, rightType) || isNumeric(ctx.checker, leftType) && isNumeric(ctx.checker, rightType)) {
let leftTypeStr = translateType(ctx.checker, leftType);
let rightTypeStr = translateType(ctx.checker, rightType);
let leftTypeInfo = getWGSLTypeInfo(leftTypeStr);
let rightTypeInfo = getWGSLTypeInfo(rightTypeStr);
if (leftTypeInfo.elementType == "f32") {
right = autoCastNumeric(
right,
translateType(ctx.checker, rightType),
translateType(ctx.checker, leftType),
cond
);
}
if (rightTypeInfo.elementType == "f32") {
left = autoCastNumeric(
left,
translateType(ctx.checker, leftType),
translateType(ctx.checker, rightType),
cond
);
}
}
return s(["select(", right, ", ", left, ", ", c2(cond.condition), ")"]);
case ts.SyntaxKind.Identifier:
let id = ast;
if (ts.isIdentifier(id)) {
let sym = ctx.checker.getSymbolAtLocation(id);
if (sym && sym.flags & ts.SymbolFlags.Alias) {
sym = ctx.checker.getAliasedSymbol(sym);
}
if (sym?.declarations?.length == 1) {
let decl2 = sym.declarations[0];
if (isUniformable(ctx.checker, decl2)) {
if (isVariableDeclarationValue(ctx.checker, decl2)) {
if (!isInSameScope(decl2, ast)) {
if (!isInShader$1(decl2)) {
if (ts.isBinaryExpression(ast.parent)) {
if (ast.parent.left == ast) {
throw new GLSLCompilationError(
`Cannot assign to variable '${id.text.toString()}' because it is not declared in the shader`,
ast
);
}
}
let _type = ctx.checker.getTypeAtLocation(decl2);
let translated = translateType(ctx.checker, _type);
let isGlobalVar = isRootNode(decl2);
let glslVarName = `${!isSpecialUniformType(translated) ? "_in_uniforms." : ""}_ext_uniform_${isGlobalVar ? "global" : "local"}_${id.text.toString()}`;
return s([glslVarName]);
} else {
return s([escapeIdentifier(id.text.toString())]);
}
}
}
}
}
return s([escapeIdentifier(id.text.toString())]);
} else {
return c2(id.expression);
}
case ts.SyntaxKind.PropertyAccessExpression:
let prop = ast;
let isStaticMember = isStaticPropertyAccessExpression(ctx.checker, prop);
if (isStaticMember) {
return s([c2(prop.expression), "_static_", c2(prop.name)]);
} else {
let propName = prop.name.getText();
if (propName == "__index") {
return s([c2(prop.expression)]);
} else if (propName == "size") {
let innerType = translateType(
ctx.checker,
ctx.checker.getTypeAtLocation(prop.expression)
);
if (innerType == "sampler") {
return s(["vec2(textureDimensions(", c2(prop.expression), "_texture))"]);
}
} else {
return s([c2(prop.expression), ".", c2(prop.name)]);
}
}
case ts.SyntaxKind.ThisKeyword:
return s(["_this"]);
case ts.SyntaxKind.FirstLiteralToken:
let lit = ast;
return s([lit.text]);
case ts.SyntaxKind.IfStatement:
let ifStmt = ast;
if (isIdentifier(ifStmt.expression)) {
if (ifStmt.expression.escapedText == "PLATFORM_WEBGPU") {
return s([c2(ifStmt.thenStatement)]);
}
if (ifStmt.expression.escapedText == "PLATFORM_WEBGL") {
if (ifStmt.elseStatement) {
return s([c2(ifStmt.elseStatement)]);
} else {
return s([""]);
}
}
}
let addBraces = false;
if (!ts.isBlock(ifStmt.thenStatement)) {
addBraces = true;
}
return s([
"if (",
c2(ifStmt.expression),
`) ${addBraces ? "{" : ""}
`,
c2(ifStmt.thenStatement),
`${addBraces ? "}" : ""}
`,
ifStmt.elseStatement ? s(["else \n", c2(ifStmt.elseStatement), "\n"]) : s([""])
]);
case ts.SyntaxKind.TrueKeyword:
return s(["true"]);
case ts.SyntaxKind.FalseKeyword:
return s(["false"]);
case ts.SyntaxKind.PostfixUnaryExpression:
let post = ast;
return s([c2(post.operand), post.operator == ts.SyntaxKind.PlusPlusToken ? "++" : "--"]);
case ts.SyntaxKind.PlusPlusToken:
return s(["++"]);
case ts.SyntaxKind.MinusMinusToken:
return s(["--"]);
case ts.SyntaxKind.ParenthesizedExpression:
let paren = ast;
return s(["(", c2(paren.expression), ")"]);
case ts.SyntaxKind.VariableDeclarationList:
let varDeclList = ast;
if (varDeclList.declarations.length > 0) {
for (let decl2 of varDeclList.declarations) {
let varDecl2 = decl2;
let type22 = ctx.checker.getTypeAtLocation(varDecl2);
let translated = translateType(ctx.checker, type22);
let postType = ": " + translated;
if (translated == "___atomic_compare_exchange_result") {
postType = "";
}
return s(["var ", varDecl2.name.getText(), postType, " = ", c2(varDecl2.initializer)]);
}
} else {
return s([""]);
}
case ts.SyntaxKind.ForStatement:
let forStmt = ast;
return s([
"for (",
c2(forStmt.initializer),
";",
c2(forStmt.condition),
";",
c2(forStmt.incrementor),
")",
c2(forStmt.statement)
]);
case ts.SyntaxKind.BinaryExpression:
let bin = ast;
let binExprText = bin.operatorToken.getText();
if (binExprText == "===") {
binExprText = "==";
}
if (bin.operatorToken.kind == ts.SyntaxKind.EqualsToken) {
let leftType2 = ctx.checker.getTypeAtLocation(bin.left);
let rightType2 = ctx.checker.getTypeAtLocation(bin.right);
if (isVector(ctx.checker, leftType2) && isVector(ctx.checker, rightType2)) {
let [leftElementType, leftElementSize] = getVectorElementType(ctx.checker, leftType2);
let [rightElementType, rightElementSize] = getVectorElementType(ctx.checker, rightType2);
if (leftElementType != rightElementType) {
if (leftElementType == "float" && rightElementType == "int") {
return s([c2(bin.left), ` = vec${leftElementSize}f(`, c2(bin.right), ")"]);
} else if (leftElementType == "int" && rightElementType == "float") {
return s([c2(bin.left), ` = vec${leftElementSize}i(`, c2(bin.right), ")"]);
}
}
}
if (isNumeric(ctx.checker, leftType2) && isNumeric(ctx.checker, rightType2)) {
let leftTypeStr = translateType(ctx.checker, leftType2);
let rightTypeStr = translateType(ctx.checker, rightType2);
if (leftTypeStr != rightTypeStr) {
return s([
c2(bin.left),
` = `,
autoCastNumeric(c2(bin.right), rightTypeStr, leftTypeStr, bin)
]);
}
}
if (isUniformAccess(ctx, bin.left)) {
if (translateType(ctx.checker, ctx.checker.getTypeAtLocation(bin.left)) == "bool") {
return s([c2(bin.left), " = select(0, 1, ", c2(bin.right), ")"]);
}
}
return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]);
}
return s([c2(bin.left), " ", binExprText, " ", c2(bin.right)]);
case ts.SyntaxKind.StringLiteral:
return s(["0"]);
case ts.SyntaxKind.ArrayLiteralExpression:
let arr = ast;
return s([
"array(",
...join(
arr.elements.map((e) => c2(e)),
", "
),
")"
]);
case ts.SyntaxKind.ElementAccessExpression:
let elem = ast;
let t = ctx.checker.getTypeAtLocation(elem.expression);
let n2 = getTypeFallback$1(ctx.checker, t);
let postfix = "";
if (n2 === "Array" || t.flags & ts.TypeFlags.Object && (t.objectFlags & ts.ObjectFlags.Tuple || t.objectFlags & ts.ObjectFlags.ArrayLiteral || t.objectFlags & ts.ObjectFlags.EvolvingArray)) {
let typeRef = t;
let args2 = typeRef.typeArguments || ctx.checker.getTypeArguments(typeRef);
let translated = translateType(ctx.checker, args2[0]);
let typeInfo = getWGSLTypeInfo(translated);
args2.length;
if (typeInfo.needsAlignment) {
translated = `vec4<${typeInfo.elementType ?? "f32"}>`;
}
let lengths = {
1: "x",
2: "xy",
3: "xyz",
4: "xyzw"
};
postfix = `.${lengths[typeInfo.length ?? 1]}`;
}
return s([c2(elem.expression), "[", c2(elem.argumentExpression), "]", postfix]);
case ts.SyntaxKind.Block:
let block = ast;
return s([
"{\n",
...join(
block.statements.map((child) => c2(child)),
";"
),
"\n}"
]);
case ts.SyntaxKind.TypeOfExpression:
return s(["0"]);
case ts.SyntaxKind.WhileStatement:
let whileStmt = ast;
return s(["while (", c2(whileStmt.expression), ") ", c2(whileStmt.statement)]);
default:
throw new GLSLCompilationError(`Invalid shader syntax '${ast.getText()}'`, ast);
}
}
function getClosureVars(checker, func) {
let result = [];
let recur = (node2) => {
if (node2.kind == ts.SyntaxKind.Identifier) {
let id = node2;
let symbol = checker.getSymbolAtLocation(id);
let declar = symbol.valueDeclaration;
if (isVariableDeclarationValue(checker, declar)) {
if (declar) {
if (!isInSameScope(declar, node2) && isInShader$1(declar)) {
result.push(symbol);
}
}
}
} else {
node2.forEachChild(recur);
}
};
recur(func);
return result;
}
function getDeclarationType(checker, node2) {
return node2.type ? checker.getTypeAtLocation(node2.type) : node2.initializer ? checker.getTypeAtLocation(node2.initializer) : checker.getTypeAtLocation(node2);
}
function isArrayType$1(type2, checker) {
return checker.isTupleType(type2) || checker.isArrayType(type2);
}
class WGSLShader {
constructor(key, source) {
this.globals = [];
this.locals = [];
this.attributeInput = "";
this.attributeOutput = "";
this.key = key;
this.source = source;
}
}
function resolveFunctionName(f) {
if (ts.isMethodDeclaration(f)) {
let parentName = "anon";
if (f.parent && ts.isClassDeclaration(f.parent)) {
parentName = f.parent.name?.text ?? "anon";
}
return removeDoubleUnderscores(
`fn_${f.getSourceFile()?.fileName.replaceAll("/", "_").replaceAll(".", "_") ?? "anon"}_${f.getStart()}_${parentName}_static_${f.name.getText() ?? "unknown"}`
);
} else {
return removeDoubleUnderscores(
`fn_${f.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${f.getStart()}_${f.name?.text.replaceAll(".", "_dot_") ?? "unknown"}`
);
}
}
function resolveStructName(c2) {
if (c2.name?.text == "ShaderInput")
return "ShaderInput";
if (c2.name?.text == "ShaderOutput")
return "ShaderOutput";
return removeDoubleUnderscores(
`str_${c2.getSourceFile().fileName.replaceAll("/", "_").replaceAll(".", "_")}_${c2.getStart()}_${c2.name?.text ?? "unknown"}`.replaceAll("__", "_i_")
);
}
function isInSameScope(node2, other) {
return closest(node2, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
}) == closest(other, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
});
}
function isInShader$1(node2) {
return closest(node2, (node22) => {
if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) {
if (hasShadeupDocTag(node22, "shader")) {
return true;
}
}
return false;
});
}
function isInRoot(node2) {
let c2 = closest(node2, (node22) => {
if (ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22) || ts.isMethodDeclaration(node22) || ts.isSourceFile(node22)) {
return true;
}
});
return c2 ? ts.isSourceFile(c2) : false;
}
function isRootNode(node2) {
let parentRoot = closest(node2, (node22) => {
if (ts.isMethodDeclaration(node22) || ts.isFunctionDeclaration(node22) || ts.isArrowFunction(node22)) {
return true;
}
if (ts.isSourceFile(node22)) {
return true;
}
});
return parentRoot && ts.isSourceFile(parentRoot);
}
function isComposedFunction(checker, func) {
let isComposed = false;
func.parameters.forEach((param) => {
let type2 = checker.getTypeAtLocation(param);
if (type2.getCallSignatures().length > 0) {
isComposed = true;
}
});
return isComposed;
}
function resolveDeps(checker, root, table = {
graph: /* @__PURE__ */ new Map(),
functions: /* @__PURE__ */ new Map(),
structs: /* @__PURE__ */ new Map(),
structsProps: /* @__PURE__ */ new Map(),
globals: /* @__PURE__ */ new Map(),
composed: /* @__PURE__ */ new Map()
}) {
function resolveFunction(f1, f2, call) {
let n1 = f1 ? resolveFunctionName(f1) : "main";
let n2 = resolveFunctionName(f2);
if (f2.name?.getText() === "__index" || f2.name?.getText() === "__index_assign" || f2.name?.getText() === "__index_assign_op" || f2.name?.getText() === "len" || f2.name?.getText() === "sample" || f2.name?.getText() === "atomic" || hasShadeupDocTag(f2, "noemit_gpu"))
return;
if (isComposedFunction(checker, f2)) {
n2 = n2 + "_composed_" + call.pos;
table.composed.set(n2, call);
}
let deps = table.graph.get(n1) ?? [];
if (!deps.includes(n2))
deps.push(n2);
table.graph.set(n1, deps);
table.functions.set(n2, f2);
}
function resolveStruct(decl, fullStruct = false) {
let name = resolveStructName(decl);
if (decl.name?.text == "atomic_internal") {
return;
}
if (table.structs.has(name)) {
if (!fullStruct) {
return;
}
}
let props = table.structsProps.get(name) ?? /* @__PURE__ */ new Set();
for (let member of decl.members) {
if (ts.isPropertyDeclaration(member)) {
let type2 = checker.getTypeAtLocation(member);
resolveTypeUse(type2, member);
if (fullStruct) {
props.add(member.name.getText());
}
}
}
if (fullStruct) {
table.structsProps.set(name, props);
}
table.structs.set(name, decl);
}
function isValidShaderType(type2, checker2) {
let symbol = type2.aliasSymbol || type2.getSymbol();
let name = checker2.typeToString(type2);
let bases = type2.getBaseTypes();
if (bases && bases.length > 0) {
for (let base of bases) {
if (!isValidShaderType(base, checker2))
return false;
}
}
if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) {
return false;
}
return !TYPE_BLACKLIST.includes(name);
}
function resolveTypeUse(typeNode, context2, fullStruct = false) {
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
if (TYPE_BLACKLIST.includes(symbol?.getName() ?? "")) {
throw new GLSLCompilationError(
`Type '${symbol?.getName()}' is not supported in shaders`,
context2
);
}
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
resolveStruct(decl, fullStruct);
}
let typestr = checker.typeToString(typeNode);
if (typeNode.aliasTypeArguments)
for (let args of typeNode.aliasTypeArguments) {
resolveTypeUse(
args,
context2,
typestr.startsWith("buffer<") || typestr.startsWith("buffer_internal<")
);
}
}
function resolvePropertyAccess(node2) {
let typeNode = checker.getTypeAtLocation(node2.expression);
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
checker.typeToString(typeNode);
if (!isValidShaderType(typeNode, checker)) {
throw new GLSLCompilationError(
`Type '${symbol?.getName()}' is not supported in shaders`,
node2
);
}
let full = checker.getTypeAtLocation(node2).getCallSignatures().length > 0;
resolveTypeUse(typeNode, node2, full);
resolveTypeUse(checker.getTypeAtLocation(node2), node2);
let prop = node2.name.getText();
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
let name2 = resolveStructName(decl);
let props = table.structsProps.get(name2) ?? /* @__PURE__ */ new Set();
props.add(prop);
table.structsProps.set(name2, props);
}
}
walkNodes$1(root, (node2) => {
if (ts.isCallExpression(node2)) {
let exprSmybol = checker.getSymbolAtLocation(node2.expression);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
let funcDeclar = exprSmybol.getDeclarations()?.[0];
exprSmybol.valueDeclaration;
if (ts.isPropertyAccessExpression(node2.expression)) {
resolveTypeUse(
checker.getTypeAtLocation(node2.expression.expression),
node2.expression.expression
);
}
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
let mapping = findSignatureMappingToWGSL(checker, exprSmybol);
if (mapping === null) {
let parentDeclar = closest(
node2,
(n) => ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n) || ts.isArrowFunction(n)
);
if (parentDeclar && ts.isArrowFunction(parentDeclar)) {
let parentParentDeclar = closest(parentDeclar, (n) => ts.isCallExpression(n));
if (parentParentDeclar && ts.isCallExpression(parentParentDeclar)) {
let parentParentSymbol = checker.getSymbolAtLocation(parentParentDeclar.expression);
if (parentParentSymbol && parentParentSymbol.flags & ts.SymbolFlags.Alias) {
parentParentSymbol = checker.getAliasedSymbol(parentParentSymbol);
}
if (parentParentSymbol) {
let parentParentFuncDeclar = parentParentSymbol.getDeclarations()?.[0];
if (parentParentFuncDeclar && (ts.isFunctionDeclaration(parentParentFuncDeclar) || ts.isMethodDeclaration(parentParentFuncDeclar))) {
resolveFunction(parentParentFuncDeclar, funcDeclar, node2);
}
}
}
} else if (parentDeclar && (ts.isFunctionDeclaration(parentDeclar) || ts.isMethodDeclaration(parentDeclar))) {
resolveFunction(parentDeclar, funcDeclar, node2);
} else {
resolveFunction(null, funcDeclar, node2);
}
if (!table.graph.has(resolveFunctionName(funcDeclar))) {
table.graph.set(resolveFunctionName(funcDeclar), []);
resolveDeps(checker, funcDeclar, table);
}
let sig = checker.getSignatureFromDeclaration(funcDeclar);
let returnType = checker.getReturnTypeOfSignature(sig);
resolveTypeUse(returnType, node2);
}
}
}
}
if (ts.isNewExpression(node2)) {
resolveTypeUse(checker.getTypeAtLocation(node2), node2.expression, true);
}
if (ts.isPropertyAccessExpression(node2)) {
resolvePropertyAccess(node2);
}
if (ts.isIdentifier(node2)) {
let type2 = checker.getTypeAtLocation(node2);
resolveTypeUse(type2, node2);
if (checker.getSymbolAtLocation(node2)) {
let decl = checker.getSymbolAtLocation(node2)?.declarations;
if (decl && ts.isVariableDeclaration(decl[0])) {
if (!isInSameScope(decl[0], node2) && decl[0].getSourceFile().fileName !== root.getSourceFile().fileName) {
if (isVariableDeclarationValue(checker, decl[0])) {
table.globals.set(node2.text.toString(), decl[0]);
}
}
}
}
}
if (ts.isVariableDeclaration(node2)) {
let type2 = checker.getTypeAtLocation(node2);
resolveTypeUse(type2, node2);
}
});
return table;
}
function resolveUniforms(checker, root) {
let uniforms = [];
walkNodesWithCalls(checker, root, (node2) => {
if (ts.isIdentifier(node2)) {
let decl = checker.getSymbolAtLocation(node2);
if (decl && decl.flags & ts.SymbolFlags.Alias) {
decl = checker.getAliasedSymbol(decl);
}
if (decl && decl.declarations && decl.declarations.length == 1) {
let declNode = decl.declarations[0];
if (declNode) {
if (isVariableDeclarationValue(checker, declNode)) {
if (!isInSameScope(declNode, node2) && !isInShader$1(declNode)) {
let indexAssign = false;
let indexRead = false;
let sampler = false;
let parent = node2.parent;
if (parent && ts.isPropertyAccessExpression(parent)) {
if (parent.expression == node2) {
if (parent.name.getText() == "__index_assign") {
indexAssign = true;
}
if (parent.name.getText() == "__index") {
indexRead = true;
if (parent.parent && parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent)) {
if (parent.parent.parent.parent && ts.isBinaryExpression(parent.parent.parent.parent) && parent.parent.parent.parent.left == parent.parent.parent) {
if (parent.parent.parent.parent.operatorToken.kind == ts.SyntaxKind.EqualsToken) {
indexAssign = true;
}
}
if (parent.parent.parent.parent && ts.isPropertyAccessExpression(parent.parent.parent.parent)) {
let propType = checker.getTypeAtLocation(parent.parent.parent);
let translatedPropType = translateType(checker, propType);
if (translatedPropType.startsWith("atomic<")) {
if (parent.parent.parent.parent.name.getText() != "read") {
indexAssign = true;
} else {
indexRead = true;
}
}
}
}
}
if (parent.name.getText() == "sample") {
sampler = true;
}
}
}
let idx = uniforms.findIndex((d) => d.declaration === declNode);
if (idx == -1) {
let translated = translateType(checker, checker.getTypeAtLocation(declNode));
if (translated.includes("atomic<")) {
indexAssign = true;
}
uniforms.push({
declaration: declNode,
usesIndexAssign: indexAssign,
usesIndexRead: indexRead,
usesSampler: sampler
});
} else {
uniforms[idx].usesIndexAssign = uniforms[idx].usesIndexAssign || indexAssign;
uniforms[idx].usesIndexRead = uniforms[idx].usesIndexRead || indexRead;
uniforms[idx].usesSampler = uniforms[idx].usesSampler || sampler;
}
}
}
}
}
}
});
return uniforms;
}
function isVariableDeclarationValue(checker, node2) {
try {
if (ts.isVariableDeclaration(node2) || ts.isParameter(node2)) {
let type2 = checker.getTypeAtLocation(node2);
let calls = type2.getCallSignatures();
if (calls.length != 0) {
if (type2.aliasSymbol) {
if (type2.aliasSymbol.getName() == "shader") {
return true;
}
}
}
return calls.length == 0;
} else {
return false;
}
} catch (e) {
return false;
}
}
function isUniformable(checker, decl) {
let exprSmybol = checker.getSymbolAtLocation(decl);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
exprSmybol.getDeclarations()?.[0];
}
return ts.isVariableDeclaration(decl) || ts.isParameter(decl);
}
function isValidStructType(checker, type2) {
let t = translateType(checker, type2);
return t != "sampler";
}
function addWGSLShader(key, root, checker, env2, isComputeShader = false, computeShaderSize = [1, 1, 1]) {
let deps = resolveDeps(checker, root);
let uniforms = resolveUniforms(checker, root);
let mapping = [...deps.graph.entries()].map(([k, v]) => v.map((d) => [k, d])).flat();
let sorted = [];
try {
sorted = toposort(mapping).reverse();
} catch (e) {
sorted = [];
}
let preFuncs = [];
for (let s of deps.structs.values()) {
let name = resolveStructName(s);
let hasAnyProperty = false;
let sp = deps.structsProps.get(name);
let members = s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return "";
let type2 = checker.getTypeAtLocation(m);
let translated = translateType(checker, type2);
if (translated == "bool") {
translated = "i32";
}
let preComment = "";
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
preComment = `// `;
}
}
if (!isValidStructType(checker, type2)) {
preComment = `// `;
}
if (preComment == "") {
hasAnyProperty = true;
}
return new SourceNode(
m.getStart(),
m.getEnd(),
`${preComment} ${isAlignable(translated) ? "@align(16) " : ""} ${escapeIdentifier(
m.name.getText()
)}: ${translated},
`
);
});
s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return "";
let type2 = checker.getTypeAtLocation(m);
let translated = translateType(checker, type2);
if (translated == "bool") {
translated = "i32";
}
let preComment = "";
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
preComment = `// `;
}
}
if (preComment == "") {
hasAnyProperty = true;
}
return new SourceNode(
m.getStart(),
m.getEnd(),
`${preComment} ${escapeIdentifier(m.name.getText())}: ${translated},
`
);
});
let hasAtomic = false;
let memberNames = s.members.map((m) => {
if (!ts.isPropertyDeclaration(m))
return ["", ""];
let type2 = checker.getTypeAtLocation(m);
let translated = translateType(checker, type2);
if (!sp || !sp.has(m.name.getText())) {
if (name != "ShaderInput" && name != "ShaderOutput") {
return ["", ""];
}
}
if (translated.startsWith("atomic<")) {
hasAtomic = true;
}
return [escapeIdentifier(m.name.getText()), translated, m];
}).filter((m) => m[0] != "").filter((m) => {
return isValidStructType(checker, checker.getTypeAtLocation(m[2]));
}).sort((a, b) => {
return a[0].localeCompare(b[0]);
});
if (!hasAnyProperty)
continue;
if (name == "ShaderInput" || name == "ShaderOutput") {
members.push(new SourceNode(s.getStart(), s.getEnd(), ["// %SHADER_" + name + "%"]));
}
preFuncs.push(
new SourceNode(s.getStart(), s.getEnd(), [`struct ${name} {
`, ...members, "\n};\n"])
);
if (name != "ShaderInput" && name != "ShaderOutput") {
if (!hasAtomic) {
preFuncs.push(
new SourceNode(s.getStart(), s.getEnd(), [
"fn _make_struct_" + name + "(",
...memberNames.map((m) => {
return ` ${m[0]}: ${m[1]},`;
}),
") -> ",
name,
" {\n",
"var _s: ",
name,
";\n",
...memberNames.map((m) => {
if (m[1] == "bool") {
return ` _s.${m[0]} = select(0, 1, ${m[0]});
`;
} else {
return ` _s.${m[0]} = ${m[0]};
`;
}
}),
"\nreturn _s; \n}\n"
])
);
}
}
}
let specialUniforms = [];
preFuncs.push(
new SourceNode(0, 0, ["struct _InUniformsStruct {\n/*SHADEUP_UNIFORM_STRUCT_START*/\n"])
);
let localStrs = [];
let globalStrs = [];
let workgroupVars = [];
let checkDecl = (node2) => {
let fullText = node2.getSourceFile().getFullText();
let fullStart = node2.getFullStart();
let prefix = `// @workgroup
`;
let mySelf = fullText.slice(fullStart - prefix.length, fullStart);
if (mySelf.includes("@workgroup")) {
workgroupVars.push(node2);
}
};
if (ts.isArrowFunction(root)) {
ts.forEachChild(root.body, (node2) => {
if (ts.isVariableDeclaration(node2) || ts.isVariableStatement(node2) || ts.isVariableDeclarationList) {
if (ts.isVariableDeclaration(node2)) {
checkDecl(node2);
} else if (ts.isVariableStatement(node2)) {
node2.declarationList.declarations.forEach((d) => {
checkDecl(d);
});
} else if (ts.isVariableDeclarationList(node2)) {
for (let d of node2.declarations) {
checkDecl(d);
}
}
}
});
}
let globalUnis = [];
let localUnis = [];
for (let uniformData of uniforms) {
let u = uniformData.declaration;
if (isUniformable(checker, u)) {
let _type = checker.getTypeAtLocation(u);
let translated = translateType(checker, _type);
let isGlobalVar = isRootNode(u);
let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`;
let isSpecial = isSpecialUniformType(translated);
let pushTo = isGlobalVar ? globalStrs : localStrs;
if (translated.startsWith("array")) {
pushTo.push(
new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_size: i32,\n"])
);
}
if (translated.startsWith("atomic")) {
pushTo.push(
new SourceNode(u.getStart(), u.getEnd(), ["@align(16) ", glslVarName, "_dummy: u32,\n"])
);
}
if (translated == "sampler") {
pushTo.push(
new SourceNode(u.getStart(), u.getEnd(), [
"@align(16) ",
glslVarName,
"_size: vec2,\n"
])
);
}
if (isSpecial) {
if (isGlobalVar) {
globalUnis.push(uniformData);
} else {
localUnis.push(uniformData);
}
} else {
pushTo.push(
new SourceNode(u.getStart(), u.getEnd(), [
(isAlignable(translated) ? "@align(16) " : "") + glslVarName,
": ",
translated,
",\n"
])
);
}
}
}
specialUniforms.push(...localUnis, ...globalUnis);
if (localStrs.length == 0 && globalStrs.length == 0) {
preFuncs.push(new SourceNode(0, 0, ["", "dummy", ": vec4,\n"]));
} else {
preFuncs = [...preFuncs, ...localStrs, ...globalStrs];
}
preFuncs.push(new SourceNode(0, 0, ["};\n"]));
preFuncs.push(
new SourceNode(0, 0, [
"@group(%GROUP_INDEX%) @binding(1) var _in_uniforms: _InUniformsStruct;\n"
])
);
let specialUniformsCounter = 2;
for (let uniformData of specialUniforms) {
let u = uniformData.declaration;
if (isUniformable(checker, u)) {
let _type = checker.getTypeAtLocation(u);
let translated = translateType(checker, _type, false, true);
let isGlobalVar = isRootNode(u);
let glslVarName = `_ext_uniform_${isGlobalVar ? "global" : "local"}_${u.name.getText()}`;
if (translated == "sampler" || translated.startsWith("array]+)>/g;
innerTranslated = innerTranslated.replace(vecRegex, "$1");
let textureKind = "texture_2d";
let textureKindStorage = "texture_storage_2d";
if (isArrayType$1(_type, checker)) {
textureKind = "texture_2d_array";
textureKindStorage = "texture_storage_2d_array";
}
if (translated.startsWith("array;
`,
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated};
`,
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 2}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>;
`
])
);
specialUniformsCounter += 2;
} else if (uniformData.usesIndexAssign) {
preFuncs.push(
new SourceNode(0, 0, [
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>;
`,
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}_texture_write: ${textureKindStorage}<%WRITE_TYPE_${glslVarName}%, write>;
`
])
);
specialUniformsCounter += 1;
} else if (uniformData.usesSampler || uniformData.usesIndexRead) {
preFuncs.push(
new SourceNode(0, 0, [
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}_texture: ${textureKind}<${innerTranslated}>;
`,
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter + 1}) var ${glslVarName}: ${translated};
`
])
);
specialUniformsCounter += 1;
}
} else if (translated.startsWith("atomic")) {
preFuncs.push(
new SourceNode(0, 0, [
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated};
`
])
);
} else if (translated.startsWith("array") || translated.startsWith("buffer")) {
let usageType = "read";
if (uniformData.usesIndexAssign) {
usageType = "read_write";
}
preFuncs.push(
new SourceNode(0, 0, [
`@group(%GROUP_INDEX%) @binding(${specialUniformsCounter}) var ${glslVarName}: ${translated};
`
])
);
}
specialUniformsCounter++;
}
}
for (let workgroupVar of workgroupVars) {
preFuncs.push(
new SourceNode(0, 0, [
`var ${escapeIdentifier(workgroupVar.name.getText())}: ${translateType(
checker,
checker.getTypeAtLocation(workgroupVar.type)
)};
`
])
);
}
for (let k of sorted) {
if (k == "main")
continue;
let v = deps.functions.get(k);
if (v) {
let sourceFile2 = v.getSourceFile();
let originalFile2 = env2.files.find((f) => f.path == sourceFile2.fileName);
preFuncs.push(
compile$1(
{ parentFunction: v, checker, composed: deps.composed.get(k) ?? null },
v,
originalFile2?.mapping
)
);
}
}
let sourceFile = root.getSourceFile();
let originalFile = env2.files.find((f) => f.path == sourceFile?.fileName);
let customAttributesIn = /* @__PURE__ */ new Map();
let customAttributesOut = /* @__PURE__ */ new Map();
let main = compile$1(
{
checker,
isComputeShader,
computeSize: computeShaderSize,
addCustomAttribute(type2, idx, valType, interp) {
if (type2 == "in") {
customAttributesIn.set(idx, [valType, interp]);
} else if (type2 == "out") {
customAttributesOut.set(idx, [valType, interp]);
}
}
},
root,
originalFile.mapping
);
preFuncs.push(main);
let source = new SourceNode(root.getStart(), root.getEnd(), preFuncs);
let ss = { indexMapping: [], str: "" };
source.toString(ss);
let finalShaderOutput = ss.str;
let customIns = [];
for (let [idx, [valType, interp]] of customAttributesIn.entries()) {
customIns.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType},
`);
}
finalShaderOutput = finalShaderOutput.replace("// %SHADER_ShaderInput%\n", customIns.join(""));
let customOuts = [];
for (let [idx, [valType, interp]] of customAttributesOut.entries()) {
customOuts.push(`@location(${7 + idx}) @interpolate(${interp}) custom${idx}: ${valType},
`);
}
let matches = wgslHeader.match(/fn ([^\(]+)/gm);
let headerSplits = [];
for (let i = 0; i < matches.length; i++) {
let index = wgslHeader.indexOf(matches[i]);
let toIndex = i == matches.length - 1 ? wgslHeader.length : wgslHeader.indexOf(matches[i + 1]);
headerSplits.push(wgslHeader.substring(index, toIndex));
}
let realHeader = "";
for (let i = 0; i < headerSplits.length; i++) {
let headerText = headerSplits[i];
let fnName = headerText.match(/fn ([^\(]+)/)?.[1];
if (fnName) {
if (finalShaderOutput.includes(fnName)) {
realHeader += headerText;
}
}
}
finalShaderOutput = realHeader + finalShaderOutput;
let output = new WGSLShader(`shd_${key}`, finalShaderOutput);
output.sourceMapping = ss.indexMapping;
output.attributeInput = customIns.join("");
output.attributeOutput = customOuts.join("");
for (let uniformData of uniforms) {
let u = uniformData.declaration;
if (isUniformable(checker, u)) {
let name = u.name.getText();
let isGlobalVar = isRootNode(u);
if (name) {
let filterProps = function(props) {
if (props && props.name) {
let sp = deps.structsProps.get(props.name);
let realStruct = deps.structs.get(props.name);
if (props.type == "struct" && realStruct) {
for (let fi = props.fields.length - 1; fi >= 0; fi--) {
let f = props.fields[fi];
if (!sp || !sp.has(f[0])) {
props.fields.splice(fi, 1);
} else {
if (f[1].type == "struct") {
f[1] = filterProps(f[1]);
}
}
}
}
}
if (props && (props.type == "buffer" || props.type == "primitive" && props.name == "texture2d")) {
if (uniformData.usesSampler && uniformData.usesIndexAssign) {
props.access = "sample_write";
} else if (uniformData.usesIndexAssign) {
props.access = "write";
} else if (uniformData.usesSampler) {
props.access = "sample";
} else {
props.access = "read";
}
} else if (props && props.type == "array" && props.element.type == "primitive" && props.element.name == "texture2d") {
if (uniformData.usesSampler && uniformData.usesIndexAssign) {
props.element.access = "sample_write";
} else if (uniformData.usesIndexAssign) {
props.element.access = "write";
} else if (uniformData.usesSampler) {
props.element.access = "sample";
} else {
props.element.access = "read";
}
}
return props;
};
getDeclarationType(checker, u);
let typeNode = checker.getTypeAtLocation(u);
let symbol = typeNode.aliasSymbol || typeNode.getSymbol();
let decl = symbol?.getDeclarations()?.[0];
if (decl && ts.isClassDeclaration(decl)) {
resolveStructName(decl);
}
if (isGlobalVar) {
let typeOut2 = getDeclarationType(checker, u);
output.globals.push([
name,
{
fileName: getNodeSourceFileName(u),
structure: filterProps(translateType(checker, typeOut2, true))
}
]);
} else {
output.locals.push([
name,
filterProps(translateType(checker, getDeclarationType(checker, u), true))
]);
}
}
}
}
return output;
}
function isAlignable(t) {
return t.startsWith("vec") || t == "f32" || t == "i32" || t == "u32";
}
function isSpecialUniformType(t) {
return t == "sampler" || t.startsWith("array") || t.startsWith("buffer") || t.startsWith("atomic");
}
function getNodeSourceFileName(node2) {
let found = closest(node2, (n) => ts.isSourceFile(n));
if (found && ts.isSourceFile(found)) {
return found.fileName;
} else {
return "";
}
}
function walkNodes$1(node2, cb) {
cb(node2);
node2.forEachChild((n) => walkNodes$1(n, cb));
}
function walkNodesWithCalls(checker, node2, cb) {
cb(node2);
node2.forEachChild((n) => {
if (ts.isCallExpression(node2)) {
let exprSmybol = checker.getSymbolAtLocation(node2.expression);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
if (exprSmybol) {
let funcDeclar = exprSmybol.getDeclarations()?.[0];
if (funcDeclar && (ts.isFunctionDeclaration(funcDeclar) || ts.isMethodDeclaration(funcDeclar))) {
let mapping = findSignatureMappingToWGSL(checker, exprSmybol);
if (mapping === null) {
if (funcDeclar.body) {
walkNodesWithCalls(checker, funcDeclar.body, cb);
}
}
}
}
}
walkNodesWithCalls(checker, n, cb);
});
}
function getSymbolAtLocationAndFollowAliases(checker, node2) {
let exprSmybol = checker.getSymbolAtLocation(node2);
if (exprSmybol && exprSmybol.flags & ts.SymbolFlags.Alias) {
exprSmybol = checker.getAliasedSymbol(exprSmybol);
}
return exprSmybol;
}
function findSignatureMappingToWGSL(checker, sym) {
let matcher = /=(?:wgsl|univ)\((.+)\)$/g;
if (!sym.valueDeclaration)
return null;
let doc = ts.getJSDocTags(sym.valueDeclaration);
for (let d of doc) {
if (d.tagName.text !== "shadeup")
continue;
if (typeof d.comment === "string") {
let matches = matcher.exec(d.comment);
if (matches) {
return matches[1];
}
}
}
return null;
}
function removeDoubleUnderscores(str) {
return str.replace(/__/g, "_ii");
}
let rootSymbolsFromMath = [
"abs",
"floor",
"ceil",
"round",
"sign",
"cos",
"sin",
"tan",
"acos",
"asin",
"atan",
"atan2",
"cosh",
"sinh",
"tanh",
"acosh",
"asinh",
"atanh",
"exp",
"log",
"pow",
"log2",
"log10",
"sqrt",
"inversesqrt",
"frac",
"min",
"max",
"step",
"clamp",
"saturate",
"smoothstep",
"lerp",
"bilerp",
"length",
"distance",
"dist",
"normalize",
"dot",
"reflect",
"refract",
"cross",
"degrees",
"radians",
"wrap",
"rand",
"rand2",
"rand3",
"float2x2",
"float3x3",
"float4x4",
"inverse",
"transpose",
"pingpong",
"atomic",
"mod",
"workgroupBarrier",
"storageBarrier",
"workgroupUniformLoad",
"discard",
"ddx",
"ddy",
"ddxFine",
"ddyFine",
"ddxCoarse",
"ddyCoarse",
"bitcast",
"pack4x8snorm",
"pack4x8unorm",
"pack2x16snorm",
"pack2x16unorm",
"pack2x16float",
"unpack4x8snorm",
"unpack4x8unorm",
"unpack2x16snorm",
"unpack2x16unorm",
"unpack2x16float"
];
let rootSymbolsFromAll = [
"print",
"stat",
"statGraph",
"time",
"compute",
// 'type shader',
"flush",
// 'addressWorkgroup',
// 'drawAlt',
// 'shader_start_shd_',
"globalVarInit",
// 'type ShaderInput',
// 'type ShaderOutput',
"sleep",
"__makeMap",
"__deepClone",
"map",
"array"
];
let rootSymbolsFromDraw = [
"drawIndexed",
"drawInstanced",
"draw",
"makeShader",
"ShaderInput",
"ShaderOutput",
"shader",
"drawAlt2",
// 'drawIndexedIndirect',
// 'drawInstancedIndexed',
// 'drawIndirect',
"drawCount",
"drawAttributes",
"drawAdvanced",
"computeIndirect",
"drawFullscreen",
"shader_start_shd_"
];
let rootSymbolsFromCommon = [
"pixelToClip",
"PI",
"quat",
"noise",
"spatial",
// 'mat4',
"Camera",
"Camera2d",
"buffer",
"matrix",
"texture2d",
"texture3d",
"ui",
"screenAA",
"randColor",
"randColor2",
"hsl",
"hsla",
"rgb",
"rgba",
"hslFromColor",
"hslaFromColor",
"rgbFromColor",
"rgbaFromColor",
"hsv",
"hsva",
"hsvFromColor",
"hsvaFromColor",
"cmyk",
"cmykFromColor",
"hex",
"hexFromColor",
"sin1",
"cos1",
"tan1",
"remap",
"remap1",
"color",
"wrap2",
"wrap3",
"wrap4",
"bezier"
];
let rootSymbolsFromMesh = ["mesh", "Mesh", "Model", "ModelPart", "Material"];
const header = `// This file was generated by Shadeup.
import * as __ from "/std_math";
import {${rootSymbolsFromMath.join(", ")}} from "/std_math";
import {${rootSymbolsFromAll.join(", ")}, globalVarGet as __globalVarGet} from "/std___std_all";
import {${rootSymbolsFromDraw.join(", ")}} from "/_std/drawIndexed";
import { physics, PhysicsRigidBody2d, PhysicsCollider2d, PhysicsEngine2d } from "/_std/physics";
let globalVarGet = __globalVarGet;
/**__SHADEUP_STRUCT_INJECTION_HOOK__*/
`;
class SourceNode {
constructor(startIndex, endIndex, children) {
this.startIndex = startIndex;
this.endIndex = endIndex;
if (Array.isArray(children)) {
this.children = children;
} else {
this.children = [children];
}
}
toString(s) {
let start = s.str.length;
for (const child of this.children) {
if (typeof child === "string") {
s.str += child;
} else if (child instanceof SourceNode) {
child.toString(s);
}
}
s.indexMapping.push([this.startIndex, this.endIndex, start, s.str.length]);
}
print() {
const s = { str: "", indexMapping: [] };
this.toString(s);
return s.str;
}
}
function lookupIndexMapping(indexMapping, index) {
for (const [start, end, newStart, newEnd] of indexMapping) {
if (index >= newStart && index <= newEnd) {
return start + (index - newStart);
}
}
return -1;
}
function lookupIndexMappingRange(indexMapping, start, end) {
let minStart = Infinity;
let maxEnd = -Infinity;
let size = 0;
for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) {
if (start >= newStart && end <= newEnd) {
if (oldEnd - oldStart < size || size === 0) {
minStart = oldStart;
maxEnd = oldEnd;
size = oldEnd - oldStart;
}
}
}
return { start: minStart, end: maxEnd };
}
function reverseLookupIndexMappingRange(indexMapping, start, end) {
let minStart = Infinity;
let maxEnd = -Infinity;
let size = 0;
for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) {
if (start >= oldStart && end <= oldEnd) {
if (newEnd - newStart < size || size === 0) {
minStart = newStart;
maxEnd = newEnd;
size = newEnd - newStart;
}
}
}
return { start: minStart, end: maxEnd };
}
function reverseLookupIndexMappingCursor(indexMapping, cursor) {
let exact = -Infinity;
let size = 0;
for (const [oldStart, oldEnd, newStart, newEnd] of indexMapping) {
if (cursor >= oldStart && cursor <= oldEnd) {
if (newEnd - newStart < size || size === 0) {
exact = cursor - oldStart + newStart;
size = newEnd - newStart;
}
}
}
return exact;
}
function prePass(ctx, ast) {
for (const child of ast.namedChildren) {
if (child.type === "impl_declaration") {
let _for = child.childForFieldName("for");
const name = child.childForFieldName("name");
if (_for) {
ctx.addImplFor(name.text, child);
} else {
ctx.addImpl(name.text, child);
}
}
if (child.type == "lexical_declaration") {
let variable_declarator = child.firstNamedChild;
if (variable_declarator.type == "variable_declarator") {
ctx.globals.push(variable_declarator.firstNamedChild.text);
}
}
}
}
const math_primitives = [
"atomic",
"uint",
"uint2",
"uint3",
"uint4",
"uint8",
"int",
"float",
"float2",
"float3",
"float4",
"int2",
"int3",
"int4",
"float2x2",
"float3x3",
"float4x4",
"bool"
];
const operators = {
"+": "add",
"-": "sub",
"*": "mul",
"**": "pow",
"/": "div",
"%": "mod",
"==": "eq",
"!=": "neq",
"<": "lt",
"<=": "lte",
">": "gt",
">=": "gte",
"&&": "and",
"||": "or",
"!": "not",
"&": "bitand",
"|": "bitor",
"^": "bitxor",
"<<": "lshift",
">>": "rshift",
"~": "bitnot"
};
const keyFunctions = {
float: "__.float",
int: "__.int",
uint: "__.uint",
uint2: "__.uint2",
uint3: "__.uint3",
uint4: "__.uint4",
uint8: "__.uint8",
float2: "__.float2",
float3: "__.float3",
float4: "__.float4",
int2: "__.int2",
int3: "__.int3",
int4: "__.int4",
float2x2: "__.float2x2",
float3x3: "__.float3x3",
float4x4: "__.float4x4"
};
const escapeWords = {
in: true,
out: true
};
function generateDefaultForType(name) {
switch (name) {
case "any":
return "null";
case "int":
return "__.int(0)";
case "uint":
return "__.uint(0)";
case "uint8":
return "__.uint8(0)";
case "float":
return "__.float(0.0)";
case "float2":
return "__.float2(0.0, 0.0)";
case "float3":
return "__.float3(0.0, 0.0, 0.0)";
case "float4":
return "__.float4(0.0, 0.0, 0.0, 0.0)";
case "int2":
return "__.int2(0, 0)";
case "int3":
return "__.int3(0, 0, 0)";
case "int4":
return "__.int4(0, 0, 0, 0)";
case "float2x2":
return "__.float2x2(0.0, 0.0, 0.0, 0.0)";
case "float3x3":
return "__.float3x3(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "float4x4":
return "__.float4x4(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0)";
case "bool":
return "false";
case "string":
return '""';
case "atomic":
return "atomic<__.uint>(__.uint(0))";
case "atomic":
return "atomic<__.int>(__.int(0))";
default:
if (name.endsWith("[]")) {
return "[]";
} else if (name.endsWith("]")) {
let matches = name.match(/(.+)\[(\d+)\]$/);
if (matches && matches.length > 2) {
let type2 = matches[1];
let count2 = matches[2];
let args = [];
for (let i = 0; i < parseInt(count2); i++) {
args.push(generateDefaultForType(type2));
}
return "[" + args.join(",") + "]";
} else {
return "[]";
}
} else {
if (name.startsWith("buffer") || name.startsWith("texture2d") || name.startsWith("texture3d")) {
return "null";
} else {
return "new " + name + "({})";
}
}
}
}
function isValidInteger(str) {
let n = parseInt(str);
if (n > Math.pow(2, 31) - 1 || n < -Math.pow(2, 31)) {
return false;
}
return true;
}
function compile(ctx, ast) {
function c2(myAst, errorMessage = "Syntax error") {
if (!myAst) {
console.log("error");
ctx.report(ast, errorMessage);
return s(["/*", errorMessage, "*/"]);
} else {
return compile(ctx, myAst);
}
}
function s(c22) {
return new SourceNode(ast.startIndex, ast.endIndex, c22);
}
function n(type2) {
return ast.childForFieldName(type2);
}
function flat(...c22) {
return c22.reduce((acc, cur) => {
return [...acc, ...cur];
}, []);
}
function join(c22, sep) {
return c22.filter((v) => {
if (typeof v == "string" && v.length == 0 || v instanceof SourceNode && v.children.length == 0) {
return false;
}
return true;
}).reduce((acc, cur) => {
if (acc.length === 0) {
return [cur];
}
return [...acc, sep, cur];
}, []);
}
function children() {
return ast.namedChildren.map((child) => c2(child));
}
function hasName(name) {
return ast.childForFieldName(name) !== null;
}
if (!ast) {
return new SourceNode(0, 0, ["/*", "Syntax error", "*/"]);
}
switch (ast.type) {
case "program":
return s([
header,
...ctx.fileName != "file:////_std/common.ts" ? [`import {${rootSymbolsFromCommon.join(", ")}} from "/_std/common";`] : [],
...ctx.fileName != "file:////_std/mesh.ts" ? [`import {${rootSymbolsFromMesh.join(", ")}} from "/_std/mesh";`] : [],
...ctx.fileName != "file:////_std/sdf.ts" ? [`import { sdf } from "/_std/sdf";`] : [],
...ast.children.map((child) => c2(child))
]);
case "expression_statement":
if (ast.firstChild) {
if (ast.lastNamedChild?.type === "ERROR") {
return s([c2(ast.firstNamedChild), "."]);
}
if (ast.firstNamedChild.type == "workgroup") {
return s([c2(ast.firstNamedChild), "\n"]);
} else {
return s([c2(ast.firstNamedChild), ";\n"]);
}
}
case "binary_expression":
if (ast.firstChild && ast.lastChild) {
if (ast.lastChild.text == "null" && (ast.children[1].text == "!=" || ast.children[1].text == "==")) {
return s([c2(ast.firstChild), ast.children[1].text + "=", "null"]);
}
return s([
"__.",
operators[ast.children[1].text.trim()] ?? ast.children[1].text.trim(),
"( ",
c2(ast.firstNamedChild),
", ",
c2(ast.lastNamedChild),
" )"
]);
}
case "identifier":
if (keyFunctions[ast.text]) {
return s([String(keyFunctions[ast.text])]);
} else if (escapeWords[ast.text]) {
return s([String("__" + ast.text)]);
}
return s([
String(ast.text === "self" ? isInShader(ast) ? "shader_self_temp" : "this" : ast.text)
]);
case "number":
if (ast.parent?.type == "pair" && ast.parent.firstNamedChild == ast) {
return s([String(ast.text)]);
}
if (ast.text.match(/.[xyzwrgba]+$/)) {
let swizzle = (ast.text.match(/.[xyzwrgba]+$/) ?? [""])[0];
swizzle = swizzle.replace(".", "");
let raw = ast.text.replace(/.[xyzwrgba]+$/, "");
let isUint2 = raw.indexOf("u") !== -1;
let isFloat2 = raw.indexOf(".") !== -1;
return s([
String(
"__.swizzle(" + (isFloat2 ? "__.float" : isUint2 ? "__.uint" : "__.int") + "(" + raw.replace("u", "") + '), "' + swizzle + '")'
)
]);
}
let isFloat = ast.text.indexOf(".") !== -1;
let isUint = ast.text.indexOf("u") !== -1;
if (!isFloat && !isValidInteger(ast.text) && !isUint) {
ctx.report(
ast,
"Invalid integer, this overflows the 32 bit integer limit, add a .0 to the end to make it a float"
);
}
return s([
(isFloat ? "__.float" : isUint ? "__.uint" : "__.int") + "(",
new SourceNode(ast.startIndex, ast.endIndex, ast.text.replace("u", "")),
")"
]);
case "string":
return s([String(ast.text)]);
case "function_declaration":
if (ast.firstChild && ast.lastChild) {
let funcName = n("name").text;
let prefix = "";
if (funcName === "main") {
prefix += "";
prefix += "export ";
}
return s([
prefix + "function ",
c2(n("name")),
c2(n("parameters")),
...hasName("return_type") ? [c2(n("return_type")), " "] : [],
c2(n("body")),
"\n"
]);
}
case "block":
return s(children());
case "formal_parameters":
return s(["(", ...join(children(), ", "), ")"]);
case "required_parameter":
if (n("pattern")?.text === "self") {
return s([]);
}
return s(
flat(
[c2(n("pattern"))],
hasName("type") ? [": ", c2(n("type"))] : [],
hasName("value") ? [" = ", c2(n("value"))] : []
)
);
case "type_annotation":
return s([c2(ast.firstNamedChild)]);
case "type_identifier":
if (math_primitives.indexOf(ast.text) !== -1) {
return s([String("__." + ast.text)]);
}
return s([String(ast.text)]);
case "predefined_type":
if (math_primitives.indexOf(ast.text) !== -1) {
return s([String("__." + ast.text)]);
}
return s([String(ast.text)]);
case "function_type":
return s([c2(n("parameters")), " => ", c2(n("return_type"))]);
case "lookup_type":
let len = parseInt(ast.lastNamedChild?.text ?? "0");
let repeats = [];
for (let i = 0; i < len; i++) {
repeats.push(c2(ast.firstNamedChild));
}
return s(["[", ...join(repeats, ", "), "]"]);
case "arrow_function":
return s([
c2(n("parameters")),
" => ",
...hasName("return_type") ? [c2(n("return_type")), " "] : [],
c2(n("body"))
]);
case "literal_type":
return s([c2(ast.firstNamedChild)]);
case "return_statement":
if (ast.namedChildCount === 0) {
return s(["return;"]);
} else {
if (ast.lastNamedChild?.type === "ERROR") {
return s(["return ", c2(ast.firstNamedChild), "."]);
}
return s(["return ", c2(ast.firstNamedChild), ";"]);
}
case "export_statement":
return s(["export ", c2(ast.firstNamedChild), ";"]);
case "export_clause":
return s(["{", ...join(children(), ", "), "}"]);
case "export_specifier":
return s([c2(ast.firstNamedChild)]);
case "array":
return s(["[", ...join(children(), ", "), "]"]);
case "template_string":
return s(["`", ...join(children(), ""), "`"]);
case "template_substitution":
return s(["${", c2(n("expression")), "}"]);
case "template_string_segment":
return s([String(ast.text)]);
case "type_alias_declaration":
ctx.report(ast, "Type aliases aren't supported yet");
return s(["/*error*/0"]);
case "import":
return s([""]);
case "comment":
return s([String(ast.text), "\n"]);
case "call_expression":
if (n("type_arguments")) {
if (n("function").text == "buffer" || n("function").text == "texture2d" || n("function").text == "texture3d") {
let internalArgs = s([
"(",
...join(
[
...n("arguments").namedChildren.map((chi) => c2(chi)),
...n("arguments").namedChildren.length == 1 && n("function").text == "texture2d" || n("function").text == "texture3d" ? [s(['"auto"'])] : [],
s(['"', n("type_arguments").namedChild(0).text, '"'])
],
", "
),
")"
]);
return s([c2(n("function")), c2(n("type_arguments")), internalArgs]);
}
return s([c2(n("function")), c2(n("type_arguments")), c2(n("arguments"))]);
} else {
return s([c2(n("function")), c2(n("arguments"))]);
}
case "construct_expression":
return s(["new ", c2(n("identifier")), "(", c2(n("body")), ")"]);
case "member_expression":
let prop = n("property");
let p = prop.text ?? "";
let isParentAssignment = ast.parent?.type == "assignment_expression" || ast.parent?.type == "augmented_assignment_expression";
if (isParentAssignment) {
let left2 = ast.parent.childForFieldName("left");
isParentAssignment = left2.startIndex == ast.startIndex && left2.endIndex == ast.endIndex;
}
if (p.length > 0 && p.length < 5) {
let isSwizzle = true;
for (let i = 0; i < p.length; i++) {
let char = p[i];
if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") {
isSwizzle = false;
break;
}
}
if (isSwizzle) {
if (isParentAssignment) {
ast.parent.childForFieldName("right");
}
return s([
`__.swizzle(`,
c2(n("object")),
`, '`,
new SourceNode(prop.startIndex, prop.endIndex, p),
`'`,
...isParentAssignment ? [`, `, c2(ast.parent.childForFieldName("right"))] : [],
`)`
// new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, '.'),
// c(n('property')!)
]);
}
}
return s([
c2(n("object")),
new SourceNode(ast.children[1].startIndex, ast.children[1].endIndex, "."),
c2(n("property"))
]);
case "pair":
return s([c2(n("key")), ": ", c2(n("value"), "Expected value in pair")]);
case "object":
let childrens = ast.namedChildren.filter((subc) => subc.type !== "comment").map((subc) => c2(subc));
return s(["{", ...join(childrens, ", "), "}"]);
case "property_identifier":
return s([String(ast.text)]);
case "arguments":
return s(["(", ...join(children(), ", "), ")"]);
case "parenthesized_expression":
if (ast.lastNamedChild?.type === "ERROR") {
return s(["(", c2(ast.firstNamedChild), ".", ")"]);
}
return s(["(", c2(ast.firstNamedChild), ")"]);
case "function_signature":
ctx.report(ast, "Missing function body");
return s(["/*error*/0"]);
case "parenthesized_expression_vector":
if (ast.firstNamedChild) {
if (ast.firstNamedChild.type === "sequence_expression") {
return s(["__.makeVector(", c2(ast.firstNamedChild), ")"]);
} else {
return s(["(", c2(ast.firstNamedChild), ")"]);
}
}
case "if_statement":
return s([
"if ",
c2(n("condition")),
c2(n("consequence")),
hasName("alternative") ? c2(n("alternative")) : ""
]);
case "else":
return s([" else ", c2(ast.firstNamedChild), "\n"]);
case "generic_type":
return s([c2(n("name")), c2(n("type_arguments"))]);
case "type_arguments":
return s(["<", ...join(children(), ", "), ">"]);
case "array_type":
if (ast.namedChildCount == 2) {
return s([c2(ast.firstNamedChild), "[", c2(ast.lastNamedChild), "]"]);
} else {
return s([c2(ast.firstNamedChild), "[]"]);
}
case "ternary_expression":
return s([c2(n("condition")), " ? ", c2(n("consequence")), " : ", c2(n("alternative"))]);
case "update_expression":
return s([c2(n("argument")), n("operator").text]);
case "augmented_assignment_expression":
let opMapping = {
"+=": "add",
"-=": "sub",
"*=": "mul",
"/=": "div",
"%=": "mod"
};
let leftAssignAug = n("left");
if (leftAssignAug?.type === "subscript_expression") {
return s([
c2(leftAssignAug.childForFieldName("object")),
".__index_assign_op(__.",
opMapping[n("operator").text],
", ",
c2(leftAssignAug.childForFieldName("index")),
", ",
c2(n("right")),
")"
]);
}
return s([
c2(n("left")),
" = __.",
opMapping[n("operator").text],
"(",
c2(n("left")),
", ",
c2(n("right")),
")"
]);
case "for_statement":
return s([
"for (",
c2(n("initializer")),
" ",
c2(n("condition")),
" ",
c2(n("increment")),
") ",
c2(n("body"))
]);
case "for_in_statement":
let leftFor = n("left");
let rightFor = n("right");
if (leftFor.type === "parenthesized_expression") {
let forComponents = [];
for (let i = 0; i < leftFor.namedChildren[0].namedChildren.length; i++) {
let name = leftFor.namedChildren[0].namedChildren[i];
if (name.type != "identifier") {
ctx.report(
leftFor.namedChild(i),
"Invalid for loop variable name, must be x, y, z or w"
);
}
let key2 = name.text;
if (!["x", "y", "z", "w"].includes(key2)) {
ctx.report(
leftFor.namedChild(i),
"Invalid for loop variable name, must be x, y, z or w"
);
}
if (forComponents.includes(key2)) {
ctx.report(leftFor.namedChild(i), "Duplicate for loop variable name");
}
forComponents.push(key2);
}
forComponents = forComponents.reverse();
let parts = [];
parts.push(s(["let __for_iter = ", c2(rightFor), ";\n"]));
let indexes = ["x", "y", "z", "w"];
for (let n2 of forComponents) {
parts.push(
s([
"for (let ",
n2,
": __.int = __.int(0); ",
n2,
" < __for_iter[",
indexes.indexOf(n2).toString(),
"]; ",
n2,
"++) {\n"
])
);
}
parts.push(s([c2(n("body")), "\n"]));
for (let n2 of forComponents) {
parts.push(s(["}\n"]));
}
return s(parts);
}
return s(["for (let ", c2(n("left")), " of ", c2(n("right")), ") ", c2(n("body"))]);
case "while_statement":
return s(["while (", c2(n("condition")), ") ", c2(n("body"))]);
case "break_statement":
return s(["break;"]);
case "continue_statement":
return s(["continue;"]);
case "new_expression":
return s(["new ", c2(n("constructor")), c2(n("arguments"))]);
case "else_clause":
return s([" else ", c2(ast.firstNamedChild), "\n"]);
case "statement_block":
if (ast.parent.type == "method_definition") {
let recur = function(a) {
if (a.type == "identifier") {
if (a.text == "self") {
doesRefSelf = true;
}
}
a.children.forEach(recur);
};
let doesRefSelf = false;
ast.children.forEach(recur);
if (doesRefSelf) {
return s(["{let shader_self_temp = this;", ...children(), "}"]);
}
}
return s(["{", ...children(), "}"]);
case "import_statement":
let sourceString = n("source");
let fromString = sourceString.firstNamedChild?.text;
if (fromString) {
if (!fromString.startsWith("/") && !fromString.startsWith("@") && !fromString.startsWith(".")) {
fromString = "/" + fromString;
}
}
return s([
"import ",
...ast.namedChildCount == 2 ? [" ", c2(ast.firstNamedChild), " from "] : [],
new SourceNode(sourceString.startIndex, sourceString.endIndex, [
JSON.stringify(fromString)
]),
";"
]);
case "named_imports":
return s(["{", ...join(children(), ", "), "}"]);
case "import_clause":
return s([c2(ast.firstChild)]);
case "import_specifier":
return hasName("alias") ? s([c2(n("name")), " as ", c2(n("alias"))]) : c2(n("name"));
case "predefined_type":
return s([String(ast.text)]);
case "interface_declaration":
return s(["interface ", c2(n("name")), c2(n("body")), "\n"]);
case "object_method_signature_type":
return s(["{\n", ...children(), "\n}"]);
case "method_signature":
let isStaticSignature = n("parameters")?.firstNamedChild?.text != "self";
let accessibilityMethod = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private";
if (ast.parent?.type === "object_method_signature_type" && ast.parent?.parent?.type === "interface_declaration") {
accessibilityMethod = "";
}
return s([
accessibilityMethod,
" ",
...isStaticSignature ? ["static "] : [],
c2(n("name")),
c2(n("parameters")),
c2(n("return_type")),
";\n"
]);
case "type_annotation_arrow":
return s([": ", c2(ast.firstNamedChild)]);
case "struct_declaration":
let impls = ctx.implsFor.get(n("name").text) ?? [];
let properties = n("body")?.namedChildren ?? [];
properties = properties.filter((i) => {
let isStatic2 = false;
for (let child of i.children) {
if (child.type === "static") {
isStatic2 = true;
}
}
return !isStatic2;
});
let implBodies = [
...(ctx.implsFor.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")),
...(ctx.impls.get(n("name").text) ?? []).map((i) => i.childForFieldName("body")),
...properties
];
let staticProperties = n("body")?.namedChildren ?? [];
staticProperties = staticProperties.filter((i) => {
let isStatic2 = false;
for (let child of i.children) {
if (child.type === "static") {
isStatic2 = true;
}
}
return isStatic2;
});
let props = properties.map((i) => ({
name: i.childForFieldName("name")?.text ?? "_unknown",
type: i.childForFieldName("type")?.firstNamedChild?.text ?? "",
renderedType: compileToString(ctx, i.childForFieldName("type")),
default: i.childForFieldName("value") ? compileToString(ctx, i.childForFieldName("value")) : generateDefaultForType(i.childForFieldName("type")?.firstNamedChild?.text ?? "")
}));
let cls = s([
"/**@shadeup=struct*/class ",
c2(n("name")),
...impls.length > 0 ? [
" implements ",
...join(
impls.map((i) => c2(i.childForFieldName("for"))),
","
)
] : [],
" {\n",
...join(
staticProperties.map((i) => {
return s([
"public static ",
c2(i.childForFieldName("name")),
": ",
c2(i.childForFieldName("type")),
" = ",
c2(i.childForFieldName("value")),
";\n"
]);
}),
""
),
`constructor(data: {`,
`${props.map(
(i) => `${i.name}?: ${math_primitives.includes(i.type ?? "") ? "__." + i.type : i.renderedType},`
).join("\n")}`,
`}) {
`,
`${props.map((i) => `this.${i.name} = (data.${i.name} ?? ${i.default}) as any;`).join("\n")}`,
`
}
`,
...join(
implBodies.map((i) => c2(i)),
"\n"
),
"\n",
`clone(): `,
c2(n("name")),
` {
`,
`return new `,
c2(n("name")),
`({
`,
`${props.map((i) => {
return `${i.name}: __deepClone(this.${i.name}),`;
}).join("\n")}`,
`});
`,
`}
`,
"\n}",
"\n"
]);
return cls;
case "object_method_type":
return s([...children()]);
case "method_definition":
let isStatic = n("parameters")?.firstNamedChild?.text != "self";
return s([
...isStatic ? ["static "] : [],
c2(n("name")),
c2(n("parameters")),
c2(n("body")),
"\n"
]);
case "impl_for_clause":
return s([ast.firstNamedChild.text]);
case "unary_expression":
let op = ast.firstChild?.text ?? "";
if (op == "-") {
return s(["__.negate(", c2(n("argument")), ")"]);
} else if (op == "+") {
return s(["__.positive(", c2(n("argument")), ")"]);
} else if (op == "!") {
return s(["__.not(", c2(n("argument")), ")"]);
} else {
return s([c2(n("argument"))]);
}
case "class_body":
return s(["{\n", ...children(), "\n}"]);
case "public_field_definition":
let accessibility = ast.firstNamedChild?.type === "accessibility_modifier_member" ? "public" : "private";
return s([accessibility, " ", c2(n("name")), ": ", c2(n("type")), ";\n"]);
case "impl_declaration":
return s([`/* impl ${n("name")?.text} */
`]);
case "lexical_declaration":
return s([...children().map((i) => s(["let ", i, ";\n"]))]);
case "variable_declarator":
let isRoot = ast?.parent?.parent.type === "program";
return s([
c2(n("name")),
n("type") ? s([": ", c2(n("type"))]) : "",
...hasName("value") ? [
" = ",
...isRoot ? [
'globalVarInit("' + cleanName(ctx.fileName) + '", "',
c2(n("name")),
'", () => { return ',
c2(n("value")),
"; }, () => { return ",
c2(n("name")),
"; })"
] : [c2(n("value"))]
] : [" = ", generateDefaultForType(n("type").text.replace(/^:/, "")).trim()]
]);
case "object_type":
return s([
"{",
...join(
ast.namedChildren.map((i) => {
return s([c2(i), ","]);
}),
""
),
"}"
]);
case "property_signature":
return s([c2(n("name")), ": ", c2(n("type"))]);
case "workgroup_member":
let typeName = ast.childForFieldName("type")?.firstNamedChild?.text ?? "";
if (typeName === "atomic" || typeName === "atomic") {
if (hasName("value")) {
ctx.report(ast, "Atomic variables cannot have a default value");
}
return s([
"\n// @workgroup\n let ",
c2(n("name")),
": ",
c2(n("type")),
" = ",
generateDefaultForType(typeName),
";\n"
]);
}
if (hasName("value")) {
return s([
"\n// @workgroup\n let ",
c2(n("name")),
": ",
c2(n("type")),
" = ",
c2(n("value")),
";\n"
]);
} else {
let t = c2(n("type"));
return s([
"\n// @workgroup\n let ",
c2(n("name")),
": ",
t,
" = ",
generateDefaultForType(typeName),
";\n"
]);
}
case "workgroup":
return s([...children()]);
case "async_block":
return s([
"/** Runs immediately but does not block when running async code inside (e.g. downloading textures from the gpu)*/(async () => ",
c2(n("body")),
")()"
]);
case "shader":
let encoder = new TextEncoder();
let u8a = encoder.encode(n("body").text);
let key = sha256(u8a).map((x) => x.toString(16).padStart(2, "0")).join("");
if (hasName("type_arguments")) {
let isComputeShader = n("type_arguments")?.namedChildCount == 3;
if (isComputeShader) {
let templateArgsRaw = join(
n(`type_arguments`).namedChildren.map((nc) => {
let innerString = c2(nc).print();
return innerString.replace(/__\.int\((\d+)\)/g, "$1");
}),
", "
);
let templateArgs = join(
n(`type_arguments`).namedChildren.map((nc) => {
return c2(nc);
}),
", "
);
return new SourceNode(ast.startIndex, ast.endIndex, [
new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`),
new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`),
`"${key}", /**@shadeup=shader*/(__in: ShaderInput`,
`, __out: {}`,
`) => `,
c2(n("body")),
`) as any, [`,
...templateArgs,
`]) as shader<`,
...templateArgsRaw,
">"
]);
} else {
let arg1 = n("type_arguments")?.firstNamedChild;
let arg2 = n("type_arguments")?.lastNamedChild;
return new SourceNode(ast.startIndex, ast.endIndex, [
new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`),
new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`),
`"${key}", /**@shadeup=shader*/(__in:`,
c2(arg1),
` & {vertexIndex: __.int}, __out: `,
c2(arg2),
`) => `,
c2(n("body")),
`))`
]);
}
} else {
return new SourceNode(ast.startIndex, ast.endIndex, [
new SourceNode(ast.startIndex, ast.startIndex, `shader_start_shd_(`),
new SourceNode(ast.startIndex, ast.startIndex + "shader".length, `makeShader(`),
`"${key}", /**@shadeup=shader*/(__in, __out) => `,
c2(n("body")),
`))`
]);
}
case "assignment_expression":
let left = n("left");
if (left?.type === "subscript_expression") {
return s([
c2(left.childForFieldName("object")),
".__index_assign(",
c2(left.childForFieldName("index")),
", ",
c2(n("right")),
")"
]);
} else if (left?.type == "member_expression") {
let prop2 = left.childForFieldName("property");
let p2 = prop2.text ?? "";
if (p2.length > 0 && p2.length < 5) {
let isSwizzle = true;
for (let i = 0; i < p2.length; i++) {
let char = p2[i];
if (char !== "x" && char !== "y" && char !== "z" && char !== "w" && char !== "r" && char !== "g" && char !== "b" && char !== "a") {
isSwizzle = false;
break;
}
}
if (isSwizzle) {
return s([c2(n("left"))]);
} else {
return s([c2(n("left")), " = ", c2(n("right"))]);
}
} else {
return s([c2(n("left")), " = ", c2(n("right"))]);
}
} else {
return s([c2(n("left")), " = ", c2(n("right"))]);
}
case "sequence_expression":
return s([...join(children(), ", ")]);
case "subscript_expression":
return s([c2(n("object")), ".__index(", c2(n("index")), ")"]);
case "empty_statement":
return s([""]);
case "true":
return s(["true"]);
case "false":
return s(["false"]);
case "null":
return s(["null"]);
case "union_type":
return s([...join(children(), " | ")]);
case "intersection_type":
return s([...join(children(), " & ")]);
case "ERROR":
ctx.report(ast, "Syntax error");
if (ast.firstNamedChild?.type == "identifier") {
return s([c2(ast.firstNamedChild), "."]);
}
return s(["/* ERROR */ 0"]);
default:
ctx.report(ast, "Unsupported syntax");
console.error(new Error("Bad AST " + ast.type));
return s(["/* ERROR */ 0"]);
}
}
function compileToString(ctx, ast) {
let sn = compile(ctx, ast);
let ss = {
str: "",
indexMapping: []
};
sn.toString(ss);
return ss.str;
}
function isInShader(ast) {
if (ast.type === "shader") {
return true;
}
if (ast.parent) {
return isInShader(ast.parent);
}
return false;
}
var treeSitter = { exports: {} };
(function(module, exports) {
var Module = void 0 !== Module ? Module : {}, TreeSitter = function() {
var e, t = "object" == typeof window ? { currentScript: window.document.currentScript } : null;
class Parser2 {
constructor() {
this.initialize();
}
initialize() {
throw new Error("cannot construct a Parser before calling `init()`");
}
static init(r) {
return e || (Module = Object.assign({}, Module, r), e = new Promise((e2) => {
var r2, n = {};
for (r2 in Module)
Module.hasOwnProperty(r2) && (n[r2] = Module[r2]);
var o, s, _ = [], a = "./this.program", i = function(e3, t2) {
throw t2;
}, u = false, l = false;
u = "object" == typeof window, l = "function" == typeof importScripts, o = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, s = !u && !o && !l;
var d, c2, m, f, p, h = "";
o ? (h = l ? require$$0$1.dirname(h) + "/" : __dirname + "/", d = function(e3, t2) {
return f || (f = require$$1), p || (p = require$$0$1), e3 = p.normalize(e3), f.readFileSync(e3, t2 ? null : "utf8");
}, m = function(e3) {
var t2 = d(e3, true);
return t2.buffer || (t2 = new Uint8Array(t2)), k(t2.buffer), t2;
}, process.argv.length > 1 && (a = process.argv[1].replace(/\\/g, "/")), _ = process.argv.slice(2), module.exports = Module, i = function(e3) {
process.exit(e3);
}, Module.inspect = function() {
return "[Emscripten Module object]";
}) : s ? ("undefined" != typeof read && (d = function(e3) {
return read(e3);
}), m = function(e3) {
var t2;
return "function" == typeof readbuffer ? new Uint8Array(readbuffer(e3)) : (k("object" == typeof (t2 = read(e3, "binary"))), t2);
}, "undefined" != typeof scriptArgs ? _ = scriptArgs : void 0 !== arguments && (_ = arguments), "function" == typeof quit && (i = function(e3) {
quit(e3);
}), "undefined" != typeof print && ("undefined" == typeof console && (console = {}), console.log = print, console.warn = console.error = "undefined" != typeof printErr ? printErr : print)) : (u || l) && (l ? h = self.location.href : void 0 !== t && t.currentScript && (h = t.currentScript.src), h = 0 !== h.indexOf("blob:") ? h.substr(0, h.lastIndexOf("/") + 1) : "", d = function(e3) {
var t2 = new XMLHttpRequest();
return t2.open("GET", e3, false), t2.send(null), t2.responseText;
}, l && (m = function(e3) {
var t2 = new XMLHttpRequest();
return t2.open("GET", e3, false), t2.responseType = "arraybuffer", t2.send(null), new Uint8Array(t2.response);
}), c2 = function(e3, t2, r3) {
var n2 = new XMLHttpRequest();
n2.open("GET", e3, true), n2.responseType = "arraybuffer", n2.onload = function() {
200 == n2.status || 0 == n2.status && n2.response ? t2(n2.response) : r3();
}, n2.onerror = r3, n2.send(null);
});
Module.print || console.log.bind(console);
var g2 = Module.printErr || console.warn.bind(console);
for (r2 in n)
n.hasOwnProperty(r2) && (Module[r2] = n[r2]);
n = null, Module.arguments && (_ = Module.arguments), Module.thisProgram && (a = Module.thisProgram), Module.quit && (i = Module.quit);
var w = 16;
var M, y = [];
function b(e3, t2) {
if (!M) {
M = /* @__PURE__ */ new WeakMap();
for (var r3 = 0; r3 < K.length; r3++) {
var n2 = K.get(r3);
n2 && M.set(n2, r3);
}
}
if (M.has(e3))
return M.get(e3);
var o2 = function() {
if (y.length)
return y.pop();
try {
K.grow(1);
} catch (e4) {
if (!(e4 instanceof RangeError))
throw e4;
throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
}
return K.length - 1;
}();
try {
K.set(o2, e3);
} catch (r4) {
if (!(r4 instanceof TypeError))
throw r4;
var s2 = function(e4, t3) {
if ("function" == typeof WebAssembly.Function) {
for (var r5 = { i: "i32", j: "i64", f: "f32", d: "f64" }, n3 = { parameters: [], results: "v" == t3[0] ? [] : [r5[t3[0]]] }, o3 = 1; o3 < t3.length; ++o3)
n3.parameters.push(r5[t3[o3]]);
return new WebAssembly.Function(n3, e4);
}
var s3 = [1, 0, 1, 96], _2 = t3.slice(0, 1), a2 = t3.slice(1), i2 = { i: 127, j: 126, f: 125, d: 124 };
for (s3.push(a2.length), o3 = 0; o3 < a2.length; ++o3)
s3.push(i2[a2[o3]]);
"v" == _2 ? s3.push(0) : s3 = s3.concat([1, i2[_2]]), s3[1] = s3.length - 2;
var u2 = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(s3, [2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0])), l2 = new WebAssembly.Module(u2);
return new WebAssembly.Instance(l2, { e: { f: e4 } }).exports.f;
}(e3, t2);
K.set(o2, s2);
}
return M.set(e3, o2), o2;
}
var v, S = Module.dynamicLibraries || [];
Module.wasmBinary && (v = Module.wasmBinary);
var I, A = Module.noExitRuntime || true;
function x(e3, t2, r3, n2) {
switch ("*" === (r3 = r3 || "i8").charAt(r3.length - 1) && (r3 = "i32"), r3) {
case "i1":
case "i8":
q[e3 >> 0] = t2;
break;
case "i16":
R[e3 >> 1] = t2;
break;
case "i32":
W[e3 >> 2] = t2;
break;
case "i64":
ie = [t2 >>> 0, (ae = t2, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[e3 >> 2] = ie[0], W[e3 + 4 >> 2] = ie[1];
break;
case "float":
L[e3 >> 2] = t2;
break;
case "double":
O[e3 >> 3] = t2;
break;
default:
se("invalid type for setValue: " + r3);
}
}
function N(e3, t2, r3) {
switch ("*" === (t2 = t2 || "i8").charAt(t2.length - 1) && (t2 = "i32"), t2) {
case "i1":
case "i8":
return q[e3 >> 0];
case "i16":
return R[e3 >> 1];
case "i32":
case "i64":
return W[e3 >> 2];
case "float":
return L[e3 >> 2];
case "double":
return O[e3 >> 3];
default:
se("invalid type for getValue: " + t2);
}
return null;
}
"object" != typeof WebAssembly && se("no native wasm support detected");
var P = false;
function k(e3, t2) {
e3 || se("Assertion failed: " + t2);
}
var F = 1;
var C, q, T, R, W, L, O, j = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
function $(e3, t2, r3) {
for (var n2 = t2 + r3, o2 = t2; e3[o2] && !(o2 >= n2); )
++o2;
if (o2 - t2 > 16 && e3.subarray && j)
return j.decode(e3.subarray(t2, o2));
for (var s2 = ""; t2 < o2; ) {
var _2 = e3[t2++];
if (128 & _2) {
var a2 = 63 & e3[t2++];
if (192 != (224 & _2)) {
var i2 = 63 & e3[t2++];
if ((_2 = 224 == (240 & _2) ? (15 & _2) << 12 | a2 << 6 | i2 : (7 & _2) << 18 | a2 << 12 | i2 << 6 | 63 & e3[t2++]) < 65536)
s2 += String.fromCharCode(_2);
else {
var u2 = _2 - 65536;
s2 += String.fromCharCode(55296 | u2 >> 10, 56320 | 1023 & u2);
}
} else
s2 += String.fromCharCode((31 & _2) << 6 | a2);
} else
s2 += String.fromCharCode(_2);
}
return s2;
}
function Z(e3, t2) {
return e3 ? $(T, e3, t2) : "";
}
function D(e3, t2, r3, n2) {
if (!(n2 > 0))
return 0;
for (var o2 = r3, s2 = r3 + n2 - 1, _2 = 0; _2 < e3.length; ++_2) {
var a2 = e3.charCodeAt(_2);
if (a2 >= 55296 && a2 <= 57343)
a2 = 65536 + ((1023 & a2) << 10) | 1023 & e3.charCodeAt(++_2);
if (a2 <= 127) {
if (r3 >= s2)
break;
t2[r3++] = a2;
} else if (a2 <= 2047) {
if (r3 + 1 >= s2)
break;
t2[r3++] = 192 | a2 >> 6, t2[r3++] = 128 | 63 & a2;
} else if (a2 <= 65535) {
if (r3 + 2 >= s2)
break;
t2[r3++] = 224 | a2 >> 12, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2;
} else {
if (r3 + 3 >= s2)
break;
t2[r3++] = 240 | a2 >> 18, t2[r3++] = 128 | a2 >> 12 & 63, t2[r3++] = 128 | a2 >> 6 & 63, t2[r3++] = 128 | 63 & a2;
}
}
return t2[r3] = 0, r3 - o2;
}
function z(e3, t2, r3) {
return D(e3, T, t2, r3);
}
function U(e3) {
for (var t2 = 0, r3 = 0; r3 < e3.length; ++r3) {
var n2 = e3.charCodeAt(r3);
n2 >= 55296 && n2 <= 57343 && (n2 = 65536 + ((1023 & n2) << 10) | 1023 & e3.charCodeAt(++r3)), n2 <= 127 ? ++t2 : t2 += n2 <= 2047 ? 2 : n2 <= 65535 ? 3 : 4;
}
return t2;
}
function H(e3) {
var t2 = U(e3) + 1, r3 = Be(t2);
return D(e3, q, r3, t2), r3;
}
function G(e3) {
C = e3, Module.HEAP8 = q = new Int8Array(e3), Module.HEAP16 = R = new Int16Array(e3), Module.HEAP32 = W = new Int32Array(e3), Module.HEAPU8 = T = new Uint8Array(e3), Module.HEAPU16 = new Uint16Array(e3), Module.HEAPU32 = new Uint32Array(e3), Module.HEAPF32 = L = new Float32Array(e3), Module.HEAPF64 = O = new Float64Array(e3);
}
var B = Module.INITIAL_MEMORY || 33554432;
(I = Module.wasmMemory ? Module.wasmMemory : new WebAssembly.Memory({ initial: B / 65536, maximum: 32768 })) && (C = I.buffer), B = C.byteLength, G(C);
var K = new WebAssembly.Table({ initial: 20, element: "anyfunc" }), V = [], X = [], Q = [], J = [], Y = false;
var ee = 0, re = null;
function ne(e3) {
ee++, Module.monitorRunDependencies && Module.monitorRunDependencies(ee);
}
function oe(e3) {
if (ee--, Module.monitorRunDependencies && Module.monitorRunDependencies(ee), 0 == ee && re) {
var t2 = re;
re = null, t2();
}
}
function se(e3) {
throw Module.onAbort && Module.onAbort(e3), g2(e3 += ""), P = true, e3 = "abort(" + e3 + "). Build with -s ASSERTIONS=1 for more info.", new WebAssembly.RuntimeError(e3);
}
Module.preloadedImages = {}, Module.preloadedAudios = {}, Module.preloadedWasm = {};
var _e, ae, ie, ue = "data:application/octet-stream;base64,";
function le(e3) {
return e3.startsWith(ue);
}
function de(e3) {
return e3.startsWith("file://");
}
function ce(e3) {
try {
if (e3 == _e && v)
return new Uint8Array(v);
if (m)
return m(e3);
throw "both async and sync fetching of the wasm failed";
} catch (e4) {
se(e4);
}
}
le(_e = "tree-sitter.wasm") || (_e = function(e3) {
return Module.locateFile ? Module.locateFile(e3, h) : h + e3;
}(_e));
var me = {}, fe = { get: function(e3, t2) {
return me[t2] || (me[t2] = new WebAssembly.Global({ value: "i32", mutable: true })), me[t2];
} };
function pe(e3) {
for (; e3.length > 0; ) {
var t2 = e3.shift();
if ("function" != typeof t2) {
var r3 = t2.func;
"number" == typeof r3 ? void 0 === t2.arg ? K.get(r3)() : K.get(r3)(t2.arg) : r3(void 0 === t2.arg ? null : t2.arg);
} else
t2(Module);
}
}
function he(e3) {
var t2 = 0;
function r3() {
for (var r4 = 0, n3 = 1; ; ) {
var o3 = e3[t2++];
if (r4 += (127 & o3) * n3, n3 *= 128, !(128 & o3))
break;
}
return r4;
}
if (e3 instanceof WebAssembly.Module) {
var n2 = WebAssembly.Module.customSections(e3, "dylink");
k(0 != n2.length, "need dylink section"), e3 = new Int8Array(n2[0]);
} else {
k(1836278016 == new Uint32Array(new Uint8Array(e3.subarray(0, 24)).buffer)[0], "need to see wasm magic number"), k(0 === e3[8], "need the dylink section to be first"), t2 = 9, r3(), k(6 === e3[t2]), k(e3[++t2] === "d".charCodeAt(0)), k(e3[++t2] === "y".charCodeAt(0)), k(e3[++t2] === "l".charCodeAt(0)), k(e3[++t2] === "i".charCodeAt(0)), k(e3[++t2] === "n".charCodeAt(0)), k(e3[++t2] === "k".charCodeAt(0)), t2++;
}
var o2 = {};
o2.memorySize = r3(), o2.memoryAlign = r3(), o2.tableSize = r3(), o2.tableAlign = r3();
var s2 = r3();
o2.neededDynlibs = [];
for (var _2 = 0; _2 < s2; ++_2) {
var a2 = r3(), i2 = e3.subarray(t2, t2 + a2);
t2 += a2;
var u2 = $(i2, 0);
o2.neededDynlibs.push(u2);
}
return o2;
}
var ge = 0;
function we() {
return A || ge > 0;
}
function Me(e3) {
return 0 == e3.indexOf("dynCall_") || ["stackAlloc", "stackSave", "stackRestore"].includes(e3) ? e3 : "_" + e3;
}
function ye(e3, t2) {
for (var r3 in e3)
if (e3.hasOwnProperty(r3)) {
De.hasOwnProperty(r3) || (De[r3] = e3[r3]);
var n2 = Me(r3);
Module.hasOwnProperty(n2) || (Module[n2] = e3[r3]);
}
}
var be = { nextHandle: 1, loadedLibs: {}, loadedLibNames: {} };
function ve(e3, t2, r3) {
return e3.includes("j") ? function(e4, t3, r4) {
var n2 = Module["dynCall_" + e4];
return r4 && r4.length ? n2.apply(null, [t3].concat(r4)) : n2.call(null, t3);
}(e3, t2, r3) : K.get(t2).apply(null, r3);
}
var Ee = 5251072;
function Se(e3) {
return ["__cpp_exception", "__wasm_apply_data_relocs", "__dso_handle", "__set_stack_limits"].includes(e3);
}
function Ie(e3, t2) {
var r3 = {};
for (var n2 in e3) {
var o2 = e3[n2];
"object" == typeof o2 && (o2 = o2.value), "number" == typeof o2 && (o2 += t2), r3[n2] = o2;
}
return function(e4) {
for (var t3 in e4)
if (!Se(t3)) {
var r4 = false, n3 = e4[t3];
t3.startsWith("orig$") && (t3 = t3.split("$")[1], r4 = true), me[t3] || (me[t3] = new WebAssembly.Global({ value: "i32", mutable: true })), (r4 || 0 == me[t3].value) && ("function" == typeof n3 ? me[t3].value = b(n3) : "number" == typeof n3 ? me[t3].value = n3 : g2("unhandled export type for `" + t3 + "`: " + typeof n3));
}
}(r3), r3;
}
function Ae(e3, t2) {
var r3, n2;
return t2 && (r3 = De["orig$" + e3]), r3 || (r3 = De[e3]), r3 || (r3 = Module[Me(e3)]), !r3 && e3.startsWith("invoke_") && (n2 = e3.split("_")[1], r3 = function() {
var e4 = He();
try {
return ve(n2, arguments[0], Array.prototype.slice.call(arguments, 1));
} catch (t3) {
if (Ge(e4), t3 !== t3 + 0 && "longjmp" !== t3)
throw t3;
Ke(1, 0);
}
}), r3;
}
function xe(e3, t2) {
var r3 = he(e3);
function n2() {
var n3 = Math.pow(2, r3.memoryAlign);
n3 = Math.max(n3, w);
var o2, s2, _2, a2 = (o2 = function(e4) {
if (Y)
return ze(e4);
var t3 = Ee, r4 = t3 + e4 + 15 & -16;
return Ee = r4, me.__heap_base.value = r4, t3;
}(r3.memorySize + n3), (s2 = n3) || (s2 = w), Math.ceil(o2 / s2) * s2), i2 = K.length;
K.grow(r3.tableSize);
for (var u2 = a2; u2 < a2 + r3.memorySize; u2++)
q[u2] = 0;
for (u2 = i2; u2 < i2 + r3.tableSize; u2++)
K.set(u2, null);
var l2 = new Proxy({}, { get: function(e4, t3) {
switch (t3) {
case "__memory_base":
return a2;
case "__table_base":
return i2;
}
if (t3 in De)
return De[t3];
var r4;
t3 in e4 || (e4[t3] = function() {
return r4 || (r4 = function(e5) {
var t4 = Ae(e5, false);
return t4 || (t4 = _2[e5]), t4;
}(t3)), r4.apply(null, arguments);
});
return e4[t3];
} }), d2 = { "GOT.mem": new Proxy({}, fe), "GOT.func": new Proxy({}, fe), env: l2, wasi_snapshot_preview1: l2 };
function c3(e4) {
for (var n4 = 0; n4 < r3.tableSize; n4++) {
var o3 = K.get(i2 + n4);
o3 && M.set(o3, i2 + n4);
}
_2 = Ie(e4.exports, a2), t2.allowUndefined || Pe();
var s3 = _2.__wasm_call_ctors;
return s3 || (s3 = _2.__post_instantiate), s3 && (Y ? s3() : X.push(s3)), _2;
}
if (t2.loadAsync) {
if (e3 instanceof WebAssembly.Module) {
var m2 = new WebAssembly.Instance(e3, d2);
return Promise.resolve(c3(m2));
}
return WebAssembly.instantiate(e3, d2).then(function(e4) {
return c3(e4.instance);
});
}
var f2 = e3 instanceof WebAssembly.Module ? e3 : new WebAssembly.Module(e3);
return c3(m2 = new WebAssembly.Instance(f2, d2));
}
return t2.loadAsync ? r3.neededDynlibs.reduce(function(e4, r4) {
return e4.then(function() {
return Ne(r4, t2);
});
}, Promise.resolve()).then(function() {
return n2();
}) : (r3.neededDynlibs.forEach(function(e4) {
Ne(e4, t2);
}), n2());
}
function Ne(e3, t2) {
"__main__" != e3 || be.loadedLibNames[e3] || (be.loadedLibs[-1] = { refcount: 1 / 0, name: "__main__", module: Module.asm, global: true }, be.loadedLibNames.__main__ = -1), t2 = t2 || { global: true, nodelete: true };
var r3, n2 = be.loadedLibNames[e3];
if (n2)
return r3 = be.loadedLibs[n2], t2.global && !r3.global && (r3.global = true, "loading" !== r3.module && ye(r3.module)), t2.nodelete && r3.refcount !== 1 / 0 && (r3.refcount = 1 / 0), r3.refcount++, t2.loadAsync ? Promise.resolve(n2) : n2;
function o2(e4) {
if (t2.fs) {
var r4 = t2.fs.readFile(e4, { encoding: "binary" });
return r4 instanceof Uint8Array || (r4 = new Uint8Array(r4)), t2.loadAsync ? Promise.resolve(r4) : r4;
}
return t2.loadAsync ? (n3 = e4, fetch(n3, { credentials: "same-origin" }).then(function(e5) {
if (!e5.ok)
throw "failed to load binary file at '" + n3 + "'";
return e5.arrayBuffer();
}).then(function(e5) {
return new Uint8Array(e5);
})) : m(e4);
var n3;
}
function s2() {
if (void 0 !== Module.preloadedWasm && void 0 !== Module.preloadedWasm[e3]) {
var r4 = Module.preloadedWasm[e3];
return t2.loadAsync ? Promise.resolve(r4) : r4;
}
return t2.loadAsync ? o2(e3).then(function(e4) {
return xe(e4, t2);
}) : xe(o2(e3), t2);
}
function _2(e4) {
r3.global && ye(e4), r3.module = e4;
}
return n2 = be.nextHandle++, r3 = { refcount: t2.nodelete ? 1 / 0 : 1, name: e3, module: "loading", global: t2.global }, be.loadedLibNames[e3] = n2, be.loadedLibs[n2] = r3, t2.loadAsync ? s2().then(function(e4) {
return _2(e4), n2;
}) : (_2(s2()), n2);
}
function Pe() {
for (var e3 in me)
if (0 == me[e3].value) {
var t2 = Ae(e3, true);
"function" == typeof t2 ? me[e3].value = b(t2, t2.sig) : "number" == typeof t2 ? me[e3].value = t2 : k(false, "bad export type for `" + e3 + "`: " + typeof t2);
}
}
Module.___heap_base = Ee;
var ke, Fe = new WebAssembly.Global({ value: "i32", mutable: true }, 5251072);
function Ce() {
se();
}
Module._abort = Ce, Ce.sig = "v", ke = o ? function() {
var e3 = process.hrtime();
return 1e3 * e3[0] + e3[1] / 1e6;
} : "undefined" != typeof dateNow ? dateNow : function() {
return performance.now();
};
var qe = true;
function Te(e3, t2) {
var r3, n2;
if (0 === e3)
r3 = Date.now();
else {
if (1 !== e3 && 4 !== e3 || !qe)
return n2 = 28, W[Ue() >> 2] = n2, -1;
r3 = ke();
}
return W[t2 >> 2] = r3 / 1e3 | 0, W[t2 + 4 >> 2] = r3 % 1e3 * 1e3 * 1e3 | 0, 0;
}
function Re(e3) {
try {
return I.grow(e3 - C.byteLength + 65535 >>> 16), G(I.buffer), 1;
} catch (e4) {
}
}
function We(e3) {
Je(e3);
}
Te.sig = "iii", We.sig = "vi";
var Le = { mappings: {}, DEFAULT_POLLMASK: 5, umask: 511, calculateAt: function(e3, t2, r3) {
if ("/" === t2[0])
return t2;
var n2;
if (-100 === e3)
n2 = FS.cwd();
else {
var o2 = FS.getStream(e3);
if (!o2)
throw new FS.ErrnoError(8);
n2 = o2.path;
}
if (0 == t2.length) {
if (!r3)
throw new FS.ErrnoError(44);
return n2;
}
return PATH.join2(n2, t2);
}, doStat: function(e3, t2, r3) {
try {
var n2 = e3(t2);
} catch (e4) {
if (e4 && e4.node && PATH.normalize(t2) !== PATH.normalize(FS.getPath(e4.node)))
return -54;
throw e4;
}
return W[r3 >> 2] = n2.dev, W[r3 + 4 >> 2] = 0, W[r3 + 8 >> 2] = n2.ino, W[r3 + 12 >> 2] = n2.mode, W[r3 + 16 >> 2] = n2.nlink, W[r3 + 20 >> 2] = n2.uid, W[r3 + 24 >> 2] = n2.gid, W[r3 + 28 >> 2] = n2.rdev, W[r3 + 32 >> 2] = 0, ie = [n2.size >>> 0, (ae = n2.size, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 40 >> 2] = ie[0], W[r3 + 44 >> 2] = ie[1], W[r3 + 48 >> 2] = 4096, W[r3 + 52 >> 2] = n2.blocks, W[r3 + 56 >> 2] = n2.atime.getTime() / 1e3 | 0, W[r3 + 60 >> 2] = 0, W[r3 + 64 >> 2] = n2.mtime.getTime() / 1e3 | 0, W[r3 + 68 >> 2] = 0, W[r3 + 72 >> 2] = n2.ctime.getTime() / 1e3 | 0, W[r3 + 76 >> 2] = 0, ie = [n2.ino >>> 0, (ae = n2.ino, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[r3 + 80 >> 2] = ie[0], W[r3 + 84 >> 2] = ie[1], 0;
}, doMsync: function(e3, t2, r3, n2, o2) {
var s2 = T.slice(e3, e3 + r3);
FS.msync(t2, s2, o2, r3, n2);
}, doMkdir: function(e3, t2) {
return "/" === (e3 = PATH.normalize(e3))[e3.length - 1] && (e3 = e3.substr(0, e3.length - 1)), FS.mkdir(e3, t2, 0), 0;
}, doMknod: function(e3, t2, r3) {
switch (61440 & t2) {
case 32768:
case 8192:
case 24576:
case 4096:
case 49152:
break;
default:
return -28;
}
return FS.mknod(e3, t2, r3), 0;
}, doReadlink: function(e3, t2, r3) {
if (r3 <= 0)
return -28;
var n2 = FS.readlink(e3), o2 = Math.min(r3, U(n2)), s2 = q[t2 + o2];
return z(n2, t2, r3 + 1), q[t2 + o2] = s2, o2;
}, doAccess: function(e3, t2) {
if (-8 & t2)
return -28;
var r3;
if (!(r3 = FS.lookupPath(e3, { follow: true }).node))
return -44;
var n2 = "";
return 4 & t2 && (n2 += "r"), 2 & t2 && (n2 += "w"), 1 & t2 && (n2 += "x"), n2 && FS.nodePermissions(r3, n2) ? -2 : 0;
}, doDup: function(e3, t2, r3) {
var n2 = FS.getStream(r3);
return n2 && FS.close(n2), FS.open(e3, t2, 0, r3, r3).fd;
}, doReadv: function(e3, t2, r3, n2) {
for (var o2 = 0, s2 = 0; s2 < r3; s2++) {
var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.read(e3, q, _2, a2, n2);
if (i2 < 0)
return -1;
if (o2 += i2, i2 < a2)
break;
}
return o2;
}, doWritev: function(e3, t2, r3, n2) {
for (var o2 = 0, s2 = 0; s2 < r3; s2++) {
var _2 = W[t2 + 8 * s2 >> 2], a2 = W[t2 + (8 * s2 + 4) >> 2], i2 = FS.write(e3, q, _2, a2, n2);
if (i2 < 0)
return -1;
o2 += i2;
}
return o2;
}, varargs: void 0, get: function() {
return Le.varargs += 4, W[Le.varargs - 4 >> 2];
}, getStr: function(e3) {
return Z(e3);
}, getStreamFromFD: function(e3) {
var t2 = FS.getStream(e3);
if (!t2)
throw new FS.ErrnoError(8);
return t2;
}, get64: function(e3, t2) {
return e3;
} };
function Oe(e3) {
try {
var t2 = Le.getStreamFromFD(e3);
return FS.close(t2), 0;
} catch (e4) {
return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno;
}
}
function je(e3, t2, r3, n2) {
try {
var o2 = Le.getStreamFromFD(e3), s2 = Le.doWritev(o2, t2, r3);
return W[n2 >> 2] = s2, 0;
} catch (e4) {
return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno;
}
}
function $e(e3) {
}
Oe.sig = "ii", je.sig = "iiiii", $e.sig = "vi";
var Ze, De = { __heap_base: Ee, __indirect_function_table: K, __memory_base: 1024, __stack_pointer: Fe, __table_base: 1, abort: Ce, clock_gettime: Te, emscripten_memcpy_big: function(e3, t2, r3) {
T.copyWithin(e3, t2, t2 + r3);
}, emscripten_resize_heap: function(e3) {
var t2, r3, n2 = T.length;
if ((e3 >>>= 0) > 2147483648)
return false;
for (var o2 = 1; o2 <= 4; o2 *= 2) {
var s2 = n2 * (1 + 0.2 / o2);
if (s2 = Math.min(s2, e3 + 100663296), Re(Math.min(2147483648, ((t2 = Math.max(e3, s2)) % (r3 = 65536) > 0 && (t2 += r3 - t2 % r3), t2))))
return true;
}
return false;
}, exit: We, fd_close: Oe, fd_seek: function(e3, t2, r3, n2, o2) {
try {
var s2 = Le.getStreamFromFD(e3), _2 = 4294967296 * r3 + (t2 >>> 0);
return _2 <= -9007199254740992 || _2 >= 9007199254740992 ? -61 : (FS.llseek(s2, _2, n2), ie = [s2.position >>> 0, (ae = s2.position, +Math.abs(ae) >= 1 ? ae > 0 ? (0 | Math.min(+Math.floor(ae / 4294967296), 4294967295)) >>> 0 : ~~+Math.ceil((ae - +(~~ae >>> 0)) / 4294967296) >>> 0 : 0)], W[o2 >> 2] = ie[0], W[o2 + 4 >> 2] = ie[1], s2.getdents && 0 === _2 && 0 === n2 && (s2.getdents = null), 0);
} catch (e4) {
return "undefined" != typeof FS && e4 instanceof FS.ErrnoError || se(e4), e4.errno;
}
}, fd_write: je, memory: I, setTempRet0: $e, tree_sitter_log_callback: function(e3, t2) {
if (pt) {
const r3 = Z(t2);
pt(r3, 0 !== e3);
}
}, tree_sitter_parse_callback: function(e3, t2, r3, n2, o2) {
var s2 = ft(t2, { row: r3, column: n2 });
"string" == typeof s2 ? (x(o2, s2.length, "i32"), function(e4, t3, r4) {
if (void 0 === r4 && (r4 = 2147483647), r4 < 2)
return 0;
for (var n3 = (r4 -= 2) < 2 * e4.length ? r4 / 2 : e4.length, o3 = 0; o3 < n3; ++o3) {
var s3 = e4.charCodeAt(o3);
R[t3 >> 1] = s3, t3 += 2;
}
R[t3 >> 1] = 0;
}(s2, e3, 10240)) : x(o2, 0, "i32");
} }, ze = (function() {
var e3 = { env: De, wasi_snapshot_preview1: De, "GOT.mem": new Proxy(De, fe), "GOT.func": new Proxy(De, fe) };
function t2(e4, t3) {
var r4 = e4.exports;
r4 = Ie(r4, 1024), Module.asm = r4;
var n3, o2 = he(t3);
o2.neededDynlibs && (S = o2.neededDynlibs.concat(S)), ye(r4), n3 = Module.asm.__wasm_call_ctors, X.unshift(n3), oe();
}
function r3(e4) {
t2(e4.instance, e4.module);
}
function n2(t3) {
return function() {
if (!v && (u || l)) {
if ("function" == typeof fetch && !de(_e))
return fetch(_e, { credentials: "same-origin" }).then(function(e4) {
if (!e4.ok)
throw "failed to load wasm binary file at '" + _e + "'";
return e4.arrayBuffer();
}).catch(function() {
return ce(_e);
});
if (c2)
return new Promise(function(e4, t4) {
c2(_e, function(t5) {
e4(new Uint8Array(t5));
}, t4);
});
}
return Promise.resolve().then(function() {
return ce(_e);
});
}().then(function(t4) {
return WebAssembly.instantiate(t4, e3);
}).then(t3, function(e4) {
g2("failed to asynchronously prepare wasm: " + e4), se(e4);
});
}
if (ne(), Module.instantiateWasm)
try {
return Module.instantiateWasm(e3, t2);
} catch (e4) {
return g2("Module.instantiateWasm callback failed with error: " + e4), false;
}
v || "function" != typeof WebAssembly.instantiateStreaming || le(_e) || de(_e) || "function" != typeof fetch ? n2(r3) : fetch(_e, { credentials: "same-origin" }).then(function(t3) {
return WebAssembly.instantiateStreaming(t3, e3).then(r3, function(e4) {
return g2("wasm streaming compile failed: " + e4), g2("falling back to ArrayBuffer instantiation"), n2(r3);
});
});
}(), Module.___wasm_call_ctors = function() {
return (Module.___wasm_call_ctors = Module.asm.__wasm_call_ctors).apply(null, arguments);
}, Module._malloc = function() {
return (ze = Module._malloc = Module.asm.malloc).apply(null, arguments);
}), Ue = (Module._calloc = function() {
return (Module._calloc = Module.asm.calloc).apply(null, arguments);
}, Module._realloc = function() {
return (Module._realloc = Module.asm.realloc).apply(null, arguments);
}, Module._free = function() {
return (Module._free = Module.asm.free).apply(null, arguments);
}, Module._ts_language_symbol_count = function() {
return (Module._ts_language_symbol_count = Module.asm.ts_language_symbol_count).apply(null, arguments);
}, Module._ts_language_version = function() {
return (Module._ts_language_version = Module.asm.ts_language_version).apply(null, arguments);
}, Module._ts_language_field_count = function() {
return (Module._ts_language_field_count = Module.asm.ts_language_field_count).apply(null, arguments);
}, Module._ts_language_symbol_name = function() {
return (Module._ts_language_symbol_name = Module.asm.ts_language_symbol_name).apply(null, arguments);
}, Module._ts_language_symbol_for_name = function() {
return (Module._ts_language_symbol_for_name = Module.asm.ts_language_symbol_for_name).apply(null, arguments);
}, Module._ts_language_symbol_type = function() {
return (Module._ts_language_symbol_type = Module.asm.ts_language_symbol_type).apply(null, arguments);
}, Module._ts_language_field_name_for_id = function() {
return (Module._ts_language_field_name_for_id = Module.asm.ts_language_field_name_for_id).apply(null, arguments);
}, Module._memcpy = function() {
return (Module._memcpy = Module.asm.memcpy).apply(null, arguments);
}, Module._ts_parser_delete = function() {
return (Module._ts_parser_delete = Module.asm.ts_parser_delete).apply(null, arguments);
}, Module._ts_parser_reset = function() {
return (Module._ts_parser_reset = Module.asm.ts_parser_reset).apply(null, arguments);
}, Module._ts_parser_set_language = function() {
return (Module._ts_parser_set_language = Module.asm.ts_parser_set_language).apply(null, arguments);
}, Module._ts_parser_timeout_micros = function() {
return (Module._ts_parser_timeout_micros = Module.asm.ts_parser_timeout_micros).apply(null, arguments);
}, Module._ts_parser_set_timeout_micros = function() {
return (Module._ts_parser_set_timeout_micros = Module.asm.ts_parser_set_timeout_micros).apply(null, arguments);
}, Module._memmove = function() {
return (Module._memmove = Module.asm.memmove).apply(null, arguments);
}, Module._memcmp = function() {
return (Module._memcmp = Module.asm.memcmp).apply(null, arguments);
}, Module._ts_query_new = function() {
return (Module._ts_query_new = Module.asm.ts_query_new).apply(null, arguments);
}, Module._ts_query_delete = function() {
return (Module._ts_query_delete = Module.asm.ts_query_delete).apply(null, arguments);
}, Module._iswspace = function() {
return (Module._iswspace = Module.asm.iswspace).apply(null, arguments);
}, Module._iswalnum = function() {
return (Module._iswalnum = Module.asm.iswalnum).apply(null, arguments);
}, Module._ts_query_pattern_count = function() {
return (Module._ts_query_pattern_count = Module.asm.ts_query_pattern_count).apply(null, arguments);
}, Module._ts_query_capture_count = function() {
return (Module._ts_query_capture_count = Module.asm.ts_query_capture_count).apply(null, arguments);
}, Module._ts_query_string_count = function() {
return (Module._ts_query_string_count = Module.asm.ts_query_string_count).apply(null, arguments);
}, Module._ts_query_capture_name_for_id = function() {
return (Module._ts_query_capture_name_for_id = Module.asm.ts_query_capture_name_for_id).apply(null, arguments);
}, Module._ts_query_string_value_for_id = function() {
return (Module._ts_query_string_value_for_id = Module.asm.ts_query_string_value_for_id).apply(null, arguments);
}, Module._ts_query_predicates_for_pattern = function() {
return (Module._ts_query_predicates_for_pattern = Module.asm.ts_query_predicates_for_pattern).apply(null, arguments);
}, Module._ts_tree_copy = function() {
return (Module._ts_tree_copy = Module.asm.ts_tree_copy).apply(null, arguments);
}, Module._ts_tree_delete = function() {
return (Module._ts_tree_delete = Module.asm.ts_tree_delete).apply(null, arguments);
}, Module._ts_init = function() {
return (Module._ts_init = Module.asm.ts_init).apply(null, arguments);
}, Module._ts_parser_new_wasm = function() {
return (Module._ts_parser_new_wasm = Module.asm.ts_parser_new_wasm).apply(null, arguments);
}, Module._ts_parser_enable_logger_wasm = function() {
return (Module._ts_parser_enable_logger_wasm = Module.asm.ts_parser_enable_logger_wasm).apply(null, arguments);
}, Module._ts_parser_parse_wasm = function() {
return (Module._ts_parser_parse_wasm = Module.asm.ts_parser_parse_wasm).apply(null, arguments);
}, Module._ts_language_type_is_named_wasm = function() {
return (Module._ts_language_type_is_named_wasm = Module.asm.ts_language_type_is_named_wasm).apply(null, arguments);
}, Module._ts_language_type_is_visible_wasm = function() {
return (Module._ts_language_type_is_visible_wasm = Module.asm.ts_language_type_is_visible_wasm).apply(null, arguments);
}, Module._ts_tree_root_node_wasm = function() {
return (Module._ts_tree_root_node_wasm = Module.asm.ts_tree_root_node_wasm).apply(null, arguments);
}, Module._ts_tree_edit_wasm = function() {
return (Module._ts_tree_edit_wasm = Module.asm.ts_tree_edit_wasm).apply(null, arguments);
}, Module._ts_tree_get_changed_ranges_wasm = function() {
return (Module._ts_tree_get_changed_ranges_wasm = Module.asm.ts_tree_get_changed_ranges_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_new_wasm = function() {
return (Module._ts_tree_cursor_new_wasm = Module.asm.ts_tree_cursor_new_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_delete_wasm = function() {
return (Module._ts_tree_cursor_delete_wasm = Module.asm.ts_tree_cursor_delete_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_reset_wasm = function() {
return (Module._ts_tree_cursor_reset_wasm = Module.asm.ts_tree_cursor_reset_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_goto_first_child_wasm = function() {
return (Module._ts_tree_cursor_goto_first_child_wasm = Module.asm.ts_tree_cursor_goto_first_child_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_goto_next_sibling_wasm = function() {
return (Module._ts_tree_cursor_goto_next_sibling_wasm = Module.asm.ts_tree_cursor_goto_next_sibling_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_goto_parent_wasm = function() {
return (Module._ts_tree_cursor_goto_parent_wasm = Module.asm.ts_tree_cursor_goto_parent_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_node_type_id_wasm = function() {
return (Module._ts_tree_cursor_current_node_type_id_wasm = Module.asm.ts_tree_cursor_current_node_type_id_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_node_is_named_wasm = function() {
return (Module._ts_tree_cursor_current_node_is_named_wasm = Module.asm.ts_tree_cursor_current_node_is_named_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_node_is_missing_wasm = function() {
return (Module._ts_tree_cursor_current_node_is_missing_wasm = Module.asm.ts_tree_cursor_current_node_is_missing_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_node_id_wasm = function() {
return (Module._ts_tree_cursor_current_node_id_wasm = Module.asm.ts_tree_cursor_current_node_id_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_start_position_wasm = function() {
return (Module._ts_tree_cursor_start_position_wasm = Module.asm.ts_tree_cursor_start_position_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_end_position_wasm = function() {
return (Module._ts_tree_cursor_end_position_wasm = Module.asm.ts_tree_cursor_end_position_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_start_index_wasm = function() {
return (Module._ts_tree_cursor_start_index_wasm = Module.asm.ts_tree_cursor_start_index_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_end_index_wasm = function() {
return (Module._ts_tree_cursor_end_index_wasm = Module.asm.ts_tree_cursor_end_index_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_field_id_wasm = function() {
return (Module._ts_tree_cursor_current_field_id_wasm = Module.asm.ts_tree_cursor_current_field_id_wasm).apply(null, arguments);
}, Module._ts_tree_cursor_current_node_wasm = function() {
return (Module._ts_tree_cursor_current_node_wasm = Module.asm.ts_tree_cursor_current_node_wasm).apply(null, arguments);
}, Module._ts_node_symbol_wasm = function() {
return (Module._ts_node_symbol_wasm = Module.asm.ts_node_symbol_wasm).apply(null, arguments);
}, Module._ts_node_child_count_wasm = function() {
return (Module._ts_node_child_count_wasm = Module.asm.ts_node_child_count_wasm).apply(null, arguments);
}, Module._ts_node_named_child_count_wasm = function() {
return (Module._ts_node_named_child_count_wasm = Module.asm.ts_node_named_child_count_wasm).apply(null, arguments);
}, Module._ts_node_child_wasm = function() {
return (Module._ts_node_child_wasm = Module.asm.ts_node_child_wasm).apply(null, arguments);
}, Module._ts_node_named_child_wasm = function() {
return (Module._ts_node_named_child_wasm = Module.asm.ts_node_named_child_wasm).apply(null, arguments);
}, Module._ts_node_child_by_field_id_wasm = function() {
return (Module._ts_node_child_by_field_id_wasm = Module.asm.ts_node_child_by_field_id_wasm).apply(null, arguments);
}, Module._ts_node_next_sibling_wasm = function() {
return (Module._ts_node_next_sibling_wasm = Module.asm.ts_node_next_sibling_wasm).apply(null, arguments);
}, Module._ts_node_prev_sibling_wasm = function() {
return (Module._ts_node_prev_sibling_wasm = Module.asm.ts_node_prev_sibling_wasm).apply(null, arguments);
}, Module._ts_node_next_named_sibling_wasm = function() {
return (Module._ts_node_next_named_sibling_wasm = Module.asm.ts_node_next_named_sibling_wasm).apply(null, arguments);
}, Module._ts_node_prev_named_sibling_wasm = function() {
return (Module._ts_node_prev_named_sibling_wasm = Module.asm.ts_node_prev_named_sibling_wasm).apply(null, arguments);
}, Module._ts_node_parent_wasm = function() {
return (Module._ts_node_parent_wasm = Module.asm.ts_node_parent_wasm).apply(null, arguments);
}, Module._ts_node_descendant_for_index_wasm = function() {
return (Module._ts_node_descendant_for_index_wasm = Module.asm.ts_node_descendant_for_index_wasm).apply(null, arguments);
}, Module._ts_node_named_descendant_for_index_wasm = function() {
return (Module._ts_node_named_descendant_for_index_wasm = Module.asm.ts_node_named_descendant_for_index_wasm).apply(null, arguments);
}, Module._ts_node_descendant_for_position_wasm = function() {
return (Module._ts_node_descendant_for_position_wasm = Module.asm.ts_node_descendant_for_position_wasm).apply(null, arguments);
}, Module._ts_node_named_descendant_for_position_wasm = function() {
return (Module._ts_node_named_descendant_for_position_wasm = Module.asm.ts_node_named_descendant_for_position_wasm).apply(null, arguments);
}, Module._ts_node_start_point_wasm = function() {
return (Module._ts_node_start_point_wasm = Module.asm.ts_node_start_point_wasm).apply(null, arguments);
}, Module._ts_node_end_point_wasm = function() {
return (Module._ts_node_end_point_wasm = Module.asm.ts_node_end_point_wasm).apply(null, arguments);
}, Module._ts_node_start_index_wasm = function() {
return (Module._ts_node_start_index_wasm = Module.asm.ts_node_start_index_wasm).apply(null, arguments);
}, Module._ts_node_end_index_wasm = function() {
return (Module._ts_node_end_index_wasm = Module.asm.ts_node_end_index_wasm).apply(null, arguments);
}, Module._ts_node_to_string_wasm = function() {
return (Module._ts_node_to_string_wasm = Module.asm.ts_node_to_string_wasm).apply(null, arguments);
}, Module._ts_node_children_wasm = function() {
return (Module._ts_node_children_wasm = Module.asm.ts_node_children_wasm).apply(null, arguments);
}, Module._ts_node_named_children_wasm = function() {
return (Module._ts_node_named_children_wasm = Module.asm.ts_node_named_children_wasm).apply(null, arguments);
}, Module._ts_node_descendants_of_type_wasm = function() {
return (Module._ts_node_descendants_of_type_wasm = Module.asm.ts_node_descendants_of_type_wasm).apply(null, arguments);
}, Module._ts_node_is_named_wasm = function() {
return (Module._ts_node_is_named_wasm = Module.asm.ts_node_is_named_wasm).apply(null, arguments);
}, Module._ts_node_has_changes_wasm = function() {
return (Module._ts_node_has_changes_wasm = Module.asm.ts_node_has_changes_wasm).apply(null, arguments);
}, Module._ts_node_has_error_wasm = function() {
return (Module._ts_node_has_error_wasm = Module.asm.ts_node_has_error_wasm).apply(null, arguments);
}, Module._ts_node_is_missing_wasm = function() {
return (Module._ts_node_is_missing_wasm = Module.asm.ts_node_is_missing_wasm).apply(null, arguments);
}, Module._ts_query_matches_wasm = function() {
return (Module._ts_query_matches_wasm = Module.asm.ts_query_matches_wasm).apply(null, arguments);
}, Module._ts_query_captures_wasm = function() {
return (Module._ts_query_captures_wasm = Module.asm.ts_query_captures_wasm).apply(null, arguments);
}, Module._iswdigit = function() {
return (Module._iswdigit = Module.asm.iswdigit).apply(null, arguments);
}, Module._iswalpha = function() {
return (Module._iswalpha = Module.asm.iswalpha).apply(null, arguments);
}, Module._iswlower = function() {
return (Module._iswlower = Module.asm.iswlower).apply(null, arguments);
}, Module._towupper = function() {
return (Module._towupper = Module.asm.towupper).apply(null, arguments);
}, Module.___errno_location = function() {
return (Ue = Module.___errno_location = Module.asm.__errno_location).apply(null, arguments);
}), He = (Module._memchr = function() {
return (Module._memchr = Module.asm.memchr).apply(null, arguments);
}, Module._strlen = function() {
return (Module._strlen = Module.asm.strlen).apply(null, arguments);
}, Module.stackSave = function() {
return (He = Module.stackSave = Module.asm.stackSave).apply(null, arguments);
}), Ge = Module.stackRestore = function() {
return (Ge = Module.stackRestore = Module.asm.stackRestore).apply(null, arguments);
}, Be = Module.stackAlloc = function() {
return (Be = Module.stackAlloc = Module.asm.stackAlloc).apply(null, arguments);
}, Ke = Module._setThrew = function() {
return (Ke = Module._setThrew = Module.asm.setThrew).apply(null, arguments);
};
Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = function() {
return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = function() {
return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = function() {
return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = function() {
return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm).apply(null, arguments);
}, Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = function() {
return (Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm = Module.asm._ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = function() {
return (Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc = Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = function() {
return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev).apply(null, arguments);
}, Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = function() {
return (Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw = Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw).apply(null, arguments);
}, Module.__Znwm = function() {
return (Module.__Znwm = Module.asm._Znwm).apply(null, arguments);
}, Module.__ZdlPv = function() {
return (Module.__ZdlPv = Module.asm._ZdlPv).apply(null, arguments);
}, Module.dynCall_jiji = function() {
return (Module.dynCall_jiji = Module.asm.dynCall_jiji).apply(null, arguments);
}, Module._orig$ts_parser_timeout_micros = function() {
return (Module._orig$ts_parser_timeout_micros = Module.asm.orig$ts_parser_timeout_micros).apply(null, arguments);
}, Module._orig$ts_parser_set_timeout_micros = function() {
return (Module._orig$ts_parser_set_timeout_micros = Module.asm.orig$ts_parser_set_timeout_micros).apply(null, arguments);
};
function Ve(e3) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + e3 + ")", this.status = e3;
}
Module.allocate = function(e3, t2) {
var r3;
return r3 = t2 == F ? Be(e3.length) : ze(e3.length), e3.subarray || e3.slice ? T.set(e3, r3) : T.set(new Uint8Array(e3), r3), r3;
};
re = function e3() {
Ze || Qe(), Ze || (re = e3);
};
var Xe = false;
function Qe(e3) {
function t2() {
Ze || (Ze = true, Module.calledRun = true, P || (Y = true, pe(X), pe(Q), Module.onRuntimeInitialized && Module.onRuntimeInitialized(), Ye && function(e4) {
var t3 = Module._main;
if (t3) {
var r3 = (e4 = e4 || []).length + 1, n2 = Be(4 * (r3 + 1));
W[n2 >> 2] = H(a);
for (var o2 = 1; o2 < r3; o2++)
W[(n2 >> 2) + o2] = H(e4[o2 - 1]);
W[(n2 >> 2) + r3] = 0;
try {
Je(t3(r3, n2), true);
} catch (e5) {
if (e5 instanceof Ve)
return;
if ("unwind" == e5)
return;
var s2 = e5;
e5 && "object" == typeof e5 && e5.stack && (s2 = [e5, e5.stack]), g2("exception thrown: " + s2), i(1, e5);
} finally {
}
}
}(e3), function() {
if (Module.postRun)
for ("function" == typeof Module.postRun && (Module.postRun = [Module.postRun]); Module.postRun.length; )
e4 = Module.postRun.shift(), J.unshift(e4);
var e4;
pe(J);
}()));
}
e3 = e3 || _, ee > 0 || !Xe && (function() {
if (S.length) {
if (!m)
return ne(), void S.reduce(function(e4, t3) {
return e4.then(function() {
return Ne(t3, { loadAsync: true, global: true, nodelete: true, allowUndefined: true });
});
}, Promise.resolve()).then(function() {
oe(), Pe();
});
S.forEach(function(e4) {
Ne(e4, { global: true, nodelete: true, allowUndefined: true });
}), Pe();
} else
Pe();
}(), Xe = true, ee > 0) || (!function() {
if (Module.preRun)
for ("function" == typeof Module.preRun && (Module.preRun = [Module.preRun]); Module.preRun.length; )
e4 = Module.preRun.shift(), V.unshift(e4);
var e4;
pe(V);
}(), ee > 0 || (Module.setStatus ? (Module.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
Module.setStatus("");
}, 1), t2();
}, 1)) : t2()));
}
function Je(e3, t2) {
t2 && we() && 0 === e3 || (we() || (Module.onExit && Module.onExit(e3), P = true), i(e3, new Ve(e3)));
}
if (Module.run = Qe, Module.preInit)
for ("function" == typeof Module.preInit && (Module.preInit = [Module.preInit]); Module.preInit.length > 0; )
Module.preInit.pop()();
var Ye = true;
Module.noInitialRun && (Ye = false), Qe();
const et = Module, tt = {}, rt = 4, nt = 5 * rt, ot = 2 * rt, st = 2 * rt + 2 * ot, _t = { row: 0, column: 0 }, at = /[\w-.]*/g, it = 1, ut = 2, lt = /^_?tree_sitter_\w+/;
var dt, ct, mt, ft, pt;
class ParserImpl {
static init() {
mt = et._ts_init(), dt = N(mt, "i32"), ct = N(mt + rt, "i32");
}
initialize() {
et._ts_parser_new_wasm(), this[0] = N(mt, "i32"), this[1] = N(mt + rt, "i32");
}
delete() {
et._ts_parser_delete(this[0]), et._free(this[1]), this[0] = 0, this[1] = 0;
}
setLanguage(e3) {
let t2;
if (e3) {
if (e3.constructor !== Language)
throw new Error("Argument must be a Language");
{
t2 = e3[0];
const r3 = et._ts_language_version(t2);
if (r3 < ct || dt < r3)
throw new Error(`Incompatible language version ${r3}. Compatibility range ${ct} through ${dt}.`);
}
} else
t2 = 0, e3 = null;
return this.language = e3, et._ts_parser_set_language(this[0], t2), this;
}
getLanguage() {
return this.language;
}
parse(e3, t2, r3) {
if ("string" == typeof e3)
ft = (t3, r4, n3) => e3.slice(t3, n3);
else {
if ("function" != typeof e3)
throw new Error("Argument must be a string or a function");
ft = e3;
}
this.logCallback ? (pt = this.logCallback, et._ts_parser_enable_logger_wasm(this[0], 1)) : (pt = null, et._ts_parser_enable_logger_wasm(this[0], 0));
let n2 = 0, o2 = 0;
if (r3 && r3.includedRanges) {
n2 = r3.includedRanges.length;
let e4 = o2 = et._calloc(n2, st);
for (let t3 = 0; t3 < n2; t3++)
At(e4, r3.includedRanges[t3]), e4 += st;
}
const s2 = et._ts_parser_parse_wasm(this[0], this[1], t2 ? t2[0] : 0, o2, n2);
if (!s2)
throw ft = null, pt = null, new Error("Parsing failed");
const _2 = new Tree(tt, s2, this.language, ft);
return ft = null, pt = null, _2;
}
reset() {
et._ts_parser_reset(this[0]);
}
setTimeoutMicros(e3) {
et._ts_parser_set_timeout_micros(this[0], e3);
}
getTimeoutMicros() {
return et._ts_parser_timeout_micros(this[0]);
}
setLogger(e3) {
if (e3) {
if ("function" != typeof e3)
throw new Error("Logger callback must be a function");
} else
e3 = null;
return this.logCallback = e3, this;
}
getLogger() {
return this.logCallback;
}
}
class Tree {
constructor(e3, t2, r3, n2) {
wt(e3), this[0] = t2, this.language = r3, this.textCallback = n2;
}
copy() {
const e3 = et._ts_tree_copy(this[0]);
return new Tree(tt, e3, this.language, this.textCallback);
}
delete() {
et._ts_tree_delete(this[0]), this[0] = 0;
}
edit(e3) {
!function(e4) {
let t2 = mt;
St(t2, e4.startPosition), St(t2 += ot, e4.oldEndPosition), St(t2 += ot, e4.newEndPosition), x(t2 += ot, e4.startIndex, "i32"), x(t2 += rt, e4.oldEndIndex, "i32"), x(t2 += rt, e4.newEndIndex, "i32"), t2 += rt;
}(e3), et._ts_tree_edit_wasm(this[0]);
}
get rootNode() {
return et._ts_tree_root_node_wasm(this[0]), bt(this);
}
getLanguage() {
return this.language;
}
walk() {
return this.rootNode.walk();
}
getChangedRanges(e3) {
if (e3.constructor !== Tree)
throw new TypeError("Argument must be a Tree");
et._ts_tree_get_changed_ranges_wasm(this[0], e3[0]);
const t2 = N(mt, "i32"), r3 = N(mt + rt, "i32"), n2 = new Array(t2);
if (t2 > 0) {
let e4 = r3;
for (let r4 = 0; r4 < t2; r4++)
n2[r4] = xt(e4), e4 += st;
et._free(r3);
}
return n2;
}
}
class Node {
constructor(e3, t2) {
wt(e3), this.tree = t2;
}
get typeId() {
return yt(this), et._ts_node_symbol_wasm(this.tree[0]);
}
get type() {
return this.tree.language.types[this.typeId] || "ERROR";
}
get endPosition() {
return yt(this), et._ts_node_end_point_wasm(this.tree[0]), It(mt);
}
get endIndex() {
return yt(this), et._ts_node_end_index_wasm(this.tree[0]);
}
get text() {
return ht(this.tree, this.startIndex, this.endIndex);
}
isNamed() {
return yt(this), 1 === et._ts_node_is_named_wasm(this.tree[0]);
}
hasError() {
return yt(this), 1 === et._ts_node_has_error_wasm(this.tree[0]);
}
hasChanges() {
return yt(this), 1 === et._ts_node_has_changes_wasm(this.tree[0]);
}
isMissing() {
return yt(this), 1 === et._ts_node_is_missing_wasm(this.tree[0]);
}
equals(e3) {
return this.id === e3.id;
}
child(e3) {
return yt(this), et._ts_node_child_wasm(this.tree[0], e3), bt(this.tree);
}
namedChild(e3) {
return yt(this), et._ts_node_named_child_wasm(this.tree[0], e3), bt(this.tree);
}
childForFieldId(e3) {
return yt(this), et._ts_node_child_by_field_id_wasm(this.tree[0], e3), bt(this.tree);
}
childForFieldName(e3) {
const t2 = this.tree.language.fields.indexOf(e3);
if (-1 !== t2)
return this.childForFieldId(t2);
}
get childCount() {
return yt(this), et._ts_node_child_count_wasm(this.tree[0]);
}
get namedChildCount() {
return yt(this), et._ts_node_named_child_count_wasm(this.tree[0]);
}
get firstChild() {
return this.child(0);
}
get firstNamedChild() {
return this.namedChild(0);
}
get lastChild() {
return this.child(this.childCount - 1);
}
get lastNamedChild() {
return this.namedChild(this.namedChildCount - 1);
}
get children() {
if (!this._children) {
yt(this), et._ts_node_children_wasm(this.tree[0]);
const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32");
if (this._children = new Array(e3), e3 > 0) {
let r3 = t2;
for (let t3 = 0; t3 < e3; t3++)
this._children[t3] = bt(this.tree, r3), r3 += nt;
et._free(t2);
}
}
return this._children;
}
get namedChildren() {
if (!this._namedChildren) {
yt(this), et._ts_node_named_children_wasm(this.tree[0]);
const e3 = N(mt, "i32"), t2 = N(mt + rt, "i32");
if (this._namedChildren = new Array(e3), e3 > 0) {
let r3 = t2;
for (let t3 = 0; t3 < e3; t3++)
this._namedChildren[t3] = bt(this.tree, r3), r3 += nt;
et._free(t2);
}
}
return this._namedChildren;
}
descendantsOfType(e3, t2, r3) {
Array.isArray(e3) || (e3 = [e3]), t2 || (t2 = _t), r3 || (r3 = _t);
const n2 = [], o2 = this.tree.language.types;
for (let t3 = 0, r4 = o2.length; t3 < r4; t3++)
e3.includes(o2[t3]) && n2.push(t3);
const s2 = et._malloc(rt * n2.length);
for (let e4 = 0, t3 = n2.length; e4 < t3; e4++)
x(s2 + e4 * rt, n2[e4], "i32");
yt(this), et._ts_node_descendants_of_type_wasm(this.tree[0], s2, n2.length, t2.row, t2.column, r3.row, r3.column);
const _2 = N(mt, "i32"), a2 = N(mt + rt, "i32"), i2 = new Array(_2);
if (_2 > 0) {
let e4 = a2;
for (let t3 = 0; t3 < _2; t3++)
i2[t3] = bt(this.tree, e4), e4 += nt;
}
return et._free(a2), et._free(s2), i2;
}
get nextSibling() {
return yt(this), et._ts_node_next_sibling_wasm(this.tree[0]), bt(this.tree);
}
get previousSibling() {
return yt(this), et._ts_node_prev_sibling_wasm(this.tree[0]), bt(this.tree);
}
get nextNamedSibling() {
return yt(this), et._ts_node_next_named_sibling_wasm(this.tree[0]), bt(this.tree);
}
get previousNamedSibling() {
return yt(this), et._ts_node_prev_named_sibling_wasm(this.tree[0]), bt(this.tree);
}
get parent() {
return yt(this), et._ts_node_parent_wasm(this.tree[0]), bt(this.tree);
}
descendantForIndex(e3, t2 = e3) {
if ("number" != typeof e3 || "number" != typeof t2)
throw new Error("Arguments must be numbers");
yt(this);
let r3 = mt + nt;
return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_descendant_for_index_wasm(this.tree[0]), bt(this.tree);
}
namedDescendantForIndex(e3, t2 = e3) {
if ("number" != typeof e3 || "number" != typeof t2)
throw new Error("Arguments must be numbers");
yt(this);
let r3 = mt + nt;
return x(r3, e3, "i32"), x(r3 + rt, t2, "i32"), et._ts_node_named_descendant_for_index_wasm(this.tree[0]), bt(this.tree);
}
descendantForPosition(e3, t2 = e3) {
if (!Mt(e3) || !Mt(t2))
throw new Error("Arguments must be {row, column} objects");
yt(this);
let r3 = mt + nt;
return St(r3, e3), St(r3 + ot, t2), et._ts_node_descendant_for_position_wasm(this.tree[0]), bt(this.tree);
}
namedDescendantForPosition(e3, t2 = e3) {
if (!Mt(e3) || !Mt(t2))
throw new Error("Arguments must be {row, column} objects");
yt(this);
let r3 = mt + nt;
return St(r3, e3), St(r3 + ot, t2), et._ts_node_named_descendant_for_position_wasm(this.tree[0]), bt(this.tree);
}
walk() {
return yt(this), et._ts_tree_cursor_new_wasm(this.tree[0]), new TreeCursor(tt, this.tree);
}
toString() {
yt(this);
const e3 = et._ts_node_to_string_wasm(this.tree[0]), t2 = function(e4) {
for (var t3 = ""; ; ) {
var r3 = T[e4++ >> 0];
if (!r3)
return t3;
t3 += String.fromCharCode(r3);
}
}(e3);
return et._free(e3), t2;
}
}
class TreeCursor {
constructor(e3, t2) {
wt(e3), this.tree = t2, Et(this);
}
delete() {
vt(this), et._ts_tree_cursor_delete_wasm(this.tree[0]), this[0] = this[1] = this[2] = 0;
}
reset(e3) {
yt(e3), vt(this, mt + nt), et._ts_tree_cursor_reset_wasm(this.tree[0]), Et(this);
}
get nodeType() {
return this.tree.language.types[this.nodeTypeId] || "ERROR";
}
get nodeTypeId() {
return vt(this), et._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
}
get nodeId() {
return vt(this), et._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
}
get nodeIsNamed() {
return vt(this), 1 === et._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]);
}
get nodeIsMissing() {
return vt(this), 1 === et._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]);
}
get nodeText() {
vt(this);
const e3 = et._ts_tree_cursor_start_index_wasm(this.tree[0]), t2 = et._ts_tree_cursor_end_index_wasm(this.tree[0]);
return ht(this.tree, e3, t2);
}
get startPosition() {
return vt(this), et._ts_tree_cursor_start_position_wasm(this.tree[0]), It(mt);
}
get endPosition() {
return vt(this), et._ts_tree_cursor_end_position_wasm(this.tree[0]), It(mt);
}
get startIndex() {
return vt(this), et._ts_tree_cursor_start_index_wasm(this.tree[0]);
}
get endIndex() {
return vt(this), et._ts_tree_cursor_end_index_wasm(this.tree[0]);
}
currentNode() {
return vt(this), et._ts_tree_cursor_current_node_wasm(this.tree[0]), bt(this.tree);
}
currentFieldId() {
return vt(this), et._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
}
currentFieldName() {
return this.tree.language.fields[this.currentFieldId()];
}
gotoFirstChild() {
vt(this);
const e3 = et._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
return Et(this), 1 === e3;
}
gotoNextSibling() {
vt(this);
const e3 = et._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
return Et(this), 1 === e3;
}
gotoParent() {
vt(this);
const e3 = et._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
return Et(this), 1 === e3;
}
}
class Language {
constructor(e3, t2) {
wt(e3), this[0] = t2, this.types = new Array(et._ts_language_symbol_count(this[0]));
for (let e4 = 0, t3 = this.types.length; e4 < t3; e4++)
et._ts_language_symbol_type(this[0], e4) < 2 && (this.types[e4] = Z(et._ts_language_symbol_name(this[0], e4)));
this.fields = new Array(et._ts_language_field_count(this[0]) + 1);
for (let e4 = 0, t3 = this.fields.length; e4 < t3; e4++) {
const t4 = et._ts_language_field_name_for_id(this[0], e4);
this.fields[e4] = 0 !== t4 ? Z(t4) : null;
}
}
get version() {
return et._ts_language_version(this[0]);
}
get fieldCount() {
return this.fields.length - 1;
}
fieldIdForName(e3) {
const t2 = this.fields.indexOf(e3);
return -1 !== t2 ? t2 : null;
}
fieldNameForId(e3) {
return this.fields[e3] || null;
}
idForNodeType(e3, t2) {
const r3 = U(e3), n2 = et._malloc(r3 + 1);
z(e3, n2, r3 + 1);
const o2 = et._ts_language_symbol_for_name(this[0], n2, r3, t2);
return et._free(n2), o2 || null;
}
get nodeTypeCount() {
return et._ts_language_symbol_count(this[0]);
}
nodeTypeForId(e3) {
const t2 = et._ts_language_symbol_name(this[0], e3);
return t2 ? Z(t2) : null;
}
nodeTypeIsNamed(e3) {
return !!et._ts_language_type_is_named_wasm(this[0], e3);
}
nodeTypeIsVisible(e3) {
return !!et._ts_language_type_is_visible_wasm(this[0], e3);
}
query(e3) {
const t2 = U(e3), r3 = et._malloc(t2 + 1);
z(e3, r3, t2 + 1);
const n2 = et._ts_query_new(this[0], r3, t2, mt, mt + rt);
if (!n2) {
const t3 = N(mt + rt, "i32"), n3 = Z(r3, N(mt, "i32")).length, o3 = e3.substr(n3, 100).split("\n")[0];
let s3, _3 = o3.match(at)[0];
switch (t3) {
case 2:
s3 = new RangeError(`Bad node name '${_3}'`);
break;
case 3:
s3 = new RangeError(`Bad field name '${_3}'`);
break;
case 4:
s3 = new RangeError(`Bad capture name @${_3}`);
break;
case 5:
s3 = new TypeError(`Bad pattern structure at offset ${n3}: '${o3}'...`), _3 = "";
break;
default:
s3 = new SyntaxError(`Bad syntax at offset ${n3}: '${o3}'...`), _3 = "";
}
throw s3.index = n3, s3.length = _3.length, et._free(r3), s3;
}
const o2 = et._ts_query_string_count(n2), s2 = et._ts_query_capture_count(n2), _2 = et._ts_query_pattern_count(n2), a2 = new Array(s2), i2 = new Array(o2);
for (let e4 = 0; e4 < s2; e4++) {
const t3 = et._ts_query_capture_name_for_id(n2, e4, mt), r4 = N(mt, "i32");
a2[e4] = Z(t3, r4);
}
for (let e4 = 0; e4 < o2; e4++) {
const t3 = et._ts_query_string_value_for_id(n2, e4, mt), r4 = N(mt, "i32");
i2[e4] = Z(t3, r4);
}
const u2 = new Array(_2), l2 = new Array(_2), d2 = new Array(_2), c3 = new Array(_2), m2 = new Array(_2);
for (let e4 = 0; e4 < _2; e4++) {
const t3 = et._ts_query_predicates_for_pattern(n2, e4, mt), r4 = N(mt, "i32");
c3[e4] = [], m2[e4] = [];
const o3 = [];
let s3 = t3;
for (let t4 = 0; t4 < r4; t4++) {
const t5 = N(s3, "i32"), r5 = N(s3 += rt, "i32");
if (s3 += rt, t5 === it)
o3.push({ type: "capture", name: a2[r5] });
else if (t5 === ut)
o3.push({ type: "string", value: i2[r5] });
else if (o3.length > 0) {
if ("string" !== o3[0].type)
throw new Error("Predicates must begin with a literal value");
const t6 = o3[0].value;
let r6 = true;
switch (t6) {
case "not-eq?":
r6 = false;
case "eq?":
if (3 !== o3.length)
throw new Error(`Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${o3.length - 1}`);
if ("capture" !== o3[1].type)
throw new Error(`First argument of \`#eq?\` predicate must be a capture. Got "${o3[1].value}"`);
if ("capture" === o3[2].type) {
const t7 = o3[1].name, n4 = o3[2].name;
m2[e4].push(function(e5) {
let o4, s5;
for (const r7 of e5)
r7.name === t7 && (o4 = r7.node), r7.name === n4 && (s5 = r7.node);
return void 0 === o4 || void 0 === s5 || o4.text === s5.text === r6;
});
} else {
const t7 = o3[1].name, n4 = o3[2].value;
m2[e4].push(function(e5) {
for (const o4 of e5)
if (o4.name === t7)
return o4.node.text === n4 === r6;
return true;
});
}
break;
case "not-match?":
r6 = false;
case "match?":
if (3 !== o3.length)
throw new Error(`Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${o3.length - 1}.`);
if ("capture" !== o3[1].type)
throw new Error(`First argument of \`#match?\` predicate must be a capture. Got "${o3[1].value}".`);
if ("string" !== o3[2].type)
throw new Error(`Second argument of \`#match?\` predicate must be a string. Got @${o3[2].value}.`);
const n3 = o3[1].name, s4 = new RegExp(o3[2].value);
m2[e4].push(function(e5) {
for (const t7 of e5)
if (t7.name === n3)
return s4.test(t7.node.text) === r6;
return true;
});
break;
case "set!":
if (o3.length < 2 || o3.length > 3)
throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`);
if (o3.some((e5) => "string" !== e5.type))
throw new Error('Arguments to `#set!` predicate must be a strings.".');
u2[e4] || (u2[e4] = {}), u2[e4][o3[1].value] = o3[2] ? o3[2].value : null;
break;
case "is?":
case "is-not?":
if (o3.length < 2 || o3.length > 3)
throw new Error(`Wrong number of arguments to \`#${t6}\` predicate. Expected 1 or 2. Got ${o3.length - 1}.`);
if (o3.some((e5) => "string" !== e5.type))
throw new Error(`Arguments to \`#${t6}\` predicate must be a strings.".`);
const _3 = "is?" === t6 ? l2 : d2;
_3[e4] || (_3[e4] = {}), _3[e4][o3[1].value] = o3[2] ? o3[2].value : null;
break;
default:
c3[e4].push({ operator: t6, operands: o3.slice(1) });
}
o3.length = 0;
}
}
Object.freeze(u2[e4]), Object.freeze(l2[e4]), Object.freeze(d2[e4]);
}
return et._free(r3), new Query(tt, n2, a2, m2, c3, Object.freeze(u2), Object.freeze(l2), Object.freeze(d2));
}
static load(e3) {
let t2;
if (e3 instanceof Uint8Array)
t2 = Promise.resolve(e3);
else {
const r4 = e3;
if ("undefined" != typeof process && process.versions && process.versions.node) {
const e4 = require$$1;
t2 = Promise.resolve(e4.readFileSync(r4));
} else
t2 = fetch(r4).then((e4) => e4.arrayBuffer().then((t3) => {
if (e4.ok)
return new Uint8Array(t3);
{
const r5 = new TextDecoder("utf-8").decode(t3);
throw new Error(`Language.load failed with status ${e4.status}.
${r5}`);
}
}));
}
const r3 = "function" == typeof loadSideModule ? loadSideModule : xe;
return t2.then((e4) => r3(e4, { loadAsync: true })).then((e4) => {
const t3 = Object.keys(e4), r4 = t3.find((e5) => lt.test(e5) && !e5.includes("external_scanner_"));
r4 || console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(t3, null, 2)}`);
const n2 = e4[r4]();
return new Language(tt, n2);
});
}
}
class Query {
constructor(e3, t2, r3, n2, o2, s2, _2, a2) {
wt(e3), this[0] = t2, this.captureNames = r3, this.textPredicates = n2, this.predicates = o2, this.setProperties = s2, this.assertedProperties = _2, this.refutedProperties = a2, this.exceededMatchLimit = false;
}
delete() {
et._ts_query_delete(this[0]), this[0] = 0;
}
matches(e3, t2, r3, n2) {
t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {});
let o2 = n2.matchLimit;
if (void 0 === o2)
o2 = 0;
else if ("number" != typeof o2)
throw new Error("Arguments must be numbers");
yt(e3), et._ts_query_matches_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2);
const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = new Array(s2);
this.exceededMatchLimit = !!a2;
let u2 = 0, l2 = _2;
for (let t3 = 0; t3 < s2; t3++) {
const r4 = N(l2, "i32"), n3 = N(l2 += rt, "i32");
l2 += rt;
const o3 = new Array(n3);
if (l2 = gt(this, e3.tree, l2, o3), this.textPredicates[r4].every((e4) => e4(o3))) {
i2[u2++] = { pattern: r4, captures: o3 };
const e4 = this.setProperties[r4];
e4 && (i2[t3].setProperties = e4);
const n4 = this.assertedProperties[r4];
n4 && (i2[t3].assertedProperties = n4);
const s3 = this.refutedProperties[r4];
s3 && (i2[t3].refutedProperties = s3);
}
}
return i2.length = u2, et._free(_2), i2;
}
captures(e3, t2, r3, n2) {
t2 || (t2 = _t), r3 || (r3 = _t), n2 || (n2 = {});
let o2 = n2.matchLimit;
if (void 0 === o2)
o2 = 0;
else if ("number" != typeof o2)
throw new Error("Arguments must be numbers");
yt(e3), et._ts_query_captures_wasm(this[0], e3.tree[0], t2.row, t2.column, r3.row, r3.column, o2);
const s2 = N(mt, "i32"), _2 = N(mt + rt, "i32"), a2 = N(mt + 2 * rt, "i32"), i2 = [];
this.exceededMatchLimit = !!a2;
const u2 = [];
let l2 = _2;
for (let t3 = 0; t3 < s2; t3++) {
const t4 = N(l2, "i32"), r4 = N(l2 += rt, "i32"), n3 = N(l2 += rt, "i32");
if (l2 += rt, u2.length = r4, l2 = gt(this, e3.tree, l2, u2), this.textPredicates[t4].every((e4) => e4(u2))) {
const e4 = u2[n3], r5 = this.setProperties[t4];
r5 && (e4.setProperties = r5);
const o3 = this.assertedProperties[t4];
o3 && (e4.assertedProperties = o3);
const s3 = this.refutedProperties[t4];
s3 && (e4.refutedProperties = s3), i2.push(e4);
}
}
return et._free(_2), i2;
}
predicatesForPattern(e3) {
return this.predicates[e3];
}
didExceedMatchLimit() {
return this.exceededMatchLimit;
}
}
function ht(e3, t2, r3) {
const n2 = r3 - t2;
let o2 = e3.textCallback(t2, null, r3);
for (t2 += o2.length; t2 < r3; ) {
const n3 = e3.textCallback(t2, null, r3);
if (!(n3 && n3.length > 0))
break;
t2 += n3.length, o2 += n3;
}
return t2 > r3 && (o2 = o2.slice(0, n2)), o2;
}
function gt(e3, t2, r3, n2) {
for (let o2 = 0, s2 = n2.length; o2 < s2; o2++) {
const s3 = N(r3, "i32"), _2 = bt(t2, r3 += rt);
r3 += nt, n2[o2] = { name: e3.captureNames[s3], node: _2 };
}
return r3;
}
function wt(e3) {
if (e3 !== tt)
throw new Error("Illegal constructor");
}
function Mt(e3) {
return e3 && "number" == typeof e3.row && "number" == typeof e3.column;
}
function yt(e3) {
let t2 = mt;
x(t2, e3.id, "i32"), x(t2 += rt, e3.startIndex, "i32"), x(t2 += rt, e3.startPosition.row, "i32"), x(t2 += rt, e3.startPosition.column, "i32"), x(t2 += rt, e3[0], "i32");
}
function bt(e3, t2 = mt) {
const r3 = N(t2, "i32");
if (0 === r3)
return null;
const n2 = N(t2 += rt, "i32"), o2 = N(t2 += rt, "i32"), s2 = N(t2 += rt, "i32"), _2 = N(t2 += rt, "i32"), a2 = new Node(tt, e3);
return a2.id = r3, a2.startIndex = n2, a2.startPosition = { row: o2, column: s2 }, a2[0] = _2, a2;
}
function vt(e3, t2 = mt) {
x(t2 + 0 * rt, e3[0], "i32"), x(t2 + 1 * rt, e3[1], "i32"), x(t2 + 2 * rt, e3[2], "i32");
}
function Et(e3) {
e3[0] = N(mt + 0 * rt, "i32"), e3[1] = N(mt + 1 * rt, "i32"), e3[2] = N(mt + 2 * rt, "i32");
}
function St(e3, t2) {
x(e3, t2.row, "i32"), x(e3 + rt, t2.column, "i32");
}
function It(e3) {
return { row: N(e3, "i32"), column: N(e3 + rt, "i32") };
}
function At(e3, t2) {
St(e3, t2.startPosition), St(e3 += ot, t2.endPosition), x(e3 += ot, t2.startIndex, "i32"), x(e3 += rt, t2.endIndex, "i32"), e3 += rt;
}
function xt(e3) {
const t2 = {};
return t2.startPosition = It(e3), e3 += ot, t2.endPosition = It(e3), e3 += ot, t2.startIndex = N(e3, "i32"), e3 += rt, t2.endIndex = N(e3, "i32"), t2;
}
for (const e3 of Object.getOwnPropertyNames(ParserImpl.prototype))
Object.defineProperty(Parser2.prototype, e3, { value: ParserImpl.prototype[e3], enumerable: false, writable: false });
Parser2.Language = Language, Module.onRuntimeInitialized = () => {
ParserImpl.init(), e2();
};
}));
}
}
return Parser2;
}();
module.exports = TreeSitter;
})(treeSitter);
var treeSitterExports = treeSitter.exports;
const Parser = /* @__PURE__ */ getDefaultExportFromCjs(treeSitterExports);
const treeSitterShadeupURL = "";
async function getShadeupParser() {
if (typeof process === "object" && process.versions && process.versions.node) {
return global.shadeupParser();
}
let url = treeSitterShadeupURL;
let shadeUrl = treeSitterShadeupURL;
await Parser.init({
locateFile(scriptName, scriptDirectory) {
return url;
}
});
const parser = new Parser();
parser.setLanguage(await Parser.Language.load(shadeUrl));
return parser;
}
class AstContext {
constructor(fileName) {
this.impls = /* @__PURE__ */ new Map();
this.implsFor = /* @__PURE__ */ new Map();
this.shaders = [];
this.diagnostics = [];
this.globals = [];
this.fileName = fileName;
}
report(node2, message) {
this.diagnostics.push({ message, node: node2 });
}
addImpl(name, node2) {
if (this.impls.has(name)) {
this.impls.get(name).push(node2);
} else {
this.impls.set(name, [node2]);
}
}
addImplFor(name, node2) {
if (this.implsFor.has(name)) {
this.implsFor.get(name).push(node2);
} else {
this.implsFor.set(name, [node2]);
}
}
}
const stdMath = "export type bool = boolean;\r\nexport type float = number & { _opaque_float: 2 };\r\nexport type int = number & { _opaque_int: 1 } & float;\r\nexport type uint = number & { _opaque_uint: 1 };\r\ntype scalar = float | int | uint;\r\n\r\nexport type float2 = [float, float] & { _opaque_vector_float_2: 2; length: 2 };\r\nexport type float3 = [float, float, float] & { _opaque_vector_float_3: 3; length: 3 };\r\nexport type float4 = [float, float, float, float] & { _opaque_vector_float_4: 4; length: 4 };\r\nexport type int2 = [int, int] & { _opaque_vector_int_2: 2 } & float2;\r\nexport type int3 = [int, int, int] & { _opaque_vector_int_3: 3 } & float3;\r\nexport type int4 = [int, int, int, int] & { _opaque_vector_int_4: 4 } & float4;\r\n\r\nexport type uint2 = [uint, uint] & { _opaque_vector_uint_2: 2 } & float2;\r\nexport type uint3 = [uint, uint, uint] & { _opaque_vector_uint_3: 3 } & float3;\r\nexport type uint4 = [uint, uint, uint, uint] & { _opaque_vector_uint_4: 4 } & float4;\r\n\r\nexport type uint8 = number & { _opaque_uint8: 1 };\r\n\r\ntype anyFloat = float2 | float3 | float4;\r\ntype anyInt = int2 | int3 | int4;\r\ntype anyUint = uint2 | uint3 | uint4;\r\n\r\ntype vector2 = float2 | int2 | uint2;\r\ntype vector3 = float3 | int3 | uint3;\r\ntype vector4 = float4 | int4 | uint4;\r\n\r\ntype vector = vector2 | vector3 | vector4;\r\n\r\ntype vectorOrScalar = vector | scalar;\r\n\r\nexport interface float2x2 extends Omit<[float, float, float, float], '__index'> {\r\n __matrix: 2;\r\n [index: int]: float;\r\n __index(index: number): [float, float];\r\n}\r\n\r\nexport interface float3x3\r\n extends Omit<[float, float, float, float, float, float, float, float, float], '__index'> {\r\n __matrix: 3;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float];\r\n}\r\n\r\nexport interface float4x4\r\n extends Omit<\r\n [\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float,\r\n float\r\n ],\r\n '__index'\r\n > {\r\n __matrix: 4;\r\n [index: int]: float;\r\n __index(index: number): [float, float, float, float];\r\n}\r\n\r\nfunction isVector(v: vectorOrScalar): v is vector {\r\n return Array.isArray(v);\r\n}\r\n\r\nfunction isScalar(v: vectorOrScalar): v is scalar {\r\n return typeof v === 'number';\r\n}\r\n\r\nfunction isMatrix(v: number[]): v is float2x2 | float3x3 | float4x4 {\r\n return !!(v as any).__matrix;\r\n}\r\n\r\n/** @shadeup=glsl(!mat2(0)) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(m00: number, m01: number, m10: number, m11: number): float2x2;\r\n/** @shadeup=glsl(mat2) @shadeup=wgsl(mat2x2) */\r\nexport function float2x2(...args: float[]): float2x2 {\r\n let arr = [0, 0, 0, 0] as any as float2x2;\r\n if (args.length === 4) {\r\n arr = [...args] as any as float2x2;\r\n }\r\n\r\n applyMatrix2x2Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(!mat3(0)) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m20: number,\r\n m21: number,\r\n m22: number\r\n): float3x3;\r\n/** @shadeup=glsl(mat3) @shadeup=wgsl(mat3x3) */\r\nexport function float3x3(...args: float[]): float3x3 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float3x3;\r\n if (args.length === 9) {\r\n arr = [...args] as any as float3x3;\r\n }\r\n\r\n applyMatrix3x3Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\nfunction applyMatrix4x4Methods(arr: float4x4): void {\r\n (arr as any).__matrix = 4;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 4], arr[index * 4 + 1], arr[index * 4 + 2], arr[index * 4 + 3]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 4 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 4 + index_inner] = op_fn(arr[index * 4 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float4) {\r\n arr[index * 4] = value[0];\r\n arr[index * 4 + 1] = value[1];\r\n arr[index * 4 + 2] = value[2];\r\n arr[index * 4 + 3] = value[3];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 4] = op_fn(arr[index * 4], value[0]);\r\n arr[index * 4 + 1] = op_fn(arr[index * 4 + 1], value[1]);\r\n arr[index * 4 + 2] = op_fn(arr[index * 4 + 2], value[2]);\r\n arr[index * 4 + 3] = op_fn(arr[index * 4 + 3], value[3]);\r\n };\r\n}\r\n(window as any).applyMatrix4x4Methods = applyMatrix4x4Methods;\r\n\r\nfunction applyMatrix3x3Methods(arr: float3x3): void {\r\n (arr as any).__matrix = 3;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 3], arr[index * 3 + 1], arr[index * 3 + 2]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 3 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 3 + index_inner] = op_fn(arr[index * 3 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 3] = value[0];\r\n arr[index * 3 + 1] = value[1];\r\n arr[index * 3 + 2] = value[2];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 3] = op_fn(arr[index * 3], value[0]);\r\n arr[index * 3 + 1] = op_fn(arr[index * 3 + 1], value[1]);\r\n arr[index * 3 + 2] = op_fn(arr[index * 3 + 2], value[2]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix3x3Methods = applyMatrix3x3Methods;\r\n\r\nfunction applyMatrix2x2Methods(arr: float2x2): void {\r\n (arr as any).__matrix = 2;\r\n\r\n (arr as any).__index = function (index: number) {\r\n let out_arr = [arr[index * 2], arr[index * 2 + 1]];\r\n out_arr.__index = (index_inner: int) => {\r\n return out_arr[index_inner];\r\n };\r\n out_arr.__index_assign = (index_inner: int, value: float) => {\r\n arr[index * 2 + index_inner] = value;\r\n };\r\n\r\n out_arr.__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index_inner: int,\r\n value: any\r\n ) {\r\n arr[index * 2 + index_inner] = op_fn(arr[index * 2 + index_inner], value);\r\n };\r\n\r\n return out_arr;\r\n };\r\n\r\n (arr as any).__index_assign = function (index: int, value: float3) {\r\n arr[index * 2] = value[0];\r\n arr[index * 2 + 1] = value[1];\r\n };\r\n\r\n (arr as any).__index_assign_op = function (\r\n op_fn: (a: any, b: any) => any,\r\n index: int,\r\n value: any\r\n ) {\r\n arr[index * 2] = op_fn(arr[index * 2], value[0]);\r\n arr[index * 2 + 1] = op_fn(arr[index * 2 + 1], value[1]);\r\n };\r\n}\r\n\r\n(window as any).applyMatrix2x2Methods = applyMatrix2x2Methods;\r\n\r\n/** @shadeup=glsl(!mat4(0)) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(\r\n m00: number,\r\n m01: number,\r\n m02: number,\r\n m03: number,\r\n m10: number,\r\n m11: number,\r\n m12: number,\r\n m13: number,\r\n m20: number,\r\n m21: number,\r\n m22: number,\r\n m23: number,\r\n m30: number,\r\n m31: number,\r\n m32: number,\r\n m33: number\r\n): float4x4;\r\n/** @shadeup=glsl(mat4) @shadeup=wgsl(mat4x4) */\r\nexport function float4x4(...args: float[]): float4x4 {\r\n let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] as any as float4x4;\r\n if (args.length === 16) {\r\n arr = [...args] as any as float4x4;\r\n }\r\n\r\n applyMatrix4x4Methods(arr);\r\n\r\n return arr;\r\n}\r\n\r\n/** @shadeup=glsl(float) @shadeup=wgsl(f32) */\r\nexport function float(x: number): float {\r\n return x as float;\r\n}\r\n\r\n/** @shadeup=glsl(int) @shadeup=wgsl(i32) */\r\nexport function int(x: number): int {\r\n return (x | 0) as int;\r\n}\r\n\r\n/** @shadeup=glsl(uint) @shadeup=wgsl(u32) */\r\nexport function uint(x: number): uint {\r\n return (x >>> 0) as uint;\r\n}\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(x: number, y: number): float2;\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(xy: vector2): float2;\r\n\r\n/** @shadeup=glsl(float2) @shadeup=wgsl(vec2) */\r\nexport function float2(...args: (vectorOrScalar | number)[]): float2 {\r\n return args.flat() as float2;\r\n}\r\n\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, y: number, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xy: vector2, z: number): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(x: number, yz: vector2): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(xyz: vector3): float3;\r\n/** @shadeup=glsl(float3) @shadeup=wgsl(vec3) */\r\nexport function float3(...args: (vectorOrScalar | number)[]): float3 {\r\n return args.flat() as float3;\r\n}\r\n\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yz: vector2, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, z: number, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, y: number, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xy: vector2, zw: vector2): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyz: vector3, w: number): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(x: number, yzw: vector3): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(xyzw: int4): float4;\r\nexport function float4(xyzw: float4): float4;\r\n/** @shadeup=glsl(float4) @shadeup=wgsl(vec4) */\r\nexport function float4(...args: (vectorOrScalar | number)[]): float4 {\r\n return args.flat() as float4;\r\n}\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(x: number, y: number): int2;\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(xy: vector2): int2;\r\n\r\n/** @shadeup=glsl(int2) @shadeup=wgsl(vec2) */\r\nexport function int2(...args: (vectorOrScalar | number)[]): int2 {\r\n return args.flat().map((x) => x | 0) as int2;\r\n}\r\n\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, y: number, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xy: vector2, z: number): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(x: number, yz: vector2): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(xyz: vector3): int3;\r\n/** @shadeup=glsl(int3) @shadeup=wgsl(vec3) */\r\nexport function int3(...args: (vectorOrScalar | number)[]): int3 {\r\n return args.flat().map((x) => x | 0) as int3;\r\n}\r\n\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yz: vector2, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, z: number, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, y: number, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xy: vector2, zw: vector2): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyz: vector3, w: number): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(x: number, yzw: vector3): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(xyzw: float4): int4;\r\nexport function int4(xyzw: int4): int4;\r\n/** @shadeup=glsl(int4) @shadeup=wgsl(vec4) */\r\nexport function int4(...args: (vectorOrScalar | number)[]): int4 {\r\n return args.flat().map((x) => x | 0) as int4;\r\n}\r\n\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(x: number, y: number): uint2;\r\n/** @shadeup=glsl(uint2) @shadeup=wgsl(vec2) */\r\nexport function uint2(xy: vector2): uint2;\r\nexport function uint2(...args: (vectorOrScalar | number)[]): uint2 {\r\n return args.flat().map((x) => x >>> 0) as uint2;\r\n}\r\n\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, y: number, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xy: vector2, z: number): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(x: number, yz: vector2): uint3;\r\n/** @shadeup=glsl(uint3) @shadeup=wgsl(vec3) */\r\nexport function uint3(xyz: vector3): uint3;\r\nexport function uint3(...args: (vectorOrScalar | number)[]): uint3 {\r\n return args.flat().map((x) => x >>> 0) as uint3;\r\n}\r\n\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, yz: vector2, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, z: number, w: number): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(x: number, y: number, zw: vector2): uint4;\r\n/** @shadeup=glsl(uint4) @shadeup=wgsl(vec4) */\r\nexport function uint4(xy: vector2, zw: vector2): uint4;\r\nexport function uint4(xyz: vector3, w: number): uint4;\r\nexport function uint4(x: number, yzw: vector3): uint4;\r\nexport function uint4(xyzw: float4): uint4;\r\nexport function uint4(xyzw: uint4): uint4;\r\nexport function uint4(...args: (vectorOrScalar | number)[]): uint4 {\r\n return args.flat().map((x) => x >>> 0) as uint4;\r\n}\r\n\r\nexport function uint8(x: number): uint8 {\r\n return ((x >>> 0) & 0xff) as uint8;\r\n}\r\n\r\nfunction componentMath(a: any, b: any, f: (a: number, b: number) => number): vectorOrScalar {\r\n let aIsScalar = isScalar(a);\r\n let bIsScalar = isScalar(b);\r\n if (aIsScalar && bIsScalar) {\r\n return f(a, b) as scalar;\r\n }\r\n if (!aIsScalar && !bIsScalar) {\r\n if (a.length !== b.length) {\r\n throw new Error('Cannot perform component-wise math on vectors of different lengths');\r\n }\r\n // return a.map((a, i) => f(a, b[i])) as vector;\r\n if (a.length == 2) {\r\n return [f(a[0], b[0]), f(a[1], b[1])] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2])] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])] as vector;\r\n }\r\n } else if (!aIsScalar && bIsScalar) {\r\n if (a.length == 2) {\r\n return [f(a[0], b), f(a[1], b)] as vector;\r\n } else if (a.length == 3) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b)] as vector;\r\n } else if (a.length == 4) {\r\n return [f(a[0], b), f(a[1], b), f(a[2], b), f(a[3], b)] as vector;\r\n }\r\n } else if (!bIsScalar && aIsScalar) {\r\n if (b.length == 2) {\r\n return [f(a, b[0]), f(a, b[1])] as vector;\r\n } else if (b.length == 3) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2])] as vector;\r\n } else if (b.length == 4) {\r\n return [f(a, b[0]), f(a, b[1]), f(a, b[2]), f(a, b[3])] as vector;\r\n }\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\nfunction componentMathSingular(a: vectorOrScalar, f: (a: number) => number): vectorOrScalar {\r\n if (isScalar(a)) {\r\n return f(a) as scalar;\r\n }\r\n if (isVector(a)) {\r\n return a.map((a, i) => f(a)) as vector;\r\n }\r\n\r\n throw new Error('Cannot perform component-wise math on a scalar and a vector');\r\n}\r\n\r\ntype cCallCb = (a: number, b: number) => number;\r\ntype cCallCbSingle = (a: number) => number;\r\n\r\nfunction cCall(cb: cCallCb, a: scalar, b: scalar): scalar;\r\nfunction cCall(cb: cCallCb, a: vector, b: scalar): vector;\r\nfunction cCall(cb: cCallCb, a: vector2, b: vector2): vector2;\r\nfunction cCall(cb: cCallCb, a: vector3, b: vector3): vector3;\r\nfunction cCall(cb: cCallCb, a: vector4, b: vector4): vector4;\r\nfunction cCall(cb: cCallCb, a: vectorOrScalar, b: vectorOrScalar): vectorOrScalar {\r\n return componentMath(a, b, (a, b) => a + b);\r\n}\r\n\r\nexport type vectorOverload_2to1_3to3 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n};\r\nexport type vectorOverload_2to1_3to3_4to4 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n};\r\nexport type vectorOverload_2to1_3to1_4to1 = {\r\n (a: float2, b: float2): float;\r\n (a: float3, b: float3): float;\r\n (a: float4, b: float4): float;\r\n\r\n (a: int2, b: int2): int;\r\n (a: int3, b: int3): int;\r\n (a: int4, b: int4): int;\r\n\r\n (a: float2, b: int2): float;\r\n (a: float3, b: int3): float;\r\n (a: float4, b: int4): float;\r\n\r\n (a: int2, b: float2): float;\r\n (a: int3, b: float3): float;\r\n (a: int4, b: float4): float;\r\n};\r\n\r\nexport type componentOverload = {\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n\r\n (a: int, b: float): float;\r\n (a: float, b: int): float;\r\n\r\n (a: float, b: float): float;\r\n\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: int2, b: float): float2;\r\n (a: int3, b: float): float3;\r\n (a: int4, b: float): float4;\r\n\r\n (a: float2, b: int): float2;\r\n (a: float3, b: int): float3;\r\n (a: float4, b: int): float4;\r\n (a: float2, b: float): float2;\r\n\r\n (a: float, b: float2): float2;\r\n (a: float, b: float3): float3;\r\n (a: float, b: float4): float4;\r\n\r\n (a: int, b: int2): int2;\r\n (a: int, b: int3): int3;\r\n (a: int, b: int4): int4;\r\n\r\n (a: float, b: int2): float2;\r\n (a: float, b: int3): float3;\r\n (a: float, b: int4): float4;\r\n\r\n (a: int, b: float2): float2;\r\n (a: int, b: float3): float3;\r\n (a: int, b: float4): float4;\r\n\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n\r\n (a: float2, b: int2): float2;\r\n (a: float3, b: int3): float3;\r\n (a: float4, b: int4): float4;\r\n\r\n (a: int2, b: float2): float2;\r\n (a: int3, b: float3): float3;\r\n (a: int4, b: float4): float4;\r\n\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadMatch = {\r\n (a: uint, b: uint): uint;\r\n (a: uint2, b: uint2): uint2;\r\n (a: uint3, b: uint3): uint3;\r\n (a: uint4, b: uint4): uint4;\r\n (a: uint2, b: uint): uint2;\r\n (a: uint3, b: uint): uint3;\r\n (a: uint4, b: uint): uint4;\r\n\r\n (a: int, b: int): int;\r\n (a: int2, b: int2): int2;\r\n (a: int3, b: int3): int3;\r\n (a: int4, b: int4): int4;\r\n (a: int2, b: int): int2;\r\n (a: int3, b: int): int3;\r\n (a: int4, b: int): int4;\r\n\r\n (a: float, b: float): float;\r\n (a: float2, b: float2): float2;\r\n (a: float3, b: float3): float3;\r\n (a: float4, b: float4): float4;\r\n (a: float2, b: float): float2;\r\n (a: float3, b: float): float3;\r\n (a: float4, b: float): float4;\r\n};\r\n\r\nexport type componentOverloadSingular = {\r\n (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n (a: int2): int2;\r\n (a: int3): int3;\r\n (a: int4): int4;\r\n\r\n (a: uint): uint;\r\n (a: uint2): uint2;\r\n (a: uint3): uint3;\r\n (a: uint4): uint4;\r\n};\r\n\r\nexport type componentOverloadSingularFloat = {\r\n // (a: int): int;\r\n (a: float): float;\r\n\r\n (a: float2): float2;\r\n (a: float3): float3;\r\n (a: float4): float4;\r\n\r\n // (a: int2): int2;\r\n // (a: int3): int3;\r\n // (a: int4): int4;\r\n};\r\n\r\nexport type componentOverloadMatrix = {\r\n (a: float2x2, b: float2): float2;\r\n (a: float3x3, b: float3): float3;\r\n (a: float4x4, b: float4): float4;\r\n\r\n (a: float2, b: float2x2): float2;\r\n (a: float3, b: float3x3): float3;\r\n (a: float4, b: float4x4): float4;\r\n\r\n (a: float2x2, b: float2x2): float2x2;\r\n (a: float3x3, b: float3x3): float3x3;\r\n (a: float4x4, b: float4x4): float4x4;\r\n\r\n (a: float2x2, b: float): float2x2;\r\n (a: float3x3, b: float): float3x3;\r\n (a: float4x4, b: float): float4x4;\r\n\r\n (a: float, b: float2x2): float2x2;\r\n (a: float, b: float3x3): float3x3;\r\n (a: float, b: float4x4): float4x4;\r\n};\r\n\r\nfunction componentOp(cb: cCallCb): componentOverload;\r\n\r\nfunction componentOp(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpMatch(cb: cCallCb): componentOverloadMatch;\r\nfunction componentOpMatch(cb: cCallCb) {\r\n return (a: any, b: any) => componentMath(a, b, cb);\r\n}\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle): componentOverloadSingular;\r\n\r\nfunction componentOpSingular(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle): componentOverloadSingularFloat;\r\n\r\nfunction componentOpSingularFloat(cb: cCallCbSingle) {\r\n return (a: any) => componentMathSingular(a, cb);\r\n}\r\n\r\n/** @shadeup=univ(!$0$ + $1$)*/\r\nexport const add: componentOverload & ((a: string, b: string) => string) = (\r\n a: any,\r\n b: any\r\n): any => {\r\n if (typeof a === 'string' && typeof b === 'string') {\r\n return `${a}${b}`;\r\n } else {\r\n let addOp: (a: any, b: any) => any = componentOp((a, b) => a + b);\r\n let v: any = addOp(a, b);\r\n return v;\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ - $1$)*/\r\nexport const sub = componentOp((a, b) => a - b);\r\n\r\ntype matrix = float2x2 | float3x3 | float4x4;\r\n\r\nfunction matrixMul(a: matrix, b: matrix): matrix {\r\n // Multiply two square matrices of the same dimension row-major\r\n\r\n let dimension = a.__matrix;\r\n\r\n let out: float2x2 | float3x3 | float4x4;\r\n if (dimension === 2) {\r\n out = float2x2();\r\n } else if (dimension === 3) {\r\n out = float3x3();\r\n } else if (dimension === 4) {\r\n var a00 = a[0 * 4 + 0];\r\n var a01 = a[0 * 4 + 1];\r\n var a02 = a[0 * 4 + 2];\r\n var a03 = a[0 * 4 + 3];\r\n var a10 = a[1 * 4 + 0];\r\n var a11 = a[1 * 4 + 1];\r\n var a12 = a[1 * 4 + 2];\r\n var a13 = a[1 * 4 + 3];\r\n var a20 = a[2 * 4 + 0];\r\n var a21 = a[2 * 4 + 1];\r\n var a22 = a[2 * 4 + 2];\r\n var a23 = a[2 * 4 + 3];\r\n var a30 = a[3 * 4 + 0];\r\n var a31 = a[3 * 4 + 1];\r\n var a32 = a[3 * 4 + 2];\r\n var a33 = a[3 * 4 + 3];\r\n var b00 = b[0 * 4 + 0];\r\n var b01 = b[0 * 4 + 1];\r\n var b02 = b[0 * 4 + 2];\r\n var b03 = b[0 * 4 + 3];\r\n var b10 = b[1 * 4 + 0];\r\n var b11 = b[1 * 4 + 1];\r\n var b12 = b[1 * 4 + 2];\r\n var b13 = b[1 * 4 + 3];\r\n var b20 = b[2 * 4 + 0];\r\n var b21 = b[2 * 4 + 1];\r\n var b22 = b[2 * 4 + 2];\r\n var b23 = b[2 * 4 + 3];\r\n var b30 = b[3 * 4 + 0];\r\n var b31 = b[3 * 4 + 1];\r\n var b32 = b[3 * 4 + 2];\r\n var b33 = b[3 * 4 + 3];\r\n return float4x4(\r\n b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30,\r\n b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31,\r\n b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32,\r\n b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33,\r\n b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30,\r\n b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31,\r\n b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32,\r\n b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33,\r\n b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30,\r\n b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31,\r\n b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32,\r\n b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33,\r\n b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30,\r\n b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31,\r\n b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32,\r\n b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33\r\n );\r\n out = float4x4();\r\n }\r\n\r\n for (let i = 0; i < dimension; i++) {\r\n for (let j = 0; j < dimension; j++) {\r\n let sum: float = float(0);\r\n for (let k = 0; k < dimension; k++) {\r\n sum += float(a[i * dimension + k] * b[k * dimension + j]);\r\n }\r\n out[i * dimension + j] = sum;\r\n }\r\n }\r\n\r\n return out;\r\n\r\n if (a.__matrix === 2 && b.__matrix === 2) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a10 = a[2];\r\n let a11 = a[3];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b10 = b[2];\r\n let b11 = b[3];\r\n\r\n let v = float2x2(\r\n a00 * b00 + a01 * b10,\r\n a00 * b01 + a01 * b11,\r\n a10 * b00 + a11 * b10,\r\n a10 * b01 + a11 * b11\r\n );\r\n\r\n return v;\r\n } else if (a.__matrix === 3 && b.__matrix === 3) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a10 = a[3];\r\n let a11 = a[4];\r\n let a12 = a[5];\r\n let a20 = a[6];\r\n let a21 = a[7];\r\n let a22 = a[8];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b10 = b[3];\r\n let b11 = b[4];\r\n let b12 = b[5];\r\n let b20 = b[6];\r\n let b21 = b[7];\r\n let b22 = b[8];\r\n\r\n let v = float3x3(\r\n a00 * b00 + a01 * b10 + a02 * b20,\r\n a00 * b01 + a01 * b11 + a02 * b21,\r\n a00 * b02 + a01 * b12 + a02 * b22,\r\n a10 * b00 + a11 * b10 + a12 * b20,\r\n a10 * b01 + a11 * b11 + a12 * b21,\r\n a10 * b02 + a11 * b12 + a12 * b22,\r\n a20 * b00 + a21 * b10 + a22 * b20,\r\n a20 * b01 + a21 * b11 + a22 * b21,\r\n a20 * b02 + a21 * b12 + a22 * b22\r\n );\r\n return v;\r\n } else if (a.__matrix === 4 && b.__matrix === 4) {\r\n let a00 = a[0];\r\n let a01 = a[1];\r\n let a02 = a[2];\r\n let a03 = a[3];\r\n let a10 = a[4];\r\n let a11 = a[5];\r\n let a12 = a[6];\r\n let a13 = a[7];\r\n let a20 = a[8];\r\n let a21 = a[9];\r\n let a22 = a[10];\r\n let a23 = a[11];\r\n let a30 = a[12];\r\n let a31 = a[13];\r\n let a32 = a[14];\r\n let a33 = a[15];\r\n\r\n let b00 = b[0];\r\n let b01 = b[1];\r\n let b02 = b[2];\r\n let b03 = b[3];\r\n let b10 = b[4];\r\n let b11 = b[5];\r\n let b12 = b[6];\r\n let b13 = b[7];\r\n let b20 = b[8];\r\n let b21 = b[9];\r\n let b22 = b[10];\r\n let b23 = b[11];\r\n let b30 = b[12];\r\n let b31 = b[13];\r\n let b32 = b[14];\r\n let b33 = b[15];\r\n\r\n let v = float4x4(\r\n a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30,\r\n a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31,\r\n a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32,\r\n a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33,\r\n a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30,\r\n a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31,\r\n a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32,\r\n a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33,\r\n a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30,\r\n a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31,\r\n a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32,\r\n a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33,\r\n a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30,\r\n a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31,\r\n a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32,\r\n a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33\r\n );\r\n\r\n return v;\r\n } else {\r\n throw new Error('Invalid matrix multiplication');\r\n }\r\n}\r\n\r\nfunction matrixInversefloat2x2(m: float2x2): float2x2 {\r\n let a = m.__index(0).__index(0),\r\n b = m.__index(1).__index(0),\r\n c = m.__index(0).__index(1),\r\n d = m.__index(1).__index(1);\r\n let det = a * d - b * c;\r\n if (det === 0) {\r\n throw new Error('Matrix determinant is zero');\r\n }\r\n let detInv = 1.0 / det;\r\n return float2x2(d * detInv, -b * detInv, -c * detInv, a * detInv);\r\n}\r\nfunction matrixInversefloat3x3(m: float3x3): float3x3 {\r\n let n11 = m.__index(0).__index(0),\r\n n12 = m.__index(1).__index(0),\r\n n13 = m.__index(2).__index(0);\r\n let n21 = m.__index(0).__index(1),\r\n n22 = m.__index(1).__index(1),\r\n n23 = m.__index(2).__index(1);\r\n let n31 = m.__index(0).__index(2),\r\n n32 = m.__index(1).__index(2),\r\n n33 = m.__index(2).__index(2);\r\n let t11 = n33 * n22 - n32 * n23,\r\n t12 = n32 * n13 - n33 * n12,\r\n t13 = n23 * n12 - n22 * n13;\r\n let det = n11 * t11 + n21 * t12 + n31 * t13;\r\n if (det === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n let detInv = 1 / det;\r\n let v = float3x3(\r\n t11 * detInv,\r\n (n31 * n23 - n33 * n21) * detInv,\r\n (n32 * n21 - n31 * n22) * detInv,\r\n t12 * detInv,\r\n (n33 * n11 - n31 * n13) * detInv,\r\n (n31 * n12 - n32 * n11) * detInv,\r\n t13 * detInv,\r\n (n21 * n13 - n23 * n11) * detInv,\r\n (n22 * n11 - n21 * n12) * detInv\r\n );\r\n return v;\r\n}\r\nfunction matrixInversefloat4x4(m: float4x4): float4x4 {\r\n var m00 = m[0 * 4 + 0];\r\n var m01 = m[0 * 4 + 1];\r\n var m02 = m[0 * 4 + 2];\r\n var m03 = m[0 * 4 + 3];\r\n var m10 = m[1 * 4 + 0];\r\n var m11 = m[1 * 4 + 1];\r\n var m12 = m[1 * 4 + 2];\r\n var m13 = m[1 * 4 + 3];\r\n var m20 = m[2 * 4 + 0];\r\n var m21 = m[2 * 4 + 1];\r\n var m22 = m[2 * 4 + 2];\r\n var m23 = m[2 * 4 + 3];\r\n var m30 = m[3 * 4 + 0];\r\n var m31 = m[3 * 4 + 1];\r\n var m32 = m[3 * 4 + 2];\r\n var m33 = m[3 * 4 + 3];\r\n var tmp_0 = m22 * m33;\r\n var tmp_1 = m32 * m23;\r\n var tmp_2 = m12 * m33;\r\n var tmp_3 = m32 * m13;\r\n var tmp_4 = m12 * m23;\r\n var tmp_5 = m22 * m13;\r\n var tmp_6 = m02 * m33;\r\n var tmp_7 = m32 * m03;\r\n var tmp_8 = m02 * m23;\r\n var tmp_9 = m22 * m03;\r\n var tmp_10 = m02 * m13;\r\n var tmp_11 = m12 * m03;\r\n var tmp_12 = m20 * m31;\r\n var tmp_13 = m30 * m21;\r\n var tmp_14 = m10 * m31;\r\n var tmp_15 = m30 * m11;\r\n var tmp_16 = m10 * m21;\r\n var tmp_17 = m20 * m11;\r\n var tmp_18 = m00 * m31;\r\n var tmp_19 = m30 * m01;\r\n var tmp_20 = m00 * m21;\r\n var tmp_21 = m20 * m01;\r\n var tmp_22 = m00 * m11;\r\n var tmp_23 = m10 * m01;\r\n\r\n var t0 = tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31 - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\r\n var t1 = tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31 - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\r\n var t2 = tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31 - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\r\n var t3 = tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21 - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\r\n\r\n var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\r\n if (d === 0) {\r\n throw new Error('Invalid matrix inverse');\r\n }\r\n return float4x4(\r\n d * t0,\r\n d * t1,\r\n d * t2,\r\n d * t3,\r\n d * (tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30 - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)),\r\n d * (tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30 - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)),\r\n d * (tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30 - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)),\r\n d * (tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20 - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)),\r\n d * (tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33 - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)),\r\n d * (tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33 - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)),\r\n d * (tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33 - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)),\r\n d * (tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23 - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)),\r\n d * (tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12 - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)),\r\n d * (tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22 - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)),\r\n d * (tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02 - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)),\r\n d * (tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12 - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02))\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat2x2(m: float2x2): float2x2 {\r\n return float2x2(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat3x3(m: float3x3): float3x3 {\r\n return float3x3(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2)\r\n );\r\n}\r\n\r\nfunction matrixTransposefloat4x4(m: float4x4): float4x4 {\r\n return float4x4(\r\n m.__index(0).__index(0),\r\n m.__index(1).__index(0),\r\n m.__index(2).__index(0),\r\n m.__index(3).__index(0),\r\n m.__index(0).__index(1),\r\n m.__index(1).__index(1),\r\n m.__index(2).__index(1),\r\n m.__index(3).__index(1),\r\n m.__index(0).__index(2),\r\n m.__index(1).__index(2),\r\n m.__index(2).__index(2),\r\n m.__index(3).__index(2),\r\n m.__index(0).__index(3),\r\n m.__index(1).__index(3),\r\n m.__index(2).__index(3),\r\n m.__index(3).__index(3)\r\n );\r\n}\r\n\r\nfunction matrixMul2x2float2(a: float2x2, b: float2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j * 2 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMul3x3float3(a: float3x3, b: float3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j * 3 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMul4x4float4(a: float4x4, b: float4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 4; j++) {\r\n for (let i = 0; i < 4; i++) {\r\n c[i] += a[j * 4 + i] * b[j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nfunction matrixMulfloat22x2(a: float2, b: float2x2): float2 {\r\n let c: number[] = [0 as scalar, 0 as scalar];\r\n\r\n for (let j = 0; j < 2; j++) {\r\n for (let i = 0; i < 2; i++) {\r\n c[i] += a[j] * b[i * 2 + j];\r\n }\r\n }\r\n\r\n return c as float2;\r\n}\r\n\r\nfunction matrixMulfloat33x3(a: float3, b: float3x3): float3 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 3; i++) {\r\n for (let j = 0; j < 3; j++) {\r\n c[i] += a[j] * b[i * 3 + j];\r\n }\r\n }\r\n\r\n return c as float3;\r\n}\r\n\r\nfunction matrixMulfloat44x4(a: float4, b: float4x4): float4 {\r\n let c: number[] = [0 as scalar, 0 as scalar, 0 as scalar, 0 as scalar];\r\n\r\n for (let i = 0; i < 4; i++) {\r\n for (let j = 0; j < 4; j++) {\r\n c[i] += a[j] * b[i * 4 + j];\r\n }\r\n }\r\n\r\n return c as float4;\r\n}\r\n\r\nlet mulFunc: (a: any, b: any) => any = componentOp((a, b) => a * b);\r\n\r\n/** @shadeup=univ(#matrix_inverse)*/\r\nexport function inverse(a: float2x2): float2x2;\r\nexport function inverse(a: float3x3): float3x3;\r\nexport function inverse(a: float4x4): float4x4;\r\nexport function inverse(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixInversefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixInversefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixInversefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(#matrix_transpose)*/\r\nexport function transpose(a: float2x2): float2x2;\r\nexport function transpose(a: float3x3): float3x3;\r\nexport function transpose(a: float4x4): float4x4;\r\nexport function transpose(a: float2x2 | float3x3 | float4x4): float2x2 | float3x3 | float4x4 {\r\n if (a.__matrix == 2) {\r\n return matrixTransposefloat2x2(a as float2x2);\r\n } else if (a.__matrix == 3) {\r\n return matrixTransposefloat3x3(a as float3x3);\r\n } else if (a.__matrix == 4) {\r\n return matrixTransposefloat4x4(a as float4x4);\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!$0$ * $1$)*/\r\nexport const mul: componentOverload & componentOverloadMatrix = (a: any, b: any): any => {\r\n if (isMatrix(a) || isMatrix(b)) {\r\n if (isMatrix(a) && isMatrix(b)) {\r\n return matrixMul(a, b);\r\n } else {\r\n if (isMatrix(a) && typeof b == 'number') {\r\n return componentMath(b as scalar, a as any, (a, b) => a * b);\r\n } else if (isMatrix(b) && typeof a == 'number') {\r\n return componentMath(a as scalar, b as any, (a, b) => a * b);\r\n } else {\r\n if (isMatrix(a)) {\r\n if (a.length == 4) {\r\n return matrixMul2x2float2(a as float2x2, b as float2);\r\n } else if (a.length == 9) {\r\n return matrixMul3x3float3(a as float3x3, b as float3);\r\n } else if (a.length == 16) {\r\n return matrixMul4x4float4(a as float4x4, b as float4);\r\n }\r\n } else if (isMatrix(b)) {\r\n if (b.length == 4) {\r\n return matrixMulfloat22x2(a as float2, b as float2x2);\r\n } else if (b.length == 9) {\r\n return matrixMulfloat33x3(a as float3, b as float3x3);\r\n } else if (b.length == 16) {\r\n return matrixMulfloat44x4(a as float4, b as float4x4);\r\n }\r\n }\r\n }\r\n }\r\n } else {\r\n return mulFunc(a, b);\r\n }\r\n};\r\n\r\n/** @shadeup=univ(!$0$ / $1$)*/\r\nexport const div = componentOp((a, b) => a / b);\r\n\r\n/** @shadeup=glsl(!$0$ ** $1$) @shadeup=wgsl(!pow($0$, $1$))*/\r\nexport const pow = componentOp((a, b) => Math.pow(a, b));\r\n\r\n/** @shadeup=wgsl(!$0$ % $1$) @shadeup=glsl(!mod($0$, $1$))*/\r\nexport const mod = componentOpMatch((a, b) => a - b * Math.floor(a / b));\r\n\r\n/** @shadeup=univ(!$0$ & $1$)*/\r\nexport const bitand = componentOp((a, b) => a & b);\r\n\r\n/** @shadeup=univ(!$0$ | $1$)*/\r\nexport const bitor = componentOp((a, b) => a | b);\r\n\r\n/** @shadeup=univ(!$0$ ^ $1$)*/\r\nexport const bitxor = componentOp((a, b) => a ^ b);\r\n\r\n/** @shadeup=glsl(!$0$ << $1$) @shadeup=wgsl(!$0$ << u32($1$))*/\r\nexport const lshift = componentOp((a, b) => a << b);\r\n\r\n/** @shadeup=glsl(!$0$ >> $1$) @shadeup=wgsl(!$0$ >> u32($1$))*/\r\nexport const rshift = componentOp((a, b) => a >> b);\r\n\r\n/** @shadeup=univ(!~$0$)*/\r\nexport const bitnot = componentOpSingular((a) => ~a);\r\n\r\n/** @shadeup=univ(!-($0$))*/\r\nexport const negate = componentOpSingular((a) => -a);\r\n\r\n/** @shadeup=univ(!+($0$))*/\r\nexport const positive = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=univ(abs)*/\r\nexport const abs = componentOpSingular((a) => Math.abs(a));\r\n\r\n/** @shadeup=glsl(floor) @shadeup=wgsl(!floor(f32(1.0) * $0$))*/\r\nexport const floor = componentOpSingular(Math.floor);\r\n\r\n/** @shadeup=glsl(ceil) @shadeup=wgsl(!ceil(f32(1.0) * $0$))*/\r\nexport const ceil = componentOpSingular(Math.ceil);\r\n\r\n/** @shadeup=univ(round)*/\r\nexport const round = componentOpSingular(Math.round);\r\n\r\n/** @shadeup=univ(sign)*/\r\nexport const sign = componentOpSingular(Math.sign);\r\n\r\n/** @shadeup=univ(cos) */\r\nexport const cos = componentOpSingular(Math.cos);\r\n\r\n/** @shadeup=univ(sin) */\r\nexport const sin = componentOpSingularFloat(Math.sin);\r\n\r\n/** @shadeup=univ(tan) */\r\nexport const tan = componentOpSingular(Math.tan);\r\n\r\n/** @shadeup=univ(acos) */\r\nexport const acos = componentOpSingular(Math.acos);\r\n\r\n/** @shadeup=univ(asin) */\r\nexport const asin = componentOpSingular(Math.asin);\r\n\r\n/** @shadeup=univ(atan) */\r\nexport const atan = componentOpSingular(Math.atan);\r\n\r\n/** @shadeup=univ(atan2) */\r\nexport const atan2: (dy: float, dx: float) => float = Math.atan2 as any;\r\n\r\n/** @shadeup=univ(cosh) */\r\nexport const cosh = componentOpSingular(Math.cosh);\r\n\r\n/** @shadeup=univ(sinh) */\r\nexport const sinh = componentOpSingular(Math.sinh);\r\n\r\n/** @shadeup=univ(tanh) */\r\nexport const tanh = componentOpSingular(Math.tanh);\r\n\r\n/** @shadeup=univ(acosh) */\r\nexport const acosh = componentOpSingular(Math.acosh);\r\n\r\n/** @shadeup=univ(asinh) */\r\nexport const asinh = componentOpSingular(Math.asinh);\r\n\r\n/** @shadeup=univ(atanh) */\r\nexport const atanh = componentOpSingular(Math.atanh);\r\n\r\n/** @shadeup=univ(exp) */\r\nexport const exp = componentOpSingular(Math.exp);\r\n\r\n/** @shadeup=univ(log) */\r\nexport const log = componentOpSingular(Math.log);\r\n\r\n/** @shadeup=univ(log2) */\r\nexport const log2 = componentOpSingular(Math.log2);\r\n\r\n/** @shadeup=univ(log10) */\r\nexport const log10 = componentOpSingular(Math.log10);\r\n\r\n/** @shadeup=univ(sqrt) */\r\nexport const sqrt = componentOpSingular(Math.sqrt);\r\n\r\n/** @shadeup=univ(inversesqrt) */\r\nexport const inversesqrt = componentOpSingular((a) => 1 / Math.sqrt(a));\r\n\r\n/** @shadeup=univ(fract)*/\r\nexport const frac = componentOpSingular((a) => a - Math.floor(a));\r\n\r\nexport function wrap(x: float, low: float, high: float): float {\r\n if (lt(x, low)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(low, x);\r\n let ms = mod(s1, rng);\r\n return sub(high, ms);\r\n } else if (gte(x, high)) {\r\n let rng = sub(high, low);\r\n let s1 = sub(x, high);\r\n let ms = mod(s1, rng);\r\n return add(low, ms);\r\n } else {\r\n return x;\r\n }\r\n // return add(mod(sub(x, low), sub(high, low)), low) as T;\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\n\r\nexport function rand(seed?: float): float {\r\n if (typeof seed === 'number') {\r\n return frac(mul(sin(mul(seed, float(91.3458))), float(47453.5453))) as float;\r\n } else {\r\n return Math.random() as float;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand2(seed: float2): float {\r\n return frac(mul(sin(dot(seed, float2(12.9898, 4.1414))), float(43758.5453)));\r\n}\r\n\r\n/**\r\n * Returns a deterministic (same seed = same output) random float between 0-1\r\n *\r\n * **Note:** See the noise package for more advanced random functions\r\n */\r\nexport function rand3(seed: float3): float {\r\n return rand2(add(swizzle(seed, 'xy'), rand(swizzle(seed, 'z'))));\r\n}\r\n\r\n// export function remap(x: float, low1: float, high1: float, low2: float, high2: float): float {\r\n// return add(low2, mul(div(sub(x, low1), sub(high1, low1)), sub(high2, low2)));\r\n// }\r\n\r\nexport function pingpong(x: float, length: float): float {\r\n const t = mod(x, mul(length, float(2)));\r\n return sub(length, abs(sub(t, length)));\r\n}\r\n\r\nfunction vectorMath_2to1_3to3(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3\r\n): vectorOverload_2to1_3to3 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction vectorMath_2to1_3to3_4to4(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => vector3,\r\n cb4: (a: vector4, b: vector4) => vector4\r\n): vectorOverload_2to1_3to3_4to4 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\nfunction vectorMath_2to1_3to1_4to1(\r\n cb2: (a: vector2, b: vector2) => scalar,\r\n cb3: (a: vector3, b: vector3) => scalar,\r\n cb4: (a: vector4, b: vector4) => scalar\r\n): vectorOverload_2to1_3to1_4to1 {\r\n return (a: any, b: any): any => {\r\n if (a.length === 2 && b.length === 2) {\r\n return cb2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return cb3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return cb4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n };\r\n}\r\n\r\nfunction cross2(a: float2, b: float2): any {\r\n return a[0] * b[1] - a[1] * b[0];\r\n}\r\n\r\nfunction cross3(a: float3, b: float3): any {\r\n return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\r\n}\r\n\r\nexport const cross = vectorMath_2to1_3to3(cross2, cross3);\r\n\r\nfunction dot2(a: float2, b: float2): any {\r\n return a[0] * b[0] + a[1] * b[1];\r\n}\r\n\r\nfunction dot3(a: float3, b: float3): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\r\n}\r\n\r\nfunction dot4(a: float4, b: float4): any {\r\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\r\n}\r\n\r\n/** @shadeup=univ(dot)*/\r\nexport const dot = vectorMath_2to1_3to1_4to1(dot2, dot3, dot4);\r\n\r\nfunction lerp1(a: float, b: float, t: float): float {\r\n return (a + (b - a) * t) as float;\r\n}\r\n\r\nfunction lerp2(a: float2, b: float2, t: float): float2 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t)] as float2;\r\n}\r\n\r\nfunction lerp3(a: float3, b: float3, t: float): float3 {\r\n return [lerp1(a[0], b[0], t), lerp1(a[1], b[1], t), lerp1(a[2], b[2], t)] as float3;\r\n}\r\n\r\nfunction lerp4(a: float4, b: float4, t: float): float4 {\r\n return [\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n ] as float4;\r\n}\r\n\r\nfunction lerp2x2(a: float2x2, b: float2x2, t: float): float2x2 {\r\n return float2x2(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t)\r\n );\r\n}\r\n\r\nfunction lerp3x3(a: float3x3, b: float3x3, t: float): float3x3 {\r\n return float3x3(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t)\r\n );\r\n}\r\n\r\nfunction lerp4x4(a: float4x4, b: float4x4, t: float): float4x4 {\r\n return float4x4(\r\n lerp1(a[0], b[0], t),\r\n lerp1(a[1], b[1], t),\r\n lerp1(a[2], b[2], t),\r\n lerp1(a[3], b[3], t),\r\n lerp1(a[4], b[4], t),\r\n lerp1(a[5], b[5], t),\r\n lerp1(a[6], b[6], t),\r\n lerp1(a[7], b[7], t),\r\n lerp1(a[8], b[8], t),\r\n lerp1(a[9], b[9], t),\r\n lerp1(a[10], b[10], t),\r\n lerp1(a[11], b[11], t),\r\n lerp1(a[12], b[12], t),\r\n lerp1(a[13], b[13], t),\r\n lerp1(a[14], b[14], t),\r\n lerp1(a[15], b[15], t)\r\n );\r\n}\r\n\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: float, b: float, t: float): float;\r\nexport function lerp(a: float2, b: float2, t: float): float2;\r\nexport function lerp(a: float3, b: float3, t: float): float3;\r\nexport function lerp(a: float4, b: float4, t: float): float4;\r\nexport function lerp(a: float2x2, b: float2x2, t: float): float2x2;\r\nexport function lerp(a: float3x3, b: float3x3, t: float): float3x3;\r\nexport function lerp(a: float4x4, b: float4x4, t: float): float4x4;\r\n/** @shadeup=univ(mix)*/\r\nexport function lerp(a: any, b: any, t: float): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof t === 'number') {\r\n return lerp1(a as float, b as float, t);\r\n } else if (isMatrix(a) && isMatrix(b)) {\r\n if (a.length === 4 && b.length === 4) {\r\n return lerp2x2(a as float2x2, b as float2x2, t);\r\n } else if (a.length === 9 && b.length === 9) {\r\n return lerp3x3(a as float3x3, b as float3x3, t);\r\n } else if (a.length === 16 && b.length === 16) {\r\n return lerp4x4(a as float4x4, b as float4x4, t);\r\n } else {\r\n throw new Error('Invalid matrix length');\r\n }\r\n } else if (a.length === 2 && b.length === 2 && typeof t === 'number') {\r\n return lerp2(a, b, t as float);\r\n } else if (a.length === 3 && b.length === 3 && typeof t === 'number') {\r\n return lerp3(a, b, t);\r\n } else if (a.length === 4 && b.length === 4 && typeof t === 'number') {\r\n return lerp4(a, b, t);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: float, b: float, c: float, d: float, u: float, v: float): float;\r\nexport function bilerp(a: float2, b: float2, c: float2, d: float2, u: float, v: float): float2;\r\nexport function bilerp(a: float3, b: float3, c: float3, d: float3, u: float, v: float): float3;\r\nexport function bilerp(a: float4, b: float4, c: float4, d: float4, u: float, v: float): float4;\r\nexport function bilerp(\r\n a: float2x2,\r\n b: float2x2,\r\n c: float2x2,\r\n d: float2x2,\r\n u: float,\r\n v: float\r\n): float2x2;\r\nexport function bilerp(\r\n a: float3x3,\r\n b: float3x3,\r\n c: float3x3,\r\n d: float3x3,\r\n u: float,\r\n v: float\r\n): float3x3;\r\nexport function bilerp(\r\n a: float4x4,\r\n b: float4x4,\r\n c: float4x4,\r\n d: float4x4,\r\n u: float,\r\n v: float\r\n): float4x4;\r\n/** @shadeup=univ(!bilerp_`0`($0$, $1$, $2$, $3$, $4$, $5$)) */\r\nexport function bilerp(a: any, b: any, c: any, d: any, u: float, v: float): any {\r\n return lerp(lerp(a, b, u), lerp(c, d, u), v);\r\n}\r\n\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: float): float;\r\nexport function length(a: float2): float;\r\nexport function length(a: float3): float;\r\nexport function length(a: float4): float;\r\n/** @shadeup=univ(length)*/\r\nexport function length(a: any): any {\r\n if (typeof a === 'number') {\r\n return Math.abs(a);\r\n } else if (a.length === 2) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2));\r\n } else if (a.length === 3) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2));\r\n } else if (a.length === 4) {\r\n return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2));\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport function dist(a: float, b: float): float;\r\nexport function dist(a: float2, b: float2): float;\r\nexport function dist(a: float3, b: float3): float;\r\nexport function dist(a: float4, b: float4): float;\r\nexport function dist(a: T, b: T): float {\r\n return length(sub(a, b));\r\n}\r\n\r\n/** @shadeup=univ(distance)*/\r\nexport const distance = dist;\r\n\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: float2): float2;\r\nexport function normalize(a: float3): float3;\r\nexport function normalize(a: float4): float4;\r\n/** @shadeup=univ(normalize)*/\r\nexport function normalize(a: any): any {\r\n if (a.length === 2) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l];\r\n } else if (a.length === 3) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l];\r\n } else if (a.length === 4) {\r\n let l = length(a);\r\n return [a[0] / l, a[1] / l, a[2] / l, a[3] / l];\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: float2, b: float2): float2;\r\nexport function reflect(a: float3, b: float3): float3;\r\nexport function reflect(a: float4, b: float4): float4;\r\n/** @shadeup=univ(reflect)*/\r\nexport function reflect(a: any, b: any): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return reflect2(a, b);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return reflect3(a, b);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return reflect4(a, b);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction reflect2(b, a) {\r\n let dot = dot2(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1]];\r\n}\r\n\r\nfunction reflect3(b, a) {\r\n let dot = dot3(a, b);\r\n return [b[0] - 2 * dot * a[0], b[1] - 2 * dot * a[1], b[2] - 2 * dot * a[2]];\r\n}\r\n\r\nfunction reflect4(b, a) {\r\n let dot = dot4(a, b);\r\n return [\r\n b[0] - 2 * dot * a[0],\r\n b[1] - 2 * dot * a[1],\r\n b[2] - 2 * dot * a[2],\r\n b[3] - 2 * dot * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: float2, b: float2, eta: float): float2;\r\nexport function refract(a: float3, b: float3, eta: float): float3;\r\nexport function refract(a: float4, b: float4, eta: float): float4;\r\n/** @shadeup=univ(refract)*/\r\nexport function refract(a: any, b: any, eta: number): any {\r\n if (a.length === 2 && b.length === 2) {\r\n return refract2(a, b, eta);\r\n } else if (a.length === 3 && b.length === 3) {\r\n return refract3(a, b, eta);\r\n } else if (a.length === 4 && b.length === 4) {\r\n return refract4(a, b, eta);\r\n } else {\r\n throw new Error('Invalid vector length');\r\n }\r\n}\r\n\r\nfunction refract2(b, a, eta) {\r\n let dot = dot2(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1]\r\n ];\r\n}\r\n\r\nfunction refract3(b, a, eta) {\r\n let dot = dot3(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2]\r\n ];\r\n}\r\n\r\nfunction refract4(b, a, eta) {\r\n let dot = dot4(a, b);\r\n let k = 1 - eta * eta * (1 - dot * dot);\r\n return k < 0\r\n ? [0, 0, 0, 0]\r\n : [\r\n eta * b[0] - (eta * dot + Math.sqrt(k)) * a[0],\r\n eta * b[1] - (eta * dot + Math.sqrt(k)) * a[1],\r\n eta * b[2] - (eta * dot + Math.sqrt(k)) * a[2],\r\n eta * b[3] - (eta * dot + Math.sqrt(k)) * a[3]\r\n ];\r\n}\r\n\r\n/** @shadeup=univ(degrees)*/\r\nexport function degrees(a: float): float {\r\n return float((a * 180) / Math.PI);\r\n}\r\n\r\n/** @shadeup=univ(radians)*/\r\nexport function radians(a: float): float {\r\n return float((a * Math.PI) / 180);\r\n}\r\n\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: float, x: float): float;\r\nexport function step(edge: int, x: float): float;\r\nexport function step(edge: T, x: T): T;\r\nexport function step(edge: float, x: T): T;\r\nexport function step(edge: int, x: T): T;\r\n/** @shadeup=univ(step)*/\r\nexport function step(edge: any, x: any): any {\r\n if (typeof edge === 'number') {\r\n if (typeof x === 'number') {\r\n return x < edge ? 0 : 1;\r\n } else {\r\n return x.map((v) => (v < edge ? 0 : 1));\r\n }\r\n } else {\r\n if (typeof x === 'number') {\r\n return edge.map((v) => (x < v ? 0 : 1));\r\n } else {\r\n return edge.map((v, i) => (x[i] < v ? 0 : 1));\r\n }\r\n }\r\n}\r\n\r\nfunction _smoothstep(a, b, x) {\r\n let t = clamp((x - a) / (b - a), 0, 1);\r\n return t * t * (3 - 2 * t);\r\n}\r\n\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: float, b: float, x: float): float;\r\nexport function smoothstep(a: float2, b: float2, x: float2): float2;\r\nexport function smoothstep(a: float3, b: float3, x: float3): float3;\r\nexport function smoothstep(a: float4, b: float4, x: float4): float4;\r\n/** @shadeup=univ(smoothstep)*/\r\nexport function smoothstep(a: any, b: any, x: any): any {\r\n if (typeof a === 'number' && typeof b === 'number' && typeof x === 'number') {\r\n return _smoothstep(a, b, x);\r\n } else if (typeof a === 'number' && typeof b === 'number') {\r\n return x.map((v) => _smoothstep(a, b, v));\r\n } else {\r\n return a.map((v, i) => _smoothstep(v, b[i], x[i]));\r\n }\r\n}\r\n\r\nfunction componentReduce(vectors: vector[], cb: (a: scalar[]) => scalar) {\r\n let result: scalar[] = [];\r\n for (let i = 0; i < vectors[0].length; i++) {\r\n result.push(cb(vectors.map((v) => v[i])));\r\n }\r\n return result;\r\n}\r\n\r\n/** @shadeup=univ(min)*/\r\n\r\nexport function min(a: int, ...b: int[]): int;\r\nexport function min(a: int2, ...b: int2[]): int2;\r\nexport function min(a: int3, ...b: int3[]): int3;\r\nexport function min(a: int4, ...b: int4[]): int4;\r\nexport function min(a: float, ...b: float[]): float;\r\nexport function min(a: float2, ...b: float2[]): float2;\r\nexport function min(a: float3, ...b: float3[]): float3;\r\nexport function min(a: float4, ...b: float4[]): float4;\r\n\r\nexport function min(a: float, b: T): T;\r\nexport function min(a: T, b: float): T;\r\nexport function min(a: int, b: T): T;\r\nexport function min(a: T, b: int): T;\r\n\r\n/** @shadeup=univ(min)*/\r\nexport function min(...args: T[]): T {\r\n if (args.length == 1) {\r\n if (Array.isArray(args[0])) {\r\n return Math.min(...args[0]) as T;\r\n } else {\r\n return args[0];\r\n }\r\n } else {\r\n if (Array.isArray(args[0]) && !Array.isArray(args[1])) {\r\n let minTo = args[1] as float;\r\n return args[0].map((v) => Math.min(v, minTo)) as T;\r\n } else if (!Array.isArray(args[0]) && Array.isArray(args[1])) {\r\n let minFrom = args[0] as float;\r\n return args[1].map((v) => Math.min(minFrom, v)) as T;\r\n } else if (Array.isArray(args[0])) {\r\n return componentReduce(args as vector[], (a) => Math.min(...a) as scalar) as T;\r\n } else {\r\n return Math.min(...(args as number[])) as T;\r\n }\r\n }\r\n}\r\n\r\n/** @shadeup=univ(max)*/\r\n\r\nexport function max(a: int, ...b: int[]): int;\r\nexport function max(a: float, ...b: int[]): float;\r\nexport function max(a: int, ...b: float[]): float;\r\nexport function max(a: int2, ...b: int2[]): int2;\r\nexport function max(a: int3, ...b: int3[]): int3;\r\nexport function max(a: int4, ...b: int4[]): int4;\r\nexport function max(a: float, ...b: float[]): float;\r\nexport function max(a: float2, ...b: float2[]): float2;\r\nexport function max(a: float3, ...b: float3[]): float3;\r\nexport function max(a: float4, ...b: float4[]): float4;\r\n\r\nexport function max(a: float, b: T): T;\r\nexport function max